text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Update entry footer structure for pages
<?php /** * The template used for displaying page content in page.php * * @package Flacso */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="page-header"> <?php the_title( '<h1 class="page-title">', '</h1>' ); ?> </header><!-- .page-header --> <div class="entry-content"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'flacso' ), 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <?php edit_post_link( __( 'Edit', 'flacso' ), '<footer class="entry-footer"><span class="edit-link">', '</span></footer>' ); ?> </article><!-- #post-## -->
<?php /** * The template used for displaying page content in page.php * * @package Flacso */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="page-header"> <?php the_title( '<h1 class="page-title">', '</h1>' ); ?> </header><!-- .page-header --> <div class="entry-content"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'flacso' ), 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <footer class="entry-footer"> <?php edit_post_link( __( 'Edit', 'flacso' ), '<span class="edit-link">', '</span>' ); ?> </footer><!-- .entry-footer --> </article><!-- #post-## -->
Add print_ip method for debugging
import socks import socket import json from stem.control import Controller from stem import Signal from urllib2 import urlopen class Tor(object): """Tor class for socks proxy and controller""" def __init__(self, socks_port=9050, control_port=9051, control_password=""): self.socks_port = socks_port self.control_port = control_port self.control_password = control_password self.default_socket = socket.socket def connect(self): """connect to Tor socks proxy""" socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", self.socks_port) socket.socket = socks.socksocket def disconnect(self): """disconnect Tor socks proxy""" socket.socket = self.default_socket def change_relay(self): """change Tor relay to obtain new ip""" with Controller.from_port(port=self.control_port) as controller: controller.authenticate(self.control_password) controller.signal(Signal.NEWNYM) def print_ip(): """print ip for debug""" json_str = urlopen('http://ip-api.com/json').read().decode('UTF-8') ip_dict = json.loads(json_str) for key, value in ip_dict.items(): print("%s: %s" % (key, value))
import socks import socket from stem.control import Controller from stem import Signal class Tor(object): """Tor class for socks proxy and controller""" def __init__(self, socks_port=9050, control_port=9051, control_password=""): self.socks_port = socks_port self.control_port = control_port self.control_password = control_password self.default_socket = socket.socket def connect(self): """connect to Tor socks proxy""" socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", self.socks_port) socket.socket = socks.socksocket def disconnect(self): """disconnect Tor socks proxy""" socket.socket = self.default_socket def change_relay(self): """change Tor relay to obtain new ip""" with Controller.from_port(port=self.control_port) as controller: controller.authenticate(self.control_password) controller.signal(Signal.NEWNYM)
Add generic Config type in Management Result
package org.fakekoji.jobmanager; import org.fakekoji.jobmanager.model.JobUpdateResults; import java.util.Objects; public class ManagementResult <C> { public final C config; public final JobUpdateResults jobUpdateResults; public ManagementResult(C config, JobUpdateResults jobUpdateResults) { this.config = config; this.jobUpdateResults = jobUpdateResults; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ManagementResult)) return false; ManagementResult that = (ManagementResult) o; return Objects.equals(config, that.config) && Objects.equals(jobUpdateResults, that.jobUpdateResults); } @Override public int hashCode() { return Objects.hash(config, jobUpdateResults); } @Override public String toString() { return "ManagementResult{" + "config=" + config + ", jobupdateResults=" + jobUpdateResults + '}'; } }
package org.fakekoji.jobmanager; import org.fakekoji.jobmanager.model.JobUpdateResults; import java.util.Objects; public class ManagementResult { public final Object config; public final JobUpdateResults jobUpdateResults; public ManagementResult(Object config, JobUpdateResults jobUpdateResults) { this.config = config; this.jobUpdateResults = jobUpdateResults; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ManagementResult)) return false; ManagementResult that = (ManagementResult) o; return Objects.equals(config, that.config) && Objects.equals(jobUpdateResults, that.jobUpdateResults); } @Override public int hashCode() { return Objects.hash(config, jobUpdateResults); } @Override public String toString() { return "ManagementResult{" + "config=" + config + ", jobupdateResults=" + jobUpdateResults + '}'; } }
Replace observer with a computed property
import Component from '@ember/component'; import { get, computed } from '@ember/object'; export default Component.extend({ tagName: 'span', classNames: 'latex-maths', attributeBindings: ['maths:data-maths'], expr: null, display: false, throwOnError: true, errorColor: '#cc0000', maths: computed('expr', 'display', 'throwOnError', 'errorColor', { get() { const expr = get(this, 'expr'); const el = get(this, 'element'); const displayMode = get(this, 'display'); const throwOnError = get(this, 'throwOnError'); const errorColor = get(this, 'errorColor'); if (expr && el) { window.katex.render(expr, el, { displayMode, throwOnError, errorColor, }); } return expr; }, }), });
import Component from '@ember/component'; import { get, observer } from '@ember/object'; import { once } from '@ember/runloop'; export default Component.extend({ tagName: 'span', classNames: 'latex-maths', expr: null, display: false, throwOnError: true, errorColor: '#cc0000', didInsertElement() { this.typeset(); }, _observer: observer('expr', 'display', 'throwOnError', 'errorColor', function() { once(this, 'typeset'); }), typeset() { const expr = get(this, 'expr'); const el = get(this, 'element'); const display = get(this, 'display'); const throwOnError = get(this, 'throwOnError'); const errorColor = get(this, 'errorColor'); if (expr && el) { window.katex.render(expr, el, { displayMode: display, throwOnError: throwOnError, errorColor: errorColor, }); } } });
Handle non-matching lines which don't cause match errors and don't clean the empty lines if there are no cleaned lines
# -*- coding: utf-8 -*- import re import sublime, sublime_plugin class TotalFileCommand(sublime_plugin.TextCommand): def run(self, edit): cleaned = [] numbers = [] region = sublime.Region(0, self.view.size()); for lineRegion in self.view.lines(region): line = self.view.substr(lineRegion) if (line == ""): break try: m = re.match(u"£\s*([0-9\.,]{1,9})\s*(.*)", line, re.U) if (m): cost = float(m.group(1).strip(' ')) numbers.append(cost) desc = m.group(2) cleaned.append(u"£{0:>9.2f} {1}".format(cost, desc)) else: cleaned.append(line) except ValueError: cleaned.append(line) total = sum(numbers) if (len(cleaned) > 0): while cleaned[-1].strip() == '': del cleaned[-1] cleaned.append("") cleaned.append(u"£{0:>9.2f} Total".format(total)) cleaned = '\n'.join(cleaned) #edit = self.view.begin_edit("") self.view.erase(edit, region) self.view.insert(edit, 0, cleaned) #self.view.end_edit(edit)
# -*- coding: utf-8 -*- import re import sublime, sublime_plugin class TotalFileCommand(sublime_plugin.TextCommand): def run(self, edit): cleaned = [] numbers = [] region = sublime.Region(0, self.view.size()); for lineRegion in self.view.lines(region): line = self.view.substr(lineRegion) if (line == ""): break try: m = re.match(ur"£\s*([0-9\.,]{1,9})\s(.*)", line) if (m): cost = float(m.group(1).strip(' ')) numbers.append(cost) desc = m.group(2) cleaned.append(u"£{0:>9.2f} {1}".format(cost, desc)) except ValueError: cleaned.append(line) total = sum(numbers) while cleaned[-1].strip() == '': del cleaned[-1] cleaned.append("") cleaned.append(u"£{0:>9.2f} Total".format(total)) cleaned = '\n'.join(cleaned) #edit = self.view.begin_edit("") self.view.erase(edit, region) self.view.insert(edit, 0, cleaned) #self.view.end_edit(edit)
Disable hot reloading in test environment
import path from 'path' import fs from 'fs' const root = path.join(__dirname, '..') const src = path.join(root, 'src') const dist = path.join(root, 'dist') const prod = process.env.NODE_ENV === 'production' const test = process.env.NODE_ENV === 'test' const dev = !prod && !test const hotLoader = !test && process.env.HOT_RELOAD === 'react-hot-loader' const nodeModulesDirectory = path.join(root, 'node_modules') const nodeModulesExternals = fs.readdirSync(nodeModulesDirectory) .filter(name => name !== '.bin') .reduce((acc, name) => ( acc[name] = `commonjs ${name}`, acc ), {}) export default { root, src, dist, prod, dev, hotLoader, nodeMixin: { target: 'node', node: { console: false, process: false, global: false, Buffer: false, __filename: false, __dirname: false }, externals: [nodeModulesExternals] } }
import path from 'path' import fs from 'fs' const root = path.join(__dirname, '..') const src = path.join(root, 'src') const dist = path.join(root, 'dist') const prod = process.env.NODE_ENV === 'production' const dev = !prod const hotLoader = process.env.HOT_RELOAD === 'react-hot-loader' const nodeModulesDirectory = path.join(root, 'node_modules') const nodeModulesExternals = fs.readdirSync(nodeModulesDirectory) .filter(name => name !== '.bin') .reduce((acc, name) => ( acc[name] = `commonjs ${name}`, acc ), {}) export default { root, src, dist, prod, dev, hotLoader, nodeMixin: { target: 'node', node: { console: false, process: false, global: false, Buffer: false, __filename: false, __dirname: false }, externals: [nodeModulesExternals] } }
Add explanation about using __slots__
"""Models for the response of the configuration object.""" from __future__ import division, print_function, unicode_literals from readthedocs.config.utils import to_dict class Base(object): """ Base class for every configuration. Each inherited class should define its attibutes in the `__slots__` attribute. We are using `__slots__` so we can't add more attributes by mistake, this is similar to a namedtuple. """ def __init__(self, **kwargs): for name in self.__slots__: setattr(self, name, kwargs[name]) def as_dict(self): return { name: to_dict(getattr(self, name)) for name in self.__slots__ } class Build(Base): __slots__ = ('image',) class Python(Base): __slots__ = ('version', 'install', 'use_system_site_packages') class PythonInstallRequirements(Base): __slots__ = ('requirements',) class PythonInstall(Base): __slots__ = ('path', 'method', 'extra_requirements',) class Conda(Base): __slots__ = ('environment',) class Sphinx(Base): __slots__ = ('builder', 'configuration', 'fail_on_warning') class Mkdocs(Base): __slots__ = ('configuration', 'fail_on_warning') class Submodules(Base): __slots__ = ('include', 'exclude', 'recursive')
"""Models for the response of the configuration object.""" from __future__ import division, print_function, unicode_literals from readthedocs.config.utils import to_dict class Base(object): """ Base class for every configuration. Each inherited class should define its attibutes in the `__slots__` attribute. """ def __init__(self, **kwargs): for name in self.__slots__: setattr(self, name, kwargs[name]) def as_dict(self): return { name: to_dict(getattr(self, name)) for name in self.__slots__ } class Build(Base): __slots__ = ('image',) class Python(Base): __slots__ = ('version', 'install', 'use_system_site_packages') class PythonInstallRequirements(Base): __slots__ = ('requirements',) class PythonInstall(Base): __slots__ = ('path', 'method', 'extra_requirements',) class Conda(Base): __slots__ = ('environment',) class Sphinx(Base): __slots__ = ('builder', 'configuration', 'fail_on_warning') class Mkdocs(Base): __slots__ = ('configuration', 'fail_on_warning') class Submodules(Base): __slots__ = ('include', 'exclude', 'recursive')
Correct import syntax for fs
import * as fs from 'fs' const rethinkdbConfig = (() => { const cert = fs.readFileSync(path.resolve(__dirname, '../cert')) let config = { host: process.env.RETHINKDB_HOST || 'localhost', port: process.env.RETHINKDB_PORT || 28015, db: 'quill_lessons' } if (process.env.RETHINKDB_AUTH_KEY) { config['authKey'] = process.env.RETHINKDB_AUTH_KEY } if (process.env.RETHINKDB_USER) { config['user'] = process.env.RETHINKDB_USER } if (process.env.RETHINKDB_PASSWORD) { config['password'] = process.env.RETHINKDB_PASSWORD } if (cert) { config['ssl'] = { ca: cert } } return config })() export default rethinkdbConfig
import { fs } from 'fs'; const rethinkdbConfig = (() => { const cert = fs.readFileSync(path.resolve(__dirname, '../cert')) let config = { host: process.env.RETHINKDB_HOST || 'localhost', port: process.env.RETHINKDB_PORT || 28015, db: 'quill_lessons' } if (process.env.RETHINKDB_AUTH_KEY) { config['authKey'] = process.env.RETHINKDB_AUTH_KEY } if (process.env.RETHINKDB_USER) { config['user'] = process.env.RETHINKDB_USER } if (process.env.RETHINKDB_PASSWORD) { config['password'] = process.env.RETHINKDB_PASSWORD } if (cert) { config['ssl'] = { ca: cert } } return config })() export default rethinkdbConfig
Update dependencies to add redis and pylibmc
from setuptools import setup setup(name="gimlet", version='0.1', description='Simple High-Performance WSGI Sessions', long_description='', classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Development Status :: 3 - Alpha', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware', 'Topic :: Internet :: WWW/HTTP :: Session', ], keywords='wsgi sessions middleware beaker cookie', url='http://github.com/storborg/gimlet', author='Scott Torborg', author_email='scott@cartlogic.com', install_requires=[ 'itsdangerous', 'webob', 'redis', 'pylibmc', # Required for cookie encryption. 'pycrypto', # These are for tests. 'coverage', 'nose>=1.1', 'nose-cover3', 'webtest', ], license='MIT', packages=['gimlet'], test_suite='nose.collector', tests_require=['nose'], zip_safe=False)
from setuptools import setup setup(name="gimlet", version='0.1', description='Simple High-Performance WSGI Sessions', long_description='', classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Development Status :: 3 - Alpha', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware', 'Topic :: Internet :: WWW/HTTP :: Session', ], keywords='wsgi sessions middleware beaker cookie', url='http://github.com/storborg/gimlet', author='Scott Torborg', author_email='scott@cartlogic.com', install_requires=[ 'itsdangerous', 'webob', # Required for cookie encryption. 'pycrypto', # These are for tests. 'coverage', 'nose>=1.1', 'nose-cover3', 'webtest', ], license='MIT', packages=['gimlet'], test_suite='nose.collector', tests_require=['nose'], zip_safe=False)
Replace the old Host model with a new one. The new Host model doesn't need the host user to have a profile. Instead it will contain the user to whom the Host entity belongs to as the parent of the Host entity to maintain transactionality between User and Host updates. --HG-- extra : rebase_source : cee68153ab1cfdb77cc955f14ae8f7ef02d5157a
#!/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 Model for Host.""" __authors__ = [ '"Madhusudan.C.S" <madhusudancs@gmail.com>', ] from google.appengine.ext import db from django.utils.translation import ugettext import soc.models.base class Host(soc.models.base.ModelWithFieldAttributes): """Model containing host specific data. The User entity corresponding to this host will be the parent of this entity. """ notify_slot_transfer = db.BooleanProperty(required=False, default=True, verbose_name=ugettext('Notify of slot transfer updates')) notify_slot_transfer.help_text = ugettext( 'Whether to send an email notification when slot transfer requests ' 'are made or updated.') notify_slot_transfer.group = ugettext("1. Notification settings")
#!/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 Host Model.""" __authors__ = [ '"Todd Larsen" <tlarsen@google.com>', '"Sverre Rabbelier" <sverre@rabbelier.nl>', ] import soc.models.role import soc.models.sponsor class Host(soc.models.role.Role): """Host details for a specific Program. """ pass
Remove the files Matt re-added This reverts commit 18106dac8014cd215ba01ac416bccd3bdebc6fa9.
<?php /* * This file is part of the YDD\Vebra package. * * (c) 2012 Damon Jones <damon@yummyduckdesign.co.uk> and Matthew Davis <matt@yummyduckdesign.co.uk> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace YDD\Vebra\Model; /** * ChangedPropertySummary */ class ChangedPropertySummary extends PropertySummary { protected $lastAction; /** * set LastAction * * @param string $lastAction * * @return object */ public function setLastAction($lastAction) { $this->lastAction = $lastAction; return $this; } /** * get LastAction * * @return string */ public function getLastAction() { return $this->lastAction; } }
<?php /* * This file is part of the YDD\Vebra package. * * (c) 2012 Damon Jones <damon@yummyduckdesign.co.uk> and Matthew Davis <matt@yummyduckdesign.co.uk> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace YDD\Vebra\Model; /** * ChangedPropertySummary */ class ChangedPropertySummary extends PropertySummary { protected $lastAction; /** * set LastAction * * @param string $lastAction * * @return object */ public function setLastAction($lastAction) { $this->lastAction = $lastAction; return $this; } /** * get LastAction * * @return string */ public function getLastAction() { return $this->lastAction; } /** * get ClientId * * @return int $clientId */ public function getClientId() { preg_match('#branch\/(\d+)/#', $this->url, $matches); return isset($matches[1]) ? (int) $matches[1] : null; } }
Add time.sleep(0.05) in test module
import time def run(seed): """ function to run Args: seed: The value of each line striped in seed file Returns: String, object, list, directory, etc. """ name, age = seed.split(',') return 'Hello World! {}, {}'.format(seed, int(age)) def callback(result): """ callback function to call Args: result: ProcessTask instance pool_task_with_timeout() method returned result = { 'seed': 'Jone', 'data': 'Hello World! Jone', 'exception': None } result = { 'seed': 'Jone', 'data': None, 'exception': 'ValueError: invalid literal' } Returns: Anything want to return. """ seed = result['seed'] data = result['data'] exception = result['exception'] time.sleep(0.05) print('seed: "{}", data: "{}", exception: "{}"' .format(seed, data, exception))
def run(seed): """ function to run Args: seed: The value of each line striped in seed file Returns: String, object, list, directory, etc. """ name, age = seed.split(',') return 'Hello World! {}, {}'.format(seed, int(age)) def callback(result): """ callback function to call Args: result: ProcessTask instance pool_task_with_timeout() method returned result = { 'seed': 'Jone', 'data': 'Hello World! Jone', 'exception': None } or result = { 'seed': 'Jone', 'data': None, 'exception': 'ValueError: invalid literal' } Returns: Anything want to return. """ seed = result['seed'] data = result['data'] exception = result['exception'] print('seed: "{}", data: "{}", exception: "{}"' .format(seed, data, exception))
Format short durations without "0 hours"
from datetime import time from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from django import template register = template.Library() @register.filter def sec_to_time(sec): """ Converts seconds to a time object >>> t = sec_to_time(1000) >>> (t.hour, t.minute, t.second) (0, 16, 40) """ s = int(sec) hour = int(s / 60 / 60) minute = int((s / 60) % 60) sec = int(s % 60 ) return time(hour, minute, sec) @register.filter @mark_safe def format_duration(sec): """ Converts seconds into a duration string >>> format_duration(1000) '16m 40s' >>> format_duration(10009) '2h 46m 49s' """ hours = int(sec / 60 / 60) minutes = int((sec / 60) % 60) seconds = int(sec % 60) if hours: return _('{h}h {m}m {s}s').format(h=hours, m=minutes, s=seconds) else: return _('{m}m {s}s').format(m=minutes, s=seconds)
from datetime import time from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from django import template register = template.Library() @register.filter def sec_to_time(sec): """ Converts seconds to a time object >>> t = sec_to_time(1000) >>> (t.hour, t.minute, t.second) (0, 16, 40) """ s = int(sec) hour = int(s / 60 / 60) minute = int((s / 60) % 60) sec = int(s % 60 ) return time(hour, minute, sec) @register.filter @mark_safe def format_duration(sec): """ Converts seconds into a duration string >>> format_duration(1000) '0h 16m 40s' """ hours = int(sec / 60 / 60) minutes = int((sec / 60) % 60) seconds = int(sec % 60) return _('{h}h {m}m {s}s').format(h=hours, m=minutes, s=seconds)
Fix for prerender, ensure window exists
var React = require('react'); var debounce = require('lodash/function/debounce'); var matchers = {}; var mediaChangeCallback; var onMediaChange = function () { mediaChangeCallback(); }; var MatchMediaBase = { childContextTypes: { mediaQueries: React.PropTypes.object }, getChildContext: function () { return { mediaQueries: this.getMatchedMedia() }; }, init: function (mediaQueryOpts) { if (!mediaQueryOpts || typeof window === "undefined") { return; } for (var key in mediaQueryOpts) { matchers[key] = window.matchMedia(mediaQueryOpts[key]); matchers[key].addListener(onMediaChange); } }, componentWillMount: function () { mediaChangeCallback = this.handleMediaChange; }, componentWillUnmount: function () { mediaChangeCallback = null; if (!matchers) { return; } for (var key in matchers) { matchers[key].removeListener(handleMediaChange); } }, getMatchedMedia: function () { if (!matchers) { return; } var matchedQueries = {}; for (var key in matchers) { matchedQueries[key] = matchers[key].matches; } return matchedQueries; }, handleMediaChange: debounce(function () { this.forceUpdate(); }, 10, { maxWait: 250 }) }; module.exports = MatchMediaBase;
var React = require('react'); var debounce = require('lodash/function/debounce'); var matchers = {}; var mediaChangeCallback; var onMediaChange = function () { mediaChangeCallback(); }; var MatchMediaBase = { childContextTypes: { mediaQueries: React.PropTypes.object }, getChildContext: function () { return { mediaQueries: this.getMatchedMedia() }; }, init: function (mediaQueryOpts) { if (!mediaQueryOpts) { return; } for (var key in mediaQueryOpts) { matchers[key] = window.matchMedia(mediaQueryOpts[key]); matchers[key].addListener(onMediaChange); } }, componentWillMount: function () { mediaChangeCallback = this.handleMediaChange; }, componentWillUnmount: function () { mediaChangeCallback = null; if (!matchers) { return; } for (var key in matchers) { matchers[key].removeListener(handleMediaChange); } }, getMatchedMedia: function () { if (!matchers) { return; } var matchedQueries = {}; for (var key in matchers) { matchedQueries[key] = matchers[key].matches; } return matchedQueries; }, handleMediaChange: debounce(function () { this.forceUpdate(); }, 10, { maxWait: 250 }) }; module.exports = MatchMediaBase;
Fix google visualization undefined error similar to https://github.com/sir-dunxalot/ember-google-charts/pull/56 (with failing tests), see also the comment in https://github.com/sir-dunxalot/ember-google-charts/issues/57
import RSVP from 'rsvp'; import Service from '@ember/service'; export default Service.extend({ language: 'en', init() { this._super(...arguments); this.googlePackages = this.googlePackages || ['corechart', 'bar', 'line', 'scatter']; this.defaultOptions = this.defaultOptions || { animation: { duration: 500, startup: false, }, }; }, loadPackages() { const { google: { charts, visualization } } = window; return new RSVP.Promise((resolve, reject) => { if (visualization !== undefined) { resolve(); } else { charts.load('current', { language: this.get('language'), packages: this.get('googlePackages'), }); charts.setOnLoadCallback((ex) => { if (ex) { reject(ex); } resolve(); }); } }); }, });
import RSVP from 'rsvp'; import Service from '@ember/service'; export default Service.extend({ language: 'en', init() { this._super(...arguments); this.googlePackages = this.googlePackages || ['corechart', 'bar', 'line', 'scatter']; this.defaultOptions = this.defaultOptions || { animation: { duration: 500, startup: false, }, }; }, loadPackages() { const { google: { charts } } = window; return new RSVP.Promise((resolve, reject) => { const packagesAreLoaded = charts.loader; if (packagesAreLoaded) { resolve(); } else { charts.load('current', { language: this.get('language'), packages: this.get('googlePackages'), }); charts.setOnLoadCallback((ex) => { if (ex) { reject(ex); } resolve(); }); } }); }, });
Improve problem description for wrong PHP version
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Install\Prerequisite; use Illuminate\Support\Collection; class PhpVersion implements PrerequisiteInterface { protected $minVersion; public function __construct($minVersion) { $this->minVersion = $minVersion; } public function problems(): Collection { if (version_compare(PHP_VERSION, $this->minVersion, '<')) { return collect()->push([ 'message' => "PHP $this->minVersion is required.", 'detail' => 'You are running version '.PHP_VERSION.'. You might want to talk to your system administrator about upgrading to the latest PHP version.', ]); } return collect(); } }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Install\Prerequisite; use Illuminate\Support\Collection; class PhpVersion implements PrerequisiteInterface { protected $minVersion; public function __construct($minVersion) { $this->minVersion = $minVersion; } public function problems(): Collection { if (version_compare(PHP_VERSION, $this->minVersion, '<')) { return collect()->push([ 'message' => "PHP $this->minVersion is required.", 'detail' => 'You are running version '.PHP_VERSION.'. Talk to your hosting provider about upgrading to the latest PHP version.', ]); } return collect(); } }
Change header and footer colors
window.addEventListener("load", function () { var pk = new Piklor(".color-picker", [ "#f44336" , "#e91e63" , "#3f51b5" , "#4caf50" , "#ffc107" , "#795548" ], { open: ".picker-wrapper .btn" , position: "auto" }) , wrapperEl = pk.getElm(".picker-wrapper") , header = pk.getElm("header") , footer = pk.getElm("footer") ; pk.colorChosen(function (col) { wrapperEl.style.backgroundColor = col; header.style.backgroundColor = col; footer.style.backgroundColor = col; }); });
window.addEventListener("load", function () { var pk = new Piklor(".color-picker", [ "#f44336" , "#e91e63" , "#3f51b5" , "#4caf50" , "#ffc107" , "#795548" ], { open: ".picker-wrapper .btn" , position: "auto" }) , wrapperEl = document.querySelector(".picker-wrapper") ; pk.colorChosen(function (col) { wrapperEl.style.backgroundColor = col; }); });
Revert "Revert "OLMIS-3533: Added javadoc for Reason type priority field"" This reverts commit 68cd7a11b50c4f4a194f6d439e6b83b3b2f46243.
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2017 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms * of the GNU Affero General Public License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. *   * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  * See the GNU Affero General Public License for more details. You should have received a copy of * the GNU Affero General Public License along with this program. If not, see * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.  */ package org.openlmis.stockmanagement.domain.reason; import lombok.Getter; public enum ReasonType { CREDIT(2), DEBIT(1), BALANCE_ADJUSTMENT(0); /** * Value of this field will be used to set correct order of stock card line items if both * occurred and processed dates have the same date for the following line items. It is * important that types that are used to increase (like {@link #CREDIT}) should have higher * priority than types that are used to decrease (like {@link #DEBIT}). */ @Getter private int priority; ReasonType(int priority) { this.priority = priority; } }
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2017 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms * of the GNU Affero General Public License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. *   * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  * See the GNU Affero General Public License for more details. You should have received a copy of * the GNU Affero General Public License along with this program. If not, see * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.  */ package org.openlmis.stockmanagement.domain.reason; import lombok.Getter; public enum ReasonType { CREDIT(2), DEBIT(1), BALANCE_ADJUSTMENT(0); @Getter private int priority; ReasonType(int priority) { this.priority = priority; } }
Use the right graph style path in the editor
from logging import FileHandler from app import app from api import api from models import db import os from flask import request app.config.from_pyfile('../server.cfg') @app.route("/edit_graph_style", methods=['GET','POST']) def edit_graph_style(): style_path = app.config['GRAPH_STYLE_PATH'] if request.method == 'POST': with open(style_path, 'w') as f: f.write(request.form['text']) with open(style_path) as f: return """ <form method="POST"> <textarea name="text" style="width: 800; height: 600">{0}</textarea> <br/> <input type="submit" value="Save"/> </form> """.format(f.read()) api_prefix = None if app.debug: app.add_url_rule('/', 'root', lambda: app.send_static_file('index.html')) api_prefix = '/api' else: # Production file_handler = FileHandler(app.config['LOG_FILE']) app.logger.addHandler(file_handler) app.register_blueprint(api, url_prefix=api_prefix)
from logging import FileHandler from app import app from api import api from models import db import os from flask import request app.config.from_pyfile('../server.cfg') @app.route("/edit_graph_style", methods=['GET','POST']) def edit_graph_style(): filename = os.path.dirname(os.path.abspath(__file__)) + "/graph_style.json" if request.method == 'POST': with open(filename, 'w') as f: f.write(request.form['text']) with open(filename) as f: return """ <form method="POST"> <textarea name="text" style="width: 800; height: 600">{0}</textarea> <br/> <input type="submit" value="Save"/> </form> """.format(f.read()) api_prefix = None if app.debug: app.add_url_rule('/', 'root', lambda: app.send_static_file('index.html')) api_prefix = '/api' else: # Production file_handler = FileHandler(app.config['LOG_FILE']) app.logger.addHandler(file_handler) app.register_blueprint(api, url_prefix=api_prefix)
Use authentication service to signout
<?php /** * Created by PhpStorm. * User: dtome * Date: 18/02/17 * Time: 18:24 */ namespace Slx\UserInterface\Controllers\User; use Silex\Application; use Slx\Infrastructure\Service\User\AuthenticateUserService; class SignOutController { /** * @var Application */ private $application; /** * SignOutController constructor. * * @param Application $application */ public function __construct(Application $application) { $this->application = $application; } /** * @return \Symfony\Component\HttpFoundation\RedirectResponse */ public function indexAction() { (new AuthenticateUserService($this->application['session']))->removeSession(); return $this->application->redirect($this->application['url_generator']->generate('signin')); } }
<?php /** * Created by PhpStorm. * User: dtome * Date: 18/02/17 * Time: 18:24 */ namespace Slx\UserInterface\Controllers\User; use Silex\Application; class SignOutController { /** * @var Application */ private $application; /** * SignOutController constructor. * * @param Application $application */ public function __construct(Application $application) { $this->application = $application; } /** * @return \Symfony\Component\HttpFoundation\RedirectResponse */ public function indexAction() { $this->application['signout.service']->execute(); return $this->application->redirect($this->application['url_generator']->generate('signin')); } }
Check that itemAltLabel is string
<?php namespace Wikidata; use Wikidata\Property; class Entity { /** * @var string Entity Id */ public $id; /** * @var string Entity language */ public $lang; /** * @var string Entity label */ public $label; /** * @var string A link to a Wikipedia article about this entity */ public $wikipedia_article; /** * @var string[] List of entity aliases */ public $aliases = []; /** * @var string Entity description */ public $description; /** * @var \Illuminate\Support\Collection Collection of entity properties */ public $properties; /** * @param array $data * @param string $lang */ public function __construct($data, $lang) { $this->parseData($data); $this->lang = $lang; } /** * Parse input data * * @param array $data */ private function parseData($data) { $this->id = get_id($data[0]['item']); $this->label = $data[0]['itemLabel']; $this->wikipedia_article = $data[0]['wikipediaArticle']; $this->aliases = is_string($data[0]['itemAltLabel']) ? explode(', ', $data[0]['itemAltLabel']) : []; $this->description = $data[0]['itemDescription']; $collection = collect($data)->groupBy('prop'); $this->properties = $collection->mapWithKeys(function($item) { $property = new Property($item); return [$property->id => $property]; }); } }
<?php namespace Wikidata; use Wikidata\Property; class Entity { /** * @var string Entity Id */ public $id; /** * @var string Entity language */ public $lang; /** * @var string Entity label */ public $label; /** * @var string A link to a Wikipedia article about this entity */ public $wikipedia_article; /** * @var string[] List of entity aliases */ public $aliases = []; /** * @var string Entity description */ public $description; /** * @var \Illuminate\Support\Collection Collection of entity properties */ public $properties; /** * @param array $data * @param string $lang */ public function __construct($data, $lang) { $this->parseData($data); $this->lang = $lang; } /** * Parse input data * * @param array $data */ private function parseData($data) { $this->id = get_id($data[0]['item']); $this->label = $data[0]['itemLabel']; $this->wikipedia_article = $data[0]['wikipediaArticle']; $this->aliases = explode(', ', $data[0]['itemAltLabel']); $this->description = $data[0]['itemDescription']; $collection = collect($data)->groupBy('prop'); $this->properties = $collection->mapWithKeys(function($item) { $property = new Property($item); return [$property->id => $property]; }); } }
:art: Reduce number of extra fields for prettyness
from django.contrib import admin from .models import ( Patient, PatientRegister, FluVaccine, Sample, CollectionType, Symptom, ObservedSymptom ) class FluVaccineInline(admin.StackedInline): model = FluVaccine extra = 1 class SampleInline(admin.StackedInline): model = Sample extra = 1 class ObservedSymptomInline(admin.StackedInline): model = ObservedSymptom extra = 1 class PatientRegisterAdmin(admin.ModelAdmin): fieldsets = [ ('Informações do Paciente', {'fields': ['patient']}), ('Dados institucionais', {'fields': ['id_gal_origin']}), ] inlines = [ SampleInline, FluVaccineInline, ObservedSymptomInline, ] admin.site.register(Patient) admin.site.register(PatientRegister, PatientRegisterAdmin) admin.site.register(Sample) admin.site.register(CollectionType) admin.site.register(Symptom)
from django.contrib import admin from .models import ( Patient, PatientRegister, FluVaccine, Sample, CollectionType, Symptom, ObservedSymptom ) class FluVaccineInline(admin.StackedInline): model = FluVaccine extra = 1 class SampleInline(admin.StackedInline): model = Sample extra = 1 class ObservedSymptomInline(admin.StackedInline): model = ObservedSymptom extra = 2 class PatientRegisterAdmin(admin.ModelAdmin): fieldsets = [ ('Informações do Paciente', {'fields': ['patient']}), ('Dados institucionais', {'fields': ['id_gal_origin']}), ] inlines = [ SampleInline, FluVaccineInline, ObservedSymptomInline, ] admin.site.register(Patient) admin.site.register(PatientRegister, PatientRegisterAdmin) admin.site.register(Sample) admin.site.register(CollectionType) admin.site.register(Symptom)
Fix get next new moon
#!/usr/bin/env python import datetime import random import ephem from nodes import Node class Random(Node): char = "H" args = 1 results = 1 def random_choice(self, inp:Node.indexable): """Choose one in a list randomly""" return [random.choice(inp)] def randint(self, inp:int): """Random number between 0 and inp inclusive""" return random.randint(0,inp) def get_next_new_moon(self, time: Node.clock): """Gets the date of the next new moon""" new_time = datetime.datetime(*time.time_obj[:7]) return ephem.next_new_moon(new_time)
#!/usr/bin/env python import datetime import random import ephem from nodes import Node class Random(Node): char = "H" args = 1 results = 1 def random_choice(self, inp:Node.indexable): """Choose one in a list randomly""" return [random.choice(inp)] def randint(self, inp:int): """Random number between 0 and inp inclusive""" return random.randint(0,inp) def get_next_new_moon(self, time: Node.clock): """Gets the date of the next full moon""" new_time = datetime.datetime(*time.time_obj[:7]) return ephem.next_full_moon(new_time)
Change SERVICE_LIST to a tuple
# 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/. from django.conf import settings from configman import configuration, ConfigFileFutureProxy, Namespace from socorro.app.socorro_app import App from socorro.dataservice.util import ( classes_in_namespaces_converter, ) SERVICES_LIST = ('socorro.external.postgresql.bugs_service.Bugs',) # Allow configman to dynamically load the configuration and classes # for our API dataservice objects def_source = Namespace() def_source.namespace('services') def_source.services.add_option( 'service_list', default=','.join(SERVICES_LIST), from_string_converter=classes_in_namespaces_converter() ) settings.DATASERVICE_CONFIG = configuration( definition_source=[ def_source, App.get_required_config(), ], values_source_list=[ settings.DATASERVICE_INI, ConfigFileFutureProxy, ] )
# 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/. from django.conf import settings from configman import configuration, ConfigFileFutureProxy, Namespace from socorro.app.socorro_app import App from socorro.dataservice.util import ( classes_in_namespaces_converter, ) SERVICES_LIST = ('socorro.external.postgresql.bugs_service.Bugs') # Allow configman to dynamically load the configuration and classes # for our API dataservice objects def_source = Namespace() def_source.namespace('services') def_source.services.add_option( 'service_list', default=SERVICES_LIST, from_string_converter=classes_in_namespaces_converter() ) settings.DATASERVICE_CONFIG = configuration( definition_source=[ def_source, App.get_required_config(), ], values_source_list=[ settings.DATASERVICE_INI, ConfigFileFutureProxy, ] )
Add check for null/empty results in commit selection dialog. Bug: 353151 Change-Id: Ia3ca7764b4d7dde41da6f9219ff43d322c9f4ab5 Signed-off-by: Kevin Sawicki <ffb4761cba839470133bee36aeb139f58d7dbaa9@github.com>
/******************************************************************************* * Copyright (c) 2011 GitHub Inc. * 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: * Kevin Sawicki (GitHub Inc.) - initial API and implementation *******************************************************************************/ package org.eclipse.egit.ui.internal.commit; import org.eclipse.jface.action.IAction; import org.eclipse.jface.window.Window; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindowActionDelegate; import org.eclipse.ui.actions.ActionDelegate; /** * Open commit action */ public class OpenCommitAction extends ActionDelegate implements IWorkbenchWindowActionDelegate { private Shell shell; @Override public void run(IAction action) { CommitSelectionDialog dialog = new CommitSelectionDialog(shell, true); if (Window.OK != dialog.open()) return; Object[] results = dialog.getResult(); if (results == null || results.length == 0) return; for (Object result : results) CommitEditor.openQuiet((RepositoryCommit) result); } public void init(IWorkbenchWindow window) { shell = window.getShell(); } }
/******************************************************************************* * Copyright (c) 2011 GitHub Inc. * 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: * Kevin Sawicki (GitHub Inc.) - initial API and implementation *******************************************************************************/ package org.eclipse.egit.ui.internal.commit; import org.eclipse.jface.action.IAction; import org.eclipse.jface.window.Window; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindowActionDelegate; import org.eclipse.ui.actions.ActionDelegate; /** * Open commit action */ public class OpenCommitAction extends ActionDelegate implements IWorkbenchWindowActionDelegate { private Shell shell; @Override public void run(IAction action) { CommitSelectionDialog dialog = new CommitSelectionDialog(shell, true); if (Window.OK == dialog.open()) for (Object result : dialog.getResult()) CommitEditor.openQuiet((RepositoryCommit) result); } public void init(IWorkbenchWindow window) { shell = window.getShell(); } }
Convert immutable state to plain JS object before logging
import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import promise from 'redux-promise'; import createLogger from 'redux-logger'; import { reducer } from '~reslab/redux/reducer'; const logger = createLogger({ stateTransformer: s => s.toJS() }); const store = createStore(reducer, applyMiddleware(thunk, promise, logger)); // Taken from https://github.com/reactjs/redux/issues/303#issuecomment-125184409 // // This function implements an observer pattern on the store. // // To observe, call this function with an optional selector function and a // change handler. Whenever the store dispatches an action, the selector is used // to extract some part of the new state, compare it to the last state, and, if // they are known to not be the same object, the change handler is invoked on // both the new state and the old one. const observe = (store, onChange, selector) => { let lastState; const handler = () => { let nextState = store.getState(); if (!lastState || selector(nextState) !== selector(lastState)) { onChange(nextState, lastState); lastState = nextState; } }; let unsubscribe = store.subscribe(handler); handler(); return unsubscribe; }; // A convenience function that points observe() at the application store. const observeStore = (onChange, selector = v => v) => observe(store, onChange, selector); export { store, observe, observeStore };
import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import promise from 'redux-promise'; import createLogger from 'redux-logger'; import { reducer } from '~reslab/redux/reducer'; const logger = createLogger(); const store = createStore(reducer, applyMiddleware(thunk, promise, logger)); // Taken from https://github.com/reactjs/redux/issues/303#issuecomment-125184409 // // This function implements an observer pattern on the store. // // To observe, call this function with an optional selector function and a // change handler. Whenever the store dispatches an action, the selector is used // to extract some part of the new state, compare it to the last state, and, if // they are known to not be the same object, the change handler is invoked on // both the new state and the old one. const observe = (store, onChange, selector) => { let lastState; const handler = () => { let nextState = store.getState(); if (!lastState || selector(nextState) !== selector(lastState)) { onChange(nextState, lastState); lastState = nextState; } }; let unsubscribe = store.subscribe(handler); handler(); return unsubscribe; }; // A convenience function that points observe() at the application store. const observeStore = (onChange, selector = v => v) => observe(store, onChange, selector); export { store, observe, observeStore };
Add total results to class constructor
package org.gluu.oxtrust.model.scim2; import java.util.ArrayList; import java.util.List; /** * @author Rahat Ali Date: 05.08.2015 * Udpated by jgomer on 2017-10-01. */ public class ListResponse { private int totalResults; private int startIndex; private int itemsPerPage; private List<BaseScimResource> resources; public ListResponse(int sindex, int ippage, int total){ totalResults=total; startIndex=sindex; itemsPerPage=ippage; resources =new ArrayList<BaseScimResource>(); } public void addResource(BaseScimResource resource){ resources.add(resource); } public int getTotalResults() { return totalResults; } public int getStartIndex() { return startIndex; } public int getItemsPerPage() { return itemsPerPage; } public List<BaseScimResource> getResources() { return resources; } public void setResources(List<BaseScimResource> resources) { this.resources = resources; } }
package org.gluu.oxtrust.model.scim2; import java.util.ArrayList; import java.util.List; /** * @author Rahat Ali Date: 05.08.2015 * Udpated by jgomer on 2017-10-01. */ public class ListResponse { private int totalResults; private int startIndex; private int itemsPerPage; private List<BaseScimResource> resources; public ListResponse(int sindex, int ippage){ totalResults=0; startIndex=sindex; itemsPerPage=ippage; resources =new ArrayList<BaseScimResource>(); } public void addResource(BaseScimResource resource){ resources.add(resource); totalResults++; } public int getTotalResults() { return totalResults; } public int getStartIndex() { return startIndex; } public int getItemsPerPage() { return itemsPerPage; } public List<BaseScimResource> getResources() { return resources; } }
Change name from heat_jeos to heat-jeos Signed-off-by: Jeff Peeler <d776211e63e47e40d00501ffdb86a800e0782fea@redhat.com>
#!/usr/bin/python # # 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 gettext import os import subprocess import setuptools setuptools.setup( name='heat-jeos', version='1', description='The heat-jeos project provides services for creating ' '(J)ust (E)nough (O)perating (S)ystem images', license='Apache License (2.0)', author='Heat API Developers', author_email='discuss@heat-api.org', url='http://heat-api.org.org/', packages=setuptools.find_packages(exclude=['bin']), include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.6', 'Environment :: No Input/Output (Daemon)', ], scripts=['bin/heat-jeos'], py_modules=[])
#!/usr/bin/python # # 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 gettext import os import subprocess import setuptools setuptools.setup( name='heat_jeos', version='1', description='The heat-jeos project provides services for creating ' '(J)ust (E)nough (O)perating (S)ystem images', license='Apache License (2.0)', author='Heat API Developers', author_email='discuss@heat-api.org', url='http://heat-api.org.org/', packages=setuptools.find_packages(exclude=['bin']), include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.6', 'Environment :: No Input/Output (Daemon)', ], scripts=['bin/heat-jeos'], py_modules=[])
Delete feature when clicking its `.remove-button` in Rule Browser.
var Rule = Backbone.Model.extend({ initialize: function() { this.urlRoot = '/rules'; }, }); $(document).ready(function() { $('.rule-item').on('mouseenter', function() { $(this).addClass('highlighted'); var controls = $('<span>').addClass('pull-right controls'); controls.append($.editButton($(this).attr('id'))); controls.append($.removeButton($(this).attr('id'))); $(this).find('h2').append(controls); $('.edit-button').on('click', function(e) { var ruleID = $(e.currentTarget).parents('.rule-item').attr('id'); window.location.href = document.URL + '/' + ruleID + '/input'; }); $('.remove-button').on('click', function(e) { var ruleID = $(e.currentTarget).parents('.rule-item').attr('id') .substring(1); var rule = new Rule({ id: ruleID }); rule.destroy(); }); }); $('.rule-item').on('mouseleave', function() { $(this).removeClass('highlighted'); $(this).find('.controls').remove(); }); });
$(document).ready(function() { $('.rule-item').on('mouseenter', function() { $(this).addClass('highlighted'); var controls = $('<span>').addClass('pull-right controls'); controls.append($.editButton($(this).attr('id'))); controls.append($.removeButton($(this).attr('id'))); $(this).find('h2').append(controls); $('.edit-button').on('click', function(e) { var ruleID = $(e.currentTarget).parents('.rule-item').attr('id'); window.location.href = document.URL + '/' + ruleID + '/input'; }); }); $('.rule-item').on('mouseleave', function() { $(this).removeClass('highlighted'); $(this).find('.controls').remove(); }); });
Make test server for swift demo run on a particular port.
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ // Enable FOAM swift support. global.FOAM_FLAGS = { 'node': true, 'debug': true, }; var dir = __dirname; var root = dir + '/../..'; require(root + '/src/foam.js'); var srcPaths = [ dir + '/../../src', dir + '/js', ] var executor = foam.classloader.NodeJsModelExecutor.create({ classpaths: srcPaths, }); Promise.all([ executor.__subContext__.arequire('Test'), ]).then(function(models) { var Test = foam.lookup('Test'); var box = foam.box.Context.create({ myname: '/test', }); box.socketService = foam.net.node.SocketService.create({ port: 7000, delegate: box.registry, }, box) var dao = foam.dao.EasyDAO.create({ of: Test, daoType: 'MDAO', }); dao.put(Test.create({firstName: 'Mike'})); box.registry.register( 'TestDAO', null, foam.box.SkeletonBox.create({ data: dao, }) ) box.socketService });
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ // Enable FOAM swift support. global.FOAM_FLAGS = { 'node': true, 'debug': true, }; var dir = __dirname; var root = dir + '/../..'; require(root + '/src/foam.js'); var srcPaths = [ dir + '/../../src', dir + '/js', ] var executor = foam.classloader.NodeJsModelExecutor.create({ classpaths: srcPaths, }); Promise.all([ executor.__subContext__.arequire('Test'), ]).then(function(models) { var Test = foam.lookup('Test'); var box = foam.box.Context.create({ myname: '/test', }); var dao = foam.dao.EasyDAO.create({ of: Test, daoType: 'MDAO', }); dao.put(Test.create({firstName: 'Mike'})); box.registry.register( 'TestDAO', null, foam.box.SkeletonBox.create({ data: dao, }) ) box.socketService });
Update tests ControlModule and InputData
package control; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import com.health.control.*; public class ControlModuleTest { private ControlModule cm; @Before public void setUp() { cm = new ControlModule(); } @Test public void setData() { InputData id1 = new InputData("path/to/xml1.xml", "path/to/data1.txt"); InputData id2 = new InputData("path/to/xml2.xml", "path/to/data2.txt"); InputData id3 = new InputData("path/to/xml3.xml", "path/to/data3.txt"); InputData[] id = {id1, id2, id3}; cm.setData(id); InputData[] expected = {id1, id2, id3}; assertArrayEquals(expected, cm.getScript()); } @Test public void setScript() { cm.setScript("hist('histogram.png', avgByDay.AvgCreatinine, avgByDay.DateTime.DayOfYear, 365);"); String expected = "hist('histogram.png', avgByDay.AvgCreatinine, avgByDay.DateTime.DayOfYear, 365);"; assertEquals(expected, cm.getScript()); } @Test public void getData() { } }
package control; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import com.health.control.*; public class ControlModuleTest { private ControlModule cm; @Before public void setUp() { cm = new ControlModule(); } @Test public void setData() { InputData id1 = new InputData("path/to/xml1.xml", "path/to/data1.txt"); InputData id2 = new InputData("path/to/xml2.xml", "path/to/data2.txt"); InputData id3 = new InputData("path/to/xml3.xml", "path/to/data3.txt"); InputData[] id = {id1, id2, id3}; cm.setData(id); InputData[] expected = {id1, id2, id3}; assertEquals(expected, cm.getScript()); } @Test public void setScript() { cm.setScript("hist('histogram.png', avgByDay.AvgCreatinine, avgByDay.DateTime.DayOfYear, 365);"); String expected = "hist('histogram.png', avgByDay.AvgCreatinine, avgByDay.DateTime.DayOfYear, 365);"; assertEquals(expected, cm.getScript()); } @Test public void getData() { } }
Set upload paths for redactor
window.init_redactor = function(){ var csrf_token = $('meta[name=csrf-token]').attr('content'); var csrf_param = $('meta[name=csrf-param]').attr('content'); var params; if (csrf_param !== undefined && csrf_token !== undefined) { params = csrf_param + "=" + encodeURIComponent(csrf_token); } $('.visual_editor').redactor( { "imageUpload":"/redactor_images?" + params, "fileUpload":"/redactor_resources?" + params, "path":"/assets/redactor-rails", "buttonSource": true, "imageResizable": true, "plugins": [ 'fontsize', 'fontcolor', 'fontfamily', 'fullscreen', 'clips' ], $(document).on( 'ready page:load', window.init_redactor );
window.init_redactor = function(){ var csrf_token = $('meta[name=csrf-token]').attr('content'); var csrf_param = $('meta[name=csrf-param]').attr('content'); var params; if (csrf_param !== undefined && csrf_token !== undefined) { params = csrf_param + "=" + encodeURIComponent(csrf_token); } $('.visual_editor').redactor( { "imageUpload":"/redactor_images?" + params, "path":"/assets/redactor-rails", "css":"style.css"} ); } "plugins": [ 'fontsize', 'fontcolor', 'fontfamily', 'fullscreen', 'clips' ], $(document).on( 'ready page:load', window.init_redactor );
Update gravity value to be more accurate
package alfredo.phx; import alfredo.Component; import alfredo.Entity; import alfredo.Scene; import alfredo.geom.Vector; import java.util.ArrayList; /** * * @author TheMonsterOfTheDeep */ public class Physics { public static final Vector gravity = new Vector(0, 9.807f); public static void tick() { Entity[] entities = Entity.getAllEntities(); ArrayList<Body> bodies = new ArrayList(); for(Entity e : entities) { Body b = e.getComponent(Body.class); if(b != null) { bodies.add(b); } } for(Body b : bodies) { b.acceleration.set(gravity); } Scene.getCurrent().tick(); for(Entity e : entities) { for (Component c : e.getComponents()) { c.tick(); } } } }
package alfredo.phx; import alfredo.Component; import alfredo.Entity; import alfredo.Scene; import alfredo.geom.Vector; import java.util.ArrayList; /** * * @author TheMonsterOfTheDeep */ public class Physics { public static Vector gravity = new Vector(0, 9.81f); public static void tick() { Entity[] entities = Entity.getAllEntities(); ArrayList<Body> bodies = new ArrayList(); for(Entity e : entities) { Body b = e.getComponent(Body.class); if(b != null) { bodies.add(b); } } for(Body b : bodies) { b.acceleration.set(gravity); } Scene.getCurrent().tick(); for(Entity e : entities) { for (Component c : e.getComponents()) { c.tick(); } } } }
Update sendmail default path configuration
<?php return array( /* |-------------------------------------------------------------------------- | Default Swift Mailer Transport |-------------------------------------------------------------------------- | | The name of your default Swift Mailer Transport. This transport will used | as the default for all mailing operations unless a different name is | given when performing said operation. This transport name should be | listed in the array of transports below. | */ 'default' => 'mail', /* |-------------------------------------------------------------------------- | Swift Mailer Transports |-------------------------------------------------------------------------- | | Below is the configuration for each of the Swift Mailer transports. For | more information refer to: | | http://swiftmailer.org/docs/sending.html | */ 'transports' => array( 'smtp' => array( 'host' => 'smtp.example.com', 'port' => 25, 'username' => 'username', 'password' => 'password', 'encryption' => null, ), 'sendmail' => array( 'command' => '/usr/sbin/sendmail -bs', ), 'mail', ), );
<?php return array( /* |-------------------------------------------------------------------------- | Default Swift Mailer Transport |-------------------------------------------------------------------------- | | The name of your default Swift Mailer Transport. This transport will used | as the default for all mailing operations unless a different name is | given when performing said operation. This transport name should be | listed in the array of transports below. | */ 'default' => 'mail', /* |-------------------------------------------------------------------------- | Swift Mailer Transports |-------------------------------------------------------------------------- | | Below is the configuration for each of the Swift Mailer transports. For | more information refer to: | | http://swiftmailer.org/docs/sending.html | */ 'transports' => array( 'smtp' => array( 'host' => 'smtp.example.com', 'port' => 25, 'username' => 'username', 'password' => 'password', 'encryption' => null, ), 'sendmail' => array( 'command' => '/user/sbin/sendmail -bs', ), 'mail', ), );
Update tests to use class-based interface
import unittest from tests.either_or import either_or class nxppyTests(unittest.TestCase): """Basic tests for the NXP Read Library python wrapper.""" def test_import(self): """Test that it can be imported""" import nxppy @either_or('detect') def test_detect_mifare_present(self): """Test that we can read the UID from a present Mifare card. Either this test or the "absent" test below will pass, but never both. """ import nxppy reader = nxppy.Mifare() self.assertIsInstance(reader, nxppy.Mifare) self.assertIsInstance(reader.select(), str, "Card UID is not a string") @either_or('detect') def test_detect_mifare_absent(self): """Test that an absent card results in a None response. Either this test or the "present" test above will pass, but never both. """ import nxppy reader = nxppy.Mifare() self.assertIsInstance(reader, nxppy.Mifare) self.assertIsNone(reader.select(), "Card UID is not None")
import unittest from either_or import either_or class nxppyTests(unittest.TestCase): """Basic tests for the NXP Read Library python wrapper.""" def test_import(self): """Test that it can be imported""" import nxppy @either_or('detect') def test_detect_mifare_present(self): """Test that we can read the UID from a present Mifare card. Either this test or the "absent" test below will pass, but never both. """ import nxppy self.assertIsInstance(nxppy.read_mifare(), str, "Card UID is not a string") @either_or('detect') def test_detect_mifare_absent(self): """Test that an absent card results in a None response. Either this test or the "present" test above will pass, but never both. """ import nxppy self.assertIsNone(nxppy.read_mifare(), "Card UID is not None")
Allow story location and section to be null
import marshmallow class StorySchema(marshmallow.Schema): id = marshmallow.fields.Int(dump_only=True) title = marshmallow.fields.Str(required=True) created = marshmallow.fields.DateTime(dump_only=True) event_time = marshmallow.fields.DateTime(allow_none=True) location = marshmallow.fields.Str(allow_none=True) section = marshmallow.fields.Str(allow_none=True) @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'stories' if many else 'story' return {key: data} class PersonSchema(marshmallow.Schema): id = marshmallow.fields.Int(dump_only=True) name = marshmallow.fields.Str(required=True) @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'people' if many else 'person' return {key: data} class AddStoryPersonSchema(marshmallow.Schema): id = marshmallow.fields.Int() @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'story_people' if many else 'story_person' return {key: data}
import marshmallow class StorySchema(marshmallow.Schema): id = marshmallow.fields.Int(dump_only=True) title = marshmallow.fields.Str(required=True) created = marshmallow.fields.DateTime(dump_only=True) event_time = marshmallow.fields.DateTime(allow_none=True) location = marshmallow.fields.Str() section = marshmallow.fields.Str() @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'stories' if many else 'story' return {key: data} class PersonSchema(marshmallow.Schema): id = marshmallow.fields.Int(dump_only=True) name = marshmallow.fields.Str(required=True) @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'people' if many else 'person' return {key: data} class AddStoryPersonSchema(marshmallow.Schema): id = marshmallow.fields.Int() @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'story_people' if many else 'story_person' return {key: data}
Add upper limit of pandas
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='windpowerlib', version='0.1.2dev', description='Creating time series of wind power plants.', url='http://github.com/wind-python/windpowerlib', author='oemof developer group', author_email='windpowerlib@rl-institut.de', license=None, packages=['windpowerlib'], package_data={ 'windpowerlib': [os.path.join('data', '*.csv')]}, long_description=read('README.rst'), zip_safe=False, install_requires=['pandas >= 0.19.1, < 0.25.0', 'requests'], extras_require={ 'dev': ['pytest', 'jupyter', 'sphinx_rtd_theme', 'nbformat']})
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='windpowerlib', version='0.1.2dev', description='Creating time series of wind power plants.', url='http://github.com/wind-python/windpowerlib', author='oemof developer group', author_email='windpowerlib@rl-institut.de', license=None, packages=['windpowerlib'], package_data={ 'windpowerlib': [os.path.join('data', '*.csv')]}, long_description=read('README.rst'), zip_safe=False, install_requires=['pandas >= 0.19.1', 'requests'], extras_require={ 'dev': ['pytest', 'jupyter', 'sphinx_rtd_theme', 'nbformat']})
Use mongodb as production session store
/** * Hellosleep */ // Load .env for development environments (process.env.NODE_ENV !== 'production') && require('dotenv').load(); const keystone = require('keystone'); keystone.init({ 'name': '睡吧', 'brand': '睡吧', 'less': 'public', 'static': 'public', 'views': 'templates/views', 'view engine': 'jade', 'port': process.env.PORT || 3000, 'session': true, 'auth': true, 'user model': 'User', 'cookie secret': '--- insomnia ---', 'mongo': process.env.MONGO_URI || 'mongodb://localhost/hellosleep', 'auto update': true, 'session store': 'mongo', // editor configuration 'wysiwyg additional buttons': 'styleselect', 'basedir': __dirname }); keystone.import('models'); keystone.set('routes', require('./routes')); keystone.set('locals', { ga: { property: process.env.GA_SITE_PROPERTY, domain: process.env.GA_SITE_DOMAIN }, env: process.env.NODE_ENV || "development" }); keystone.start();
/** * Hellosleep */ // Load .env for development environments (process.env.NODE_ENV !== 'production') && require('dotenv').load(); const keystone = require('keystone'); keystone.init({ 'name': '睡吧', 'brand': '睡吧', 'less': 'public', 'static': 'public', 'views': 'templates/views', 'view engine': 'jade', 'port': process.env.PORT || 3000, 'session': true, 'auth': true, 'user model': 'User', 'cookie secret': '--- insomnia ---', 'mongo': process.env.MONGO_URI || 'mongodb://localhost/hellosleep', 'auto update': true, // 'session store': 'mongo', // editor configuration 'wysiwyg additional buttons': 'styleselect', 'basedir': __dirname }); keystone.import('models'); keystone.set('routes', require('./routes')); keystone.set('locals', { ga: { property: process.env.GA_SITE_PROPERTY, domain: process.env.GA_SITE_DOMAIN }, env: process.env.NODE_ENV || "development" }); keystone.start();
Make some aliases and use classes as identifiers Signed-off-by: Camilo Sperberg <9fc10dd65f77fb6c78cda83e986d969eee8e0d9c@jouwweb.nl>
<?php use JwPersistentUser\Model\ModuleOptions; use JwPersistentUser\Model\ModuleOptionsFactory; use JwPersistentUser\Service\CookieService; use JwPersistentUser\Service\CookieServiceFactory; use JwPersistentUser\Service\RememberMeService; use JwPersistentUser\Service\RememberMeServiceFactory; use JwPersistentUser\Service\UserAlwaysValid; use Zend\ServiceManager\Factory\InvokableFactory; return [ 'service_manager' => [ 'factories' => [ ModuleOptions::class => ModuleOptionsFactory::class, RememberMeService::class => RememberMeServiceFactory::class, CookieService::class => CookieServiceFactory::class, UserAlwaysValid::class => InvokableFactory::class, ], 'aliases' => [ 'JwPersistentUser\UserValidity' => UserAlwaysValid::class, 'JwPersistentUser\Service\RememberMe' => RememberMeService::class, 'JwPersistentUser\ModuleOptions' => ModuleOptions::class, 'JwPersistentUser\Service\Cookie' => CookieService::class, ], ], ];
<?php return [ 'service_manager' => [ 'factories' => [ 'JwPersistentUser\ModuleOptions' => 'JwPersistentUser\Model\ModuleOptionsFactory', 'JwPersistentUser\Service\RememberMe' => 'JwPersistentUser\Service\RememberMeServiceFactory', 'JwPersistentUser\Service\Cookie' => 'JwPersistentUser\Service\CookieServiceFactory', 'JwPersistentUser\Service\UserAlwaysValid' => \Zend\ServiceManager\Factory\InvokableFactory::class, ], 'aliases' => [ 'JwPersistentUser\UserValidity' => 'JwPersistentUser\Service\UserAlwaysValid', ], ], ];
[libzookeeper] Enable Kerberos automatically based on HDFS security We don't need another property that way and Kerberos is a all or nothing setup. Even if HDFS is not used in Hue, the default hue.ini has security set to false.
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. 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 kazoo.client import KazooClient from hadoop import cluster from desktop.lib.exceptions_renderable import PopupException from libzookeeper.conf import PRINCIPAL_NAME def get_children_data(ensemble, namespace, read_only=True): hdfs = cluster.get_hdfs() if hdfs is None: raise PopupException(_('No [hdfs] configured in hue.ini.')) if hdfs.security_enabled: sasl_server_principal = PRINCIPAL_NAME.get() else: sasl_server_principal = None zk = KazooClient(hosts=ensemble, read_only=read_only, sasl_server_principal=sasl_server_principal) zk.start() children_data = [] children = zk.get_children(namespace) for node in children: data, stat = zk.get("%s/%s" % (namespace, node)) children_data.append(data) zk.stop() return children_data
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. 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 kazoo.client import KazooClient from libzookeeper.conf import PRINCIPAL_NAME def get_children_data(ensemble, namespace, read_only=True): zk = KazooClient(hosts=ensemble, read_only=read_only, sasl_server_principal=PRINCIPAL_NAME.get()) zk.start() children_data = [] children = zk.get_children(namespace) for node in children: data, stat = zk.get("%s/%s" % (namespace, node)) children_data.append(data) zk.stop() return children_data
Remove second from job overview.
app.controller("MainController", ["$scope", "$http", "units", "unit", function($scope, $http, units, unit) { // Convert 0 or 1 from database to false or true for Angular. Yup... units.get(function(data) { $scope.units = data; $scope.changeState = function() { unit.update({ id:this.unit.unitId }, this.unit); } }); $http.get("/actions/show_schedule") .then(function(res) { function doubleDigit(n){ return n > 9 ? "" + n: "0" + n; } $scope.jobCurr = res.data; for(var i=0; i<$scope.jobCurr.length; i++) { $scope.jobCurr[i].jobName = ($scope.jobCurr[i].newState == 1 ? 'Turn on ' : 'Turn off ')+$scope.jobCurr[i].unitName; $scope.jobCurr[i].timeHr = doubleDigit($scope.jobCurr[i].hour)+":"+doubleDigit($scope.jobCurr[i].min); } console.log($scope.jobCurr); }); }]);
app.controller("MainController", ["$scope", "$http", "units", "unit", function($scope, $http, units, unit) { // Convert 0 or 1 from database to false or true for Angular. Yup... units.get(function(data) { $scope.units = data; $scope.changeState = function() { unit.update({ id:this.unit.unitId }, this.unit); } }); $http.get("/actions/show_schedule") .then(function(res) { function doubleDigit(n){ return n > 9 ? "" + n: "0" + n; } $scope.jobCurr = res.data; for(var i=0; i<$scope.jobCurr.length; i++) { $scope.jobCurr[i].jobName = ($scope.jobCurr[i].newState == 1 ? 'Turn on ' : 'Turn off ')+$scope.jobCurr[i].unitName; $scope.jobCurr[i].timeHr = doubleDigit($scope.jobCurr[i].hour)+":"+doubleDigit($scope.jobCurr[i].min)+":"+doubleDigit($scope.jobCurr[i].sec); } console.log($scope.jobCurr); }); }]);
Use print_function in toplevel script. (Avoid logging hassle for now)
from __future__ import print_function import numpy from desitarget.io import read_tractor, write_targets from desitarget.cuts import LRG, ELG, BGS, QSO from desitarget import targetmask from argparse import ArgumentParser ap = ArgumentParser() ap.add_argument("--type", choices=["tractor"], default="tractor", help="Assume a type for src files") ap.add_argument("src", help="File that stores Candidates/Objects") ap.add_argument("dest", help="File that stores targets") TYPES = { 'LRG': LRG, 'ELG': ELG, 'BGS': BGS, 'QSO': QSO, } def main(): ns = ap.parse_args() candidates = read_tractor(ns.src) # FIXME: fits doesn't like u8; there must be a workaround # but lets stick with i8 for now. tsbits = numpy.zeros(len(candidates), dtype='i8') for t in TYPES.keys(): cut = TYPES[t] bitfield = targetmask.mask(t) with numpy.errstate(all='ignore'): mask = cut.apply(candidates) tsbits[mask] |= bitfield assert ((tsbits & bitfield) != 0).sum() == mask.sum() print (t, 'selected', mask.sum()) write_targets(ns.dest, candidates, tsbits) print ('written to', ns.dest) if __name__ == "__main__": main()
import numpy from desitarget.io import read_tractor, write_targets from desitarget.cuts import LRG, ELG, BGS, QSO from desitarget import targetmask from argparse import ArgumentParser ap = ArgumentParser() ap.add_argument("--type", choices=["tractor"], default="tractor", help="Assume a type for src files") ap.add_argument("src", help="File that stores Candidates/Objects") ap.add_argument("dest", help="File that stores targets") TYPES = { 'LRG': LRG, 'ELG': ELG, 'BGS': BGS, 'QSO': QSO, } def main(): ns = ap.parse_args() candidates = read_tractor(ns.src) # FIXME: fits doesn't like u8; there must be a workaround # but lets stick with i8 for now. tsbits = numpy.zeros(len(candidates), dtype='i8') for t in TYPES.keys(): cut = TYPES[t] bitfield = targetmask.mask(t) with numpy.errstate(all='ignore'): mask = cut.apply(candidates) tsbits[mask] |= bitfield assert ((tsbits & bitfield) != 0).sum() == mask.sum() print (t, 'selected', mask.sum()) write_targets(ns.dest, candidates, tsbits) print ('written to', ns.dest) if __name__ == "__main__": main()
[FIX] module_auto_update: Rollback cursor if param exists Without this patch, when upgrading after you have stored the deprecated features parameter, the cursor became broken and no more migrations could happen. You got this error: Traceback (most recent call last): File "/usr/local/bin/odoo", line 6, in <module> exec(compile(open(__file__).read(), __file__, 'exec')) File "/opt/odoo/custom/src/odoo/odoo.py", line 160, in <module> main() File "/opt/odoo/custom/src/odoo/odoo.py", line 157, in main openerp.cli.main() File "/opt/odoo/custom/src/odoo/openerp/cli/command.py", line 64, in main o.run(args) File "/opt/odoo/custom/src/odoo/openerp/cli/shell.py", line 65, in run self.shell(openerp.tools.config['db_name']) File "/opt/odoo/custom/src/odoo/openerp/cli/shell.py", line 52, in shell registry = openerp.modules.registry.RegistryManager.get(dbname) File "/opt/odoo/custom/src/odoo/openerp/modules/registry.py", line 355, in get update_module) File "/opt/odoo/custom/src/odoo/openerp/modules/registry.py", line 386, in new openerp.modules.load_modules(registry._db, force_demo, status, update_module) File "/opt/odoo/custom/src/odoo/openerp/modules/loading.py", line 335, in load_modules force, status, report, loaded_modules, update_module) File "/opt/odoo/custom/src/odoo/openerp/modules/loading.py", line 239, in load_marked_modules loaded, processed = load_module_graph(cr, graph, progressdict, report=report, skip_modules=loaded_modules, perform_checks=perform_checks) File "/opt/odoo/custom/src/odoo/openerp/modules/loading.py", line 136, in load_module_graph registry.setup_models(cr, partial=True) File "/opt/odoo/custom/src/odoo/openerp/modules/registry.py", line 186, in setup_models cr.execute('select model, transient from ir_model where state=%s', ('manual',)) File "/opt/odoo/custom/src/odoo/openerp/sql_db.py", line 154, in wrapper return f(self, *args, **kwargs) File "/opt/odoo/custom/src/odoo/openerp/sql_db.py", line 233, in execute res = self._obj.execute(query, params) psycopg2.InternalError: current transaction is aborted, commands ignored until end of transaction block Now you can safely migrate, be that parameter pre-created or not.
# -*- coding: utf-8 -*- # Copyright 2018 Tecnativa - Jairo Llopis # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). import logging from psycopg2 import IntegrityError from odoo.addons.module_auto_update.models.module_deprecated import \ PARAM_DEPRECATED _logger = logging.getLogger(__name__) def migrate(cr, version): """Autoenable deprecated behavior.""" try: with cr.savepoint(): cr.execute( """INSERT INTO ir_config_parameter (key, value) VALUES (%s, '1')""", (PARAM_DEPRECATED,) ) _logger.warn("Deprecated features have been autoenabled, see " "addon's README to know how to upgrade to the new " "supported autoupdate mechanism.") except IntegrityError: _logger.info("Deprecated features setting exists, not autoenabling")
# -*- coding: utf-8 -*- # Copyright 2018 Tecnativa - Jairo Llopis # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). import logging from psycopg2 import IntegrityError from odoo.addons.module_auto_update.models.module_deprecated import \ PARAM_DEPRECATED _logger = logging.getLogger(__name__) def migrate(cr, version): """Autoenable deprecated behavior.""" try: cr.execute( "INSERT INTO ir_config_parameter (key, value) VALUES (%s, '1')", (PARAM_DEPRECATED,) ) _logger.warn("Deprecated features have been autoenabled, see " "addon's README to know how to upgrade to the new " "supported autoupdate mechanism.") except IntegrityError: _logger.info("Deprecated features setting exists, not autoenabling")
Remove unnecessary node of DSL
import Orchestrator from 'orchestrator' import TaskBuilder from './task-builder' export const orchestrator = new Orchestrator() /** * Creates a task of the given name and dependencies. * * @param {string} taskName The task name * @param {string|string[]} deps (The list of) the dependency task names */ export function createTask(taskName, deps) { const builder = new TaskBuilder(taskName) orchestrator.add(taskName, deps, () => builder.getTask().execute()) const modifier = { /** * Adds the behavior of the action. * @param {Function} action The behavior o the action */ do(action) { builder.addAction(action) return modifier }, /** * Adds the way of getting a container * @param {string|string[]} names The names of the containers * @param {object} param The parameters for getting containers */ get(names, params) { builder.containerGet(names, params) return modifier }, /** * Adds the way of creating a container * @param {object|object[]} names The names of the containers */ create(params) { builder.containerCreate(params) return modifier } } return modifier }
import Orchestrator from 'orchestrator' import TaskBuilder from './task-builder' export const orchestrator = new Orchestrator() /** * Creates a task of the given name and dependencies. * * @param {string} taskName The task name * @param {string|string[]} deps (The list of) the dependency task names */ export function createTask(taskName, deps) { const builder = new TaskBuilder(taskName) orchestrator.add(taskName, deps, () => builder.getTask().execute()) const modifier = { /** * Adds the behavior of the action. * @param {Function} action The behavior o the action */ do(action) { builder.addAction(action) return modifier }, /** * @return {object} */ get container() { return modifier }, /** * Adds the way of getting a container * @param {string|string[]} names The names of the containers * @param {object} param The parameters for getting containers */ get(names, params) { builder.containerGet(names, params) return modifier }, /** * Adds the way of creating a container * @param {object|object[]} names The names of the containers */ create(params) { builder.containerCreate(params) return modifier } } return modifier }
Rearrange imports in previous migration. According to mg bad things can happen if you try to do stuff outside of a migration's upgrade() function.
"""message contact association Revision ID: 223041bb858b Revises: 2c9f3a06de09 Create Date: 2014-04-28 23:52:05.449401 """ # revision identifiers, used by Alembic. revision = '223041bb858b' down_revision = '2c9f3a06de09' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'messagecontactassociation', sa.Column('id', sa.Integer(), nullable=False), sa.Column('contact_id', sa.Integer(), nullable=False), sa.Column('message_id', sa.Integer(), nullable=False), sa.Column('field', sa.Enum('from_addr', 'to_addr', 'cc_addr', 'bcc_addr'), nullable=True), sa.ForeignKeyConstraint(['contact_id'], ['contact.id'], ), sa.ForeignKeyConstraint(['message_id'], ['message.id'], ), sa.PrimaryKeyConstraint('id', 'contact_id', 'message_id') ) # Yes, this is a terrible hack. But tools/rerank_contacts.py already # contains a script to process contacts from messages, so it's very # expedient. import sys sys.path.append('./tools') from rerank_contacts import rerank_contacts rerank_contacts() def downgrade(): op.drop_table('messagecontactassociation')
"""message contact association Revision ID: 223041bb858b Revises: 2c9f3a06de09 Create Date: 2014-04-28 23:52:05.449401 """ # revision identifiers, used by Alembic. revision = '223041bb858b' down_revision = '2c9f3a06de09' # Yes, this is a terrible hack. But tools/rerank_contacts.py already contains a # script to process contacts from messages, so it's very expedient. import sys sys.path.append('./tools') from rerank_contacts import rerank_contacts from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'messagecontactassociation', sa.Column('id', sa.Integer(), nullable=False), sa.Column('contact_id', sa.Integer(), nullable=False), sa.Column('message_id', sa.Integer(), nullable=False), sa.Column('field', sa.Enum('from_addr', 'to_addr', 'cc_addr', 'bcc_addr'), nullable=True), sa.ForeignKeyConstraint(['contact_id'], ['contact.id'], ), sa.ForeignKeyConstraint(['message_id'], ['message.id'], ), sa.PrimaryKeyConstraint('id', 'contact_id', 'message_id') ) rerank_contacts() def downgrade(): op.drop_table('messagecontactassociation')
Convert scope from []string to formatting string when error is generated.
package jsonstructure import ( "fmt" "strings" ) type SchemaError struct { Scope string Err error } type EnumError struct { SchemaError } func (e *SchemaError) Error() string { return fmt.Sprintf("At %s: %s", e.Scope, e.Err.Error()) } func (e *EnumError) Error() string { return fmt.Sprintf("At %s: %s", e.Scope, e.Err.Error()) } func errorAt(err error, scope []string) error { if err == nil { return nil } msg := "/" + strings.Join(scope, "/") return &SchemaError{ Scope: msg, Err: err, } } func enumError(err error, scope []string) error { if err == nil { return nil } msg := "/" + strings.Join(scope, "/") return &EnumError{ SchemaError: SchemaError{ Scope: msg, Err: err, }, } }
package jsonstructure import ( "fmt" "strings" ) type SchemaError struct { Scope []string Err error } type EnumError struct { SchemaError } func (e *SchemaError) Error() string { return fmt.Sprintf("At /%s: %s", strings.Join(e.Scope, "/"), e.Err.Error()) } func (e *EnumError) Error() string { return fmt.Sprintf("At /%s: %s", strings.Join(e.Scope, "/"), e.Err.Error()) } func errorAt(err error, scope []string) error { if err == nil { return nil } return &SchemaError{ Scope: scope, Err: err, } } func enumError(err error, scope []string) error { if err == nil { return nil } return &EnumError{ SchemaError: SchemaError{ Scope: scope, Err: err, }, } }
Fix the path because the file had moved.
#!/bin/node import path from 'path'; import fs from 'fs'; import {all as rawMetadata} from '../katas/es6/language/__raw-metadata__'; import {writeToFileAsJson} from './_external-deps/filesystem'; import MetaData from './metadata.js'; import FlatMetaData from './flat-metadata'; import GroupedMetaData from './grouped-metadata'; const katasDir = path.join(__dirname, '../katas'); const destinationDir = path.join(__dirname, '../../dist/katas/es6/language'); const buildMetadata = () => { const allJsonFile = path.join(destinationDir, '__all__.json'); const groupedJsonFile = path.join(destinationDir, '__grouped__.json'); new MetaData(writeToFileAsJson) .convertWith(rawMetadata, FlatMetaData) .writeToFile(allJsonFile); new MetaData(writeToFileAsJson) .convertWith(rawMetadata, GroupedMetaData) .writeToFile(groupedJsonFile); fs.unlinkSync(path.join(destinationDir, '__raw-metadata__.js')); }; // TODO copy __raw-metadata__.js to dist ... or not? buildMetadata(); import {convertTestsToKatas} from './convert-tests-to-katas'; convertTestsToKatas({sourceDir: katasDir, destinationDir});
#!/bin/node import path from 'path'; import fs from 'fs'; import {all as rawMetadata} from '../katas/es6/language/__raw-metadata__'; import {writeToFileAsJson} from './_external-deps/filesystem'; import MetaData from './metadata.js'; import FlatMetaData from './flat-metadata'; import GroupedMetaData from './grouped-metadata'; const katasDir = path.join(__dirname, '../katas'); const destinationDir = path.join(__dirname, '../dist/katas/es6/language'); const buildMetadata = () => { const allJsonFile = path.join(destinationDir, '__all__.json'); const groupedJsonFile = path.join(destinationDir, '__grouped__.json'); new MetaData(writeToFileAsJson) .convertWith(rawMetadata, FlatMetaData) .writeToFile(allJsonFile); new MetaData(writeToFileAsJson) .convertWith(rawMetadata, GroupedMetaData) .writeToFile(groupedJsonFile); fs.unlinkSync(path.join(destinationDir, '__raw-metadata__.js')); }; // TODO copy __raw-metadata__.js to dist ... or not? buildMetadata(); import {convertTestsToKatas} from './convert-tests-to-katas'; convertTestsToKatas({sourceDir: katasDir, destinationDir});
Add missing cast for unknown types
/* * Copyright (C) 2013 Michał Charmas (http://blog.charmas.pl) * * 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 pl.charmas.serializablegenerator.typeserializers.serializers; import com.intellij.psi.PsiField; import pl.charmas.serializablegenerator.typeserializers.TypeSerializer; public class UnknownTypeSerializer implements TypeSerializer { @Override public String writeValue(PsiField field, String out) { return out + ".writeObject(this." + field.getName() + ");"; } @Override public String readValue(PsiField field, String in) { return "this." + field.getName() + " = (" + field.getType().getCanonicalText() + ") " + in + ".readObject();"; } }
/* * Copyright (C) 2013 Michał Charmas (http://blog.charmas.pl) * * 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 pl.charmas.serializablegenerator.typeserializers.serializers; import com.intellij.psi.PsiField; import pl.charmas.serializablegenerator.typeserializers.TypeSerializer; public class UnknownTypeSerializer implements TypeSerializer { @Override public String writeValue(PsiField field, String out) { return out + ".writeObject(this." + field.getName() + ");"; } @Override public String readValue(PsiField field, String in) { return "this." + field.getName() + " = " + in + ".readObject();"; } }
Use single quotes on require
var assert = require('assert'), should = require('should'), child_process = require('child_process'); describe('CLI', function () { describe('#help', function () { it('should return help instructions', function (done) { var command = 'sass-lint -h'; child_process.exec(command, function(err, stdout, stderr) { if (err) return done(err); assert(stdout.indexOf('Usage') > 0); done(null); }); }); }); describe('#version', function () { it('should return a version', function (done) { var command = 'sass-lint -V'; child_process.exec(command, function(err, stdout, stderr) { if (err) return done(err); stdout.should.match(/^[0-9]+.[0-9]+(.[0-9]+)?/); done(null); }); }); }); });
var assert = require("assert"), should = require('should'), child_process = require('child_process'); describe('CLI', function () { describe('#help', function () { it('should return help instructions', function (done) { var command = 'sass-lint -h'; child_process.exec(command, function(err, stdout, stderr) { if (err) return done(err); assert(stdout.indexOf('Usage') > 0); done(null); }); }); }); describe('#version', function () { it('should return a version', function (done) { var command = 'sass-lint -V'; child_process.exec(command, function(err, stdout, stderr) { if (err) return done(err); stdout.should.match(/^[0-9]+.[0-9]+(.[0-9]+)?/); done(null); }); }); }); });
Add constants for table category selection
/* * Copyright 2014 Codenvy, S.A. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codenvy.ide.ext.datasource.client.explorer; import com.google.gwt.i18n.client.Constants; import com.google.gwt.i18n.client.LocalizableResource.DefaultLocale; /** * Constant interface for the datasource explorer. * * @author "Mickaël Leduque" */ @DefaultLocale("en") public interface DatasourceExplorerConstants extends Constants { /** The tooltip for the refresh button. */ @DefaultStringValue("Refresh and explore") String exploreButtonTooltip(); /** The string used in the part (top). */ @DefaultStringValue("Datasource Explorer") String datasourceExplorerPartTitle(); /** The string used in the side tab. */ @DefaultStringValue("Datasource") String datasourceExplorerTabTitle(); @DefaultStringArrayValue({"Simplest - Tables and views", "Standard - adds materialized views, aliases, syn.", "System - add system tables/views", "All existing table types"}) String[] tableCategories(); }
/* * Copyright 2014 Codenvy, S.A. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codenvy.ide.ext.datasource.client.explorer; import com.google.gwt.i18n.client.LocalizableResource.DefaultLocale; import com.google.gwt.i18n.client.Messages; /** * Constant interface for the datasource explorer. * * @author "Mickaël Leduque" */ @DefaultLocale("en") public interface DatasourceExplorerConstants extends Messages { /** The tooltip for the refresh button. */ @DefaultMessage("Refresh and explore") String exploreButtonTooltip(); /** The string used in the part (top). */ @DefaultMessage("Datasource Explorer") String datasourceExplorerPartTitle(); /** The string used in the side tab. */ @DefaultMessage("Datasource") String datasourceExplorerTabTitle(); }
Add methods to Auth endpoint
/* * The MIT License (MIT) * * Copyright (c) 2016 Vincent Zhang/PhoenixLAB * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package co.phoenixlab.discord.api.endpoints; import co.phoenixlab.discord.api.entities.TokenResponse; import co.phoenixlab.discord.api.request.EmailPasswordLoginRequest; import co.phoenixlab.discord.api.request.LogoutRequest; public interface AuthenticationEndpoint { TokenResponse logIn(EmailPasswordLoginRequest request) throws ApiException; void logOut(LogoutRequest request) throws ApiException; }
/* * The MIT License (MIT) * * Copyright (c) 2016 Vincent Zhang/PhoenixLAB * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package co.phoenixlab.discord.api.endpoints; public interface AuthenticationEndpoint { }
Allow modifier key press when opening table rows
// Forest tables $(document).on('mouseenter', '.forest-table tbody tr', function() { var $row = $(this); $row.addClass('active'); $(document).one('turbolinks:before-cache.forestTables', function() { $row.removeClass('active'); }); }); $(document).on('mouseleave', '.forest-table tbody tr', function() { var $row = $(this); $row.removeClass('active'); }); $(document).on('click', '.forest-table tbody tr', function(e) { var $row = $(this); if ( !$(e.target).closest('a').length ) { var $button = $row.find('a.forest-table__link:first'); if ( !$button.length ) { $button = $row.find('a.btn-primary:first'); } var url = $button.attr('href'); if ( url ) { if ( e.metaKey || e.ctrlKey ) { window.open( url, '_blank' ); } else if ( e.shiftKey ) { window.open( url, '_blank' ); window.focus(); } else { Turbolinks.visit(url); } } } });
// Forest tables $(document).on('mouseenter', '.forest-table tbody tr', function() { var $row = $(this); $row.addClass('active'); $(document).one('turbolinks:before-cache.forestTables', function() { $row.removeClass('active'); }); }); $(document).on('mouseleave', '.forest-table tbody tr', function() { var $row = $(this); $row.removeClass('active'); }); $(document).on('click', '.forest-table tbody tr', function(e) { var $row = $(this); if ( !$(e.target).closest('a').length ) { var $button = $row.find('a.forest-table__link:first'); if ( !$button.length ) { $button = $row.find('a.btn-primary:first'); } var url = $button.attr('href'); if ( url ) { Turbolinks.visit(url); } } });
Replace print statement by print function.
from __future__ import print_function from datetime import datetime from django.db.backends import util import sqlparse from debug_toolbar.utils import ms_from_timedelta class PrintQueryWrapper(util.CursorDebugWrapper): def execute(self, sql, params=()): starttime = datetime.now() try: return self.cursor.execute(sql, params) finally: raw_sql = self.db.ops.last_executed_query(self.cursor, sql, params) execution_time = ms_from_timedelta(datetime.now() - starttime) formatted_sql = sqlparse.format(raw_sql, reindent=True) print('%s [%.2fms]' % (formatted_sql, execution_time)) util.CursorDebugWrapper = PrintQueryWrapper
from datetime import datetime from django.db.backends import util import sqlparse from debug_toolbar.utils import ms_from_timedelta class PrintQueryWrapper(util.CursorDebugWrapper): def execute(self, sql, params=()): starttime = datetime.now() try: return self.cursor.execute(sql, params) finally: raw_sql = self.db.ops.last_executed_query(self.cursor, sql, params) execution_time = datetime.now() - starttime print sqlparse.format(raw_sql, reindent=True), print ' [%.2fms]' % (ms_from_timedelta(execution_time),) print util.CursorDebugWrapper = PrintQueryWrapper
Put `import inspect` at the top of the file
import inspect def check_unexpected_kwargs(kwargs, **unexpected): for key, message in unexpected.items(): if key in kwargs: raise ValueError(message) def parse_kwargs(kwargs, *name_and_values): values = [kwargs.pop(name, default_value) for name, default_value in name_and_values] if kwargs: caller = inspect.stack()[1] args = ', '.join(repr(arg) for arg in sorted(kwargs.keys())) message = caller[3] + \ '() got unexpected keyword argument(s) {}'.format(args) raise TypeError(message) return tuple(values) def assert_kwargs_empty(kwargs): # It only checks if kwargs is empty. parse_kwargs(kwargs)
def check_unexpected_kwargs(kwargs, **unexpected): for key, message in unexpected.items(): if key in kwargs: raise ValueError(message) def parse_kwargs(kwargs, *name_and_values): values = [kwargs.pop(name, default_value) for name, default_value in name_and_values] if kwargs: import inspect caller = inspect.stack()[1] args = ', '.join(repr(arg) for arg in sorted(kwargs.keys())) message = caller[3] + \ '() got unexpected keyword argument(s) {}'.format(args) raise TypeError(message) return tuple(values) def assert_kwargs_empty(kwargs): # It only checks if kwargs is empty. parse_kwargs(kwargs)
Add files to the ScriptResponse
package api import "time" type ScriptsRequest struct { Args []string `json:"args,omitempty"` Files map[string]string `json:"files,omitempty"` CallbackURL string `json:"callback_url,omitempty"` } type ScriptsResponse struct { ID string `json:"id"` Script string `json:"script"` Args []string `json:"args"` Files map[string]string `json:"files,omitempty"` CallbackURL string `json:"callback_url"` Status string `json:"status"` StartTime time.Time `json:"start_time"` EndTime time.Time `json:"end_time"` Duration string `json:"duration"` Output string `json:"output"` ExecLog string `json:"exec_log"` }
package api import "time" type ScriptsRequest struct { Args []string `json:"args,omitempty"` Files map[string]string `json:"files,omitempty"` CallbackURL string `json:"callback_url,omitempty"` } type ScriptsResponse struct { ID string `json:"id"` Script string `json:"script"` Args []string `json:"args"` CallbackURL string `json:"callback_url"` Status string `json:"status"` StartTime time.Time `json:"start_time"` EndTime time.Time `json:"end_time"` Duration string `json:"duration"` Output string `json:"output"` ExecLog string `json:"exec_log"` }
Set paths tmp to development. Need to write a env fix for that.
<?php namespace jorenvanhocht\Blogify\Commands; use Illuminate\Console\Command; class BlogifyMigrateCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'blogify:migrate'; /** * The console command description. * * @var string */ protected $description = 'Run the migrations for the Blogify package'; /** * @var array */ protected $paths; /** * Construct the class */ public function __construct() { parent::__construct(); $this->paths = [ 'packages/jorenvanhocht/blogify/database/Migrations', 'packages/jorenvanhocht/tracert/database/Migrations', ]; } /** * Execute the console command. * * @return mixed */ public function fire() { foreach ($this->paths as $path) { $this->call('migrate', ['--path' => $path]); } } }
<?php namespace jorenvanhocht\Blogify\Commands; use Illuminate\Console\Command; class BlogifyMigrateCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'blogify:migrate'; /** * The console command description. * * @var string */ protected $description = 'Run the migrations for the Blogify package'; /** * @var array */ protected $paths; /** * Construct the class */ public function __construct() { parent::__construct(); $this->paths = [ 'vendor/jorenvanhocht/blogify/database/Migrations', 'vendor/jorenvanhocht/tracert/database/Migrations', ]; } /** * Execute the console command. * * @return mixed */ public function fire() { foreach ($this->paths as $path) { $this->call('migrate', ['--path' => $path]); } } }
Fix admin show map tool.
<? $db2 = new SmrMySqlDatabase(); $account_id = $_REQUEST['account_id']; if (!empty($account_id)) { require_once(get_file_loc('SmrPort.class.inc')); $game_id = $var['game_id']; // delete all entries from the player_visited_sector/port table $db->query('DELETE FROM player_visited_sector WHERE account_id = '.$account_id.' AND game_id = '.$game_id); $db->query('DELETE FROM player_visited_port WHERE account_id = '.$account_id.' AND game_id = '.$game_id); // add port infos $db->query('SELECT sector_id FROM port WHERE game_id = '.$game_id.' ORDER BY sector_id'); while ($db->nextRecord()) { SmrPort::getPort($game_id,$db->getField('sector_id'))->addCachePort($account_id); } } forward(create_container('skeleton.php', 'game_play.php')) ?>
<? $db2 = new SmrMySqlDatabase(); $account_id = $_REQUEST['account_id']; if (!empty($account_id)) { require_once(get_file_loc('SmrPort.class.inc')); $game_id = $var['game_id']; // delete all entries from the player_visited_sector/port table $db->query('DELETE FROM player_visited_sector WHERE account_id = '.$account_id.' AND game_id = '.$game_id); $db->query('DELETE FROM player_visited_port WHERE account_id = '.$account_id.' AND game_id = '.$game_id); // add port infos $db->query('SELECT sector_id FROM port WHERE game_id = '.$game_id.' ORDER BY sector_id'); while ($db->nextRecord()) { SmrPort::getPort($game_id,$db->getField('sector_id'))->cachePort($account_id); } } forward(create_container('skeleton.php', 'game_play.php')) ?>
Remove https restriction from cookie setter.
var crypto = require('crypto'); var _ = require('underscore'); function TokenContainer() { this._tokens = {}; this._startGarbageCollecting(); } TokenContainer._hourMs = 60 * 60 * 1000; TokenContainer._collectorIntervalMs = 12 * TokenContainer._hourMs; TokenContainer._oudatedTimeMs = 48 * TokenContainer._hourMs; TokenContainer.prototype.saveToken = function(res, token) { var cookie = crypto.randomBytes(32).toString('hex'); this._tokens[cookie] = {token: token, lastUsage: Date.now()}; res.cookies.set('userid', cookie, {path: '/'}); }; TokenContainer.prototype.hasToken = function(tokenKey) { var info = this._tokens[tokenKey]; if (info) { info.lastUsage = Date.now(); } return !!info; }; TokenContainer.prototype.extractTokenKeyFromRequest = function(req) { return req.cookies.get('userid'); }; TokenContainer.prototype._startGarbageCollecting = function() { setInterval(function() { var now = Date.now(); _.each(this._tokens, function(info, cookie, cookies) { if (now - info.lastUsage > TokenContainer._oudatedTimeMs) { delete cookies[cookie]; } }); }.bind(this), TokenContainer._collectorIntervalMs); }; module.exports = TokenContainer;
var crypto = require('crypto'); var _ = require('underscore'); function TokenContainer() { this._tokens = {}; this._startGarbageCollecting(); } TokenContainer._hourMs = 60 * 60 * 1000; TokenContainer._collectorIntervalMs = 12 * TokenContainer._hourMs; TokenContainer._oudatedTimeMs = 48 * TokenContainer._hourMs; TokenContainer.prototype.saveToken = function(res, token) { var cookie = crypto.randomBytes(32).toString('hex'); this._tokens[cookie] = {token: token, lastUsage: Date.now()}; res.cookies.set('userid', cookie, {path: '/', secure: true, httpOnly: false}); }; TokenContainer.prototype.hasToken = function(tokenKey) { var info = this._tokens[tokenKey]; if (info) { info.lastUsage = Date.now(); } return !!info; }; TokenContainer.prototype.extractTokenKeyFromRequest = function(req) { return req.cookies.get('userid'); }; TokenContainer.prototype._startGarbageCollecting = function() { setInterval(function() { var now = Date.now(); _.each(this._tokens, function(info, cookie, cookies) { if (now - info.lastUsage > TokenContainer._oudatedTimeMs) { delete cookies[cookie]; } }); }.bind(this), TokenContainer._collectorIntervalMs); }; module.exports = TokenContainer;
Tweak the way namespaces are defined to fix strange instanceof error
/** * Event subscription for Microcosm */ function Diode (app) { var callbacks = [] if (this instanceof Diode) { app = this } else if (arguments.length == 0){ return new Diode() } /** * Given a CALLBACK function, add it to the Set of all callbacks. */ app.listen = app.subscribe = function (callback, scope) { callbacks.push({ callback: callback, scope: scope || app }) return app } /** * Given a CALLBACK function, remove it from the set of callbacks. * Throws an error if the callback is not included in the set. */ app.ignore = app.unsubscribe = function (unwanted) { callbacks = callbacks.filter(function(entry) { return entry.callback !== unwanted }) return app } /** * Immediately trigger every callback */ app.emit = app.publish = function () { for (var i = 0; i < callbacks.length; i++) { callbacks[i].callback.apply(callbacks[i].scope, arguments) } return app } return app } export default Diode(Diode)
/** * Event subscription for Microcosm */ var Diode = function (app) { var callbacks = [] if (this instanceof Diode) { app = this } else if (arguments.length == 0){ return new Diode() } /** * Given a CALLBACK function, add it to the Set of all callbacks. */ app.listen = app.subscribe = function (callback, scope) { callbacks.push({ callback: callback, scope: scope || app }) return app } /** * Given a CALLBACK function, remove it from the set of callbacks. * Throws an error if the callback is not included in the set. */ app.ignore = app.unsubscribe = function (unwanted) { callbacks = callbacks.filter(function(entry) { return entry.callback !== unwanted }) return app } /** * Immediately trigger every callback */ app.emit = app.publish = function () { for (var i = 0; i < callbacks.length; i++) { callbacks[i].callback.apply(callbacks[i].scope, arguments) } return app } return app } export default Diode(Diode)
Fix timestamp comparison on ciresources
import MySQLdb from datetime import datetime, timedelta db = MySQLdb.connect(host="10.0.196.2", user="ciuser", passwd="secret", db="ciresources") cur = db.cursor() f = '%Y-%m-%d %H:%M:%S' three_hours_ago_dt = datetime.utcnow() - timedelta(hours=3) three_hours_ago = three_hours_ago_dt.strftime(f) cur.execute("SELECT * FROM vlans WHERE locked!=true OR timestamp<'%s' LIMIT 1 FOR UPDATE" % three_hours_ago) row = cur.fetchone() if row is not None: min_vlan = row[0] max_vlan = row[1] vlans = {"min_vlan": min_vlan, "max_vlan":max_vlan, "timestamp": datetime.now().strftime(f)} cur.execute("UPDATE vlans SET locked=true, timestamp='%(timestamp)s' where min_vlan=%(min_vlan)s AND max_vlan=%(max_vlan)s" % vlans) else: raise Exception("No free VLANs found!") db.commit() db.close() print("%(min_vlan)s:%(max_vlan)s" % vlans)
import MySQLdb from datetime import datetime, timedelta db = MySQLdb.connect(host="10.0.196.2", user="ciuser", passwd="secret", db="ciresources") cur = db.cursor() f = '%Y-%m-%d %H:%M:%S' three_hours_ago_dt = datetime.utcnow() - timedelta(hours=3) three_hours_ago = three_hours_ago_dt.strftime(f) cur.execute("SELECT * FROM vlans WHERE locked!=true OR timestamp > '%s' LIMIT 1 FOR UPDATE" % three_hours_ago) row = cur.fetchone() if row is not None: min_vlan = row[0] max_vlan = row[1] vlans = {"min_vlan": min_vlan, "max_vlan":max_vlan, "timestamp": datetime.now().strftime(f)} cur.execute("UPDATE vlans SET locked=true, timestamp='%(timestamp)s' where min_vlan=%(min_vlan)s AND max_vlan=%(max_vlan)s" % vlans) else: raise Exception("No free VLANs found!") db.commit() db.close() print("%(min_vlan)s:%(max_vlan)s" % vlans)
Make MHRunnableImpl abstract to force subclassing ... don't want to encourage direct instantiation... at least not until the pattern emerges clearly and we can see a reason to do so.
package com.digistratum.microhost; import com.digistratum.microhost.Process.MHRunnable; /** * @TODO Add support for receiving, starting, and monitoring multiple MHRunnable's */ abstract public class MicroHostApp { /** * Constructor * * This should be called from the application main() with an instance of the RestApi; we will * put the RestApi into its own thread and let it run while we monitor. This gives us the * ability to potentially spawn more threads and/or perform additional work as needed while the * RestApi service does its job. * * @param mHRunnable RestApi RestApi instance */ public MicroHostApp(MHRunnable mHRunnable) { // Start and monitor... Thread t = new Thread(mHRunnable, "MHRunnable Instance"); t.start(); while (mHRunnable.isRunning()) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); } } } }
package com.digistratum.microhost; import com.digistratum.microhost.Process.MHRunnable; /** * @TODO Add support for receiving, starting, and monitoring multiple MHRunnable's */ public class MicroHostApp { /** * Constructor * * This should be called from the application main() with an instance of the RestApi; we will * put the RestApi into its own thread and let it run while we monitor. This gives us the * ability to potentially spawn more threads and/or perform additional work as needed while the * RestApi service does its job. * * @param mHRunnable RestApi RestApi instance */ public MicroHostApp(MHRunnable mHRunnable) { // Start and monitor... Thread t = new Thread(mHRunnable, "MHRunnable Instance"); t.start(); while (mHRunnable.isRunning()) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); } } } }
Add missing call to txn_load()
<? include '../scat.php'; include '../lib/txn.php'; $id= (int)$_REQUEST['txn']; if (!$id) die_jsonp("no transaction specified."); $txn= txn_load($db, $id); if ($txn['paid']) { die_jsonp("This order is already paid!"); } $q= "UPDATE txn_line SET allocated = ordered WHERE txn = $id"; $r= $db->query($q) or die_jsonp($db->error); $lines= $r->num_rows; $q= "UPDATE txn SET filled = NOW() WHERE id = $id"; $r= $db->query($q) or die_jsonp($db->error); $txn= txn_load($db, $id); generate_jsonp(array("success" => "Allocated all lines.", "txn" => $txn, "lines" => $r->num_rows));
<? include '../scat.php'; include '../lib/txn.php'; $id= (int)$_REQUEST['txn']; if (!$id) die_jsonp("no transaction specified."); if ($txn['paid']) { die_jsonp("This order is already paid!"); } $q= "UPDATE txn_line SET allocated = ordered WHERE txn = $id"; $r= $db->query($q) or die_jsonp($db->error); $lines= $r->num_rows; $q= "UPDATE txn SET filled = NOW() WHERE id = $id"; $r= $db->query($q) or die_jsonp($db->error); $txn= txn_load($db, $id); generate_jsonp(array("success" => "Allocated all lines.", "txn" => $txn, "lines" => $r->num_rows));
Reduce the number of processes used.
import datetime import multiprocessing from django.conf import settings from django.core.management.base import BaseCommand, CommandError from core.models import WebPage, PageScrapeResult from core.views import scrape_url class Command(BaseCommand): help = "Poll all the urls and scrape the results" can_import_settings = True def handle(self, *args, **options): pool = multiprocessing.Pool(multiprocessing.cpu_count()) today = int(datetime.date.today().strftime("%s")) now = datetime.datetime.now() curr_time = float(int(now.strftime("%s")) - now.second) mins_passed = curr_time - today for page in WebPage.objects.all(): if mins_passed % page.interval == 0 or settings.DEBUG: pool.apply_async(scrape_url, (page, )) pool.close() pool.join()
import datetime import multiprocessing from django.conf import settings from django.core.management.base import BaseCommand, CommandError from core.models import WebPage, PageScrapeResult from core.views import scrape_url class Command(BaseCommand): help = "Poll all the urls and scrape the results" can_import_settings = True def handle(self, *args, **options): pool = multiprocessing.Pool(multiprocessing.cpu_count() + 2) today = int(datetime.date.today().strftime("%s")) now = datetime.datetime.now() curr_time = float(int(now.strftime("%s")) - now.second) mins_passed = curr_time - today for page in WebPage.objects.all(): if mins_passed % page.interval == 0 or settings.DEBUG: pool.apply_async(scrape_url, (page, )) pool.close() pool.join()
Fix syntax warning in `smart_open` Fixes #20
import sys import contextlib @contextlib.contextmanager def smart_open(filename, mode="Ur"): """Open stdin or stdout using a contextmanager From: http://stackoverflow.com/a/29824059/2043465 Args: filename (str): name of file to open. Can be '-' for stdin/stdout mode (str): usual mode string for :py:func:`open` """ if filename == "-": if mode is None or mode == "" or "r" in mode: fh = sys.stdin else: fh = sys.stdout else: fh = open(filename, mode) try: yield fh finally: if filename != "-": fh.close()
import sys import contextlib @contextlib.contextmanager def smart_open(filename, mode="Ur"): """Open stdin or stdout using a contextmanager From: http://stackoverflow.com/a/29824059/2043465 Args: filename (str): name of file to open. Can be '-' for stdin/stdout mode (str): usual mode string for :py:func:`open` """ if filename == "-": if mode is None or mode == "" or "r" in mode: fh = sys.stdin else: fh = sys.stdout else: fh = open(filename, mode) try: yield fh finally: if filename is not "-": fh.close()
Fix typo in cob migrate down
import click import logbook from .utils import appcontext_command from ..ctx import context import flask_migrate _logger = logbook.Logger(__name__) @click.group() def migrate(): pass @migrate.command() @appcontext_command def init(): flask_migrate.init('migrations', False) @migrate.command() @click.option('-m', '--message', default=None) @appcontext_command def revision(message): if not context.db.metadata.tables: _logger.warning('No tables loaded!') flask_migrate.upgrade() flask_migrate.revision(autogenerate=True, message=message) @migrate.command() @appcontext_command def up(): flask_migrate.upgrade() @migrate.command() @appcontext_command def down(): flask_migrate.downgrade()
import click import logbook from .utils import appcontext_command from ..ctx import context import flask_migrate _logger = logbook.Logger(__name__) @click.group() def migrate(): pass @migrate.command() @appcontext_command def init(): flask_migrate.init('migrations', False) @migrate.command() @click.option('-m', '--message', default=None) @appcontext_command def revision(message): if not context.db.metadata.tables: _logger.warning('No tables loaded!') flask_migrate.upgrade() flask_migrate.revision(autogenerate=True, message=message) @migrate.command() @appcontext_command def up(): flask_migrate.upgrade() @migrate.command() @appcontext_command def down(): flask_migrate.upgrade()
Correct the details being given to conversion events
'use strict'; // Load requirements const engine = require('../engine'); // Configures and runs the conversion task module.exports = { run: function(job) { return new Promise((resolve, reject) => { // Check we got a file at all if ( ! job ) { return reject('No job data provided'); } // Configure the conversion engine command let command = engine.config(job.file, job.options, job.meta, (err) => { return reject(err); }); // Bind events ['start', 'filenames', 'progress', 'error', 'end'].forEach((e) => { return command.on(e, () => { // Format arguments to include details and metadata let args = Array.prototype.slice.call(arguments); args.push(job, job.meta); // Call event callback with args this['on' + e].apply(this, args); }); }); // Start processing the job return command.run(); }); }, onstart: require('./events/start'), onfilenames: require('./events/filenames'), onprogress: require('./events/progress'), onerror: require('./events/error'), onend: require('./events/end') };
'use strict'; // Load requirements const engine = require('../engine'); // Configures and runs the conversion task module.exports = { run: function(job) { return new Promise((resolve, reject) => { // Check we got a file at all if ( ! job ) { return reject('No job data provided'); } // Configure the conversion engine command let command = engine.config(job.file, job.options, job.meta, (err) => { return reject(err); }); // Bind events ['start', 'filenames', 'progress', 'error', 'end'].forEach((e) => { return command.on(e, () => { // Format arguments to include details and metadata let args = Array.prototype.slice.call(arguments); args.push(details, metadata); // Call event callback with args this['on' + e].apply(this, args); }); }); // Start processing the job return command.run(); }); }, onstart: require('./events/start'), onfilenames: require('./events/filenames'), onprogress: require('./events/progress'), onerror: require('./events/error'), onend: require('./events/end') };
Implement primitive ls-remote over git proxy.
console.log("Connecting to git repo through proxy..."); connect("tls", "github.com", "443", function (write) { console.log("Connected to remote. Sending HTTP request..."); var path = "/creationix/conquest.git/info/refs?service=git-upload-pack"; write("GET " + path + " HTTP/1.1\r\nHost: github.com\r\n\r\n"); }, function (buffer) { console.log(buffer); console.log(toString(buffer)); }); function connect(protocol, host, port, onconnect, onmessage) { var socket = new WebSocket("wss://tedit.creationix.com/proxy/" + protocol + "/" + host + "/" + port); socket.binaryType = "arraybuffer"; socket.onmessage = function (evt) { if (evt.data === "connect") { return onconnect(write); } if (typeof evt.data === "string") { console.log(evt.data); } else { onmessage(new Uint8Array(evt.data)); } }; function write(data) { return socket.send(data); } return write; } function toString(buffer) { var str = ""; for (var i = 0, l = buffer.length; i < l; i++) { str += String.fromCharCode(buffer[i]); } // Decode UTF8 return decodeURIComponent(escape(str)); }
console.log("Connecting to https://luvit.io through proxy..."); connect("tls", "luvit.io", "443", function (write) { console.log("Connected to remote. Sending HTTP request..."); write("GET / HTTP/1.1\r\nHost: luvit.io\r\n\r\n"); }, function (buffer) { console.log(buffer); console.log(toString(buffer)); }); function connect(protocol, host, port, onconnect, onmessage) { var socket = new WebSocket("wss://tedit.creationix.com/proxy/" + protocol + "/" + host + "/" + port); socket.binaryType = "arraybuffer"; socket.onmessage = function (evt) { if (evt.data === "connect") { return onconnect(write); } if (typeof evt.data === "string") { console.log(evt.data); } else { onmessage(new Uint8Array(evt.data)); } }; function write(data) { return socket.send(data); } return write; } function toString(buffer) { var str = ""; for (var i = 0, l = buffer.length; i < l; i++) { str += String.fromCharCode(buffer[i]); } // Decode UTF8 return decodeURIComponent(escape(str)); }
Order weekday columns in watchlist
from .models import ShiftSlot, weekday_loc from website.settings import WORKSHOP_OPEN_DAYS def get_shift_weekview_rows(): '''Returns a dictionary of shifts for each timeslot, for each weekday''' slots = ShiftSlot.objects.all() if not slots: return None # Could be troublesome wrt. sorting of dictionary keys. Doesn't *seem* to be an issue right now but it *technically* already is! rows = {} for slot in slots: row_header = '{} -\n{}'.format(slot.start.strftime('%H:%M'), slot.end.strftime('%H:%M')) if row_header not in rows: rows[row_header] = [] rows[row_header].append(slot) # Sort each list in the dict by weekday for time in rows.keys(): rows[time].sort(key=lambda slot: slot.weekday) return rows def get_shift_weekview_columns(): '''Returns a list of weekday name column headers to populate a weekview table with''' slots = ShiftSlot.objects.all().order_by('weekday') if not slots: return None cols = [] for slot in slots: col_header = slot.get_weekday_name() if col_header not in cols: cols.append(col_header) return cols
from .models import ShiftSlot, weekday_loc from website.settings import WORKSHOP_OPEN_DAYS def get_shift_weekview_rows(): '''Returns a dictionary of shifts for each timeslot, for each weekday''' slots = ShiftSlot.objects.all() if not slots: return None # Could be troublesome wrt. sorting of dictionary keys. Doesn't *seem* to be an issue right now but it *technically* already is! rows = {} for slot in slots: row_header = '{} -\n{}'.format(slot.start.strftime('%H:%M'), slot.end.strftime('%H:%M')) if row_header not in rows: rows[row_header] = [] rows[row_header].append(slot) # Sort each list in the dict by weekday for time in rows.keys(): rows[time].sort(key=lambda slot: slot.weekday) return rows def get_shift_weekview_columns(): '''Returns a list of weekday name column headers to populate a weekview table with''' slots = ShiftSlot.objects.all() if not slots: return None cols = [] for slot in slots: col_header = slot.get_weekday_name() if col_header not in cols: cols.append(col_header) return cols
Remove zopen in pymatgen root. Former-commit-id: 375be0147716d3b4d2dee95680eae4ee3804716b [formerly 05648421c1fa77f6f339f68be2c43bb7952e918a] Former-commit-id: e5cfaf0277815951ddb09d9d6b30876e400870d7
__author__ = ", ".join(["Shyue Ping Ong", "Anubhav Jain", "Geoffroy Hautier", "William Davidson Richard", "Stephen Dacek", "Sai Jayaraman", "Michael Kocher", "Dan Gunter", "Shreyas Cholia", "Vincent L Chevrier", "Rickard Armiento"]) __date__ = "Dec 18 2013" __version__ = "2.8.10" #Useful aliases for commonly used objects and modules. from .core import * from .serializers.json_coders import PMGJSONEncoder, PMGJSONDecoder, \ pmg_dump, pmg_load from .electronic_structure.core import Spin, Orbital from .io.smartio import read_structure, write_structure, read_mol, write_mol from .matproj.rest import MPRester
__author__ = ", ".join(["Shyue Ping Ong", "Anubhav Jain", "Geoffroy Hautier", "William Davidson Richard", "Stephen Dacek", "Sai Jayaraman", "Michael Kocher", "Dan Gunter", "Shreyas Cholia", "Vincent L Chevrier", "Rickard Armiento"]) __date__ = "Dec 18 2013" __version__ = "2.8.10" #Useful aliases for commonly used objects and modules. from .core import * from .serializers.json_coders import PMGJSONEncoder, PMGJSONDecoder, \ pmg_dump, pmg_load from .electronic_structure.core import Spin, Orbital from .util.io_utils import zopen from .io.smartio import read_structure, write_structure, read_mol, write_mol from .matproj.rest import MPRester
Duplicate block instance if we should copy it instead of aliasing from master collection
<?php namespace Concrete\Core\Block\Command; use Concrete\Core\Block\Block; use Concrete\Core\Block\Command\DeleteBlockCommand; use Concrete\Core\Page\Page; class AddAliasDefaultsBlockCommandHandler { public function __invoke(AddAliasDefaultsBlockCommand $command) { $page = Page::getByID($command->getPageID(), $command->getCollectionVersionID()); if ($page && !$page->isError()) { $mc = Page::getByID($command->getOriginalPageID(), $command->getOriginalCollectionVersionID()); if ($mc && !$mc->isError()) { $b = Block::getByID($command->getOriginalBlockID(), $mc, $command->getOriginalAreaHandle()); if ($b) { $bt = $b->getBlockTypeObject(); if ($bt->isCopiedWhenPropagated()) { $b->duplicate($page, true); } else { $b->alias($page); } } } } } }
<?php namespace Concrete\Core\Block\Command; use Concrete\Core\Block\Block; use Concrete\Core\Block\Command\DeleteBlockCommand; use Concrete\Core\Page\Page; class AddAliasDefaultsBlockCommandHandler { public function __invoke(AddAliasDefaultsBlockCommand $command) { $page = Page::getByID($command->getPageID(), $command->getCollectionVersionID()); if ($page && !$page->isError()) { $mc = Page::getByID($command->getOriginalPageID(), $command->getOriginalCollectionVersionID()); if ($mc && !$mc->isError()) { $b = Block::getByID($command->getOriginalBlockID(), $mc, $command->getOriginalAreaHandle()); if ($b) { $b->alias($page); } } } } }
Delete e Put no POO - User
const userRouter = function(app){ const _ = require('lodash'); var User = require('../model/user'); var UserList = require('../model/repository.users'); var repository = new UserList(); app.get('/user',function (req,res){ res.json(repository.GetList()); }); app.post('/user',function(req,res){ var user = new User(Number(req.body.id),req.body.nome,req.body.dataNasc,req.body.empresa,req.body.email,req.body.cadastrado); res.json(repository.Insert(user)); }); app.delete('/user/:id',function(req,res){ res.json(repository.Delete(Number(req.params.id))); }); app.put('/user/:id', function(req,res){ var user = new User(Number(req.body.id),req.body.nome,req.body.dataNasc,req.body.empresa,req.body.email,req.body.cadastrado); res.json(repository.Update(user)); }); } module.exports = userRouter;
const userRouter = function(app){ const _ = require('lodash'); var User = require('../model/user'); var UserList = require('../model/repository.users'); var repository = new UserList(); app.get('/user',function (req,res){ res.json(repository.GetList()); }); app.post('/user',function(req,res){ var user = new User(Number(req.body.id),req.body.nome,req.body.dataNasc,req.body.empresa,req.body.email,req.body.cadastrado); res.json(repository.Insert(user)); }); app.delete('/user/:id',function(req,res){ _.remove(users,['id', Number(req.params.id)]); res.json(users); }); app.put('/user/:id', function(req,res){ var i = _.findIndex(users, function(user) { return user.id === Number(req.params.id); }); users[i] = req.body; res.json(users); }); } module.exports = userRouter;
Fix 'u' to jump to user's preferred change screen Honor the user preference and jump to the preferred screen type when going up from an old style PatchScreen. The old style is still used for unified diffs of binary files. Change-Id: I92c4f95ef4a0e5e9de5196f614af62474ef96c05
// Copyright (C) 2010 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.client.patches; import com.google.gerrit.client.Gerrit; import com.google.gerrit.common.PageLinks; import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwtexpui.globalkey.client.KeyCommand; class UpToChangeCommand extends KeyCommand { private final PatchSet.Id patchSetId; UpToChangeCommand(PatchSet.Id patchSetId, int mask, int key) { super(mask, key, PatchUtil.C.upToChange()); this.patchSetId = patchSetId; } @Override public void onKeyPress(final KeyPressEvent event) { Gerrit.display(PageLinks.toChange(patchSetId)); } }
// Copyright (C) 2010 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.client.patches; import com.google.gerrit.client.Gerrit; import com.google.gerrit.client.changes.ChangeScreen; import com.google.gerrit.common.PageLinks; import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwtexpui.globalkey.client.KeyCommand; class UpToChangeCommand extends KeyCommand { private final PatchSet.Id patchSetId; UpToChangeCommand(PatchSet.Id patchSetId, int mask, int key) { super(mask, key, PatchUtil.C.upToChange()); this.patchSetId = patchSetId; } @Override public void onKeyPress(final KeyPressEvent event) { Gerrit.display(PageLinks.toChange(patchSetId), new ChangeScreen(patchSetId)); } }
Add default (7) on limit field queryset model boxes
#!/usr/bin/env python # -*- coding: utf-8 -*- #from django.conf import settings #from django.utils.importlib import import_module from django.db import models from django.utils.translation import ugettext_lazy as _ from opps.core.models import Publishable, BaseBox try: OPPS_APPS = tuple([(u"{0}.{1}".format( app._meta.app_label, app._meta.object_name), u"{0} - {1}".format( app._meta.app_label, app._meta.object_name)) for app in models.get_models() if 'opps.' in app.__module__]) except ImportError: OPPS_APPS = tuple([]) class QuerySet(Publishable): name = models.CharField(_(u"Dynamic queryset name"), max_length=140) slug = models.SlugField( _(u"Slug"), db_index=True, max_length=150, unique=True, ) model = models.CharField(_(u'Model'), max_length=150, choices=OPPS_APPS) limit = models.PositiveIntegerField(_(u'Limit'), default=7) order = models.CharField(_('Order'), max_length=1, choices=( ('-', 'DESC'), ('+', 'ASC'))) class DynamicBox(BaseBox): dynamicqueryset = models.ForeignKey( 'boxes.QuerySet', verbose_name=_(u'Query Set') )
#!/usr/bin/env python # -*- coding: utf-8 -*- #from django.conf import settings #from django.utils.importlib import import_module from django.db import models from django.utils.translation import ugettext_lazy as _ from opps.core.models import Publishable, BaseBox try: OPPS_APPS = tuple([(u"{0}.{1}".format( app._meta.app_label, app._meta.object_name), u"{0} - {1}".format( app._meta.app_label, app._meta.object_name)) for app in models.get_models() if 'opps.' in app.__module__]) except ImportError: OPPS_APPS = tuple([]) class QuerySet(Publishable): name = models.CharField(_(u"Dynamic queryset name"), max_length=140) slug = models.SlugField( _(u"Slug"), db_index=True, max_length=150, unique=True, ) model = models.CharField(_(u'Model'), max_length=150, choices=OPPS_APPS) limit = models.PositiveIntegerField(_(u'Limit')) order = models.CharField(_('Order'), max_length=1, choices=( ('-', 'DESC'), ('+', 'ASC'))) class DynamicBox(BaseBox): dynamicqueryset = models.ForeignKey( 'boxes.QuerySet', verbose_name=_(u'Query Set') )
Add imu routes and store db reference on app
let express = require('express'), bodyParser = require('body-parser'), morgan = require('morgan'), mustacheExpress = require('mustache-express'), path = require('path'), db = require('./lib/db'); // load configuration let config = { "mongo": { "host": "192.168.0.128", "port": 27017, "db": "g2x" } } // create app var app = express(); // app configuration app.set('port', (process.env.PORT || 8081)); // configure template engine app.engine('mustache', mustacheExpress()); app.set('view engine', 'mustache'); app.set('views', path.join(__dirname, 'views')); // configure middleware app.use(morgan('dev')); app.use(express.static('public')); // configure routes require('./routes/static')(app); require('./routes/imu')(app); // start server var server = app.listen(app.get('port'), function() { var port = server.address().port; console.log("Server listening on port %s", port); db(config.mongo, (err, db) => { if (err) { console.error(err); process.exit(1); } app.set('db', db); console.log("Connected to mongo server:", config.mongo); }); });
let express = require('express'), bodyParser = require('body-parser'), morgan = require('morgan'), mustacheExpress = require('mustache-express'), path = require('path'), db = require('./lib/db'); // load configuration let config = { "mongo": { "host": "192.168.0.128", "port": 27017, "db": "g2x" } } // create app var app = express(); // app configuration app.set('port', (process.env.PORT || 8081)); app.set('db', db); // configure template engine app.engine('mustache', mustacheExpress()); app.set('view engine', 'mustache'); app.set('views', path.join(__dirname, 'views')); // configure middleware app.use(morgan('dev')); app.use(express.static('public')); // configure routes require('./routes/static')(app); // start server var server = app.listen(app.get('port'), function() { var port = server.address().port; console.log("Server listening on port %s", port); db(config.mongo, (err, db) => { if (err) { console.error(err); process.exit(1); } console.log("Connected to mongo server:", config.mongo); }); });
Fix HMR for sync reducers
/** * Create the store with asynchronously loaded reducers */ import { createStore, applyMiddleware, compose } from 'redux'; import { fromJS } from 'immutable'; import { routerMiddleware } from 'react-router-redux'; import createSagaMiddleware from 'redux-saga'; import createReducer from './reducers'; const sagaMiddleware = createSagaMiddleware(); const devtools = window.devToolsExtension || (() => noop => noop); export default function configureStore(initialState = {}, history) { // Create the store with two middlewares // 1. sagaMiddleware: Makes redux-sagas work // 2. routerMiddleware: Syncs the location/URL path to the state const middlewares = [ sagaMiddleware, routerMiddleware(history), ]; const enhancers = [ applyMiddleware(...middlewares), devtools(), ]; const store = createStore( createReducer(), fromJS(initialState), compose(...enhancers) ); // Extensions store.runSaga = sagaMiddleware.run; store.asyncReducers = {}; // Async reducer registry // Make reducers hot reloadable, see http://mxs.is/googmo /* istanbul ignore next */ if (module.hot) { module.hot.accept('./reducers', () => { System.import('./reducers').then((reducerModule) => { const createReducers = reducerModule.default; const nextReducers = createReducers(store.asyncReducers); store.replaceReducer(nextReducers); }); }); } return store; }
/** * Create the store with asynchronously loaded reducers */ import { createStore, applyMiddleware, compose } from 'redux'; import { fromJS } from 'immutable'; import { routerMiddleware } from 'react-router-redux'; import createSagaMiddleware from 'redux-saga'; import createReducer from './reducers'; const sagaMiddleware = createSagaMiddleware(); const devtools = window.devToolsExtension || (() => noop => noop); export default function configureStore(initialState = {}, history) { // Create the store with two middlewares // 1. sagaMiddleware: Makes redux-sagas work // 2. routerMiddleware: Syncs the location/URL path to the state const middlewares = [ sagaMiddleware, routerMiddleware(history), ]; const enhancers = [ applyMiddleware(...middlewares), devtools(), ]; const store = createStore( createReducer(), fromJS(initialState), compose(...enhancers) ); // Extensions store.runSaga = sagaMiddleware.run; store.asyncReducers = {}; // Async reducer registry // Make reducers hot reloadable, see http://mxs.is/googmo /* istanbul ignore next */ if (module.hot) { module.hot.accept('./reducers', () => { const nextRootReducer = require('./reducers').default; // eslint-disable-line global-require store.replaceReducer(nextRootReducer); }); } return store; }
Fix version for migrations fix
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() setup( name='django-addendum', version='0.0.2', description='Simple template-based content swapping for CMS-less sites', long_description=readme, author='Ben Lopatin', author_email='ben.lopatin@wellfireinteractive.com', url='https://github.com/bennylope/django-addendum', license='BSD License', packages=find_packages(exclude=('example', 'docs')), platforms=['OS Independent'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], install_requires=[ 'Django>=1.4', ], include_package_data=True, )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() setup( name='django-addendum', version='0.0.1', description='Simple template-based content swapping for CMS-less sites', long_description=readme, author='Ben Lopatin', author_email='ben.lopatin@wellfireinteractive.com', url='https://github.com/bennylope/django-addendum', license='BSD License', packages=find_packages(exclude=('example', 'docs')), platforms=['OS Independent'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], install_requires=[ 'Django>=1.4', ], include_package_data=True, )
Fix bug in wordcloud method
from __future__ import absolute_import, division, print_function, unicode_literals from collections import Counter import re def create_wordcloud( data, plt, stopwords = ["the", "a", "or", "tai", "and", "ja", "to", "on", "in", "of", "for", "is", "i", "this", "http", "www", "fi", "com"] ): import types if isinstance( data, types.GeneratorType ): data = list( data ) if len(data) == 0: print( "Dataset empty." ) return from wordcloud import WordCloud text = '' for d in data: text += d['text_content'].lower() + ' ' text = text.strip() stopwords = map( lambda w: str(w), stopwords ) wc = WordCloud( background_color="white", width=800, height=400, stopwords = stopwords ) wc.generate( text ) plt.figure(figsize=(15,10)) plt.imshow(wc, interpolation="bilinear") plt.axis("off") plt.show()
from __future__ import absolute_import, division, print_function, unicode_literals from collections import Counter import re def create_wordcloud( data, stopwords = ["the", "a", "or", "tai", "and", "ja", "to", "on", "in", "of", "for", "is", "i", "this", "http", "www", "fi", "com"] ): import types if isinstance( data, types.GeneratorType ): data = list( data ) if len(data) == 0: print( "Dataset empty." ) return from wordcloud import WordCloud text = '' for d in data: text += d['text_content'].lower() + ' ' text = text.strip() stopwords = map( lambda w: str(w), stopwords ) wc = WordCloud( background_color="white", width=800, height=400, stopwords = stopwords ) wc.generate( text ) plt.figure(figsize=(15,10)) plt.imshow(wc, interpolation="bilinear") plt.axis("off") plt.show()
Disable RRD queue feature when testing so files are actually written when we write to them. :-)
package org.opennms.netmgt.dao.support; import java.io.ByteArrayInputStream; import java.io.IOException; import org.opennms.netmgt.rrd.RrdConfig; import org.opennms.netmgt.rrd.RrdException; import org.opennms.netmgt.rrd.RrdUtils; import org.opennms.netmgt.rrd.jrobin.JRobinRrdStrategy; public class RrdTestUtils { // Reference the class name this way so that it is refactoring resistant private static final String RRD_CONFIG = "org.opennms.rrd.strategyClass=" + JRobinRrdStrategy.class.getName() + "\norg.opennms.rrd.usequeue=false"; /** * This class cannot be instantiated. Use static methods. */ private RrdTestUtils() { } public static void initialize() throws IOException, RrdException { RrdConfig.loadProperties(new ByteArrayInputStream(RRD_CONFIG.getBytes())); RrdUtils.initialize(); } }
package org.opennms.netmgt.dao.support; import java.io.ByteArrayInputStream; import java.io.IOException; import org.opennms.netmgt.rrd.RrdConfig; import org.opennms.netmgt.rrd.RrdException; import org.opennms.netmgt.rrd.RrdUtils; import org.opennms.netmgt.rrd.jrobin.JRobinRrdStrategy; public class RrdTestUtils { // Reference the class name this way so that it is refactoring resistant private static final String RRD_CONFIG = "org.opennms.rrd.strategyClass=" + JRobinRrdStrategy.class.getName(); /** * This class cannot be instantiated. Use static methods. */ private RrdTestUtils() { } public static void initialize() throws IOException, RrdException { RrdConfig.loadProperties(new ByteArrayInputStream(RRD_CONFIG.getBytes())); RrdUtils.initialize(); } }
BAP-11419: Implement Download (Export) functionality - Fixed missed typehint
<?php namespace Oro\Bundle\TranslationBundle\Handler; use Oro\Bundle\ImportExportBundle\Handler\ExportHandler; use Oro\Bundle\TranslationBundle\Entity\Language; class TranslationExportHandler extends ExportHandler { /** * @var Language */ protected $language; /** * {@inheritdoc} */ protected function generateExportFileName($prefix, $extension) { if (($this->language instanceof Language) && ($this->language->getCode())) { return parent::generateExportFileName('translations--' . $this->language->getCode() . '--', $extension); } return parent::generateExportFileName($prefix, $extension); } /** * @param Language $language * * @return $this */ public function setLanguage(Language $language) { $this->language = $language; return $this; } }
<?php namespace Oro\Bundle\TranslationBundle\Handler; use Oro\Bundle\ImportExportBundle\Handler\ExportHandler; use Oro\Bundle\TranslationBundle\Entity\Language; class TranslationExportHandler extends ExportHandler { protected $language; /** * {@inheritdoc} */ protected function generateExportFileName($prefix, $extension) { if (($this->language instanceof Language) && ($this->language->getCode())) { return parent::generateExportFileName('translations--' . $this->language->getCode() . '--', $extension); } return parent::generateExportFileName($prefix, $extension); } /** * @param Language $language * * @return $this */ public function setLanguage(Language $language) { $this->language = $language; return $this; } }
Use the correct test to see if explode returned no results
<?php namespace Backend\Modules\MediaLibrary\Ajax; use Backend\Core\Engine\Base\AjaxAction as BackendBaseAJAXAction; use Symfony\Component\HttpFoundation\Response; /** * This AJAX-action will get all media items for a group, * which was trying to be saved, but another parent error appeared. */ class MediaItemGetAllById extends BackendBaseAJAXAction { public function execute(): void { parent::execute(); // Output success message with variables $this->output( Response::HTTP_OK, [ 'items' => $this->getMediaItems(), ] ); } protected function getMediaItems(): array { /** @var array $ids */ $ids = explode(',', $this->getRequest()->request->get('media_ids')); // We have no ids if (empty($ids)) { return []; } return $this->get('media_library.repository.item')->findById($ids); } }
<?php namespace Backend\Modules\MediaLibrary\Ajax; use Backend\Core\Engine\Base\AjaxAction as BackendBaseAJAXAction; use Symfony\Component\HttpFoundation\Response; /** * This AJAX-action will get all media items for a group, * which was trying to be saved, but another parent error appeared. */ class MediaItemGetAllById extends BackendBaseAJAXAction { public function execute(): void { parent::execute(); // Output success message with variables $this->output( Response::HTTP_OK, [ 'items' => $this->getMediaItems(), ] ); } protected function getMediaItems(): array { /** @var array $ids */ $ids = explode(',', $this->getRequest()->request->get('media_ids')); // We have no ids if ($ids === null) { return []; } return $this->get('media_library.repository.item')->findById($ids); } }
Rewrite test to match new coding standards
<?php namespace net\xp_framework\unittest\security; use security\password\PasswordStrength; /** * TestCase for PasswordStrength entry point class * * @see xp://security.password.PasswordStrength */ class PasswordStrengthTest extends \unittest\TestCase { #[@test] public function standard_algorithm_is_always_available() { $this->assertInstanceOf( 'security.password.StandardAlgorithm', PasswordStrength::getAlgorithm('standard') ); } #[@test] public function register_algorithm() { with ($class= newinstance('security.password.Algorithm', array(), '{ public function strengthOf($password) { return 0; } }')->getClass()); { PasswordStrength::setAlgorithm('null', $class); $this->assertEquals($class, PasswordStrength::getAlgorithm('null')->getClass()); } } #[@test, @expect('util.NoSuchElementException')] public function getAlgorithm_throws_an_exception_for_non_existant_algorithm() { PasswordStrength::getAlgorithm('@@NON_EXISTANT@@'); } #[@test, @expect('lang.IllegalArgumentException')] public function setAlgorithm_throws_an_exception_for_non_algorithms() { PasswordStrength::setAlgorithm('object', $this->getClass()); } }
<?php namespace net\xp_framework\unittest\security; use unittest\TestCase; use security\password\PasswordStrength; /** * TestCase for PasswordStrength entry point class * * @see xp://security.password.PasswordStrength * @purpose Unittest */ class PasswordStrengthTest extends TestCase { /** * Test standard algortihm is always available * */ #[@test] public function standardAlgorithm() { $this->assertClass( PasswordStrength::getAlgorithm('standard'), 'security.password.StandardAlgorithm' ); } /** * Test setAlgorithm() / getAlgorithm() roundtrip * */ #[@test] public function registerAlgorithm() { with ($class= newinstance('security.password.Algorithm', array(), '{ public function strengthOf($password) { return 0; } }')->getClass()); { PasswordStrength::setAlgorithm('null', $class); $this->assertEquals($class, PasswordStrength::getAlgorithm('null')->getClass()); } } /** * Test getAlgorithm() throws an exception when no algorithm is * registered by the given name * */ #[@test, @expect('util.NoSuchElementException')] public function noSuchAlgorithm() { PasswordStrength::getAlgorithm('@@NON_EXISTANT@@'); } /** * Test setAlgorithm() throws an exception when the given algorithm * is not a security.password.Algorithm subclass * */ #[@test, @expect('lang.IllegalArgumentException')] public function registerNonAlgorithm() { PasswordStrength::setAlgorithm('object', $this->getClass()); } }
Change github oauth app's perms to READONLY.
/* On window resize, call updateHeight() to resize the height of the page components so that there's no global scroll for the page. */ $(window).resize(updateHeight); /* Routers */ Meteor.Router.add({ '': function () { GAnalytics.pageview(); if (Meteor.userId()) { location.href = "/chat"; } else return 'user_loggedout_content'; }, '/chat': function () { if (Meteor.userId()) { GAnalytics.pageview('/chat'); Session.set('currentPage', 'chat'); return 'chat'; } else location.href = '/'; } }); Meteor.Router.filters({ 'login_required': function (page) { if (Meteor.user()) { return page; } else { return 'user_loggedout_content'; } } }); /* Only logged in users can access the chat page */ Meteor.Router.filter('login_required', {only: ['user_dashboard', 'chat']}); Handlebars.registerHelper("isCurrentPageHome", function () { return Session.get('currentPage') === 'home'; }); Handlebars.registerHelper("isUserLoggedIn", function () { return Meteor.user(); }); Handlebars.registerHelper("isCurrentPageChat", function () { return Session.get('currentPage') === 'chat'; }); /* Configure Accounts.ui for authentication */ Accounts.ui.config({ requestPermissions: { github: ['user:email', '(no scope)'] }, passwordSignupFields: 'USERNAME_AND_EMAIL' });
/* On window resize, call updateHeight() to resize the height of the page components so that there's no global scroll for the page. */ $(window).resize(updateHeight); /* Routers */ Meteor.Router.add({ '': function () { GAnalytics.pageview(); if (Meteor.userId()) { location.href = "/chat"; } else return 'user_loggedout_content'; }, '/chat': function () { if (Meteor.userId()) { GAnalytics.pageview('/chat'); Session.set('currentPage', 'chat'); return 'chat'; } else location.href = '/'; } }); Meteor.Router.filters({ 'login_required': function (page) { if (Meteor.user()) { return page; } else { return 'user_loggedout_content'; } } }); /* Only logged in users can access the chat page */ Meteor.Router.filter('login_required', {only: ['user_dashboard', 'chat']}); Handlebars.registerHelper("isCurrentPageHome", function () { return Session.get('currentPage') === 'home'; }); Handlebars.registerHelper("isUserLoggedIn", function () { return Meteor.user(); }); Handlebars.registerHelper("isCurrentPageChat", function () { return Session.get('currentPage') === 'chat'; }); /* Configure Accounts.ui for authentication */ Accounts.ui.config({ requestPermissions: { github: ['user', 'repo'] }, passwordSignupFields: 'USERNAME_AND_EMAIL' });
Use `0.0.0.0` instead of `localhost`
#!/usr/bin/python import os virtenv = os.path.join(os.environ.get('OPENSHIFT_PYTHON_DIR', '.'), 'virtenv') virtualenv = os.path.join(virtenv, 'bin/activate_this.py') try: exec_namespace = dict(__file__=virtualenv) with open(virtualenv, 'rb') as exec_file: file_contents = exec_file.read() compiled_code = compile(file_contents, virtualenv, 'exec') exec(compiled_code, exec_namespace) except IOError: pass from main import app as application application.config['SLACK_TEAM_ID'] = os.environ['SLACK_TEAM_ID'] application.config['SLACK_API_TOKEN'] = os.environ['SLACK_API_TOKEN'] application.config['SECRET_KEY'] = os.environ['FLASK_SECRET_KEY'] # Below for testing locally only if __name__ == '__main__': from wsgiref.simple_server import make_server httpd = make_server('0.0.0.0', 8051, application) httpd.serve_forever()
#!/usr/bin/python import os virtenv = os.path.join(os.environ.get('OPENSHIFT_PYTHON_DIR', '.'), 'virtenv') virtualenv = os.path.join(virtenv, 'bin/activate_this.py') try: exec_namespace = dict(__file__=virtualenv) with open(virtualenv, 'rb') as exec_file: file_contents = exec_file.read() compiled_code = compile(file_contents, virtualenv, 'exec') exec(compiled_code, exec_namespace) except IOError: pass from main import app as application application.config['SLACK_TEAM_ID'] = os.environ['SLACK_TEAM_ID'] application.config['SLACK_API_TOKEN'] = os.environ['SLACK_API_TOKEN'] application.config['SECRET_KEY'] = os.environ['FLASK_SECRET_KEY'] # Below for testing locally only if __name__ == '__main__': from wsgiref.simple_server import make_server httpd = make_server('localhost', 8051, application) # Wait for a single request, serve it and quit. httpd.serve_forever()
Remove storageRubeusConfig.js from osfstorage init.py
#!/usr/bin/env python # encoding: utf-8 from . import routes, views, model MODELS = [ model.OsfStorageNodeSettings, model.OsfStorageFileTree, model.OsfStorageFileRecord, model.OsfStorageFileVersion, model.OsfStorageGuidFile, ] NODE_SETTINGS_MODEL = model.OsfStorageNodeSettings ROUTES = [ routes.web_routes, routes.api_routes, ] SHORT_NAME = 'osfstorage' FULL_NAME = 'OSF Storage' OWNERS = ['node'] ADDED_DEFAULT = ['node'] ADDED_MANDATORY = ['node'] VIEWS = [] CONFIGS = [] CATEGORIES = ['storage'] INCLUDE_JS = { 'widget': [], 'page': [], 'files': [], } HAS_HGRID_FILES = True GET_HGRID_DATA = views.osf_storage_root MAX_FILE_SIZE = 128
#!/usr/bin/env python # encoding: utf-8 from . import routes, views, model MODELS = [ model.OsfStorageNodeSettings, model.OsfStorageFileTree, model.OsfStorageFileRecord, model.OsfStorageFileVersion, model.OsfStorageGuidFile, ] NODE_SETTINGS_MODEL = model.OsfStorageNodeSettings ROUTES = [ routes.web_routes, routes.api_routes, ] SHORT_NAME = 'osfstorage' FULL_NAME = 'OSF Storage' OWNERS = ['node'] ADDED_DEFAULT = ['node'] ADDED_MANDATORY = ['node'] VIEWS = [] CONFIGS = [] CATEGORIES = ['storage'] INCLUDE_JS = { 'widget': [], 'page': [], 'files': ['storageRubeusConfig.js'], } HAS_HGRID_FILES = True GET_HGRID_DATA = views.osf_storage_root MAX_FILE_SIZE = 128
Set file.path as the error object's .fileName The default error message generated when there's a syntax error in a JSX file doesn't include the source file name, only the line number the error was found on. Adding a filePath property to the error object exposes this information for use in error handlers.
'use strict'; var gutil = require('gulp-util'); var through = require('through2'); var react = require('react-tools'); module.exports = function (name) { 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(); } try { file.contents = new Buffer(react.transform(file.contents.toString())); file.path = gutil.replaceExtension(file.path, '.js'); } catch (err) { err.fileName = file.path; this.emit('error', new gutil.PluginError('gulp-react', err)); } this.push(file); cb(); }); };
'use strict'; var gutil = require('gulp-util'); var through = require('through2'); var react = require('react-tools'); module.exports = function (name) { 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(); } try { file.contents = new Buffer(react.transform(file.contents.toString())); file.path = gutil.replaceExtension(file.path, '.js'); } catch (err) { this.emit('error', new gutil.PluginError('gulp-react', err)); } this.push(file); cb(); }); };
Remove sys.path hacking from test
import sys import os import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t))
import sys import os d = os.path.dirname(__file__) sys.path.append(os.path.join(d, '../')) import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t))
Remove unnecessary Handler in splash
package com.github.charmasaur.alpsinsects.ui; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.github.charmasaur.alpsinsects.R; import com.github.charmasaur.alpsinsects.db.FieldGuideDatabase; public final class SplashActivity extends AppCompatActivity { private static final String TAG = SplashActivity.class.getSimpleName(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the database on a background thread. new Thread(new Runnable() { public void run() { Log.i(TAG, "Opening database."); FieldGuideDatabase.getInstance(getApplicationContext()).open(); Log.i(TAG, "Database opened, starting main activity."); Intent intent = new Intent(getApplicationContext(), MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); } }).start(); } }
package com.github.charmasaur.alpsinsects.ui; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.github.charmasaur.alpsinsects.R; import com.github.charmasaur.alpsinsects.db.FieldGuideDatabase; public final class SplashActivity extends AppCompatActivity { private static final String TAG = SplashActivity.class.getSimpleName(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Handler handler = new Handler(); // Load the database on a background thread. new Thread(new Runnable() { public void run() { Log.i(TAG, "Opening database."); FieldGuideDatabase.getInstance(getApplicationContext()).open(); handler.postDelayed(new Runnable() {public void run() { Log.i(TAG, "Database opened, starting main activity."); Intent intent = new Intent(getApplicationContext(), MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); }}, 0); } }).start(); } }
Remove "Exception" from the error text
package com.voodoodyne.gstrap.rest; import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.voodoodyne.gstrap.lang.Types; import lombok.RequiredArgsConstructor; import java.util.List; import java.util.stream.Collectors; /** * JSON structure of an error body from the ThrowableMapper */ @RequiredArgsConstructor public class ErrorBody { private static final String stripExceptionSuffix(final String className) { if (className.endsWith("Exception")) { return className.substring(0, className.length() - "Exception".length()); } else { return className; } } private final Throwable t; public String getMessage() { return t.getMessage(); } public String getType() { return stripExceptionSuffix(t.getClass().getSimpleName()); } public List<String> getTypes() { return Types.getTypes(t, ClientException.class, RuntimeException.class, Exception.class, Throwable.class) .stream() .map(ErrorBody::stripExceptionSuffix).collect(Collectors.toList()); } public ErrorBody getCause() { return t.getCause() == null ? null : new ErrorBody(t.getCause()); } @JsonUnwrapped public Object getAdditionalProperties() { if (t instanceof AdditionalProperties) { return ((AdditionalProperties)t).getAdditionalProperties(); } else { return null; } } }
package com.voodoodyne.gstrap.rest; import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.voodoodyne.gstrap.lang.Types; import lombok.RequiredArgsConstructor; import java.util.List; /** * JSON structure of an error body from the ThrowableMapper */ @RequiredArgsConstructor public class ErrorBody { private final Throwable t; public String getMessage() { return t.getMessage(); } public String getType() { return t.getClass().getSimpleName(); } public List<String> getTypes() { return Types.getTypes(t, ClientException.class, RuntimeException.class, Exception.class, Throwable.class); } public ErrorBody getCause() { return t.getCause() == null ? null : new ErrorBody(t.getCause()); } @JsonUnwrapped public Object getAdditionalProperties() { if (t instanceof AdditionalProperties) { return ((AdditionalProperties)t).getAdditionalProperties(); } else { return null; } } }
Make TextField also work with a QLabel view, which doesn't allow editing.
# Created On: 2012/01/23 # Copyright 2011 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licenses/bsd_license class TextField: def __init__(self, model, view): self.model = model self.view = view self.model.view = self # Make TextField also work for QLabel, which doesn't allow editing if hasattr(self.view, 'editingFinished'): self.view.editingFinished.connect(self.editingFinished) def editingFinished(self): self.model.text = self.view.text() # model --> view def refresh(self): self.view.setText(self.model.text)
# Created On: 2012/01/23 # Copyright 2011 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licenses/bsd_license class TextField: def __init__(self, model, view): self.model = model self.view = view self.model.view = self self.view.editingFinished.connect(self.editingFinished) def editingFinished(self): self.model.text = self.view.text() # model --> view def refresh(self): self.view.setText(self.model.text)
Allow all for snapshot app
var app = require('express')(); var dom = require('..'); var URL = require('url'); app.get('*', function(req, res, next) { var url = req.query.url; if (!url) return res.sendStatus(404); dom(request(url)).load({ plugins: dom.plugins.png }, function(page, settings, request) { // make sure the page is hosted with the remote url, not the localhost one settings.allow = 'all'; request.location = URL.parse(url); })(req, res, next); }); server = app.listen(process.env.PORT, function(err) { if (err) console.error(err); var port = server.address().port; console.log(` Call http://localhost:${port}/?url=<remoteUrl> to get a screenshot `); }); function request(url) { var obj = URL.parse(url); if (!obj.protocol) obj.protocol = 'http'; var mod = obj.protocol.startsWith('https') ? require('https') : require('http'); obj.headers = { 'User-Agent': "Mozilla/5.0" }; var ps = new require('stream').PassThrough(); mod.request(obj, function(res) { res.setEncoding('utf-8'); res.pipe(ps); }).end(); return ps; }
var app = require('express')(); var dom = require('..'); var URL = require('url'); app.get('*', function(req, res, next) { var url = req.query.url; if (!url) return res.sendStatus(404); dom(request(url)).load({ plugins: dom.plugins.png }, function(page, settings, request) { // make sure the page is hosted with the remote url, not the localhost one request.location = URL.parse(url); })(req, res, next); }); server = app.listen(process.env.PORT, function(err) { if (err) console.error(err); var port = server.address().port; console.log(` Call http://localhost:${port}/?url=<remoteUrl> to get a screenshot `); }); function request(url) { var obj = URL.parse(url); if (!obj.protocol) obj.protocol = 'http'; var mod = obj.protocol.startsWith('https') ? require('https') : require('http'); obj.headers = { 'User-Agent': "Mozilla/5.0" }; var ps = new require('stream').PassThrough(); mod.request(obj, function(res) { res.setEncoding('utf-8'); res.pipe(ps); }).end(); return ps; }
UI: Add edit tags to statistics chart
import React from "react"; import { Route } from "react-router"; import { View as TAView, EditTags as TAEditTags } from "ui-components/type_admin"; import Item from "./Item"; import List from "./List"; const routes = [ <Route key="charts" path="charts" component={TAView} List={List} type="stat.chart" label="Statistics" > <Route path=":_id" component={TAView} Item={Item} type="stat.chart" > <Route path="tags" component={TAView} Action={TAEditTags} type="stat.chart" /> </Route> </Route> ]; export default routes;
import React from "react"; import { Route } from "react-router"; import { View as TAView } from "ui-components/type_admin"; import Item from "./Item"; import List from "./List"; const routes = [ <Route key="charts" path="charts" component={TAView} List={List} type="stat.chart" label="Statistics" > <Route key="stat" path=":_id" component={TAView} Item={Item} type="stat.chart" /> </Route> ]; export default routes;
Allow nock to be installed locally
/** * Copyright 2014 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ var path = require('path'); process.env.NODE_RED_HOME = process.env.NODE_RED_HOME || path.resolve(__dirname+"/../../node-red"); var helper = require(path.join(process.env.NODE_RED_HOME, 'test', 'nodes', 'helper.js')); try { helper.nock = helper.nock || require("nock"); } catch(er) { helper.nock = null; } module.exports = helper;
/** * Copyright 2014 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ var path = require('path'); process.env.NODE_RED_HOME = process.env.NODE_RED_HOME || path.resolve(__dirname+"/../../node-red"); var helper = require(path.join(process.env.NODE_RED_HOME, 'test', 'nodes', 'helper.js')); module.exports = helper;
Remove tester code in publisher
import os import rospy from std_msgs.msg import String # Don't do this in your code, mkay? :) fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2) class SDPPublisher(object): def __init__(self): self.pub = rospy.Publisher('sdp_ros_fib', String, queue_size=10) self.counter = 1 self.r = rospy.Rate(1) # Hz def step(self): nfib = fib(self.counter) self.pub(String("Fibonacci number #%d = %d" % (self.counter, nfib))) self.counter += 1 self.r.sleep()
import os import rospy from std_msgs.msg import String # Don't do this in your code, mkay? :) fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2) class SDPPublisher(object): def __init__(self): self.pub = rospy.Publisher('sdp_ros_fib', String, queue_size=10) self.counter = 1 self.r = rospy.Rate(1) # Hz def step(self): nfib = fib(self.counter) self.pub(String("Fibonacci number #%d = %d" % (self.counter, nfib))) self.counter += 1 self.r.sleep() def main(): pub = SDPPublisher() while not rospy.is_shutdown(): pub.step() if __name__ == "__main__": main()
Update cookies to use universal-cookie
import Cookies from 'universal-cookie'; import { Meteor } from 'meteor/meteor'; import { getRenderContext } from './render_context.js'; const cookie = new Cookies(); function setToken(loginToken, expires) { if (loginToken && expires !== -1) { cookie.set('meteor_login_token', loginToken, { path: '/', expires, }); } else { cookie.remove('meteor_login_token', { path: '/', }); } } function resetToken() { const context = getRenderContext(); const loginToken = global.localStorage['Meteor.loginToken']; const loginTokenExpires = new Date(global.localStorage['Meteor.loginTokenExpires']); if (loginToken) { setToken(loginToken, loginTokenExpires); } else { setToken(null, -1); } context.loginToken = loginToken; } Meteor.startup(() => { resetToken(); }); const originalSetItem = Meteor._localStorage.setItem; Meteor._localStorage.setItem = function setItem(key, value) { if (key === 'Meteor.loginToken') { Meteor.defer(resetToken); } originalSetItem.call(Meteor._localStorage, key, value); }; const originalRemoveItem = Meteor._localStorage.removeItem; Meteor._localStorage.removeItem = function removeItem(key) { if (key === 'Meteor.loginToken') { Meteor.defer(resetToken); } originalRemoveItem.call(Meteor._localStorage, key); };
import cookie from 'react-cookie'; import { Meteor } from 'meteor/meteor'; import { getRenderContext } from './render_context.js'; function setToken(loginToken, expires) { if (loginToken && expires !== -1) { cookie.save('meteor_login_token', loginToken, { path: '/', expires, }); } else { cookie.remove('meteor_login_token', { path: '/', }); } } function resetToken() { const context = getRenderContext(); const loginToken = global.localStorage['Meteor.loginToken']; const loginTokenExpires = new Date(global.localStorage['Meteor.loginTokenExpires']); if (loginToken) { setToken(loginToken, loginTokenExpires); } else { setToken(null, -1); } context.loginToken = loginToken; } Meteor.startup(() => { resetToken(); }); const originalSetItem = Meteor._localStorage.setItem; Meteor._localStorage.setItem = function setItem(key, value) { if (key === 'Meteor.loginToken') { Meteor.defer(resetToken); } originalSetItem.call(Meteor._localStorage, key, value); }; const originalRemoveItem = Meteor._localStorage.removeItem; Meteor._localStorage.removeItem = function removeItem(key) { if (key === 'Meteor.loginToken') { Meteor.defer(resetToken); } originalRemoveItem.call(Meteor._localStorage, key); };
Make developers an admin on registration
import re from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from user import tokens from user.models import User REGEX_PATTERN = getattr(settings, 'REGEX_HACKATHON_ORGANIZER_EMAIL', None) DEV_EMAILS = getattr(settings, 'HACKATHON_DEV_EMAILS', None) # Make user organizer or admin if fits regex @receiver(post_save, sender=User) def user_organizer(sender, instance, created, *args, **kwargs): if not created: return None if REGEX_PATTERN and re.match(REGEX_PATTERN, instance.email): instance.is_organizer = True instance.save() if DEV_EMAILS and instance.email in DEV_EMAILS: instance.is_admin = True instance.save() # Send user verification @receiver(post_save, sender=User) def user_verify_email(sender, instance, created, *args, **kwargs): if created and not instance.email_verified: msg = tokens.generate_verify_email(instance) msg.send()
import re from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from user import tokens from user.models import User REGEX_PATTERN = getattr(settings, 'REGEX_HACKATHON_ORGANIZER_EMAIL', None) # MAke user organizer if fits regex @receiver(post_save, sender=User) def user_organizer(sender, instance, created, *args, **kwargs): if not REGEX_PATTERN or not created: return None if re.match(REGEX_PATTERN, instance.email): instance.is_organizer = True instance.save() # Send user verification @receiver(post_save, sender=User) def user_verify_email(sender, instance, created, *args, **kwargs): if created and not instance.email_verified: msg = tokens.generate_verify_email(instance) msg.send()
Change Player data members to protected
package com.pm.server.player; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; import com.pm.server.datatype.Coordinate; import com.pm.server.utils.JsonUtils; @Component public abstract class PlayerImpl implements Player { protected Integer id = 0; protected Coordinate location; private final static Logger log = LogManager.getLogger(PlayerImpl.class.getName()); public void setId(Integer id) { log.debug("Setting id to {}", id); this.id = id; } public int getId() { return id; } public void setLocation(Coordinate location) { String locationString = JsonUtils.objectToJson(location); if(locationString != null) { log.debug("Setting location to {}", locationString); } this.location = location; } public Coordinate getLocation() { return location; } }
package com.pm.server.player; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; import com.pm.server.datatype.Coordinate; import com.pm.server.utils.JsonUtils; @Component public abstract class PlayerImpl implements Player { private Integer id = 0; private Coordinate location; private final static Logger log = LogManager.getLogger(PlayerImpl.class.getName()); public void setId(Integer id) { log.debug("Setting id to {}", id); this.id = id; } public int getId() { return id; } public void setLocation(Coordinate location) { String locationString = JsonUtils.objectToJson(location); if(locationString != null) { log.debug("Setting location to {}", locationString); } this.location = location; } public Coordinate getLocation() { return location; } }
Add Content-Length header on attachment downloader
<?php namespace BNETDocs\Views\Attachment; use \CarlBennett\MVC\Libraries\Common; use \BNETDocs\Libraries\Exceptions\IncorrectModelException; use \BNETDocs\Libraries\Model; use \BNETDocs\Libraries\View; use \BNETDocs\Models\Attachment\Download as DownloadModel; use \DateTime; class DownloadRaw extends View { public function getMimeType() { return "application/octet-stream"; } public function render(Model &$model) { if (!$model instanceof DownloadModel) { throw new IncorrectModelException(); } $model->extra_headers = [ "Content-Disposition" => "attachment;filename=\"" . $model->attachment->getFilename() . "\"", "Content-Length" => (string) strlen($model->attachment->getContent()), "Last-Modified" => $model->attachment->getCreatedDateTime()->format( DateTime::RFC1123 ) ]; echo $model->attachment->getContent(); } }
<?php namespace BNETDocs\Views\Attachment; use \CarlBennett\MVC\Libraries\Common; use \BNETDocs\Libraries\Exceptions\IncorrectModelException; use \BNETDocs\Libraries\Model; use \BNETDocs\Libraries\View; use \BNETDocs\Models\Attachment\Download as DownloadModel; use \DateTime; class DownloadRaw extends View { public function getMimeType() { return "application/octet-stream"; } public function render(Model &$model) { if (!$model instanceof DownloadModel) { throw new IncorrectModelException(); } $model->extra_headers = [ "Content-Disposition" => "attachment;filename=\"" . $model->attachment->getFilename() . "\"", "Last-Modified" => $model->attachment->getCreatedDateTime()->format( DateTime::RFC1123 ) ]; echo $model->attachment->getContent(); } }
Remove erroneous newton milestone tag Change https://review.openstack.org/268941 inadvertently tagged alembic migration 3d0e74aa7d37 with the newton milestone. Remove it. Change-Id: I46f98a824d2a190c29fb26b62025772de2e4e33e Partial-Bug: #1623108
# Copyright 2016 Mirantis # # 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. # """Add flavor_id to Router Revision ID: 3d0e74aa7d37 Revises: a963b38d82f4 Create Date: 2016-05-05 00:22:47.618593 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '3d0e74aa7d37' down_revision = 'a963b38d82f4' def upgrade(): op.add_column('routers', sa.Column('flavor_id', sa.String(length=36), sa.ForeignKey('flavors.id'), nullable=True))
# Copyright 2016 Mirantis # # 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. # """Add flavor_id to Router Revision ID: 3d0e74aa7d37 Revises: a963b38d82f4 Create Date: 2016-05-05 00:22:47.618593 """ from alembic import op import sqlalchemy as sa from neutron.db import migration # revision identifiers, used by Alembic. revision = '3d0e74aa7d37' down_revision = 'a963b38d82f4' # milestone identifier, used by neutron-db-manage neutron_milestone = [migration.NEWTON] def upgrade(): op.add_column('routers', sa.Column('flavor_id', sa.String(length=36), sa.ForeignKey('flavors.id'), nullable=True))
Update the Microsoft Edge app ID
// Karme Edge Launcher // ================= // Dependencies // ------------ var urlparse = require('url').parse var urlformat = require('url').format // Constants // --------- var EDGE_COMMAND = [ 'powershell', 'start', 'shell:AppsFolder\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge' ] var TIMEOUT = 1000 // Constructor function EdgeBrowser (baseBrowserDecorator) { baseBrowserDecorator(this) this._getOptions = function (url) { var urlObj = urlparse(url, true) // url.format does not want search attribute delete urlObj.search url = urlformat(urlObj) return EDGE_COMMAND.splice(1).concat(url) } var baseOnProcessExit = this._onProcessExit this._onProcessExit = function (code, errorOutput) { setTimeout(function () { baseOnProcessExit(code, errorOutput) }, TIMEOUT) } } EdgeBrowser.prototype = { name: 'Edge', DEFAULT_CMD: { win32: EDGE_COMMAND[0] }, ENV_CMD: 'EDGE_BIN' } EdgeBrowser.$inject = ['baseBrowserDecorator'] // Publish di module // ----------------- module.exports = { 'launcher:Edge': ['type', EdgeBrowser] }
// Karme Edge Launcher // ================= // Dependencies // ------------ var urlparse = require('url').parse var urlformat = require('url').format // Constants // --------- var EDGE_COMMAND = [ 'powershell', 'start', 'shell:AppsFolder\\Microsoft.Windows.Spartan_cw5n1h2txyewy!Microsoft.Spartan.Spartan' ] var TIMEOUT = 1000 // Constructor function EdgeBrowser (baseBrowserDecorator) { baseBrowserDecorator(this) this._getOptions = function (url) { var urlObj = urlparse(url, true) // url.format does not want search attribute delete urlObj.search url = urlformat(urlObj) return EDGE_COMMAND.splice(1).concat(url) } var baseOnProcessExit = this._onProcessExit this._onProcessExit = function (code, errorOutput) { setTimeout(function () { baseOnProcessExit(code, errorOutput) }, TIMEOUT) } } EdgeBrowser.prototype = { name: 'Edge', DEFAULT_CMD: { win32: EDGE_COMMAND[0] }, ENV_CMD: 'EDGE_BIN' } EdgeBrowser.$inject = ['baseBrowserDecorator'] // Publish di module // ----------------- module.exports = { 'launcher:Edge': ['type', EdgeBrowser] }
Remove unneeded public visibility modifier
package com.stolets.rxdiffutil.diffrequest; import android.support.annotation.NonNull; import com.stolets.rxdiffutil.di.FragmentScope; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static com.stolets.rxdiffutil.internal.Preconditions.checkNotNull; /** * Manages the diff requests lifecycle. */ @FragmentScope public final class DiffRequestManager { @NonNull private Map<String, DiffRequest> mPendingRequests = new HashMap<>(); /** * Adds a new {@link DiffRequest} to the pending list. * @param diffRequest A new {@link DiffRequest}. * Note: if a request with the same tag is already exists it will be replaced. */ void addPendingRequest(@NonNull final DiffRequest diffRequest) { checkNotNull(diffRequest, "diffRequest must not be null!"); mPendingRequests.put(diffRequest.getTag(), diffRequest); } /** * @return A map holding all pending requests. Note: the returned map is unmodifiable. */ @NonNull Map<String, DiffRequest> getPendingRequests() { return Collections.unmodifiableMap(mPendingRequests); } }
package com.stolets.rxdiffutil.diffrequest; import android.support.annotation.NonNull; import com.stolets.rxdiffutil.di.FragmentScope; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static com.stolets.rxdiffutil.internal.Preconditions.checkNotNull; /** * Manages the diff requests lifecycle. */ @FragmentScope public final class DiffRequestManager { @NonNull private Map<String, DiffRequest> mPendingRequests = new HashMap<>(); /** * Adds a new {@link DiffRequest} to the pending list. * @param diffRequest A new {@link DiffRequest}. * Note: if a request with the same tag is already exists it will be replaced. */ public void addPendingRequest(@NonNull final DiffRequest diffRequest) { checkNotNull(diffRequest, "diffRequest must not be null!"); mPendingRequests.put(diffRequest.getTag(), diffRequest); } /** * @return A map holding all pending requests. Note: the returned map is unmodifiable. */ @NonNull public Map<String, DiffRequest> getPendingRequests() { return Collections.unmodifiableMap(mPendingRequests); } }