text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Allow setting error.code as well as error.message for callbackWithError()
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. try { var runtime = require('org.chromium.runtime.runtime'); } catch(e) {} // Typical Usage: // // if (fail_condition) // return callbackWithError('You should blah blah', fail, optional_args_to_fail...) function callbackWithError(msg, callback) { var err; if (typeof msg == 'string') { err = { 'message' : msg }; } else { err = msg; } if (typeof callback !== 'function') { console.error(err.message); return; } try { if (typeof runtime !== 'undefined') { runtime.lastError = err; } else { console.error(err.message); } callback.apply(null, Array.prototype.slice.call(arguments, 2)); } finally { if (typeof runtime !== 'undefined') delete runtime.lastError; } } module.exports = { callbackWithError: callbackWithError };
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. try { var runtime = require('org.chromium.runtime.runtime'); } catch(e) {} // Typical Usage: // // if (fail_condition) // return callbackWithError('You should blah blah', fail, optional_args_to_fail...) function callbackWithError(msg, callback) { if (typeof callback !== 'function') { console.error(msg); return; } try { if (typeof runtime !== 'undefined') { runtime.lastError = { 'message' : msg }; } else { console.error(msg); } callback.apply(null, Array.prototype.slice.call(arguments, 2)); } finally { if (typeof runtime !== 'undefined') delete runtime.lastError; } } module.exports = { callbackWithError: callbackWithError };
Add TODO for interactive map classifier
# coding: utf-8 # # Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softwar # 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. """Rules for CoordTwoDim objects.""" __author__ = 'Sean Lip' from extensions.rules import base class Within(base.CoordTwoDimRule): description = 'is within {{d|Real}} km of {{p|CoordTwoDim}}' class NotWithin(base.CoordTwoDimRule): description = 'is not within {{d|Real}} km of {{p|CoordTwoDim}}' class FuzzyMatches(base.CoordTwoDimRule): description = 'is similar to {{training_data|ListOfCoordTwoDim}}' # TODO(wxy): Create a better classifier for this interaction. Currently, # the frontend implementation of this rule returns a booleen value, # checking if the answer is close to any point in the training data. # If this fails, the answer should then go to a backend classifier that # picks the answer group with the best matching answer group.
# coding: utf-8 # # Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softwar # 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. """Rules for CoordTwoDim objects.""" __author__ = 'Sean Lip' from extensions.rules import base class Within(base.CoordTwoDimRule): description = 'is within {{d|Real}} km of {{p|CoordTwoDim}}' class NotWithin(base.CoordTwoDimRule): description = 'is not within {{d|Real}} km of {{p|CoordTwoDim}}' class FuzzyMatches(base.CoordTwoDimRule): description = 'is similar to {{training_data|ListOfCoordTwoDim}}'
Make sure the markers get ouput
require('ti-mocha'); var should = require('should'); describe('Smoke tests', function () { it('should work', function () { true.should.be.true; }); }); describe('Require', function () { it('should work', function () { require('module-a'); }); }); describe('Module calling', function () { var DeepThink; var deepthink it('should work', function () { DeepThink = require('module-a'); deepthink = new DeepThink(); deepthink.answer().should.be.eql(42); deepthink.answer.is(deepthink.answer()).should.be.true; }); it('should throw on missing native deps', function () { (function () { deepthink.magratea(); }).should.throw(); }); it('should work inside module, between modules', function () { deepthink.identity().call(null, 42).should.eql(42); require('module-c').call(null, 42).should.eql(42); should(deepthink.identity() === require('module-c')).be.true; }); }); mocha.run(function (failures) { if (failures > 0) { Ti.API.error('[TESTS WITH FAILURES]'); } else { Ti.API.error('[TESTS ALL OK]'); } });
require('ti-mocha'); var should = require('should'); describe('Smoke tests', function () { it('should work', function () { true.should.be.true; }); }); describe('Require', function () { it('should work', function () { require('module-a'); }); }); describe('Module calling', function () { var DeepThink; var deepthink it('should work', function () { DeepThink = require('module-a'); deepthink = new DeepThink(); deepthink.answer().should.be.eql(42); deepthink.answer.is(deepthink.answer()).should.be.true; }); it('should throw on missing native deps', function () { (function () { deepthink.magratea(); }).should.throw(); }); it('should work inside module, between modules', function () { deepthink.identity().call(null, 42).should.eql(42); require('module-c').call(null, 42).should.eql(42); should(deepthink.identity() === require('module-c')).be.true; }); }); mocha.run(function (failures) { if (failures > 0) { Ti.API.info('[TESTS WITH FAILURES]'); } else { Ti.API.info('[TESTS ALL OK]'); } });
Fix line endings in bin for linux
#!/usr/bin/env node var argv = require('optimist').argv; var debug = argv.debug; delete argv.debug; var outputFormat = argv.output; delete argv.output; var options = {}; for(var key in argv) { var value = argv[key]; if( key == '_' || key.charAt(0) == '$' || (typeof value != 'string' && typeof value != 'number') ) continue; options[key] = value; } var Gamedig = require('../lib/index'); if(debug) Gamedig.debug = true; Gamedig.query( options, function(state) { if(outputFormat == 'pretty') { console.log(JSON.stringify(state,null,' ')); } else { console.log(JSON.stringify(state)); } } );
#!/usr/bin/env node var argv = require('optimist').argv; var debug = argv.debug; delete argv.debug; var outputFormat = argv.output; delete argv.output; var options = {}; for(var key in argv) { var value = argv[key]; if( key == '_' || key.charAt(0) == '$' || (typeof value != 'string' && typeof value != 'number') ) continue; options[key] = value; } var Gamedig = require('../lib/index'); if(debug) Gamedig.debug = true; Gamedig.query( options, function(state) { if(outputFormat == 'pretty') { console.log(JSON.stringify(state,null,' ')); } else { console.log(JSON.stringify(state)); } } );
Set version to 1.9.0-pre to indicate pre-release code
# file findingaids/__init__.py # # Copyright 2012 Emory University Library # # 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. __version_info__ = (1, 9, 0, 'pre') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join(str(i) for i in __version_info__[:-1]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],))
# file findingaids/__init__.py # # Copyright 2012 Emory University Library # # 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. __version_info__ = (1, 9, 0, None) # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join(str(i) for i in __version_info__[:-1]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],))
Fix primary key concurrency issues
package de.philipphager.disclosure.database.app.mapper; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import de.philipphager.disclosure.database.app.model.App; import de.philipphager.disclosure.util.Mapper; import javax.inject.Inject; public class ToAppMapper implements Mapper<ApplicationInfo, App> { private final PackageManager packageManager; @Inject public ToAppMapper(PackageManager packageManager) { this.packageManager = packageManager; } @Override public App map(ApplicationInfo from) { return App.builder() .label(String.valueOf(packageManager.getApplicationLabel(from))) .packageName(from.packageName) .process(from.processName) .sourceDir(from.sourceDir) .flags(from.flags) .build(); } }
package de.philipphager.disclosure.database.app.mapper; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import de.philipphager.disclosure.database.app.model.App; import de.philipphager.disclosure.util.Mapper; import javax.inject.Inject; public class ToAppMapper implements Mapper<ApplicationInfo, App> { private final PackageManager packageManager; @Inject public ToAppMapper(PackageManager packageManager) { this.packageManager = packageManager; } @Override public App map(ApplicationInfo from) { return App.builder() .id(0L) .label(String.valueOf(packageManager.getApplicationLabel(from))) .packageName(from.packageName) .process(from.processName) .sourceDir(from.sourceDir) .flags(from.flags) .build(); } }
Fix typing in SPlitFrame return values.
package hex; import jsr166y.CountedCompleter; import water.*; import water.fvec.*; public class SplitFrame extends Job<SplitFrame> { public Frame dataset; public double[] ratios; public Key<Frame>[] destKeys; public SplitFrame(Key<SplitFrame> dest, String desc) { super(dest, desc); } public SplitFrame() { super(Key.make(), null); } public void execImpl() { if (ratios.length < 0) throw new IllegalArgumentException("No ratio specified!"); if (ratios.length > 100) throw new IllegalArgumentException("Too many frame splits demanded!"); for( double p : ratios ) if( p < 0.0 || p > 1.0 ) throw new IllegalArgumentException("Ratios must be between 0 and 1"); FrameSplitter fs = new FrameSplitter(new H2O.H2OCountedCompleter() { @Override protected void compute2() {} public void onCompletion(CountedCompleter cc){ done();} public boolean onExceptionalCompletion(Throwable ex, CountedCompleter cc) { failed(ex); return true; } }, this.dataset, this.ratios, this.destKeys, this._key); start(fs, ratios.length + 1); } }
package hex; import jsr166y.CountedCompleter; import water.*; import water.fvec.*; public class SplitFrame extends Job<SplitFrame> { public Frame dataset; public double[] ratios; public Key[] destKeys; public SplitFrame(Key<SplitFrame> dest, String desc) { super(dest, desc); } public SplitFrame() { super(Key.make(), null); } public void execImpl() { if (ratios.length < 0) throw new IllegalArgumentException("No ratio specified!"); if (ratios.length > 100) throw new IllegalArgumentException("Too many frame splits demanded!"); for( double p : ratios ) if( p < 0.0 || p > 1.0 ) throw new IllegalArgumentException("Ratios must be between 0 and 1"); FrameSplitter fs = new FrameSplitter(new H2O.H2OCountedCompleter() { @Override protected void compute2() {} public void onCompletion(CountedCompleter cc){ done();} public boolean onExceptionalCompletion(Throwable ex, CountedCompleter cc) { failed(ex); return true; } }, this.dataset, this.ratios, this.destKeys, this._key); start(fs, ratios.length + 1); } }
[android] Fix Android Expo Client crash when opening old experiences
// Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent.branch; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.net.Uri; import host.exp.exponent.RNObject; import io.branch.referral.Branch; public class BranchManager { public static boolean isEnabled(Context context) { try { final ApplicationInfo ai = context.getPackageManager().getApplicationInfo( context.getPackageName(), PackageManager.GET_META_DATA); if (ai.metaData != null) { return ai.metaData.getString("io.branch.sdk.BranchKey") != null; } } catch (final PackageManager.NameNotFoundException ignore) { } return false; } public static void initialize(Application application) { if (!isEnabled(application)) { return; } Branch.getAutoInstance(application); } public static void handleLink(Activity activity, String uri, String sdkVersion) { if (!isEnabled(activity)) { return; } RNObject branchModule = new RNObject("host.exp.exponent.modules.api.standalone.branch.RNBranchModule"); branchModule.loadVersion(sdkVersion); branchModule.callStatic("initSession", Uri.parse(uri), activity); } }
// Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent.branch; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.net.Uri; import host.exp.exponent.ABIVersion; import host.exp.exponent.RNObject; import io.branch.referral.Branch; public class BranchManager { public static boolean isEnabled(Context context) { try { final ApplicationInfo ai = context.getPackageManager().getApplicationInfo( context.getPackageName(), PackageManager.GET_META_DATA); if (ai.metaData != null) { return ai.metaData.getString("io.branch.sdk.BranchKey") != null; } } catch (final PackageManager.NameNotFoundException ignore) {} return false; } public static void initialize(Application application) { if (!isEnabled(application)) { return; } Branch.getAutoInstance(application); } public static void handleLink(Activity activity, String uri, String sdkVersion) { RNObject branchModule = new RNObject("host.exp.exponent.modules.api.standalone.branch.RNBranchModule"); branchModule.loadVersion(sdkVersion); branchModule.callStatic("initSession", Uri.parse(uri), activity); } }
Add failing unit test for getFolderSubjects() with actual object
const assert = require('chai').assert const { getFolderSubjects } = require('../checkAnyDataPresent.js') describe('checkAnyDataPresent', () => { describe('getFolderSubjects()', () => { it('returns only unique subjects', () => { // Pseudo-FileList object but an array simulates it const fileList = [ { relativePath: 'sub-01/files' }, { relativePath: 'sub-01/another' }, { relativePath: 'sub-02/data' }, ] assert.lengthOf(getFolderSubjects(fileList), 2) }) it('filters out emptyroom subject', () => { const fileList = [ { relativePath: 'sub-01/files' }, { relativePath: 'sub-emptyroom/data' }, ] assert.lengthOf(getFolderSubjects(fileList), 1) }) it('works for deeply nested files', () => { const fileList = [ { relativePath: 'sub-01/files/a.nii.gz' }, { relativePath: 'sub-01/another/b.nii.gz' }, { relativePath: 'sub-02/data/test' }, ] assert.lengthOf(getFolderSubjects(fileList), 2) }) it('works with object arguments', () => { const fileList = { 0: { relativePath: 'sub-01/anat/one.nii.gz' } } assert.lengthOf(getFolderSubjects(fileList), 1) }) }) })
const assert = require('chai').assert const { getFolderSubjects } = require('../checkAnyDataPresent.js') describe('checkAnyDataPresent', () => { describe('getFolderSubjects()', () => { it('returns only unique subjects', () => { // Native FileList but an array simulates it const fileList = [ { relativePath: 'sub-01/files' }, { relativePath: 'sub-01/another' }, { relativePath: 'sub-02/data' }, ] assert.lengthOf(getFolderSubjects(fileList), 2) }) it('filters out emptyroom subject', () => { const fileList = [ { relativePath: 'sub-01/files' }, { relativePath: 'sub-emptyroom/data' }, ] assert.lengthOf(getFolderSubjects(fileList), 1) }) it('works for deeply nested files', () => { const fileList = [ { relativePath: 'sub-01/files/a.nii.gz' }, { relativePath: 'sub-01/another/b.nii.gz' }, { relativePath: 'sub-02/data/test' }, ] assert.lengthOf(getFolderSubjects(fileList), 2) }) }) })
Return a random set of factors
import random from collections import defaultdict def largest_palindrome(max_factor, min_factor=0): return _palindromes(max_factor, min_factor, max) def smallest_palindrome(max_factor, min_factor=0): return _palindromes(max_factor, min_factor, min) def _palindromes(max_factor, min_factor, minmax): pals = defaultdict(set) for i in range(min_factor, max_factor+1): for j in range(min_factor, max_factor+1): p = i * j if is_palindrome(p): pals[p].add(tuple(sorted([i,j]))) value = minmax(pals) factors = random.choice(list(pals[value])) return (value, factors) def is_palindrome(n): return str(n) == str(n)[::-1]
from collections import defaultdict def largest_palindrome(max_factor, min_factor=0): return _palindromes(max_factor, min_factor, max) def smallest_palindrome(max_factor, min_factor=0): return _palindromes(max_factor, min_factor, min) def _palindromes(max_factor, min_factor, minmax): pals = defaultdict(set) for i in range(min_factor, max_factor+1): for j in range(min_factor, max_factor+1): p = i * j if is_palindrome(p): pals[p].add(tuple(sorted([i,j]))) value = minmax(pals) factors = pals[value] return (value, factors) def is_palindrome(n): return str(n) == str(n)[::-1]
General: Throw with an invalid ENV.
'use strict'; /*! * Config.js is responsible for rendering the top-level configuration as * required by client, server, or both. _No information should exist here that * cannot be seen by the client_, as Browserify will bundle the generated * code with the client. * * If the configuration doesn't seem to match on the client and on the server, * _make sure the same environment variables are specified on both!_ */ var os = require('os'); var env = process.env.NODE_ENV || 'development'; var validEnvs = ['development', 'production']; if (validEnvs.indexOf(env) === -1) { throw new Error('Invalid environment name:', env); } function byEnv(config) { validEnvs.forEach(function (name) { if (typeof config[name] === 'undefined') { console.warn('Configuration missing value for environment:', name); } }); return config[env]; } module.exports = { env: env, port: process.env.PORT || 8080, cluster: { instances: byEnv({ development: 2, production: os.cpus().length }) }, logger: { format: byEnv({ development: 'dev', production: 'combined' }) } };
'use strict'; /*! * Config.js is responsible for rendering the top-level configuration as * required by client, server, or both. _No information should exist here that * cannot be seen by the client_, as Browserify will bundle the generated * code with the client. * * If the configuration doesn't seem to match on the client and on the server, * _make sure the same environment variables are specified on both!_ */ var os = require('os'); var env = process.env.NODE_ENV || 'development'; var validEnvs = ['development', 'production']; if (validEnvs.indexOf(env) === -1) { console.error('Invalid environment name:', env); } function byEnv(config) { validEnvs.forEach(function (name) { if (typeof config[name] === 'undefined') { console.warn('Configuration missing value for environment:', name); } }); return config[env]; } module.exports = { env: env, port: process.env.PORT || 8080, cluster: { instances: byEnv({ development: 2, production: os.cpus().length }) }, logger: { format: byEnv({ development: 'dev', production: 'combined' }) } };
Remove 2.6, add 3.5 and 3.6
#!/usr/bin/python # -*- coding: utf-8 -*- import os from setuptools import setup def read(*paths): """ read files """ with open(os.path.join(*paths), 'r') as filename: return filename.read() install_requires = read('requirements.txt').splitlines() try: import argparse except ImportError: install_requires.append('argparse') setup( name="slacker-cli", version="0.4.0", description="Send messages to slack from command line", long_description=(read('README.rst')), url="https://github.com/juanpabloaj/slacker-cli", install_requires=install_requires, license='MIT', author="JuanPablo AJ", author_email="jpabloaj@gmail.com", packages=['slacker_cli'], test_suite="tests", entry_points={ 'console_scripts': [ 'slacker=slacker_cli:main', ], }, classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6' ] )
#!/usr/bin/python # -*- coding: utf-8 -*- import os from setuptools import setup def read(*paths): """ read files """ with open(os.path.join(*paths), 'r') as filename: return filename.read() install_requires = read('requirements.txt').splitlines() try: import argparse except ImportError: install_requires.append('argparse') setup( name="slacker-cli", version="0.4.0", description="Send messages to slack from command line", long_description=(read('README.rst')), url="https://github.com/juanpabloaj/slacker-cli", install_requires=install_requires, license='MIT', author="JuanPablo AJ", author_email="jpabloaj@gmail.com", packages=['slacker_cli'], test_suite="tests", entry_points={ 'console_scripts': [ 'slacker=slacker_cli:main', ], }, classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4' ] )
Reset landing page upon successful authentication This change ensures that, when the user later returns to the landing page, such as when they log out, it's in the default state and shows the Signup frame again.
'use strict'; import { API_LOGIN_SUCCESS, API_SIGNUP_SUCCESS } from 'app/actions/auth'; import { SET_PAGE_LOGIN_STATE, SET_PAGE_SIGNUP_STATE, SET_OVERRIDE_FRAME, CLEAR_OVERRIDE_FRAME } from 'app/actions/landingPage'; import { initialLPState } from 'app/constants'; export default function landingPageState(state = initialLPState, action) { switch (action.type) { case SET_PAGE_LOGIN_STATE: return { ...state, frame: 'login' }; case SET_PAGE_SIGNUP_STATE: return { ...state, frame: 'signup' }; case SET_OVERRIDE_FRAME: return { ...state, overrideFrame: action.frame }; case CLEAR_OVERRIDE_FRAME: case API_LOGIN_SUCCESS: case API_SIGNUP_SUCCESS: return initialLPState; } return state; }
'use strict'; import { API_LOGIN_SUCCESS, API_SIGNUP_SUCCESS } from 'app/actions/auth'; import { SET_PAGE_LOGIN_STATE, SET_PAGE_SIGNUP_STATE, SET_OVERRIDE_FRAME, CLEAR_OVERRIDE_FRAME } from 'app/actions/landingPage'; import { initialLPState } from 'app/constants'; export default function landingPageState(state = initialLPState, action) { switch (action.type) { case SET_PAGE_LOGIN_STATE: return { ...state, frame: 'login' }; case SET_PAGE_SIGNUP_STATE: return { ...state, frame: 'signup' }; case SET_OVERRIDE_FRAME: return { ...state, overrideFrame: action.frame }; case CLEAR_OVERRIDE_FRAME: case API_LOGIN_SUCCESS: case API_SIGNUP_SUCCESS: return { ...state, overrideFrame: initialLPState.overrideFrame }; } return state; }
Revert "Remove the __future__ flags" This reverts commit 24b3332ca0c0005483d5f310604cca984efd1ce9.
from __future__ import print_function from __future__ import division import sys import types from ast import PyCF_ONLY_AST PY2 = sys.version_info[0] == 2 PYPY = hasattr(sys, 'pypy_translation_info') _identity = lambda x: x if not PY2: string_types = (str,) integer_types = (int,) long = int class_types = (type,) from io import StringIO import builtins def to_bytes(s): return s.encode() def to_str(b): return b.decode() else: string_types = (str, unicode) integer_types = (int, long) long = long class_types = (type, types.ClassType) from cStringIO import StringIO import __builtin__ as builtins to_bytes = _identity to_str = _identity def ast_parse(s): return compile(s, '<string>', 'exec', \ print_function.compiler_flag|division.compiler_flag|PyCF_ONLY_AST)
import sys import types from ast import PyCF_ONLY_AST PY2 = sys.version_info[0] == 2 PYPY = hasattr(sys, 'pypy_translation_info') _identity = lambda x: x if not PY2: string_types = (str,) integer_types = (int,) long = int class_types = (type,) from io import StringIO import builtins def to_bytes(s): return s.encode() def to_str(b): return b.decode() else: string_types = (str, unicode) integer_types = (int, long) long = long class_types = (type, types.ClassType) from cStringIO import StringIO import __builtin__ as builtins to_bytes = _identity to_str = _identity def ast_parse(s): return compile(s, '<string>', 'exec', PyCF_ONLY_AST)
Remove crm as dependency of event_sale There is no need for CRM to have event management. Introduced at 64d63ffaa6f5f2e72084ea6aedc6f2c2b7130ca6 for probably no reason...
# -*- coding: utf-8 -*- { 'name': 'Events Sales', 'version': '1.1', 'category': 'Tools', 'website': 'https://www.odoo.com/page/events', 'description': """ Creating registration with sale orders. ======================================= This module allows you to automate and connect your registration creation with your main sale flow and therefore, to enable the invoicing feature of registrations. It defines a new kind of service products that offers you the possibility to choose an event category associated with it. When you encode a sale order for that product, you will be able to choose an existing event of that category and when you confirm your sale order it will automatically create a registration for this event. """, 'depends': ['event', 'sale'], 'data': [ 'views/event.xml', 'views/product.xml', 'views/sale_order.xml', 'event_sale_data.xml', 'report/event_event_templates.xml', 'security/ir.model.access.csv', 'wizard/event_edit_registration.xml', ], 'demo': ['event_demo.xml'], 'test': ['test/confirm.yml'], 'installable': True, 'auto_install': True }
# -*- coding: utf-8 -*- { 'name': 'Events Sales', 'version': '1.1', 'category': 'Tools', 'website': 'https://www.odoo.com/page/events', 'description': """ Creating registration with sale orders. ======================================= This module allows you to automate and connect your registration creation with your main sale flow and therefore, to enable the invoicing feature of registrations. It defines a new kind of service products that offers you the possibility to choose an event category associated with it. When you encode a sale order for that product, you will be able to choose an existing event of that category and when you confirm your sale order it will automatically create a registration for this event. """, 'depends': ['event', 'sale_crm'], 'data': [ 'views/event.xml', 'views/product.xml', 'views/sale_order.xml', 'event_sale_data.xml', 'report/event_event_templates.xml', 'security/ir.model.access.csv', 'wizard/event_edit_registration.xml', ], 'demo': ['event_demo.xml'], 'test': ['test/confirm.yml'], 'installable': True, 'auto_install': True }
Fix - filename not showed for current_page
<?php /** * Call pages by their filename like: * {{ pages['page2'].title }} * * @author James Doyle * @link http://ohdoylerules.com/ * @license http://opensource.org/licenses/MIT */ class Pico_Get_By_Filename { private function _make_filename($url) { $filename = substr($url, (strrpos($url, '/'))); $filename = str_replace('/', '', $filename); // need to find a way around files with the same name if (strlen($filename) <= 1) { $filename .= 'index'; } return $filename; } public function get_pages(&$pages, &$current_page, &$prev_page, &$next_page) { $temp = array(); foreach ($pages as $page) { $filename = $this->_make_filename($page['url']); $page['filename'] = $filename; $temp[$filename] = $page; } $filename = $this->_make_filename($current_page['url']); $current_page['filename'] = $filename; $pages = $temp; } } // End of file
<?php /** * Call pages by their filename like: * {{ pages['page2'].title }} * * @author James Doyle * @link http://ohdoylerules.com/ * @license http://opensource.org/licenses/MIT */ class Pico_Get_By_Filename { private function _make_filename($url) { $filename = substr($url, (strrpos($url, '/'))); $filename = str_replace('/', '', $filename); // need to find a way around files with the same name if (strlen($filename) <= 1) { $filename .= 'index'; } return $filename; } public function get_pages(&$pages, &$current_page, &$prev_page, &$next_page) { $temp = array(); foreach ($pages as $page) { $filename = $this->_make_filename($page['url']); $page['filename'] = $filename; $temp[$filename] = $page; } $pages = $temp; } } // End of file
Add check if the file contains only comments
const updateComment = (body, ast, commentArr = []) => { body = body.map((obj, index, array) => { if (obj.type === 'Line' || obj.type === 'Block') { commentArr.push(obj) if (array[index + 1] === undefined) { if (index - commentArr.length === -1) ast.leadingComments = commentArr else array[index - commentArr.length].trailingComments = commentArr return undefined } if (!(array[index + 1].type === 'Line' || array[index + 1].type === 'Block')) { array[index + 1].leadingComments = commentArr commentArr = [] } return undefined } return obj }).filter(stmt => stmt !== undefined) return body } /* Module Exports updateComment */ module.exports = updateComment
const updateComment = (body, commentArr = []) => { body = body.map((obj, index, array) => { if (obj.type === 'Line' || obj.type === 'Block') { commentArr.push(obj) if (array[index + 1] === undefined) { array[index - commentArr.length].trailingComments = commentArr return undefined } if (!(array[index + 1].type === 'Line' || array[index + 1].type === 'Block')) { array[index + 1].leadingComments = commentArr commentArr = [] } return undefined } return obj }).filter(stmt => stmt !== undefined) return body } /* Module Exports updateComment */ module.exports = updateComment
Update path to Gondola repository
package main import ( "path" "gnd.la/app" "gnd.la/apps/docs" "gnd.la/net/urlutil" ) const ( gondolaURL = "http://www.gondolaweb.com" ) func gndlaHandler(ctx *app.Context) { if ctx.FormValue("go-get") == "1" { ctx.MustExecute("goget.html", nil) return } // Check if the request path is a pkg name var p string pkg := path.Join("gnd.la", ctx.R.URL.Path) if _, err := docs.DefaultContext.Import(pkg, "", 0); err == nil { p = ctx.MustReverse(docs.PackageHandlerName, pkg) } redir, err := urlutil.Join(gondolaURL, p) if err != nil { panic(err) } ctx.Redirect(redir, false) }
package main import ( "path" "gnd.la/app" "gnd.la/apps/docs" "gnd.la/net/urlutil" ) const ( //gondolaURL = "http://www.gondolaweb.com" gondolaURL = "ssh://abra.rm-fr.net/home/fiam/git/gondola.git" ) func gndlaHandler(ctx *app.Context) { if ctx.FormValue("go-get") == "1" { ctx.MustExecute("goget.html", nil) return } // Check if the request path is a pkg name var p string pkg := path.Join("gnd.la", ctx.R.URL.Path) if _, err := docs.DefaultContext.Import(pkg, "", 0); err == nil { p = ctx.MustReverse(docs.PackageHandlerName, pkg) } redir, err := urlutil.Join(gondolaURL, p) if err != nil { panic(err) } ctx.Redirect(redir, false) }
Fix the bug that allowed to type more than one period in a float number.
package gui_elements; import javafx.scene.control.TextField; import javafx.scene.input.KeyEvent; /** * */ public class FloatField extends TextField { public FloatField() { this.addEventFilter(KeyEvent.KEY_TYPED, t -> { char ar[] = t.getCharacter().toCharArray(); char ch = ar[t.getCharacter().toCharArray().length - 1]; if (!((ch >= '0' && ch <= '9') || (ch == '.' & !getText().contains(".")))) { t.consume(); } }); } public float getValue() { return Float.parseFloat(getText()); } }
package gui_elements; import javafx.scene.control.TextField; import javafx.scene.input.KeyEvent; /** * */ public class FloatField extends TextField { public FloatField() { this.addEventFilter(KeyEvent.KEY_TYPED, t -> { char ar[] = t.getCharacter().toCharArray(); char ch = ar[t.getCharacter().toCharArray().length - 1]; if (!((ch >= '0' && ch <= '9') || ch == '.')) { t.consume(); } }); } public float getValue() { return Float.parseFloat(getText()); } }
Use the real source's IP even when behind proxy nginx sets X-Real-IP to the user's real IP.
'use strict'; var ua = require('universal-analytics'); var url = require('url'); var extend = require('extend'); var config = require('./config'); function pageview(options) { return function(req, res, next) { var defaults = { dp: req.path, dh: _getUrl(req), dr: req.get('Referer'), uip: req.get('X-Real-IP') || req.ip, ua: req.get('User-Agent'), }; if (req.visitor) { req.visitor .pageview(extend(defaults, options)) .send(); } next(); }; } function sendEvent(req, category, action, label, value, options) { var defaults = { t: 'event', ni: true, ec: category, ea: action, el: label, ev: value, }; pageview(extend(defaults, options))(req, {}, function(){}); } function _getUrl(req) { return url.format({ protocol: req.protocol, host: req.get('host'), }); } module.exports = { trackingId: config.analytics.tracking_id, middleware: ua.middleware, pageview: pageview, sendEvent: sendEvent, };
'use strict'; var ua = require('universal-analytics'); var url = require('url'); var extend = require('extend'); var config = require('./config'); function pageview(options) { return function(req, res, next) { var defaults = { dp: req.path, dh: _getUrl(req), dr: req.get('Referer'), uip: req.ip, ua: req.get('User-Agent'), }; if (req.visitor) { req.visitor .pageview(extend(defaults, options)) .send(); } next(); }; } function sendEvent(req, category, action, label, value, options) { var defaults = { t: 'event', ni: true, ec: category, ea: action, el: label, ev: value, }; pageview(extend(defaults, options))(req, {}, function(){}); } function _getUrl(req) { return url.format({ protocol: req.protocol, host: req.get('host'), }); } module.exports = { trackingId: config.analytics.tracking_id, middleware: ua.middleware, pageview: pageview, sendEvent: sendEvent, };
Use assert_allclose so we can see the appveyor failure
from numpy.testing import assert_allclose from menpodetect.opencv import (load_opencv_frontal_face_detector, load_opencv_eye_detector) import menpo.io as mio takeo = mio.import_builtin_asset.takeo_ppm() def test_frontal_face_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy) assert len(pcs) == 1 assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4 def test_frontal_face_detector_min_neighbors(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy, min_neighbours=100) assert len(pcs) == 0 assert takeo_copy.n_channels == 3 def test_eye_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_eye_detector() pcs = opencv_detector(takeo_copy, min_size=(5, 5)) assert_allclose(len(pcs), 1) assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4
from menpodetect.opencv import (load_opencv_frontal_face_detector, load_opencv_eye_detector) import menpo.io as mio takeo = mio.import_builtin_asset.takeo_ppm() def test_frontal_face_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy) assert len(pcs) == 1 assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4 def test_frontal_face_detector_min_neighbors(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy, min_neighbours=100) assert len(pcs) == 0 assert takeo_copy.n_channels == 3 def test_eye_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_eye_detector() pcs = opencv_detector(takeo_copy, min_size=(5, 5)) assert len(pcs) == 1 assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4
Fix setting content version on admin page.
/** * Copyright 2014 Ian Davies * * 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. */ define([], function() { var PageController = ['$scope', 'auth', 'api', function($scope, auth, api) { $scope.contentVersion = api.contentVersion.get(); $scope.setVersion = function() { api.admin.synchroniseDatastores().then(function() { api.contentVersion.set({version: $scope.contentVersion.liveVersion}, {}).$promise.then(function(data) { $scope.contentVersion = api.contentVersion.get(); }); }) } }] return { PageController: PageController, }; })
/** * Copyright 2014 Ian Davies * * 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. */ define([], function() { var PageController = ['$scope', 'auth', 'api', function($scope, auth, api) { $scope.contentVersion = api.contentVersion.get(); $scope.setVersion = function() { api.admin.synchroniseDatastores().then(function() { api.contentVersion.set({version: $scope.contentVersion.liveVersion}, {}).then(function(data) { $scope.contentVersion = api.contentVersion.get(); }); }) } }] return { PageController: PageController, }; })
Update to latest TIFF API.
// // CommentSurgery.java // import loci.formats.tiff.TiffSaver; import loci.formats.tiff.TiffTools; /** * Performs "surgery" on a TIFF ImageDescription comment, particularly the * OME-XML comment found in OME-TIFF files. Note that this code must be * tailored to a specific need by editing the commented out code below to * make desired alterations to the comment. */ public class CommentSurgery { public static void main(String[] args) throws Exception { // the -test flag will print proposed changes to stdout // rather than actually changing the comment boolean test = args[0].equals("-test"); int start = test ? 1 : 0; for (int i=0; i<args.length; i++) { String id = args[i]; if (!test) System.out.println(id + ": "); String xml = TiffTools.getComment(id); if (xml == null) { System.out.println("ERROR: No OME-XML comment."); return; } int len = xml.length(); // do something to the comment; e.g.: //xml = xml.replaceAll("LogicalChannel:OWS", "LogicalChannel:OWS347-"); if (test) System.out.println(xml); else { System.out.println(len + " -> " + xml.length()); TiffSaver.overwriteComment(id, xml); } } } }
// // CommentSurgery.java // import loci.formats.TiffTools; /** * Performs "surgery" on a TIFF ImageDescription comment, particularly the * OME-XML comment found in OME-TIFF files. Note that this code must be * tailored to a specific need by editing the commented out code below to * make desired alterations to the comment. */ public class CommentSurgery { public static void main(String[] args) throws Exception { // the -test flag will print proposed changes to stdout // rather than actually changing the comment boolean test = args[0].equals("-test"); int start = test ? 1 : 0; for (int i=0; i<args.length; i++) { String id = args[i]; if (!test) System.out.println(id + ": "); String xml = TiffTools.getComment(id); if (xml == null) { System.out.println("ERROR: No OME-XML comment."); return; } int len = xml.length(); // do something to the comment; e.g.: //xml = xml.replaceAll("LogicalChannel:OWS", "LogicalChannel:OWS347-"); if (test) System.out.println(xml); else { System.out.println(len + " -> " + xml.length()); TiffTools.overwriteComment(id, xml); } } } }
Add CORS to WDS config
// @flow import path from 'path' import webpack from 'webpack' import { WDS_PORT, isProd } from './src/shared/config' export default { entry: [ 'react-hot-loader/patch', './src/client', ], output: { filename: 'js/bundle.js', path: path.resolve(__dirname, 'dist'), publicPath: isProd ? '/static/' : `http://localhost:${WDS_PORT}/dist/`, }, module: { rules: [ { test: /\.(js|jsx)$/, use: 'babel-loader', exclude: /node_modules/ }, ], }, devtool: isProd ? false : 'source-map', resolve: { extensions: ['.js', '.jsx'], }, devServer: { port: WDS_PORT, hot: true, headers: { 'Access-Control-Allow-Origin': '*', }, }, plugins: [ new webpack.optimize.OccurrenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), new webpack.NoEmitOnErrorsPlugin(), ], }
// @flow import path from 'path' import webpack from 'webpack' import { WDS_PORT, isProd } from './src/shared/config' export default { entry: [ 'react-hot-loader/patch', './src/client', ], output: { filename: 'js/bundle.js', path: path.resolve(__dirname, 'dist'), publicPath: isProd ? '/static/' : `http://localhost:${WDS_PORT}/dist/`, }, module: { rules: [ { test: /\.(js|jsx)$/, use: 'babel-loader', exclude: /node_modules/ }, ], }, devtool: isProd ? false : 'source-map', resolve: { extensions: ['.js', '.jsx'], }, devServer: { port: WDS_PORT, hot: true, }, plugins: [ new webpack.optimize.OccurrenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), new webpack.NoEmitOnErrorsPlugin(), ], }
Add '/source' static asset mount so that Source maps resolve when debugging.
/*jslint node:true */ "use strict"; var path = require('path'); var express = require('express'); var server = express(); var faye = require('faye'); var bayeux = new faye.NodeAdapter({ mount: '/meet', timeout: 45 }); var env = server.get('env'); // Heroku will specify the port to listen on with the `process.env.PORT` variable. var serverPort = process.env.PORT || 4202; // gzip scripts/css when possible. server.use(express.compress()); // Pretty print HTML outputs in development and debug configurations if(env !== 'production'){ server.locals.pretty = true; } // Development Settings server.configure(function(){ server.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); // Production Settings server.configure('production', function(){ server.use(express.errorHandler()); }); // Mount the `public` directory for static file serving. server.use(express.static(path.resolve(__dirname + "/public"))); server.use("/source", express.static(path.resolve(__dirname + "/source"))); // Set up faye realtime connections var hServer = server.listen(serverPort); bayeux.attach(hServer); console.log("Server running on port " + serverPort);
/*jslint node:true */ "use strict"; var path = require('path'); var express = require('express'); var server = express(); var faye = require('faye'); var bayeux = new faye.NodeAdapter({ mount: '/meet', timeout: 45 }); var env = server.get('env'); // Heroku will specify the port to listen on with the `process.env.PORT` variable. var serverPort = process.env.PORT || 4202; // gzip scripts/css when possible. server.use(express.compress()); // Pretty print HTML outputs in development and debug configurations if(env !== 'production'){ server.locals.pretty = true; } // Development Settings server.configure(function(){ server.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); // Production Settings server.configure('production', function(){ server.use(express.errorHandler()); }); // Mount the `public` directory for static file serving. server.use(express.static(path.resolve(__dirname + "/public"))); // Set up faye realtime connections var hServer = server.listen(serverPort); bayeux.attach(hServer); console.log("Server running on port " + serverPort);
Add --insecure option to hg clone to avoid self-assigned certificate issue
from conans import ConanFile import os class EigenConan(ConanFile): name = "eigen" version = "3.2" settings = "os", "compiler", "build_type", "arch" options = {"shared": [True, False]} default_options = "shared=True" exports = "eigen/*" url="https://github.com/jslee02/conan-dart/tree/master/eigen/3.2" def source(self): self.run('hg clone --insecure https://bitbucket.org/eigen/eigen -u 3.2.7') self.run('cd eigen') def package(self): self.copy("*", dst="include/Eigen", src="eigen/Eigen") self.copy("*", dst="include/unsupported", src="eigen/unsupported")
from conans import ConanFile import os class EigenConan(ConanFile): name = "eigen" version = "3.2" settings = "os", "compiler", "build_type", "arch" options = {"shared": [True, False]} default_options = "shared=True" exports = "eigen/*" url="https://github.com/jslee02/conan-dart/tree/master/eigen/3.2" def source(self): self.run('hg clone https://bitbucket.org/eigen/eigen -u 3.2.7') self.run('cd eigen') def package(self): self.copy("*", dst="include/Eigen", src="eigen/Eigen") self.copy("*", dst="include/unsupported", src="eigen/unsupported")
Revert the ui:image cmp validity checking. @bug W-2533777@
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ({ init: function (component) { var cmp = component.getConcreteComponent(); var imageType = cmp.get('v.imageType'), altText = cmp.get('v.alt') || '', id = cmp.getLocalId() || cmp.getGlobalId() || ''; if (imageType === 'informational' && altText.length == 0) { $A.warning('component: ' + id + ' "alt" attribute should not be empty for informational image'); } else if (imageType === 'decorative' && altText.length > 0) { $A.warning('component: ' + id + ': "alt" attribute should be empty for decorative image'); } } })
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ({ init: function (component) { if (!component || !component.isValid()) { return; } var cmp = component.getConcreteComponent(); var imageType = cmp.get('v.imageType'), altText = cmp.get('v.alt') || '', id = cmp.getLocalId() || cmp.getGlobalId() || ''; if (imageType === 'informational' && altText.length == 0) { $A.warning('component: ' + id + ' "alt" attribute should not be empty for informational image'); } else if (imageType === 'decorative' && altText.length > 0) { $A.warning('component: ' + id + ': "alt" attribute should be empty for decorative image'); } } })
Modify getting started to use svn url
package main import ( "fmt" "log" "os" "bufio" "image" "image/png" "draw2d.googlecode.com/svn/trunk/draw2d/src/pkg/draw2d" ) func saveToPngFile(filePath string, m image.Image) { f, err := os.Open(filePath, os.O_CREAT|os.O_WRONLY, 0600) if err != nil { log.Println(err) os.Exit(1) } defer f.Close() b := bufio.NewWriter(f) err = png.Encode(b, m) if err != nil { log.Println(err) os.Exit(1) } err = b.Flush() if err != nil { log.Println(err) os.Exit(1) } fmt.Printf("Wrote %s OK.\n", filePath) } func main() { i := image.NewRGBA(200, 200) gc := draw2d.NewGraphicContext(i) gc.MoveTo(10.0, 10.0) gc.LineTo(100.0, 10.0) gc.Stroke() saveToPngFile("TestPath.png", i) }
package main import ( "fmt" "log" "os" "bufio" "image" "image/png" "draw2d" ) func saveToPngFile(filePath string, m image.Image) { f, err := os.Open(filePath, os.O_CREAT|os.O_WRONLY, 0600) if err != nil { log.Println(err) os.Exit(1) } defer f.Close() b := bufio.NewWriter(f) err = png.Encode(b, m) if err != nil { log.Println(err) os.Exit(1) } err = b.Flush() if err != nil { log.Println(err) os.Exit(1) } fmt.Printf("Wrote %s OK.\n", filePath) } func main() { i := image.NewRGBA(200, 200) gc := draw2d.NewGraphicContext(i) gc.MoveTo(10.0, 10.0) gc.LineTo(100.0, 10.0) gc.Stroke() saveToPngFile("../../TestPath.png", i) }
Exit with 1 when the RPC generator tests fail
#!/usr/bin/env python3 """ Main entry point to run all tests """ import sys from pathlib import Path from unittest import TestLoader, TestSuite, TextTestRunner PATH = Path(__file__).absolute() sys.path.append(PATH.parents[1].joinpath('rpc_spec/InterfaceParser').as_posix()) sys.path.append(PATH.parents[1].as_posix()) try: from test_enums import TestEnumsProducer from test_functions import TestFunctionsProducer from test_structs import TestStructsProducer from test_code_format_and_quality import CodeFormatAndQuality except ImportError as message: print('{}. probably you did not initialize submodule'.format(message)) sys.exit(1) def main(): """ Main entry point to run all tests """ suite = TestSuite() suite.addTests(TestLoader().loadTestsFromTestCase(TestFunctionsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestEnumsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestStructsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(CodeFormatAndQuality)) ret = not runner.run(suite).wasSuccessful() sys.exit(ret) if __name__ == '__main__': main()
#!/usr/bin/env python3 """ Main entry point to run all tests """ import sys from pathlib import Path from unittest import TestLoader, TestSuite, TextTestRunner PATH = Path(__file__).absolute() sys.path.append(PATH.parents[1].joinpath('rpc_spec/InterfaceParser').as_posix()) sys.path.append(PATH.parents[1].as_posix()) try: from test_enums import TestEnumsProducer from test_functions import TestFunctionsProducer from test_structs import TestStructsProducer from test_code_format_and_quality import CodeFormatAndQuality except ImportError as message: print('{}. probably you did not initialize submodule'.format(message)) sys.exit(1) def main(): """ Main entry point to run all tests """ suite = TestSuite() suite.addTests(TestLoader().loadTestsFromTestCase(TestFunctionsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestEnumsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestStructsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(CodeFormatAndQuality)) runner = TextTestRunner(verbosity=2) runner.run(suite) if __name__ == '__main__': main()
Revert "Remove incorrect check for institution_id" This reverts commit 617df13670573b858b6c23249f4287786807d8b6.
import logging from website.notifications.exceptions import InvalidSubscriptionError from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications from website.project.signals import contributor_added, project_created from framework.auth.signals import user_confirmed logger = logging.getLogger(__name__) @project_created.connect def subscribe_creator(node): if node.institution_id or node.is_collection or node.is_deleted: return None try: subscribe_user_to_notifications(node, node.creator) except InvalidSubscriptionError as err: user = node.creator._id if node.creator else 'None' logger.warn('Skipping subscription of user {} to node {}'.format(user, node._id)) logger.warn('Reason: {}'.format(str(err))) @contributor_added.connect def subscribe_contributor(node, contributor, auth=None, *args, **kwargs): try: subscribe_user_to_notifications(node, contributor) except InvalidSubscriptionError as err: logger.warn('Skipping subscription of user {} to node {}'.format(contributor, node._id)) logger.warn('Reason: {}'.format(str(err))) @user_confirmed.connect def subscribe_confirmed_user(user): try: subscribe_user_to_global_notifications(user) except InvalidSubscriptionError as err: logger.warn('Skipping subscription of user {} to global subscriptions'.format(user)) logger.warn('Reason: {}'.format(str(err)))
import logging from website.notifications.exceptions import InvalidSubscriptionError from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications from website.project.signals import contributor_added, project_created from framework.auth.signals import user_confirmed logger = logging.getLogger(__name__) @project_created.connect def subscribe_creator(node): if node.is_collection or node.is_deleted: return None try: subscribe_user_to_notifications(node, node.creator) except InvalidSubscriptionError as err: user = node.creator._id if node.creator else 'None' logger.warn('Skipping subscription of user {} to node {}'.format(user, node._id)) logger.warn('Reason: {}'.format(str(err))) @contributor_added.connect def subscribe_contributor(node, contributor, auth=None, *args, **kwargs): try: subscribe_user_to_notifications(node, contributor) except InvalidSubscriptionError as err: logger.warn('Skipping subscription of user {} to node {}'.format(contributor, node._id)) logger.warn('Reason: {}'.format(str(err))) @user_confirmed.connect def subscribe_confirmed_user(user): try: subscribe_user_to_global_notifications(user) except InvalidSubscriptionError as err: logger.warn('Skipping subscription of user {} to global subscriptions'.format(user)) logger.warn('Reason: {}'.format(str(err)))
Add a M2M table for the subscription relation between users and comics
import uuid from django.contrib.auth.models import User from django.db import models from django.dispatch import receiver from comics.core.models import Comic @receiver(models.signals.post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) def make_secret_key(): return uuid.uuid4().hex class UserProfile(models.Model): user = models.OneToOneField(User, related_name='comics_profile') secret_key = models.CharField(max_length=32, blank=False, default=make_secret_key, help_text='Secret key for feed and API access') comics = models.ManyToManyField(Comic, through='Subscription') class Meta: db_table = 'comics_user_profile' def __unicode__(self): return u'User profile for %s' % self.user def generate_new_secret_key(self): self.secret_key = make_secret_key() class Subscription(models.Model): userprofile = models.ForeignKey(UserProfile) comic = models.ForeignKey(Comic) class Meta: db_table = 'comics_user_profile_comics'
import uuid from django.contrib.auth.models import User from django.db import models from django.dispatch import receiver from comics.core.models import Comic @receiver(models.signals.post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) def make_secret_key(): return uuid.uuid4().hex class UserProfile(models.Model): user = models.OneToOneField(User, related_name='comics_profile') secret_key = models.CharField(max_length=32, blank=False, default=make_secret_key, help_text='Secret key for feed and API access') comics = models.ManyToManyField(Comic) class Meta: db_table = 'comics_user_profile' def __unicode__(self): return u'User profile for %s' % self.user def generate_new_secret_key(self): self.secret_key = make_secret_key()
Move jQuery logic into separate functions
$(function() { //Update "tied" elements on each change of the "fill" input interjector.fillNames.forEach(function(name) { interjector.registerUpdateHandler(name, function() { interjector.setTiedText(name, interjector.getFillText(name)); }); }); //Deal with "a/an" selection $('#ijtr-option-a').click(function() { $('#interjector .tied-a-an').text('a'); }); $('#ijtr-option-an').click(function() { $('#interjector .tied-a-an').text('an'); }); }); var interjector = { //Names of classes to update fillNames: [ 'linux', 'gnu', 'components', 'os', 'posix', 'project', 'kernel', 'kernel-role', 'osys', ], //Get the element for filling in the value getFillElement: function(name) { return $('#ijtr-fill-' + name); }, //Get the elements that are tied to the value getTiedElements: function(name) { return $('#interjector .tied-' + name); }, //Register an event handler on update registerUpdateHandler: function(name, handler) { this.getFillElement(name).keyup(handler); }, //Get the filled text getFillText: function(name) { return this.getFillElement(name).val(); }, //Set the text on the tied elements setTiedText: function(name, text) { this.getTiedElements(name).text(text); }, }
$(function() { //Update "tied" elements on each change of the "fill" input interjector.fillNames.forEach(function(name) { $('#ijtr-fill-' + name).keyup(function() { $('#interjector .tied-' + name).text($('#ijtr-fill-' + name).val()); }); }); //Deal with "a/an" selection $('#ijtr-option-a').click(function() { $('#interjector .tied-a-an').text('a'); }); $('#ijtr-option-an').click(function() { $('#interjector .tied-a-an').text('an'); }); }); var interjector = { //Names of classes to update fillNames: [ 'linux', 'gnu', 'components', 'os', 'posix', 'project', 'kernel', 'kernel-role', 'osys', ], }
HG-1494: Make sure the schema gets pulled in as a module
from pymoku import Moku from pymoku.instruments import * import time, logging logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.INFO) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku('192.168.69.122')#.get_by_name('example') i = Oscilloscope() m.attach_instrument(i) try: i.set_samplerate(10) i.set_xmode(OSC_ROLL) i.commit() i.datalogger_stop() i.datalogger_start(start=0, duration=10, use_sd=True, ch1=True, ch2=True, filetype='bin') while True: time.sleep(1) trems, treme = i.datalogger_remaining() samples = i.datalogger_samples() print("Captured (%d samples); %d seconds from start, %d from end" % (samples, trems, treme)) if i.datalogger_completed(): break e = i.datalogger_error() if e: print("Error occured: %s" % e) i.datalogger_stop() i.datalogger_upload() except Exception as e: print(e) finally: m.close()
from pymoku import Moku from pymoku.instruments import * import time, logging logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.INFO) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku.get_by_name('example') i = Oscilloscope() m.attach_instrument(i) try: i.set_samplerate(10) i.set_xmode(OSC_ROLL) i.commit() i.datalogger_stop() i.datalogger_start(start=0, duration=10, use_sd=True, ch1=True, ch2=True, filetype='bin') while True: time.sleep(1) trems, treme = i.datalogger_remaining() samples = i.datalogger_samples() print("Captured (%d samples); %d seconds from start, %d from end" % (samples, trems, treme)) if i.datalogger_completed(): break e = i.datalogger_error() if e: print("Error occured: %s" % e) i.datalogger_stop() i.datalogger_upload() except Exception as e: print(e) finally: m.close()
Fix error summary not getting focus
/* global $ */ /* global GOVUK */ // Warn about using the kit in production if ( window.sessionStorage && window.sessionStorage.getItem('prototypeWarning') !== 'false' && window.console && window.console.info ) { window.console.info('GOV.UK Prototype Kit - do not use for production') window.sessionStorage.setItem('prototypeWarning', true) } $(document).ready(function () { // Use GOV.UK selection-buttons.js to set selected // and focused states for block labels var $blockLabels = $(".block-label input[type='radio'], .block-label input[type='checkbox']") new GOVUK.SelectionButtons($blockLabels) // eslint-disable-line // Use GOV.UK shim-links-with-button-role.js to trigger a link styled to look like a button, // with role="button" when the space key is pressed. GOVUK.shimLinksWithButtonRole.init() // Show and hide toggled content // Where .block-label uses the data-target attribute // to toggle hidden content var showHideContent = new GOVUK.ShowHideContent() showHideContent.init() }) $(window).load(function () { // If there is an error summary, set focus to the summary if ($('.error-summary').length) { $('.error-summary').focus() $('.error-summary a').click(function (e) { e.preventDefault() var href = $(this).attr('href') $(href).focus() }) } else { // Otherwise, set focus to the field with the error $('.error input:first').focus() } })
/* global $ */ /* global GOVUK */ // Warn about using the kit in production if ( window.sessionStorage && window.sessionStorage.getItem('prototypeWarning') !== 'false' && window.console && window.console.info ) { window.console.info('GOV.UK Prototype Kit - do not use for production') window.sessionStorage.setItem('prototypeWarning', true) } $(document).ready(function () { // Use GOV.UK selection-buttons.js to set selected // and focused states for block labels var $blockLabels = $(".block-label input[type='radio'], .block-label input[type='checkbox']") new GOVUK.SelectionButtons($blockLabels) // eslint-disable-line // Use GOV.UK shim-links-with-button-role.js to trigger a link styled to look like a button, // with role="button" when the space key is pressed. GOVUK.shimLinksWithButtonRole.init() // Show and hide toggled content // Where .block-label uses the data-target attribute // to toggle hidden content var showHideContent = new GOVUK.ShowHideContent() showHideContent.init() })
Use traits in new entity
<?php /* * This file is part of By Night. * (c) 2013-2020 Guillaume Sainthillier <guillaume.sainthillier@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace App\Entity; use App\Repository\ResetPasswordRequestRepository; use DateTimeInterface; use Doctrine\ORM\Mapping as ORM; use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordRequestInterface; use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordRequestTrait; /** * @ORM\Entity(repositoryClass=ResetPasswordRequestRepository::class) */ class ResetPasswordRequest implements ResetPasswordRequestInterface { use EntityIdentityTrait; use ResetPasswordRequestTrait; /** * @var User * @ORM\ManyToOne(targetEntity=User::class) * @ORM\JoinColumn(nullable=false) */ private User $user; public function __construct(User $user, DateTimeInterface $expiresAt, string $selector, string $hashedToken) { $this->user = $user; $this->initialize($expiresAt, $selector, $hashedToken); } public function getUser(): User { return $this->user; } }
<?php /* * This file is part of By Night. * (c) 2013-2020 Guillaume Sainthillier <guillaume.sainthillier@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace App\Entity; use App\Repository\ResetPasswordRequestRepository; use DateTimeInterface; use Doctrine\ORM\Mapping as ORM; use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordRequestInterface; use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordRequestTrait; /** * @ORM\Entity(repositoryClass=ResetPasswordRequestRepository::class) */ class ResetPasswordRequest implements ResetPasswordRequestInterface { use ResetPasswordRequestTrait; /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private int $id; /** * @ORM\ManyToOne(targetEntity=User::class) * @ORM\JoinColumn(nullable=false) */ private User $user; public function __construct(User $user, DateTimeInterface $expiresAt, string $selector, string $hashedToken) { $this->user = $user; $this->initialize($expiresAt, $selector, $hashedToken); } public function getId(): ?int { return $this->id; } public function getUser(): User { return $this->user; } }
Read config, in preparation for configurable behaviour
<?php @ini_set('display_errors', 'off'); define('DOCROOT', rtrim(realpath(dirname(__FILE__) . '/../../../'), '/')); define('DOMAIN', rtrim(rtrim($_SERVER['HTTP_HOST'], '/') . str_replace('/extensions/less_compiler/lib', NULL, dirname($_SERVER['PHP_SELF'])), '/')); // Include some parts of the engine require_once(DOCROOT . '/symphony/lib/boot/bundle.php'); require_once(CONFIG); require_once('dist/lessc.inc.php'); function processParams($string){ $param = (object)array( 'file' => 0 ); if(preg_match_all('/^(.+)$/i', $string, $matches, PREG_SET_ORDER)){ $param->file = $matches[0][1]; } return $param; } $param = processParams($_GET['param']); header('Content-type: text/css'); $lc = new lessc(WORKSPACE . '/' . $param->file); echo $lc->parse(); exit;
<?php @ini_set('display_errors', 'off'); define('DOCROOT', rtrim(realpath(dirname(__FILE__) . '/../../../'), '/')); define('DOMAIN', rtrim(rtrim($_SERVER['HTTP_HOST'], '/') . str_replace('/extensions/less_compiler/lib', NULL, dirname($_SERVER['PHP_SELF'])), '/')); // Include some parts of the engine require_once(DOCROOT . '/symphony/lib/boot/bundle.php'); require_once('dist/lessc.inc.php'); function processParams($string){ $param = (object)array( 'file' => 0 ); if(preg_match_all('/^(.+)$/i', $string, $matches, PREG_SET_ORDER)){ $param->file = $matches[0][1]; } return $param; } $param = processParams($_GET['param']); header('Content-type: text/css'); $lc = new lessc(WORKSPACE . '/' . $param->file); echo $lc->parse(); exit;
Check the copy model for failure
from test.integration.base import DBTIntegrationTest, use_profile import textwrap import yaml class TestBigqueryCopyTableFails(DBTIntegrationTest): @property def schema(self): return "bigquery_test_022" @property def models(self): return "copy-failing-models" @property def profile_config(self): return self.bigquery_profile() @property def project_config(self): return yaml.safe_load(textwrap.dedent('''\ config-version: 2 models: test: original: materialized: table copy_bad_materialization: materialized: copy ''')) @use_profile('bigquery') def test__bigquery_copy_table_fails(self): results = self.run_dbt(expect_pass=False) self.assertEqual(len(results), 2) self.assertTrue(results[1].error)
from test.integration.base import DBTIntegrationTest, use_profile import textwrap import yaml class TestBigqueryCopyTableFails(DBTIntegrationTest): @property def schema(self): return "bigquery_test_022" @property def models(self): return "copy-failing-models" @property def profile_config(self): return self.bigquery_profile() @property def project_config(self): return yaml.safe_load(textwrap.dedent('''\ config-version: 2 models: test: original: materialized: table copy_bad_materialization: materialized: copy ''')) @use_profile('bigquery') def test__bigquery_copy_table_fails(self): results = self.run_dbt(expect_pass=False) self.assertEqual(len(results), 2) self.assertTrue(results[0].error)
Correct call to remove token from sessionStorage
if (!window.fetch) { require('whatwg-fetch'); window.fetch = fetch; } const getAuthorizationField = () => { let token = window.sessionStorage.getItem('token'); if (token !== null) { return 'token ' + token; } else { return null; } }; const fetcher = (path, opts) => fetch(path, opts) .then(resp => { if (resp.ok) { return resp; } else { if (resp.status === 401) { // Unauthorized, remove token window.sessionStorage.removeItem('token') } throw resp; } }); const getJSON = (path) => fetcher(path, { headers: new Headers({ 'Authorization': getAuthorizationField() }) }).then(res => res.json()); const postJSON = (path, data) => fetcher(path, { method: 'POST', body: JSON.stringify(data), headers: new Headers({ 'Content-Type': 'application/json', 'Authorization': getAuthorizationField() }) }); module.exports = { getJSON, postJSON };
if (!window.fetch) { require('whatwg-fetch'); window.fetch = fetch; } const getAuthorizationField = () => { let token = window.sessionStorage.getItem('token'); if (token !== null) { return 'token ' + token; } else { return null; } }; const fetcher = (path, opts) => fetch(path, opts) .then(resp => { if (resp.ok) { return resp; } else { if (resp.status === 401) { // Unauthorized, remove token window.sessionStorage.getItem('token') } throw resp; } }); const getJSON = (path) => fetcher(path, { headers: new Headers({ 'Authorization': getAuthorizationField() }) }).then(res => res.json()); const postJSON = (path, data) => fetcher(path, { method: 'POST', body: JSON.stringify(data), headers: new Headers({ 'Content-Type': 'application/json', 'Authorization': getAuthorizationField() }) }); module.exports = { getJSON, postJSON };
Update with reference to global nav partial
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-type-scale/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-type-scale/tachyons-type-scale.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_type-scale.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/type-scale/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/typography/scale/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-type-scale/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-type-scale/tachyons-type-scale.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_type-scale.css', 'utf8') var template = fs.readFileSync('./templates/docs/type-scale/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS }) fs.writeFileSync('./docs/typography/scale/index.html', html)
Add @ignore annotation so alignmentfilegenerator doesn't try to get run as a test git-svn-id: b5cf87c434d9ee7c8f18865e4378c9faabe04646@2010 17392f64-ead8-4cea-ae29-09b3ab513800
package util; import org.junit.Ignore; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; /** * Generates alignment files (.aligned format) for testing * * @author Jim Robinson * @date 3/2/12 */ @Ignore public class AlignmentFileGenerator { public static void main(String[] args) throws IOException { String outputFile = "test.aligned"; String chr = "chr1"; int averageDepth = 1000; int readSize = 100; int interval = 1000; PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(outputFile)); int averageReadsPerPosition = averageDepth / readSize; int startPosition = 100; // arbitrary for (int pos = startPosition; pos < startPosition + interval; pos++) { int readCount = (int) (averageReadsPerPosition * 2 * Math.random()); while (readCount-- > 0) { pw.println(chr + "\t" + pos + "\t" + (pos + readSize) + "\t+"); } } } finally { if (pw != null) pw.close(); } } }
package util; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; /** * Generates alignment files (.aligned format) for testing * * @author Jim Robinson * @date 3/2/12 */ public class AlignmentFileGenerator { public static void main(String[] args) throws IOException { String outputFile = "test.aligned"; String chr = "chr1"; int averageDepth = 1000; int readSize = 100; int interval = 1000; PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(outputFile)); int averageReadsPerPosition = averageDepth / readSize; int startPosition = 100; // arbitrary for(int pos = startPosition; pos < startPosition + interval; pos++) { int readCount = (int) (averageReadsPerPosition * 2 * Math.random()); while(readCount-- > 0) { pw.println(chr + "\t" + pos + "\t" + (pos + readSize) + "\t+"); } } } finally { if (pw != null) pw.close(); } } }
Update package version to 1.0.0
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="pyslicer", version="1.0.0", author="SlicingDice LLC", author_email="help@slicingdice.com", description="Official Python client for SlicingDice, Data Warehouse and Analytics Database as a Service.", install_requires=["requests", "ujson"], license="BSD", keywords="slicingdice slicing dice data analysis analytics database", packages=[ 'pyslicer', 'pyslicer.core', 'pyslicer.utils', ], package_dir={'pyslicer': 'pyslicer'}, long_description=read('README.md'), classifiers=[ "Programming Language :: Python :: 2.7", "Topic :: Scientific/Engineering :: Information Analysis", ], )
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="pyslicer", version="0.1.1", author="SlicingDice LLC", author_email="help@slicingdice.com", description="Official Python client for SlicingDice, Data Warehouse and Analytics Database as a Service.", install_requires=["requests", "ujson"], license="BSD", keywords="slicingdice slicing dice data analysis analytics database", packages=[ 'pyslicer', 'pyslicer.core', 'pyslicer.utils', ], package_dir={'pyslicer': 'pyslicer'}, long_description=read('README.md'), classifiers=[ "Programming Language :: Python :: 2.7", "Topic :: Scientific/Engineering :: Information Analysis", ], )
Add a subtle gradient to the header
<section class="hero {{ $theme }} is-bold"> <div class="hero-body"> <div class="container"> <div class="columns is-mobile"> <div class="column is-3 has-text-right"> <a href="{{ url('/') }}"><img src="logo-w.svg" alt="logo" id="logo"></a> </div> <div class="column"> <h1 class="title"> <a href="{{ url('/') }}"> {{ $title = config('app.name') }} </a> </h1> <h2 class="subtitle"> {{ $subtitle }} </h2> </div> </div> </div> </div> </section>
<section class="hero {{ $theme }}"> <div class="hero-body"> <div class="container"> <div class="columns is-mobile"> <div class="column is-3 has-text-right"> <a href="{{ url('/') }}"><img src="logo-w.svg" alt="logo" id="logo"></a> </div> <div class="column"> <h1 class="title"> <a href="{{ url('/') }}"> {{ $title = config('app.name') }} </a> </h1> <h2 class="subtitle"> {{ $subtitle }} </h2> </div> </div> </div> </div> </section>
Simplify and strengthen specialist guide hide/display page ccode. If the page for the hash can't be found, the first page is shown, preventing js errors if people hack in different hashes (or click on old links)
$(function() { var container = $(".specialistguide .govspeak"); var navigation = $(".specialistguide #document_sections"); container.splitIntoPages("h2"); pages = container.find(".page"); pages.hide(); var showPage = function() { var heading = $(location.hash); if (heading.length == 0) { pages.first().show(); return; } if (heading.is(":visible")) { return; } pages.hide(); heading.parents(".page").show(); $('html, body').animate({scrollTop:heading.offset().top}, 0); } navigation.find(">li").each(function(el){ var li = $(this), pageNav = li.find('>ol'), chapterSelector = '#' + li.find('>a').attr('href').split('#')[1], inPageNavigation = $("<div class='in-page-navigation'><h3>On this page</h3></div>"); if (pageNav.length > 0) { inPageNavigation.append(pageNav); $(chapterSelector).after(inPageNavigation); } }); $(window).hashchange(showPage) $(window).hashchange(); })
$(function() { var container = $(".specialistguide .govspeak"); var navigation = $(".specialistguide #document_sections"); container.splitIntoPages("h2"); pages = container.find(".page"); pages.hide(); var showDefaultPage = function() { pages.first().show(); } var showPage = function(hash) { var heading = $(hash); if (heading.is(":visible")) { return; } pages.hide(); heading.parents(".page").show(); $('html, body').animate({scrollTop:heading.offset().top}, 0); } navigation.find(">li").each(function(el){ var li = $(this), pageNav = li.find('>ol'), chapterSelector = '#' + li.find('>a').attr('href').split('#')[1], inPageNavigation = $("<div class='in-page-navigation'><h3>On this page</h3></div>"); if (pageNav.length > 0) { inPageNavigation.append(pageNav); $(chapterSelector).after(inPageNavigation); } }); $(window).hashchange(function() { if ((location.hash == "") || (location.hash == "#undefined")) { showDefaultPage(); } else { showPage(location.hash); } }) $(window).hashchange(); })
Send location only when printing exception (Avoid leaking ID/UUID)
""" exceptions - Core exceptions """ class InvalidMembership(Exception): """ The membership provided is not valid """ pass class SourceNotFound(Exception): """ InstanceSource doesn't have an associated source. """ pass class RequestLimitExceeded(Exception): """ A limit was exceeded for the specific request """ pass class ProviderLimitExceeded(Exception): """ A limit was exceeded for the specific provider """ pass class ProviderNotActive(Exception): """ The provider that was requested is not active """ def __init__(self, provider, *args, **kwargs): self.message = "Cannot create driver on an inactive provider: %s" \ % (provider.location,) pass
""" exceptions - Core exceptions """ class InvalidMembership(Exception): """ The membership provided is not valid """ pass class SourceNotFound(Exception): """ InstanceSource doesn't have an associated source. """ pass class RequestLimitExceeded(Exception): """ A limit was exceeded for the specific request """ pass class ProviderLimitExceeded(Exception): """ A limit was exceeded for the specific provider """ pass class ProviderNotActive(Exception): """ The provider that was requested is not active """ def __init__(self, provider, *args, **kwargs): self.message = "Cannot create driver on an inactive provider:%s" \ % (provider,) pass
Add POSIX compliant newline at end of generated JSON file.
var fs = require('fs'); var async = require('async'); var os = require('os'); module.exports = function (path, data, callback) { function load (callback) { fs.readFile(path, 'utf8', callback); } function parse (content, callback) { try { var json_data = JSON.parse(content); callback(null, json_data); } catch (error) { callback(error); } } function update (json_data, callback) { for (key in data) { json_data[key] = data[key]; } callback(null, json_data); } function save (json_data, callback) { var content = JSON.stringify(json_data, null, ' ') + os.EOL; fs.writeFile(path, content, 'utf8', callback); } async.waterfall([ load, parse, update, save ], function (error, result) { callback(error); }); };
var fs = require('fs'); var async = require('async'); module.exports = function (path, data, callback) { function load (callback) { fs.readFile(path, 'utf8', callback); } function parse (content, callback) { try { var json_data = JSON.parse(content); callback(null, json_data); } catch (error) { callback(error); } } function update (json_data, callback) { for (key in data) { json_data[key] = data[key]; } callback(null, json_data); } function save (json_data, callback) { var content = JSON.stringify(json_data, null, ' '); fs.writeFile(path, content, 'utf8', callback); } async.waterfall([ load, parse, update, save ], function (error, result) { callback(error); }); };
Add the CommerceGuys solution ID.
<?php namespace CommerceGuys\AuthNet\DataTypes; class TransactionRequest extends BaseDataType { const AUTH_ONLY = 'authOnlyTransaction'; const PRIOR_AUTH_CAPTURE = 'priorAuthCaptureTransaction'; const AUTH_CAPTURE = 'authCaptureTransaction'; const CAPTURE_ONLY = 'captureOnlyTransaction'; const REFUND = 'refundTransaction'; const VOID = 'voidTransaction'; public function addPayment(CreditCard $creditCard) { $this->properties['payment'][$creditCard->getType()] = $creditCard->toArray(); $this->properties['solution']['id'] = 'A1000009'; } public function addOrder(Order $order) { $this->addDataType($order); } public function addLineItem(LineItem $lineItem) { $this->properties['lineItems'][$lineItem->getType()] = $lineItem->toArray(); } }
<?php namespace CommerceGuys\AuthNet\DataTypes; class TransactionRequest extends BaseDataType { const AUTH_ONLY = 'authOnlyTransaction'; const PRIOR_AUTH_CAPTURE = 'priorAuthCaptureTransaction'; const AUTH_CAPTURE = 'authCaptureTransaction'; const CAPTURE_ONLY = 'captureOnlyTransaction'; const REFUND = 'refundTransaction'; const VOID = 'voidTransaction'; public function addPayment(CreditCard $creditCard) { $this->properties['payment'][$creditCard->getType()] = $creditCard->toArray(); } public function addOrder(Order $order) { $this->addDataType($order); } public function addLineItem(LineItem $lineItem) { $this->properties['lineItems'][$lineItem->getType()] = $lineItem->toArray(); } }
Rename _config to config now
'use strict'; angular.module('offlineMode', []) .config(function ($httpProvider) { $httpProvider.interceptors.push('httpInterceptor'); }) .factory('httpInterceptor', function ($q) { var OFFLINE = location.search.indexOf('offline=true') > -1, config = { OFFLINE_DATA_PATH: '/offline_data', API_PATH: '/api' }; return { request: function(req) { if (OFFLINE && req) { if (req.url.indexOf(config.API_PATH) === 0) { var path = req.url.substring(config.API_PATH.length); req.url = config.OFFLINE_DATA_PATH + path + '.' + req.method.toLowerCase() + '.json'; } } return req || $q.when(req); }, config: config }; } );
'use strict'; angular.module('offlineMode', []) .config(function ($httpProvider) { $httpProvider.interceptors.push('httpInterceptor'); }) .factory('httpInterceptor', function ($q) { var OFFLINE = location.search.indexOf('offline=true') > -1, _config = { OFFLINE_DATA_PATH: '/offline_data', API_PATH: '/api' }; return { request: function(req) { if (OFFLINE && req) { if (req.url.indexOf(_config.API_PATH) === 0) { var path = req.url.substring(_config.API_PATH.length); req.url = _config.OFFLINE_DATA_PATH + path + '.' + req.method.toLowerCase() + '.json'; } } return req || $q.when(req); }, config: _config }; } );
Set default log level to 'info' in winston
const winston = require('winston'); module.exports = ({ level, transports: transports = [ { type: 'Console', options: { timestamp: true, colorize: process.env.NODE_ENV !== 'production', prettyPrint: process.env.NODE_ENV !== 'production', json: process.env.NODE_ENV === 'production', stringify: obj => JSON.stringify(obj), silent: process.env.NODE_ENV === 'test', level: 'info', }, }, ], }) => { if (level) { for (const transport of transports) { transport.options = transport.options || {}; transport.options.level = level; } } return (category, options) => { const logger = new winston.Logger(options); for (const transport of transports) { logger.add( winston.transports[transport.type], Object.assign({}, transport.options, { label: category }) ); } return logger; }; };
const winston = require('winston'); module.exports = ({ level, transports: transports = [ { type: 'Console', options: { timestamp: true, colorize: process.env.NODE_ENV !== 'production', prettyPrint: process.env.NODE_ENV !== 'production', json: process.env.NODE_ENV === 'production', stringify: obj => JSON.stringify(obj), silent: process.env.NODE_ENV === 'test', level: 'debug', }, }, ], }) => { if (level) { for (const transport of transports) { transport.options = transport.options || {}; transport.options.level = level; } } return (category, options) => { const logger = new winston.Logger(options); for (const transport of transports) { logger.add( winston.transports[transport.type], Object.assign({}, transport.options, { label: category }) ); } return logger; }; };
Use builder index as key for component instances
import * as React from "react"; /** * Component used as an indicator for build status. * Statuses are differentiated by alternative * styling rules. * @param props.status the build status. Partially determines * the styling of the rules. */ const StatusIndicator = (props) => { const className = 'indicator #'.replace('#', props.status); return ( <div className={className}></div> ); } /** * Component used to display information for a builder. * @param props.status the build status of the bot. * @param props.name the name of the bot. */ const Builder = (props) => { return ( <button className='builder' onClick={props.onClick}> <StatusIndicator status={props.status}/> {props.name} </button> ); } /** * Component used to display the list of builders that built a commit. * * @param props.builders * @param props.builders[].builder.status * @param props.builders[].builder.name */ export const BuilderGrid = (props) => { return ( <div className='builder-grid'> {props.builders.map((b, idx) => <Builder key={idx} status={b.status} name={b.name} onClick={props.onClick.bind(this, idx)}/>)} </div> ); }
import * as React from "react"; /** * Component used as an indicator for build status. * Statuses are differentiated by alternative * styling rules. * @param props.status the build status. Partially determines * the styling of the rules. */ const StatusIndicator = (props) => { const className = 'indicator #'.replace('#', props.status); return ( <div className={className}></div> ); } /** * Component used to display information for a builder. * @param props.status the build status of the bot. * @param props.name the name of the bot. */ const Builder = (props) => { return ( <button className='builder' onClick={props.onClick}> <StatusIndicator status={props.status}/> {props.name} </button> ); } /** * Component used to display the list of builders that built a commit. * * @param props.builders * @param props.builders[].builder.status * @param props.builders[].builder.name */ export const BuilderGrid = (props) => { return ( <div className='builder-grid'> {props.builders.map((b, idx) => <Builder status={b.status} name={b.name} onClick={props.onClick.bind(this, idx)}/>)} </div> ); }
Fix username parameter to match the name in the resource
define(function() { var ProjectCreationController = function($rootScope, $location, ProjectResource) { this.submit = function() { var newProject = new ProjectResource({ name: this.name, tags: this.tags }) newProject.$save({ username: $rootScope.globals.currentUser.username }, function success(project, headers) { $location.path('/projects/' + $rootScope.globals.currentUser.username + '/' + project.name) }, function error(response) { // Handle error with dialog }) } } ProjectCreationController.$inject = ['$rootScope', '$location', 'ProjectResource'] return ProjectCreationController })
define(function() { var ProjectCreationController = function($rootScope, $location, ProjectResource) { this.submit = function() { var newProject = new ProjectResource({ name: this.name, tags: this.tags }) newProject.$save({ user: $rootScope.globals.currentUser.username }, function success(project, headers) { $location.path('/projects/' + $rootScope.globals.currentUser.username + '/' + project.name) }, function error(response) { // Handle error with dialog }) } } ProjectCreationController.$inject = ['$rootScope', '$location', 'ProjectResource'] return ProjectCreationController })
Change multi-buildpack test from develop to master Co-authored-by: Don Nguyen <1487e49252176236e14c0d247a7bbbd5e8c39a5d@pivotal.io>
package integration_test import ( "path/filepath" "github.com/cloudfoundry/libbuildpack/cutlass" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("running supply buildpacks before the staticfile buildpack", func() { var app *cutlass.App AfterEach(func() { if app != nil { app.Destroy() } app = nil }) Context("the app is pushed once", func() { BeforeEach(func() { if ok, err := cutlass.ApiGreaterThan("2.65.1"); err != nil || !ok { Skip("API version does not have multi-buildpack support") } app = cutlass.New(filepath.Join(bpDir, "fixtures", "fake_supply_staticfile_app")) app.Buildpacks = []string{ "https://github.com/cloudfoundry/dotnet-core-buildpack#master", "staticfile_buildpack", } app.Disk = "1G" }) It("finds the supplied dependency in the runtime container", func() { PushAppAndConfirm(app) Expect(app.Stdout.String()).To(ContainSubstring("Supplying Dotnet Core")) Expect(app.GetBody("/")).To(ContainSubstring("This is an example app for Cloud Foundry that is only static HTML/JS/CSS assets.")) }) }) })
package integration_test import ( "path/filepath" "github.com/cloudfoundry/libbuildpack/cutlass" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("running supply buildpacks before the staticfile buildpack", func() { var app *cutlass.App AfterEach(func() { if app != nil { app.Destroy() } app = nil }) Context("the app is pushed once", func() { BeforeEach(func() { if ok, err := cutlass.ApiGreaterThan("2.65.1"); err != nil || !ok { Skip("API version does not have multi-buildpack support") } app = cutlass.New(filepath.Join(bpDir, "fixtures", "fake_supply_staticfile_app")) app.Buildpacks = []string{ "https://github.com/cloudfoundry/dotnet-core-buildpack#develop", "staticfile_buildpack", } app.Disk = "1G" }) It("finds the supplied dependency in the runtime container", func() { PushAppAndConfirm(app) Expect(app.Stdout.String()).To(ContainSubstring("Supplying Dotnet Core")) Expect(app.GetBody("/")).To(ContainSubstring("This is an example app for Cloud Foundry that is only static HTML/JS/CSS assets.")) }) }) })
Bring multis inline with each other
var get = require('./get'), getIn = require('./getIn'), assoc = require('./assoc'), dissoc = require('./dissoc'), assocIn = require('./assocIn'), dissocIn = require('./dissocIn'), deepMerge = require('./deepMerge'), update = require('./update'), updateIn = require('./updateIn'), merge = require('./merge'), util = require('./util'); function multiGet(obj, path, orValue) { if (util.isArray(path)) return getIn(obj, path, orValue); return get(obj, path, orValue); } function multiAssoc(obj, path, value) { if (util.isArray(path)) return assocIn(obj, path, value); return assoc(obj, path, value); } function multiDissoc(obj, path) { if (util.isArray(path)) return dissocIn(obj, path); return dissoc(obj, path); } function multiUpdate(obj, path, fn) { if (util.isArray(path)) return updateIn(obj, path, fn); return update(obj, path, fn); } module.exports = { get: multiGet, assoc: multiAssoc, dissoc: multiDissoc, update: multiUpdate, merge: merge, deepMerge: deepMerge };
var get = require('./get'), getIn = require('./getIn'), assoc = require('./assoc'), dissoc = require('./dissoc'), assocIn = require('./assocIn'), dissocIn = require('./dissocIn'), deepMerge = require('./deepMerge'), update = require('./update'), updateIn = require('./updateIn'), merge = require('./merge'), util = require('./util'); function multiGet(obj, path, orValue) { if (typeof path === 'string' || typeof path === 'number') return get(obj, path, orValue); return getIn(obj, path, orValue); } function multiAssoc(obj, path, value) { if (util.isArray(path)) return assocIn(obj, path, value); return assoc(obj, path, value); } function multiDissoc(obj, path) { if (util.isArray(path)) return dissocIn(obj, path); return dissoc(obj, path); } function multiUpdate(obj, path, fn) { if (typeof path === 'string' || typeof path === 'number') return update(obj, path, fn); return updateIn(obj, path, fn); } module.exports = { get: multiGet, assoc: multiAssoc, dissoc: multiDissoc, update: multiUpdate, merge: merge, deepMerge: deepMerge };
Remove todo and add comment
/* * Copyright (c) 2012 Mateusz Parzonka, Eric Bodden * 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: * Mateusz Parzonka - initial API and implementation */ package prm4j.indexing.realtime; import java.lang.ref.WeakReference; import prm4j.indexing.map.MinimalMapEntry; /** * A binding used by optimized indexing strategies. */ public interface LowLevelBinding extends prm4j.api.Binding, MinimalMapEntry<Object, LowLevelBinding>{ /** * Releases all resources used in the indexing data structure and/or notifies monitors about unreachability of the * parameter object. Amount of released resources can vary strongly with the implementation. */ void release(); /** * Register a map which uses this binding as key. * * @param nodeRef */ void registerNode(WeakReference<Node> nodeRef); boolean isDisabled(); void setDisabled(boolean disable); long getTimestamp(); void setTimestamp(long timestamp); }
/* * Copyright (c) 2012 Mateusz Parzonka, Eric Bodden * 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: * Mateusz Parzonka - initial API and implementation */ package prm4j.indexing.realtime; import java.lang.ref.WeakReference; import prm4j.indexing.map.MinimalMapEntry; /** * A binding used by optimized indexing strategies. */ public interface LowLevelBinding extends prm4j.api.Binding, MinimalMapEntry<Object, LowLevelBinding>{ /** * Releases all resources used in the indexing data structure and/or notifies monitors about unreachability of the * parameter object. Amount of released resources can vary strongly with the implementation. */ void release(); /** * Register a map where this binding is used. * * @param mapReference */ void registerNode(WeakReference<Node> nodeReference); // TODO resource registration boolean isDisabled(); void setDisabled(boolean disable); long getTimestamp(); void setTimestamp(long timestamp); }
Support Python 3.7, Django 2.2
#!/usr/bin/env python from codecs import open from setuptools import find_packages, setup with open('README.rst', 'r', 'utf-8') as f: readme = f.read() setup( name='django-paginationlinks', version='0.1.1', description='Django Pagination Links', long_description=readme, url='https://github.com/developersociety/django-paginationlinks', maintainer='The Developer Society', maintainer_email='studio@dev.ngo', platforms=['any'], packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.8', 'Framework :: Django :: 1.11', 'Framework :: Django :: 2.2', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], license='BSD', )
#!/usr/bin/env python from codecs import open from setuptools import find_packages, setup with open('README.rst', 'r', 'utf-8') as f: readme = f.read() setup( name='django-paginationlinks', version='0.1.1', description='Django Pagination Links', long_description=readme, url='https://github.com/developersociety/django-paginationlinks', maintainer='The Developer Society', maintainer_email='studio@dev.ngo', platforms=['any'], packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.8', 'Framework :: Django :: 1.11', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], license='BSD', )
Clear screen before displaying results
#! /usr/bin/env node /* * pilot-fish * https://github.com/jeffminnear/pilot-fish * * Copyright (c) 2016 Jeff Minnear * Licensed under the MIT license. */ 'use strict'; var program = require('commander'); var amazon = require('./amazon-scraper'); var gm = require('./green-man-scraper'); var gog = require('./gog-scraper'); var steam = require('./steam-scraper'); var clear = require('clear'); const chalk = require('chalk'); var colorLegend = "Prices in " + chalk.green("green") + " are current sale prices, shown next to their normal price in " + chalk.gray("gray") + "."; var divider = "=================================================================================="; program .version('0.0.1') .arguments('<title> [limit]') .action(function (title, limit) { program.title = title; program.limit = limit; }); program.parse(process.argv); if (program.title) { clear(); console.log(colorLegend + "\n" + divider); amazon(program); gm(program); gog(program); steam(program); } else { console.log(chalk.red("Sorry, you must specify a title\nFor example: pf 'dark souls'")); }
#! /usr/bin/env node /* * pilot-fish * https://github.com/jeffminnear/pilot-fish * * Copyright (c) 2016 Jeff Minnear * Licensed under the MIT license. */ 'use strict'; var program = require('commander'); var amazon = require('./amazon-scraper'); var gm = require('./green-man-scraper'); var gog = require('./gog-scraper'); var steam = require('./steam-scraper'); const chalk = require('chalk'); var colorLegend = "Prices in " + chalk.green("green") + " are current sale prices, shown next to their normal price in " + chalk.gray("gray") + "."; var divider = "=================================================================================="; program .version('0.0.1') .arguments('<title> [limit]') .action(function (title, limit) { program.title = title; program.limit = limit; }); program.parse(process.argv); if (program.title) { console.log(colorLegend + "\n" + divider); amazon(program); gm(program); gog(program); steam(program); } else { console.log(chalk.red("Sorry, you must specify a title\nFor example: pf 'dark souls'")); }
Make testcase work like expected
<?php /** * This file is part of phpDocumentor. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @copyright 2010-2017 Mike van Riel<mike@phpdoc.org> * @license http://www.opensource.org/licenses/mit-license.php MIT * @link http://phpdoc.org */ interface ExampleInterface { /** * Do something with $object and return that it worked * * @param \stdClass $object The object * @return bool */ public function doSomething(\stdClass $object); } class Example implements ExampleInterface { /** {@inheritdoc} */ public function doSomething(\stdClass $object) { // what ever return true; } } interface DeepExampleInterface extends ExampleInterface { /** * Convert $json to object and doSomething * * @param string $json * @return bool */ public function doSomethingJson($json); } class DeepExample extends Example implements DeepExampleInterface { /** {@inheritdoc} */ public function doSomethingJson($json) { return $this->doSomething(json_encode($json)); } /** {@inheritdoc} */ public function doSomething(\stdClass $object) { // do something really special return true; } }
<?php /** * This file is part of phpDocumentor. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @copyright 2010-2017 Mike van Riel<mike@phpdoc.org> * @license http://www.opensource.org/licenses/mit-license.php MIT * @link http://phpdoc.org */ interface ExampleInterface { /** * Do something with $object and return that it worked * * @param \stdClass $object The object * @return bool * @internal */ public function doSomething(\stdClass $object); } class Example implements ExampleInterface { /** {@inheritdoc} */ public function doSomething(\stdClass $object) { // what ever return true; } } interface DeepExampleInterface extends ExampleInterface { /** * Convert $json to object and doSomething * * @param string $json * @return bool */ public function doSomethingJson($json); } class DeepExample extends Example implements DeepExampleInterface { /** {@inheritdoc} */ public function doSomethingJson($json) { return $this->doSomething(json_encode($json)); } /** {@inheritdoc} */ public function doSomething(\stdClass $object) { // do something really special return true; } }
Extend game time by static methods to get parts of a time format Returns integer values for every time division like hours or minutes with the intention to be used for a "timer" like application
package de.gurkenlabs.litiengine; public class GameTime { private final IGameLoop gameLoop; public GameTime(final IGameLoop loop) { this.gameLoop = loop; } public long getDays() { return getDays(this.getMilliseconds()); } public long getHours() { return getHours(this.getMilliseconds()); } public long getMilliseconds() { return this.gameLoop.convertToMs(this.gameLoop.getTicks()); } public long getMinutes() { return getMinutes(this.getMilliseconds()); } public long getSeconds() { return getSeconds(this.getMilliseconds()); } public long getYears() { return getYears(this.getMilliseconds()); } public static long getDays(long ms) { return ms / 1000 / 60 / 60 / 24 % 365; } public static long getHours(long ms) { return ms / 1000 / 60 / 60 % 24; } public static long getMinutes(long ms) { return ms / 1000 / 60 % 60; } public static long getSeconds(long ms) { return ms / 1000 % 60; } public static long getMilliSeconds(long ms) { return ms % 1000; } public static long getYears(long ms) { return ms / 1000 / 60 / 60 / 24 / 365; } }
package de.gurkenlabs.litiengine; public class GameTime { private final IGameLoop gameLoop; public GameTime(final IGameLoop loop) { this.gameLoop = loop; } public long getDays() { return this.getMilliseconds() / 1000 / 60 / 60 / 24 % 365; } public long getHours() { return this.getMilliseconds() / 1000 / 60 / 60 % 24; } public long getMilliseconds() { return this.gameLoop.convertToMs(this.gameLoop.getTicks()); } public long getMinutes() { return this.getMilliseconds() / 1000 / 60 % 60; } public long getSeconds() { return this.getMilliseconds() / 1000 % 60; } public long getYears() { return this.getMilliseconds() / 1000 / 60 / 60 / 24 / 365; } }
Load src file as helper for jasmine
var gulp = require('gulp'); var apigen = require('gulp-apigen'); var phpunit = require('gulp-phpunit'); var spawn = require('child_process').spawn; var jasmine = require('gulp-jasmine'); var cover = require('gulp-coverage'); gulp.task('apigen', function() { gulp.src('apigen.neon').pipe(apigen('./vendor/bin/apigen')); }); gulp.task('phpunit', function() { gulp.src('phpunit.xml').pipe(phpunit('./vendor/bin/phpunit')); }); gulp.task('phpcs', function () { spawn('vendor/bin/phpcs', [], {stdio: 'inherit'}); }); gulp.task('php', ['phpcs','apigen','phpunit'], function () { }); gulp.task('jasmine', function() { gulp.src(['test/js/*Spec.js']) .pipe(cover.instrument({ pattern: ['src/webroot/js/*.js'] })) .pipe(jasmine({'config': {'spec_dir': './', 'helpers': ['src/webroot/js/organismDetails.js']}})) .pipe(cover.gather()) .pipe(cover.format()) .pipe(gulp.dest('test/js/cover'));; }); gulp.task('default', function() { // place code for your default task here });
var gulp = require('gulp'); var apigen = require('gulp-apigen'); var phpunit = require('gulp-phpunit'); var spawn = require('child_process').spawn; var jasmine = require('gulp-jasmine'); var cover = require('gulp-coverage'); gulp.task('apigen', function() { gulp.src('apigen.neon').pipe(apigen('./vendor/bin/apigen')); }); gulp.task('phpunit', function() { gulp.src('phpunit.xml').pipe(phpunit('./vendor/bin/phpunit')); }); gulp.task('phpcs', function () { spawn('vendor/bin/phpcs', [], {stdio: 'inherit'}); }); gulp.task('php', ['phpcs','apigen','phpunit'], function () { }); gulp.task('jasmine', function() { gulp.src('test/js/*Spec.js') .pipe(cover.instrument({ pattern: ['src/webroot/js/*.js']//, // debugDirectory: 'debug' })) .pipe(jasmine()) .pipe(cover.gather()) .pipe(cover.format()) .pipe(gulp.dest('test/js/cover'));; }); gulp.task('default', function() { // place code for your default task here });
Clear the search query on focus as well and some minor JS clean up.
$(document).ready(function() { $('#flash_success, #flash_notice, #flash_error').each(function() { humanMsg.displayMsg($(this).text()); }); if (window.location.href.search(/query=/) == -1) { $('#query').one('click, focus', function() { $(this).val(''); }); } $(document).bind('keyup', function(event) { if ($(event.target).is(':input')) { return; } if (event.which == 83) { $('#query').focus(); } }); if ($('.count').length > 0) { setInterval(function() { $.getJSON('/api/v1/downloads.json', function(data) { $('.count strong') .text(number_with_delimiter(data['total']) + ' downloads'); }); }, 5000); } }); // http://kevinvaldek.com/number-with-delimiter-in-javascript function number_with_delimiter(number, delimiter) { number = number + '', delimiter = delimiter || ','; var split = number.split('.'); split[0] = split[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + delimiter); return split.join('.'); };
$(document).ready(function() { var divs = "#flash_success, #flash_notice, #flash_error"; $(divs).each(function() { humanMsg.displayMsg($(this).text()); return false; }); if (window.location.href.search(/query=/) == -1) { $('#query').one('click', function() { $(this).val(''); }); } $(document).bind('keyup', function(event) { if ($(event.target).is(':input')) { return; } if (event.which == 83) { $('#query').focus(); } }); if ($('.count').length > 0) { setInterval(function() { $.getJSON("/api/v1/downloads.json", function(data) { $(".count strong").text(number_with_delimiter(data['total']) + " downloads"); }); }, 5000); } }); // http://kevinvaldek.com/number-with-delimiter-in-javascript function number_with_delimiter(number, delimiter) { number = number + '', delimiter = delimiter || ','; var split = number.split('.'); split[0] = split[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + delimiter); return split.join('.'); };
Add network-information plugin. Related to GH-885
#!/usr/bin/env node var fs = require('fs-extra'); var async = require('async'); var exec = require('child_process').exec; var colors = require('colors'); function doExec(text) { return function (done) { exec(text, function (err, stdout, stderr) { if (stdout) console.log(stdout.grey); if (stderr) console.log(stderr.red); done(err); }); }; } // Let's get started console.log('starting build...'.bgMagenta); // Copy assets to www require('./copy-assets'); // Clean fs.removeSync('./platforms'); fs.removeSync('./plugins'); async.series([ doExec('cordova platform add android firefoxos ios'), doExec('cordova plugin add https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin.git'), doExec('cordova plugin add org.apache.cordova.network-information'), // PR in progress for org.apache.cordova.camera to add dataURIs for ffos doExec('cordova plugin add https://github.com/k88hudson/cordova-plugin-camera.git') ], function (err) { // Done! if (err) return console.log('finished build, but there were errors!'.bgMagenta); console.log('finished build with no errors.'.bgMagenta); });
#!/usr/bin/env node var fs = require('fs-extra'); var async = require('async'); var exec = require('child_process').exec; var colors = require('colors'); function doExec(text) { return function (done) { exec(text, function (err, stdout, stderr) { if (stdout) console.log(stdout.grey); if (stderr) console.log(stderr.red); done(err); }); }; } // Let's get started console.log('starting build...'.bgMagenta); // Copy assets to www require('./copy-assets'); // Clean fs.removeSync('./platforms'); fs.removeSync('./plugins'); async.series([ doExec('cordova platform add android firefoxos ios'), doExec('cordova plugin add https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin.git'), // PR in progress for org.apache.cordova.camera to add dataURIs for ffos doExec('cordova plugin add https://github.com/k88hudson/cordova-plugin-camera.git') ], function (err) { // Done! if (err) return console.log('finished build, but there were errors!'.bgMagenta); console.log('finished build with no errors.'.bgMagenta); });
Add type annotations to prevent issues with planned Flow changes Summary: We're planning a fix in Flow (D24112595) that uncovers some existing errors that were previously suppressed. Adding these annotations prevents them from surfacing during the deploy of the fix. Changelog: [Internal] Reviewed By: dsainati1 Differential Revision: D24147994 fbshipit-source-id: fef59a9427da6db79d4824e39768dd5ad0a8d1a3
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow strict-local */ 'use strict'; import type {DangerouslyImpreciseStyle} from './StyleSheet'; const OUTER_PROPS = Object.assign(Object.create(null), { margin: true, marginHorizontal: true, marginVertical: true, marginBottom: true, marginTop: true, marginLeft: true, marginRight: true, flex: true, flexGrow: true, flexShrink: true, flexBasis: true, alignSelf: true, height: true, minHeight: true, maxHeight: true, width: true, minWidth: true, maxWidth: true, position: true, left: true, right: true, bottom: true, top: true, transform: true, }); function splitLayoutProps( props: ?DangerouslyImpreciseStyle, ): { outer: DangerouslyImpreciseStyle, inner: DangerouslyImpreciseStyle, ... } { const inner = {}; const outer = {}; if (props) { Object.keys(props).forEach((k: string) => { const value = props[k]; if (OUTER_PROPS[k]) { outer[k] = value; } else { inner[k] = value; } }); } return {outer, inner}; } module.exports = splitLayoutProps;
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow strict-local */ 'use strict'; import type {DangerouslyImpreciseStyle} from './StyleSheet'; const OUTER_PROPS = Object.assign(Object.create(null), { margin: true, marginHorizontal: true, marginVertical: true, marginBottom: true, marginTop: true, marginLeft: true, marginRight: true, flex: true, flexGrow: true, flexShrink: true, flexBasis: true, alignSelf: true, height: true, minHeight: true, maxHeight: true, width: true, minWidth: true, maxWidth: true, position: true, left: true, right: true, bottom: true, top: true, transform: true, }); function splitLayoutProps( props: ?DangerouslyImpreciseStyle, ): { outer: DangerouslyImpreciseStyle, inner: DangerouslyImpreciseStyle, ... } { const inner = {}; const outer = {}; if (props) { Object.keys(props).forEach(k => { const value: $ElementType<DangerouslyImpreciseStyle, typeof k> = props[k]; if (OUTER_PROPS[k]) { outer[k] = value; } else { inner[k] = value; } }); } return {outer, inner}; } module.exports = splitLayoutProps;
Use proper method name for Pheanstalk
<?php namespace Illuminate\Queue\Connectors; use Pheanstalk\Connection; use Pheanstalk\Pheanstalk; use Illuminate\Queue\BeanstalkdQueue; class BeanstalkdConnector implements ConnectorInterface { /** * Establish a queue connection. * * @param array $config * @return \Illuminate\Contracts\Queue\Queue */ public function connect(array $config) { return new BeanstalkdQueue( $this->pheanstalk($config), $config['queue'], $config['retry_after'] ?? Pheanstalk::DEFAULT_TTR, $config['block_for'] ?? 0 ); } /** * Create a Pheanstalk instance. * * @param array $config * @return \Pheanstalk\Pheanstalk */ protected function pheanstalk(array $config) { return Pheanstalk::create( $config['host'], $config['port'] ?? Pheanstalk::DEFAULT_PORT, $config['timeout'] ?? Connection::DEFAULT_CONNECT_TIMEOUT ); } }
<?php namespace Illuminate\Queue\Connectors; use Pheanstalk\Connection; use Pheanstalk\Pheanstalk; use Illuminate\Queue\BeanstalkdQueue; class BeanstalkdConnector implements ConnectorInterface { /** * Establish a queue connection. * * @param array $config * @return \Illuminate\Contracts\Queue\Queue */ public function connect(array $config) { return new BeanstalkdQueue( $this->pheanstalk($config), $config['queue'], $config['retry_after'] ?? Pheanstalk::DEFAULT_TTR, $config['block_for'] ?? 0 ); } /** * Create a Pheanstalk instance. * * @param array $config * @return \Pheanstalk\Pheanstalk */ protected function pheanstalk(array $config) { return Pheanstalk::connect( $config['host'], $config['port'] ?? Pheanstalk::DEFAULT_PORT, $config['timeout'] ?? Connection::DEFAULT_CONNECT_TIMEOUT ); } }
BAP-1626: Customize multi-step setup forms - added "client_validation" form type option (comments fixed)
<?php namespace Oro\Bundle\FormBundle\Form\Extension; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\FormView; use Symfony\Component\Form\FormInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ClientValidationExtension extends AbstractTypeExtension { /** * Add the client_validation option * * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setOptional(array('client_validation')); } /** * Pass the client validation flag to the view * * @param FormView $view * @param FormInterface $form * @param array $options */ public function buildView(FormView $view, FormInterface $form, array $options) { // set an "client_validation" variable that will be available when rendering this field $view->vars['client_validation'] = isset($options['client_validation']) ? (bool) $options['client_validation'] : true; } /** * Returns the name of the type being extended. * * @return string The name of the type being extended */ public function getExtendedType() { return 'form'; } }
<?php namespace Oro\Bundle\FormBundle\Form\Extension; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\FormView; use Symfony\Component\Form\FormInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ClientValidationExtension extends AbstractTypeExtension { /** * Add the image_path option * * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setOptional(array('client_validation')); } /** * Pass the client validation flag to the view * * @param FormView $view * @param FormInterface $form * @param array $options */ public function buildView(FormView $view, FormInterface $form, array $options) { // set an "image_url" variable that will be available when rendering this field $view->vars['client_validation'] = isset($options['client_validation']) ? (bool) $options['client_validation'] : true; } /** * Returns the name of the type being extended. * * @return string The name of the type being extended */ public function getExtendedType() { return 'form'; } }
[Update] Enable Cross Origin Resource Sharing
"""Module containing factory function for the application""" from flask import Flask, redirect from flask_restplus import Api from flask_cors import CORS from config import app_config from api_v1 import Blueprint_apiV1 from api_v1.models import db Api_V1 = Api( app=Blueprint_apiV1, title="Shopping List Api", description="An API for a Shopping List Application", contact="machariamarigi@gmail.com" ) def create_app(environment): """Factory function for the application""" app = Flask(__name__) app.config.from_object(app_config[environment]) db.init_app(app) CORS(app) app.register_blueprint(Blueprint_apiV1) # add namespaces here from api_v1 import authenticate Api_V1.add_namespace(authenticate.auth) from api_v1 import endpoints Api_V1.add_namespace(endpoints.sh_ns) @app.route('/') def reroute(): """Method to route root path to /api/v1""" return redirect('/api/v1') return app
"""Module containing factory function for the application""" from flask import Flask, redirect from flask_restplus import Api from config import app_config from api_v1 import Blueprint_apiV1 from api_v1.models import db Api_V1 = Api( app=Blueprint_apiV1, title="Shopping List Api", description="An API for a Shopping List Application", contact="machariamarigi@gmail.com" ) def create_app(environment): """Factory function for the application""" app = Flask(__name__) app.config.from_object(app_config[environment]) db.init_app(app) app.register_blueprint(Blueprint_apiV1) # add namespaces here from api_v1 import authenticate Api_V1.add_namespace(authenticate.auth) from api_v1 import endpoints Api_V1.add_namespace(endpoints.sh_ns) @app.route('/') def reroute(): """Method to route root path to /api/v1""" return redirect('/api/v1') return app
Disable service composition plugin connection
package eu.scasefp7.eclipse.core.handlers; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; /** * A command handler for exporting all service compositions to the linked ontology. * * @author themis */ public class CompileServiceCompositionsHandler extends CommandExecutorHandler { /** * This function is called when the user selects the menu item. It populates the linked ontology. * * @param event the event containing the information about which file was selected. * @return the result of the execution which must be {@code null}. */ @Override public Object execute(ExecutionEvent event) throws ExecutionException { if (getProjectOfExecutionEvent(event) != null) { // executeCommand("eu.scasefp7.eclipse.servicecomposition.commands.exportAllToOntology"); return null; } else { throw new ExecutionException("No project selected"); } } }
package eu.scasefp7.eclipse.core.handlers; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; /** * A command handler for exporting all service compositions to the linked ontology. * * @author themis */ public class CompileServiceCompositionsHandler extends CommandExecutorHandler { /** * This function is called when the user selects the menu item. It populates the linked ontology. * * @param event the event containing the information about which file was selected. * @return the result of the execution which must be {@code null}. */ @Override public Object execute(ExecutionEvent event) throws ExecutionException { if (getProjectOfExecutionEvent(event) != null) { executeCommand("eu.scasefp7.eclipse.servicecomposition.commands.exportAllToOntology"); return null; } else { throw new ExecutionException("No project selected"); } } }
Use jQuery's on/off instead of bind/unbind and specify proper events.
jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function ( oSettings, iDelay ) { var _that = this; if ( iDelay === undefined ) { iDelay = 250; } this.each( function ( i ) { $.fn.dataTableExt.iApiIndex = i; var $this = this, oTimerId = null, sPreviousSearch = null, anControl = $( 'input', _that.fnSettings().aanFeatures.f ); anControl.off( 'keyup search input' ).on( 'keyup search input', function() { var $$this = $this; if (sPreviousSearch === null || sPreviousSearch != anControl.val()) { window.clearTimeout(oTimerId); sPreviousSearch = anControl.val(); oTimerId = window.setTimeout(function() { $.fn.dataTableExt.iApiIndex = i; _that.fnFilter( anControl.val() ); }, iDelay); } }); return this; } ); return this; };
jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function ( oSettings, iDelay ) { var _that = this; if ( iDelay === undefined ) { iDelay = 250; } this.each( function ( i ) { $.fn.dataTableExt.iApiIndex = i; var $this = this, oTimerId = null, sPreviousSearch = null, anControl = $( 'input', _that.fnSettings().aanFeatures.f ); anControl.unbind( 'keyup' ).bind( 'keyup', function() { var $$this = $this; if (sPreviousSearch === null || sPreviousSearch != anControl.val()) { window.clearTimeout(oTimerId); sPreviousSearch = anControl.val(); oTimerId = window.setTimeout(function() { $.fn.dataTableExt.iApiIndex = i; _that.fnFilter( anControl.val() ); }, iDelay); } }); return this; } ); return this; };
Fix issues after upgraded dependency
<?php namespace blink\laravel\database\commands; use \Illuminate\Database\Migrations\DatabaseMigrationRepository; use \Illuminate\Database\Migrations\MigrationCreator; use \Illuminate\Database\Migrations\Migrator; use \Illuminate\Filesystem\Filesystem; use \Symfony\Component\Console\Input\InputArgument; use \Symfony\Component\Console\Input\InputInterface; use \Symfony\Component\Console\Output\OutputInterface; class ResetCommand extends BaseCommand { public $name = 'migrate:reset'; public $description = 'Rollback all database migrations'; protected function execute(InputInterface $input, OutputInterface $output) { app()->bootstrap(); $migrator = $this->getMigrator(); if (!$this->migrator->repositoryExists()) { $output->writeln('<comment>Migration table not found.</comment>'); return; } $migrator->reset($this->getMigrationPath(), false); foreach ($migrator->getNotes() as $note) { $output->writeln($note); } } }
<?php namespace blink\laravel\database\commands; use \Illuminate\Database\Migrations\DatabaseMigrationRepository; use \Illuminate\Database\Migrations\MigrationCreator; use \Illuminate\Database\Migrations\Migrator; use \Illuminate\Filesystem\Filesystem; use \Symfony\Component\Console\Input\InputArgument; use \Symfony\Component\Console\Input\InputInterface; use \Symfony\Component\Console\Output\OutputInterface; class ResetCommand extends BaseCommand { public $name = 'migrate:reset'; public $description = 'Rollback all database migrations'; protected function execute(InputInterface $input, OutputInterface $output) { app()->bootstrap(); $migrator = $this->getMigrator(); if (!$this->migrator->repositoryExists()) { $output->writeln('<comment>Migration table not found.</comment>'); return; } $migrator->reset(false); foreach ($migrator->getNotes() as $note) { $output->writeln($note); } } }
Change get min, max value method
from pymongo import MongoClient def main(): client = MongoClient() db = client.cityhotspots db.drop_collection('dineroptions') diners_collection = db.diners doc = {} diner_options_collection = db.dineroptions doc['categories'] = diners_collection.distinct('category') doc['categories'].insert(0, 'Tất cả') doc['cuisines'] = diners_collection.distinct('cuisine') doc['cuisines'].insert(0, 'Tất cả') doc['districts'] = diners_collection.distinct('address.district') doc['districts'].insert(0, 'Tất cả') doc['price_max'] = diners_collection.find_one(sort=[("price_max", -1)])['price_max'] doc['price_min'] = diners_collection.find_one(sort=[("price_min", 1)])['price_min'] diner_options_collection.insert(doc) if __name__ == '__main__': main()
from pymongo import MongoClient def main(): client = MongoClient() db = client.cityhotspots db.drop_collection('dineroptions') diners_collection = db.diners doc = {} diner_options_collection = db.dineroptions doc['categories'] = diners_collection.distinct('category') doc['categories'].insert(0, 'Tất cả') doc['cuisines'] = diners_collection.distinct('cuisine') doc['cuisines'].insert(0, 'Tất cả') doc['districts'] = diners_collection.distinct('address.district') doc['districts'].insert(0, 'Tất cả') doc['price_max'] = list(diners_collection.aggregate([{ "$group": { "_id": None, "value": {"$max": "$price_max"} } }]))[0]['value'] doc['price_min'] = list(diners_collection.aggregate([{ "$group": { "_id": None, "value": {"$min": "$price_min"} } }]))[0]['value'] diner_options_collection.insert(doc) if __name__ == '__main__': main()
Add mocha env to the eslint config
const config = { extends: ['standard', 'prettier', 'prettier/standard'], plugins: ['import', 'mocha'], env: { mocha: true }, rules: { 'import/no-extraneous-dependencies': [ 'error', { devDependencies: [ '**/test/**/*.js', '**/bootstrap-unexpected-markdown.js' ], optionalDependencies: false, peerDependencies: false } ], 'mocha/no-exclusive-tests': 'error', 'mocha/no-nested-tests': 'error', 'mocha/no-identical-title': 'error' }, parserOptions: { ecmaVersion: 9, ecmaFeatures: { globalReturn: true, jsx: true }, sourceType: 'module' } }; if (process.stdin.isTTY) { // Enable plugin-prettier when running in a terminal. Allows us to have // eslint verify prettier formatting, while not being bothered by it in our // editors. config.plugins.push('prettier'); config.rules['prettier/prettier'] = 'error'; } module.exports = config;
const config = { extends: ['standard', 'prettier', 'prettier/standard'], plugins: ['import', 'mocha'], rules: { 'import/no-extraneous-dependencies': [ 'error', { devDependencies: [ '**/test/**/*.js', '**/bootstrap-unexpected-markdown.js' ], optionalDependencies: false, peerDependencies: false } ], 'mocha/no-exclusive-tests': 'error', 'mocha/no-nested-tests': 'error', 'mocha/no-identical-title': 'error' }, parserOptions: { ecmaVersion: 9, ecmaFeatures: { globalReturn: true, jsx: true }, sourceType: 'module' } }; if (process.stdin.isTTY) { // Enable plugin-prettier when running in a terminal. Allows us to have // eslint verify prettier formatting, while not being bothered by it in our // editors. config.plugins.push('prettier'); config.rules['prettier/prettier'] = 'error'; } module.exports = config;
Update bootcode threshold to 2.5 MB
const fs = require('fs'), path = require('path'), expect = require('chai').expect, CACHE_DIR = path.join(__dirname, '/../../.cache'), THRESHOLD = 2.5 * 1024 * 1024; // 2.5 MB describe('bootcode size', function () { this.timeout(60 * 1000); it('should not exceed the threshold', function (done) { fs.readdir(CACHE_DIR, function (err, files) { if (err) { return done(err); } files.forEach(function (file) { var size = fs.statSync(CACHE_DIR + '/' + file).size; expect(size, (file + ' threshold exceeded')).to.be.below(THRESHOLD); }); done(); }); }); });
const fs = require('fs'), path = require('path'), expect = require('chai').expect, CACHE_DIR = path.join(__dirname, '/../../.cache'), THRESHOLD = 3.7 * 1024 * 1024; // 3.7 MB describe('bootcode size', function () { this.timeout(60 * 1000); it('should not exceed the threshold', function (done) { fs.readdir(CACHE_DIR, function (err, files) { if (err) { return done(err); } files.forEach(function (file) { var size = fs.statSync(CACHE_DIR + '/' + file).size; expect(size, (file + ' threshold exceeded')).to.be.below(THRESHOLD); }); done(); }); }); });
Fix CSS Modules ident name for production build
var cssnext = require('postcss-cssnext'); var postcssFocus = require('postcss-focus'); var postcssReporter = require('postcss-reporter'); var cssModulesIdentName = '[name]__[local]__[hash:base64:5]'; if (process.env.NODE_ENV === 'production') { cssModulesIdentName = '[hash:base64]'; } module.exports = { output: { publicPath: '/', libraryTarget: 'commonjs2', }, resolve: { extensions: ['', '.js', '.jsx'], modules: [ 'client', 'node_modules', ], }, module: { loaders: [ { test: /\.css$/, exclude: /node_modules/, loader: 'style-loader!css-loader?localIdentName=' + cssModulesIdentName + '&modules&importLoaders=1&sourceMap!postcss-loader', }, { test: /\.jpe?g$|\.gif$|\.png$|\.svg$/i, loader: 'url-loader?limit=10000', }, ], }, postcss: () => [ postcssFocus(), cssnext({ browsers: ['last 2 versions', 'IE > 10'], }), postcssReporter({ clearMessages: true, }), ], };
var cssnext = require('postcss-cssnext'); var postcssFocus = require('postcss-focus'); var postcssReporter = require('postcss-reporter'); module.exports = { output: { publicPath: '/', libraryTarget: 'commonjs2', }, resolve: { extensions: ['', '.js', '.jsx'], modules: [ 'client', 'node_modules', ], }, module: { loaders: [ { test: /\.css$/, exclude: /node_modules/, loader: 'style-loader!css-loader?localIdentName=[name]__[local]__[hash:base64:5]&modules&importLoaders=1&sourceMap!postcss-loader', }, { test: /\.jpe?g$|\.gif$|\.png$|\.svg$/i, loader: 'url-loader?limit=10000', }, ], }, postcss: () => [ postcssFocus(), cssnext({ browsers: ['last 2 versions', 'IE > 10'], }), postcssReporter({ clearMessages: true, }), ], };
Load 20 most recent pchats
// // Load private chat history from the archive // (function () { var connection; $(document).on('connected.ditto.chat', function (e, conn) { connection = conn; connection.mam.init(connection); connection.mam.query( Strophe.getBareJidFromJid(DITTO.chat_name), { 'with': Strophe.getBareJidFromJid(DITTO.chatee), 'before': "", 'max': 20, onMessage: onArchivedPrivateMessage } ); }); function onArchivedPrivateMessage(msg) { var msg = $(msg); var body = msg.find("body:first").text(); var from = msg.find('message').attr("from").split('@')[0]; var when = new Date(msg.find('delay').attr('stamp')); DITTO.chat.renderPrivateMessage(from, when, body); return true; } })();
// // Load private chat history from the archive // (function () { var connection; $(document).on('connected.ditto.chat', function (e, conn) { var an_hour_ago = new Date(); an_hour_ago.setHours(an_hour_ago.getHours() - 1); connection = conn; connection.mam.init(connection); connection.mam.query( Strophe.getBareJidFromJid(DITTO.chat_name), { 'with': Strophe.getBareJidFromJid(DITTO.chatee), 'start': an_hour_ago.toISOString(), // 'max': 10, onMessage: onArchivedPrivateMessage } ); }); function onArchivedPrivateMessage(msg) { var msg = $(msg); var body = msg.find("body:first").text(); var from = msg.find('message').attr("from").split('@')[0]; var when = new Date(msg.find('delay').attr('stamp')); DITTO.chat.renderPrivateMessage(from, when, body); return true; } })();
Correct Entities folder case on doctrine config
<?php /** * This file is covered by the AGPLv3 license, which can be found at the LICENSE file in the root of this project. * @copyright 2017 subtitulamos.tv */ require __DIR__.'/../vendor/autoload.php'; use Doctrine\ORM\Tools\Setup; use Doctrine\ORM\EntityManager; // Load env variables from file if (getenv('ENVIRONMENT') !== 'production') { $dotenv = new Dotenv\Dotenv(__DIR__.'/..'); $dotenv->load(); } define('DEBUG', getenv('DEBUG') == 'true'); // Initialize Doctrine's ORM stuff $config = Setup::createAnnotationMetadataConfiguration([__DIR__."/Entities"], DEBUG, null, null, false); $conn = [ 'driver' => 'pdo_mysql', 'dbname' => getenv('DATABASE_NAME'), 'user' => getenv('DATABASE_USER'), 'password' => getenv('DATABASE_PASSWORD'), 'host' => getenv('DATABASE_HOST') ]; // $entityManager is a global isntance and is used as such $entityManager = EntityManager::create($conn, $config); $entityManager->getConfiguration()->addEntityNamespace('App', '\App\Entities');
<?php /** * This file is covered by the AGPLv3 license, which can be found at the LICENSE file in the root of this project. * @copyright 2017 subtitulamos.tv */ require __DIR__.'/../vendor/autoload.php'; use Doctrine\ORM\Tools\Setup; use Doctrine\ORM\EntityManager; // Load env variables from file if (getenv('ENVIRONMENT') !== 'production') { $dotenv = new Dotenv\Dotenv(__DIR__.'/..'); $dotenv->load(); } define('DEBUG', getenv('DEBUG') == 'true'); // Initialize Doctrine's ORM stuff $config = Setup::createAnnotationMetadataConfiguration([__DIR__."/entities"], DEBUG, null, null, false); $conn = [ 'driver' => 'pdo_mysql', 'dbname' => getenv('DATABASE_NAME'), 'user' => getenv('DATABASE_USER'), 'password' => getenv('DATABASE_PASSWORD'), 'host' => getenv('DATABASE_HOST') ]; // $entityManager is a global isntance and is used as such $entityManager = EntityManager::create($conn, $config); $entityManager->getConfiguration()->addEntityNamespace('App', '\App\Entities');
Use @Ignore instead of commenting @Test
package com.github.vlsi.mat.tests.calcite; import org.junit.Ignore; import org.junit.Test; import java.sql.SQLException; public class GetByKeyTests extends SampleHeapDumpTests { @Test public void testHashMapByKey() throws SQLException { returnsInOrder("select getByKey(m.this, 'GMT') v from java.util.HashMap m where getSize(m.this) = 208", "v", "Etc/GMT"); } @Test public void testReferenceResult() throws SQLException { returnsInOrder("select length(getByKey(m.this, 'GMT')['value']) l from java.util.HashMap m where getSize(m.this) " + "= 208", "l", "7"); } @Test @Ignore public void testConcurrentHashMap() throws SQLException { returnsInOrder("select getByKey(m.this, 'MST')['ID'] c from java.util.concurrent.ConcurrentHashMap m where " + "getByKey(m.this, 'MST') is not null", "c", "MST"); } }
package com.github.vlsi.mat.tests.calcite; import org.junit.Test; import java.sql.SQLException; public class GetByKeyTests extends SampleHeapDumpTests { @Test public void testHashMapByKey() throws SQLException { returnsInOrder("select getByKey(m.this, 'GMT') v from java.util.HashMap m where getSize(m.this) = 208", "v", "Etc/GMT"); } @Test public void testReferenceResult() throws SQLException { returnsInOrder("select length(getByKey(m.this, 'GMT')['value']) l from java.util.HashMap m where getSize(m.this) " + "= 208", "l", "7"); } //@Test public void testConcurrentHashMap() throws SQLException { returnsInOrder("select getByKey(m.this, 'MST')['ID'] c from java.util.concurrent.ConcurrentHashMap m where " + "getByKey(m.this, 'MST') is not null", "c", "MST"); } }
Add vertical autosize for lane title editing
import React from 'react' import PropTypes from 'prop-types' import InlineInput from 'rt/widgets/InlineInput' import {Title, LaneHeader, RightContent } from 'rt/styles/Base' import LaneMenu from './LaneHeader/LaneMenu' const LaneHeaderComponent = ({ updateTitle, canAddLanes, onDelete, onDoubleClick, editLaneTitle, label, title, titleStyle, labelStyle, t }) => { return ( <LaneHeader onDoubleClick={onDoubleClick} editLaneTitle={editLaneTitle}> <Title style={titleStyle}> {editLaneTitle ? <InlineInput value={title} border placeholder={t('placeholder.title')} resize='vertical' onSave={updateTitle} /> : title } </Title> {label && ( <RightContent> <span style={labelStyle}>{label}</span> </RightContent> )} {canAddLanes && <LaneMenu t={t} onDelete={onDelete}/>} </LaneHeader> ) } LaneHeaderComponent.propTypes = { updateTitle: PropTypes.func, editLaneTitle: PropTypes.bool, canAddLanes: PropTypes.bool, label: PropTypes.string, title: PropTypes.string, onDelete: PropTypes.func, onDoubleClick: PropTypes.func, editLaneTitle: PropTypes.bool, t: PropTypes.func.isRequired } LaneHeaderComponent.defaultProps = { updateTitle: () => {}, editLaneTitle: false, canAddLanes: false } export default LaneHeaderComponent;
import React from 'react' import PropTypes from 'prop-types' import InlineInput from 'rt/widgets/InlineInput' import {Title, LaneHeader, RightContent } from 'rt/styles/Base' import LaneMenu from './LaneHeader/LaneMenu' const LaneHeaderComponent = ({ updateTitle, canAddLanes, onDelete, onDoubleClick, editLaneTitle, label, title, titleStyle, labelStyle, t }) => { return ( <LaneHeader onDoubleClick={onDoubleClick} editLaneTitle={editLaneTitle}> <Title style={titleStyle}> {editLaneTitle ? <InlineInput value={title} border placeholder={t('placeholder.title')} onSave={updateTitle} /> : title } </Title> {label && ( <RightContent> <span style={labelStyle}>{label}</span> </RightContent> )} {canAddLanes && <LaneMenu t={t} onDelete={onDelete}/>} </LaneHeader> ) } LaneHeaderComponent.propTypes = { updateTitle: PropTypes.func, editLaneTitle: PropTypes.bool, canAddLanes: PropTypes.bool, label: PropTypes.string, title: PropTypes.string, onDelete: PropTypes.func, onDoubleClick: PropTypes.func, editLaneTitle: PropTypes.bool, t: PropTypes.func.isRequired } LaneHeaderComponent.defaultProps = { updateTitle: () => {}, editLaneTitle: false, canAddLanes: false } export default LaneHeaderComponent;
Test DatadogMetricsBackend against datadog's get_hostname This fixes tests in Travis since the hostname returned is different
from __future__ import absolute_import from mock import patch from datadog.util.hostname import get_hostname from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(prefix='sentrytest.') @patch('datadog.threadstats.base.ThreadStats.increment') def test_incr(self, mock_incr): self.backend.incr('foo', instance='bar') mock_incr.assert_called_once_with( 'sentrytest.foo', 1, tags=['instance:bar'], host=get_hostname(), ) @patch('datadog.threadstats.base.ThreadStats.timing') def test_timing(self, mock_timing): self.backend.timing('foo', 30, instance='bar') mock_timing.assert_called_once_with( 'sentrytest.foo', 30, sample_rate=1, tags=['instance:bar'], host=get_hostname(), )
from __future__ import absolute_import import socket from mock import patch from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(prefix='sentrytest.') @patch('datadog.threadstats.base.ThreadStats.increment') def test_incr(self, mock_incr): self.backend.incr('foo', instance='bar') mock_incr.assert_called_once_with( 'sentrytest.foo', 1, tags=['instance:bar'], host=socket.gethostname(), ) @patch('datadog.threadstats.base.ThreadStats.timing') def test_timing(self, mock_timing): self.backend.timing('foo', 30, instance='bar') mock_timing.assert_called_once_with( 'sentrytest.foo', 30, sample_rate=1, tags=['instance:bar'], host=socket.gethostname(), )
Remove optimizeImages task in image task
'use strict'; if (!config.tasks.images) { return false; } let paths = { src: path.join(config.root.base, config.root.src, config.tasks.images.src, '/**', getExtensions(config.tasks.images.extensions)), dest: path.join(config.root.base, config.root.dest, config.tasks.images.dest) }; function images() { return gulp.src(paths.src, {since: cache.lastMtime('images')}) .pipe(plumber(handleErrors)) .pipe(cache('images')) .pipe(changed(paths.dest)) // Ignore unchanged files .pipe(flatten()) .pipe(chmod(config.chmod)) .pipe(gulp.dest(paths.dest)) .pipe(size({ title: 'Images:', showFiles: false }) ); } module.exports = images;
'use strict'; if (!config.tasks.images) { return false; } let paths = { src: path.join(config.root.base, config.root.src, config.tasks.images.src, '/**', getExtensions(config.tasks.images.extensions)), dest: path.join(config.root.base, config.root.dest, config.tasks.images.dest) }; function images() { return gulp.src(paths.src, {since: cache.lastMtime('images')}) .pipe(plumber(handleErrors)) .pipe(cache('images')) .pipe(changed(paths.dest)) // Ignore unchanged files .pipe(config.root.optimizeImages ? imagemin() : util.noop()) // Optimize .pipe(flatten()) .pipe(chmod(config.chmod)) .pipe(gulp.dest(paths.dest)) .pipe(size({ title: 'Images:', showFiles: false }) ); } module.exports = images;
Split the parsing of input and the exporting of the variables for reuse
import json import os def export_variables(environment_variables): for env_name, env_value in environment_variables.items(): os.environ[str(env_name)] = str(env_value) def set_environment_variables(json_file_path): """ Read and set environment variables from a flat json file. Bear in mind that env vars set this way and later on read using `os.getenv` function will be strings since after all env vars are just that - plain strings. Json file example: ``` { "FOO": "bar", "BAZ": true } ``` :param json_file_path: path to flat json file :type json_file_path: str """ if json_file_path: with open(json_file_path) as json_file: env_vars = json.loads(json_file.read()) export_variables(env_vars)
import json import os def set_environment_variables(json_file_path): """ Read and set environment variables from a flat json file. Bear in mind that env vars set this way and later on read using `os.getenv` function will be strings since after all env vars are just that - plain strings. Json file example: ``` { "FOO": "bar", "BAZ": true } ``` :param json_file_path: path to flat json file :type json_file_path: str """ if json_file_path: with open(json_file_path) as json_file: env_vars = json.loads(json_file.read()) for env_name, env_value in env_vars.items(): os.environ[str(env_name)] = str(env_value)
Fix GraphConvTensorGraph to GraphConvModel in hopv example
""" Script that trains graph-conv models on HOPV dataset. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals import numpy as np from models import GraphConvModel np.random.seed(123) import tensorflow as tf tf.set_random_seed(123) import deepchem as dc from deepchem.molnet import load_hopv # Load HOPV dataset hopv_tasks, hopv_datasets, transformers = load_hopv(featurizer='GraphConv') train_dataset, valid_dataset, test_dataset = hopv_datasets # Fit models metric = [ dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode="regression"), dc.metrics.Metric( dc.metrics.mean_absolute_error, np.mean, mode="regression") ] # Number of features on conv-mols n_feat = 75 # Batch size of models batch_size = 50 model = GraphConvModel( len(hopv_tasks), batch_size=batch_size, mode='regression') # Fit trained model model.fit(train_dataset, nb_epoch=25) print("Evaluating model") train_scores = model.evaluate(train_dataset, metric, transformers) valid_scores = model.evaluate(valid_dataset, metric, transformers) print("Train scores") print(train_scores) print("Validation scores") print(valid_scores)
""" Script that trains graph-conv models on HOPV dataset. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals import numpy as np from models import GraphConvTensorGraph np.random.seed(123) import tensorflow as tf tf.set_random_seed(123) import deepchem as dc from deepchem.molnet import load_hopv # Load HOPV dataset hopv_tasks, hopv_datasets, transformers = load_hopv(featurizer='GraphConv') train_dataset, valid_dataset, test_dataset = hopv_datasets # Fit models metric = [ dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode="regression"), dc.metrics.Metric( dc.metrics.mean_absolute_error, np.mean, mode="regression") ] # Number of features on conv-mols n_feat = 75 # Batch size of models batch_size = 50 model = GraphConvTensorGraph( len(hopv_tasks), batch_size=batch_size, mode='regression') # Fit trained model model.fit(train_dataset, nb_epoch=25) print("Evaluating model") train_scores = model.evaluate(train_dataset, metric, transformers) valid_scores = model.evaluate(valid_dataset, metric, transformers) print("Train scores") print(train_scores) print("Validation scores") print(valid_scores)
Remove cmd test temporarily so we have a build.
// khan // https://github.com/topfreegames/khan // // Licensed under the MIT license: // http://www.opensource.org/licenses/mit-license // Copyright © 2016 Top Free Games <backend@tfgco.com> package cmd // import ( // "fmt" // "os/exec" // "testing" // // . "github.com/franela/goblin" // "github.com/topfreegames/khan/api" // ) // // func runVersion() (string, error) { // goBin, err := exec.LookPath("go") // if err != nil { // return "", err // } // // cmd := exec.Command(goBin, "run", "main.go", "version") // cmd.Dir = ".." // res, err := cmd.CombinedOutput() // if err != nil { // return "", err // } // // return string(res), nil // } // // func TestVersionCommand(t *testing.T) { // g := Goblin(t) // // g.Describe("Version Cmd", func() { // g.It("Should get version", func() { // version, err := runVersion() // fmt.Println(version, err) // g.Assert(err == nil).IsTrue() // g.Assert(version).Equal(fmt.Sprintf("Khan v%s\n", api.VERSION)) // }) // }) // }
// khan // https://github.com/topfreegames/khan // // Licensed under the MIT license: // http://www.opensource.org/licenses/mit-license // Copyright © 2016 Top Free Games <backend@tfgco.com> package cmd import ( "fmt" "os/exec" "testing" . "github.com/franela/goblin" "github.com/topfreegames/khan/api" ) func runVersion() (string, error) { goBin, err := exec.LookPath("go") if err != nil { return "", err } cmd := exec.Command(goBin, "run", "main.go", "version") cmd.Dir = ".." res, err := cmd.CombinedOutput() if err != nil { return "", err } return string(res), nil } func TestVersionCommand(t *testing.T) { g := Goblin(t) g.Describe("Version Cmd", func() { g.It("Should get version", func() { version, err := runVersion() fmt.Println(version, err) g.Assert(err == nil).IsTrue() g.Assert(version).Equal(fmt.Sprintf("Khan v%s\n", api.VERSION)) }) }) }
unittests: Use laserpointer to play with nyancat to reduce sleep
<?php //namespace Mockery\Adapter\Phpunit; namespace Wecamp\FlyingLiqourice; class NyanListener implements \PHPUnit_Framework_TestListener { public function endTest(\PHPUnit_Framework_Test $test, $time) { usleep(rand(20000, 100000)); } /** * Add Mockery files to PHPUnit's blacklist so they don't showup on coverage reports */ public function startTestSuite(\PHPUnit_Framework_TestSuite $suite) { } /** * The Listening methods below are not required for Mockery */ public function addError(\PHPUnit_Framework_Test $test, \Exception $e, $time) { } public function addFailure(\PHPUnit_Framework_Test $test, \PHPUnit_Framework_AssertionFailedError $e, $time) { } public function addIncompleteTest(\PHPUnit_Framework_Test $test, \Exception $e, $time) { } public function addSkippedTest(\PHPUnit_Framework_Test $test, \Exception $e, $time) { } public function addRiskyTest(\PHPUnit_Framework_Test $test, \Exception $e, $time) { } public function endTestSuite(\PHPUnit_Framework_TestSuite $suite) { } public function startTest(\PHPUnit_Framework_Test $test) { } }
<?php //namespace Mockery\Adapter\Phpunit; namespace Wecamp\FlyingLiqourice; class NyanListener implements \PHPUnit_Framework_TestListener { public function endTest(\PHPUnit_Framework_Test $test, $time) { usleep(rand(20000, 300000)); } /** * Add Mockery files to PHPUnit's blacklist so they don't showup on coverage reports */ public function startTestSuite(\PHPUnit_Framework_TestSuite $suite) { } /** * The Listening methods below are not required for Mockery */ public function addError(\PHPUnit_Framework_Test $test, \Exception $e, $time) { } public function addFailure(\PHPUnit_Framework_Test $test, \PHPUnit_Framework_AssertionFailedError $e, $time) { } public function addIncompleteTest(\PHPUnit_Framework_Test $test, \Exception $e, $time) { } public function addSkippedTest(\PHPUnit_Framework_Test $test, \Exception $e, $time) { } public function addRiskyTest(\PHPUnit_Framework_Test $test, \Exception $e, $time) { } public function endTestSuite(\PHPUnit_Framework_TestSuite $suite) { } public function startTest(\PHPUnit_Framework_Test $test) { } }
Fix entries getting stuck in the pending map. Pending map timestamp should be composite of (IntentData.version(), wallclocktime) Change-Id: I3caf739c4fdb70535696176621649f0842eea467
/* * Copyright 2015 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.store.intent.impl; import org.onosproject.net.intent.IntentData; import org.onosproject.store.Timestamp; import org.onosproject.store.impl.ClockService; import org.onosproject.store.impl.MultiValuedTimestamp; /** * ClockService that uses IntentData versions as timestamps. */ public class IntentDataClockManager<K> implements ClockService<K, IntentData> { @Override public Timestamp getTimestamp(K key, IntentData intentData) { return new MultiValuedTimestamp<>(intentData.version(), System.nanoTime()); } }
/* * Copyright 2015 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.store.intent.impl; import org.onosproject.net.intent.IntentData; import org.onosproject.store.Timestamp; import org.onosproject.store.impl.ClockService; /** * ClockService that uses IntentData versions as timestamps. */ public class IntentDataClockManager<K> implements ClockService<K, IntentData> { @Override public Timestamp getTimestamp(K key, IntentData intentData) { return intentData.version(); } }
Handle cases when MEDUSA_URL_PREFIX isn't set
from django.conf import settings from django.core.management.base import BaseCommand from django.core.urlresolvers import set_script_prefix from django_medusa.renderers import StaticSiteRenderer from django_medusa.utils import get_static_renderers class Command(BaseCommand): can_import_settings = True help = 'Looks for \'renderers.py\' in each INSTALLED_APP, which defines '\ 'a class for processing one or more URL paths into static files.' def handle(self, *args, **options): StaticSiteRenderer.initialize_output() renderers = [Renderer() for Renderer in get_static_renderers()] for renderer in renderers: # memoize this first to avoid script prefix pollution renderer.paths # Set script prefix here url_prefix = getattr(settings, 'MEDUSA_URL_PREFIX', None) if url_prefix is not None: set_script_prefix(url_prefix) # And now generate stuff for renderer in renderers: renderer.generate() StaticSiteRenderer.finalize_output()
from django.conf import settings from django.core.management.base import BaseCommand from django.core.urlresolvers import set_script_prefix from django_medusa.renderers import StaticSiteRenderer from django_medusa.utils import get_static_renderers class Command(BaseCommand): can_import_settings = True help = 'Looks for \'renderers.py\' in each INSTALLED_APP, which defines '\ 'a class for processing one or more URL paths into static files.' def handle(self, *args, **options): StaticSiteRenderer.initialize_output() renderers = [Renderer() for Renderer in get_static_renderers()] for renderer in renderers: # memoize this first to avoid script prefix pollution renderer.paths # Set script prefix here url_prefix = getattr(settings, 'MEDUSA_URL_PREFIX') if url_prefix is not None: set_script_prefix(url_prefix) # And now generate stuff for renderer in renderers: renderer.generate() StaticSiteRenderer.finalize_output()
Verify if a integer number is even or odd - refactor
// Modules var prompt = require( 'prompt' ); // // Create a variable x and assign value 3 to it // var x = 3; // // Bind x to value 9 // x *= x; // or x = x * x; // console.log( x ); // // read input data from terminal // prompt.start(); // prompt.get({ // name : 'number', // description : 'Enter a number' // }, function( err, results ) { // console.log( results.number ); // }); // Verify if a integer number is even or odd. // If odd, verify if the number is divisible by 3 // read input data from terminal prompt.start(); prompt.get([ { name : 'number', description : 'Enter a integer' } ], function( err, results ) { var int = parseInt( results.number, 10 ); if ( int % 2 === 0 ) { console.log( int + ' is EVEN' ); } else { var msg = int.toString() + ' is ODD'; if ( int % 3 !== 0 ) { msg += ' and NOT divisible by 3'; } console.log( msg ); } }); // // Find the lowest of three numbers
// Modules var prompt = require( 'prompt' ); // // Create a variable x and assign value 3 to it // var x = 3; // // Bind x to value 9 // x *= x; // or x = x * x; // console.log( x ); // read input data from terminal prompt.start(); prompt.get({ name : 'number', description : 'Enter a number' }, function( err, results ) { console.log( results.number ); }); // // Verify if a integer number is even or odd. // // If odd, verify if the number is divisible by 3 // // read input data from terminal // process.stdin.resume(); // console.log( 'Enter a integer:' ); // process.stdin.setEncoding( 'utf8' ); // process.stdin.on( 'data', function( input ) { // var int = parseInt( input, 10 ); // if ( int % 2 === 0 ) { // console.log( 'Even' ); // } else { // console.log( 'Odd' ); // if ( int % 3 !== 0 ) { // console.log( 'And not divisible by 3' ); // } // } // process.exit(); // }); // // Find the lowest of three numbers
Move named item loop to the right scope
define(['itemObjectModel'], function(itemOM) { 'use strict'; function open(item) { function onSubitem(subitem) { switch(subitem.dataset.resourceType) { case 'STR ': subitem.getDataObject() .then(function(names) { names = names.split(/;/g); for (var i = 0; i < names.length; i++) { var namedItem = itemOM.createItem(names[i]); item.addItem(namedItem); } }); break; case 'CSND': break; } } var subitems = item.subitemsElement && item.subitemsElement.children; if (subitems) { for (var i = 0; i < subitems.length; i++) { onSubitem(subitems[i]); } } item.addEventListener(itemOM.EVT_ITEM_ADDED, function(e) { onSubitem(e.detail.item); }); return Promise.resolve(item); } return open; });
define(['itemObjectModel'], function(itemOM) { 'use strict'; function open(item) { function onSubitem(subitem) { switch(subitem.dataset.resourceType) { case 'STR ': subitem.getDataObject() .then(function(names) { names = names.split(/;/g); }); for (var i = 0; i < names.length; i++) { var namedItem = itemOM.createItem(names[i]); item.addItem(namedItem); } break; case 'CSND': break; } } var subitems = item.subitemsElement && item.subitemsElement.children; if (subitems) { for (var i = 0; i < subitems.length; i++) { onSubitem(subitems[i]); } } item.addEventListener(itemOM.EVT_ITEM_ADDED, function(e) { onSubitem(e.detail.item); }); return Promise.resolve(item); } return open; });
Read flags before standard input
#!/usr/bin/env php <?php require __DIR__ . '/vendor/autoload.php'; $flags = new donatj\Flags; $drop =& $flags->bool('drop', false, 'Include DROP TABLE?'); $inputComment =& $flags->bool('input-comment', false, 'Include original input as a comment?'); $columnFactory = new \donatj\Misstep\ColumnFactory; try { $flags->parse(); } catch( Exception $e ) { echo $e->getMessage() . "\n"; echo $flags->getDefaults(); die(1); } $jql = file_get_contents('php://stdin'); try { if( trim($jql) == '' ) { return ''; } $parser = new \donatj\Misstep\Parser($columnFactory); $renderer = new \donatj\Misstep\Renderer($jql, $inputComment, $drop); $tables = $parser->parse($jql); echo $renderer->render($tables); } catch( \donatj\Misstep\Exceptions\UserException $e ) { fwrite(STDERR, "Error: " . $e->getMessage() . "\n"); die(1); }
#!/usr/bin/env php <?php require __DIR__ . '/vendor/autoload.php'; $jql = file_get_contents('php://stdin'); $flags = new donatj\Flags; $drop =& $flags->bool('drop', false, 'Include DROP TABLE?'); $inputComment =& $flags->bool('input-comment', false, 'Include original input as a comment?'); $columnFactory = new \donatj\Misstep\ColumnFactory; try { $flags->parse(); } catch( Exception $e ) { echo $e->getMessage() . "\n"; echo $flags->getDefaults(); die(1); } try { if( trim($jql) == '' ) { return ''; } $parser = new \donatj\Misstep\Parser($columnFactory); $renderer = new \donatj\Misstep\Renderer($jql, $inputComment, $drop); $tables = $parser->parse($jql); echo $renderer->render($tables); } catch( \donatj\Misstep\Exceptions\UserException $e ) { fwrite(STDERR, "Error: " . $e->getMessage() . "\n"); die(1); }
Change to new version number
# # Konstrukteur - Static website generator # Copyright 2013 Sebastian Fastner # """ **Konstrukteur - Static website generator** Konstrukteur is a website generator that uses a template and content files to create static website output. """ __version__ = "0.1.14" __author__ = "Sebastian Fastner <mail@sebastianfastner.de>" def info(): """ Prints information about Jasy to the console. """ import jasy.core.Console as Console print("Jasy %s is a powerful web tooling framework" % __version__) print("Visit %s for details." % Console.colorize("https://github.com/sebastian-software/jasy", "underline")) print() class UserError(Exception): """ Standard Jasy error class raised whenever something happens which the system understands (somehow excepected) """ pass
# # Konstrukteur - Static website generator # Copyright 2013 Sebastian Fastner # """ **Konstrukteur - Static website generator** Konstrukteur is a website generator that uses a template and content files to create static website output. """ __version__ = "0.1.13" __author__ = "Sebastian Fastner <mail@sebastianfastner.de>" def info(): """ Prints information about Jasy to the console. """ import jasy.core.Console as Console print("Jasy %s is a powerful web tooling framework" % __version__) print("Visit %s for details." % Console.colorize("https://github.com/sebastian-software/jasy", "underline")) print() class UserError(Exception): """ Standard Jasy error class raised whenever something happens which the system understands (somehow excepected) """ pass
Fix variable initialization which failed travis build
package runner import ( "net/http" "fmt" "sync" "github.com/dudang/golt/parser" ) func ExecuteJsonGolt(testPlan parser.GoltJsons) { for _, element := range testPlan.Golt { executeElement(element) } } func executeElement(testElement parser.GoltJson) { var wg sync.WaitGroup wg.Add(testElement.Threads) for i:= 0; i < testElement.Threads; i++ { go spawnRoutine(testElement) } wg.Wait() } func spawnRoutine(testElement parser.GoltJson) { switch testElement.Method { case "GET": getRequest(testElement.URL) default: return } } func getRequest(url string) { resp, err := http.Get(url) resp.Body.Close() if err != nil { fmt.Printf("%v\n", err) } fmt.Println(resp.StatusCode) }
package runner import ( "net/http" "fmt" "sync" "github.com/dudang/golt/parser" ) func ExecuteJsonGolt(testPlan parser.GoltJsons) { for _, element := range testPlan.Golt { executeElement(element) } } func executeElement(testElement parser.GoltJson) { waitGroup := sync.WaitGroup waitGroup.Add(testElement.Threads) for i:= 0; i < testElement.Threads; i++ { go spawnRoutine(testElement) } waitGroup.Wait() } func spawnRoutine(testElement parser.GoltJson) { switch testElement.Method { case "GET": getRequest(testElement.URL) default: return } } func getRequest(url string) { resp, err := http.Get(url) resp.Body.Close() if err != nil { fmt.Printf("%v\n", err) } fmt.Println(resp.StatusCode) }
Fix user modding page title and description
{{-- Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. See the LICENCE file in the repository root for full licence text. --}} @extends('master', [ 'titlePrepend' => blade_safe(str_replace(' ', '&nbsp;', e($user->username))), 'pageDescription' => page_description($user->username), ]) @section('content') @if (Auth::user() && Auth::user()->isAdmin() && $user->isRestricted()) @include('objects._notification_banner', [ 'type' => 'warning', 'title' => trans('admin.users.restricted_banner.title'), 'message' => trans('admin.users.restricted_banner.message'), ]) @endif <div class="js-react--modding-profile osu-layout osu-layout--full"></div> @endsection @section ("script") @parent @foreach ($jsonChunks as $name => $data) <script id="json-{{$name}}" type="application/json"> {!! json_encode($data) !!} </script> @endforeach @include('layout._extra_js', ['src' => 'js/react/modding-profile.js']) @endsection
{{-- Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. See the LICENCE file in the repository root for full licence text. --}} @extends('master', [ 'titlePrepend' => $user->username, 'pageDescription' => trans('users.show.page_description', ['username' => $user->username]), ]) @section('content') @if (Auth::user() && Auth::user()->isAdmin() && $user->isRestricted()) @include('objects._notification_banner', [ 'type' => 'warning', 'title' => trans('admin.users.restricted_banner.title'), 'message' => trans('admin.users.restricted_banner.message'), ]) @endif <div class="js-react--modding-profile osu-layout osu-layout--full"></div> @endsection @section ("script") @parent @foreach ($jsonChunks as $name => $data) <script id="json-{{$name}}" type="application/json"> {!! json_encode($data) !!} </script> @endforeach @include('layout._extra_js', ['src' => 'js/react/modding-profile.js']) @endsection
Update example with working relay
<?php require_once 'common.php'; use Dapphp\TorUtils\DirectoryClient; $client = new DirectoryClient(); //$client->setPreferredServer('1.2.3.4:80'); // Optional server to always use first for directory lookups try { $descriptor = $client->getServerDescriptor('81C55D403A82BF6E7C3FBDBD41D102B7088900D9'); } catch (\Exception $ex) { echo "Request to directory failed: " . $ex->getMessage() . "\n"; exit; } echo sprintf("%-19s %40s\n", $descriptor->nickname, $descriptor->fingerprint); echo sprintf("Running %s\n", $descriptor->platform); echo sprintf("Online for %s\n", uptimeToString($descriptor->getCurrentUptime(), false)); echo sprintf("OR Address: %s:%s", $descriptor->ip_address, $descriptor->or_port); if ($descriptor->or_address) { foreach ($descriptor->or_address as $address) { echo ", $address"; } } echo "\n"; echo sprintf("Exit Policy:\n Accept:\n %s\n Reject:\n %s\n", implode("\n ", $descriptor->exit_policy4['accept']), implode("\n ", $descriptor->exit_policy4['reject']) );
<?php require_once 'common.php'; use Dapphp\TorUtils\DirectoryClient; $client = new DirectoryClient(); //$client->setPreferredServer('1.2.3.4:80'); // Optional server to always use first for directory lookups try { $descriptor = $client->getServerDescriptor('79E169B25E4C7CE99584F6ED06F379478F23E2B8'); } catch (\Exception $ex) { echo "Request to directory failed: " . $ex->getMessage() . "\n"; exit; } echo sprintf("%-19s %40s\n", $descriptor->nickname, $descriptor->fingerprint); echo sprintf("Running %s\n", $descriptor->platform); echo sprintf("Online for %s\n", uptimeToString($descriptor->getCurrentUptime(), false)); echo sprintf("OR Address: %s:%s", $descriptor->ip_address, $descriptor->or_port); if ($descriptor->or_address) { foreach ($descriptor->or_address as $address) { echo ", $address"; } } echo "\n"; echo sprintf("Exit Policy:\n Accept:\n %s\n Reject:\n %s\n", implode("\n ", $descriptor->exit_policy4['accept']), implode("\n ", $descriptor->exit_policy4['reject']) );
Use repr instead of str for odict repr
try: from collections import OrderedDict except: from ordereddict import OrderedDict try: from reprlib import recursive_repr except: # don't cope with recursive repr calls in py2 def recursive_repr(fillvalue='...'): return (lambda f: f) try: from collections.abc import Iterable except: Iterable = tuple __all__ = ["odict"] __version__ = '1.0.0' class odictType(type): syntax_error = SyntaxError("Allowed syntax: odict[<k>: <v>(, <k>: <v>...)]") def __getitem__(self, keys): if isinstance(keys, slice): keys = (keys,) if not isinstance(keys, Iterable): raise self.syntax_error od = self() for k in keys: if not isinstance(k, slice) or k.step is not None: raise self.syntax_error od[k.start] = k.stop return od @recursive_repr(fillvalue="odict[...]") def odict_repr(self): if len(self) == 0: return "odict()" else: return "odict[%s]" % (", ".join("%r: %r" % (k,v) for k,v in self.items()),) odict = odictType(str('odict'), (OrderedDict,), {"__repr__": odict_repr})
try: from collections import OrderedDict except: from ordereddict import OrderedDict try: from reprlib import recursive_repr except: # don't cope with recursive repr calls in py2 def recursive_repr(fillvalue='...'): return (lambda f: f) try: from collections.abc import Iterable except: Iterable = tuple __all__ = ["odict"] __version__ = '1.0.0' class odictType(type): syntax_error = SyntaxError("Allowed syntax: odict[<k>: <v>(, <k>: <v>...)]") def __getitem__(self, keys): if isinstance(keys, slice): keys = (keys,) if not isinstance(keys, Iterable): raise self.syntax_error od = self() for k in keys: if not isinstance(k, slice) or k.step is not None: raise self.syntax_error od[k.start] = k.stop return od @recursive_repr(fillvalue="odict[...]") def odict_repr(self): if len(self) == 0: return "odict()" else: return "odict[%s]" % (", ".join("%s: %s" % (k,v) for k,v in self.items()),) odict = odictType(str('odict'), (OrderedDict,), {"__repr__": odict_repr})
Add controller, controllerAs fields for /users route
// js/routes (function() { "use strict"; angular.module("NoteWrangler") .config(config); function config($routeProvider) { $routeProvider .when("/notes", { templateUrl: "../templates/pages/notes/index.html", controller: "NotesIndexController", controllerAs: "notesIndexCtrl" }) .when("/users", { templateUrl: "../templates/pages/users/index.html", controller: "UsersIndexController", controllerAs: "usersIndexCtrl" }) .when("/notes/new", { templateUrl: "templates/pages/notes/new.html", controller: "NotesCreateController", controllerAs: "notesCreateCtrl" }) .when("/notes/:id", { templateUrl: "templates/pages/notes/show.html", controller: "NotesShowController", controllerAs: "notesShowCtrl" }) .otherwise({ redirectTo: "/", templateUrl: "templates/pages/index/index.html" }); } })();
// js/routes (function() { "use strict"; angular.module("NoteWrangler") .config(config); function config($routeProvider) { $routeProvider .when("/notes", { templateUrl: "../templates/pages/notes/index.html", controller: "NotesIndexController", controllerAs: "notesIndexCtrl" }) .when("/users", { templateUrl: "../templates/pages/users/index.html" }) .when("/notes/new", { templateUrl: "templates/pages/notes/new.html", controller: "NotesCreateController", controllerAs: "notesCreateCtrl" }) .when("/notes/:id", { templateUrl: "templates/pages/notes/show.html", controller: "NotesShowController", controllerAs: "notesShowCtrl" }) .otherwise({ redirectTo: "/", templateUrl: "templates/pages/index/index.html" }); } })();
Fix awkward wording for http.Proxying
package http import stdhttp "net/http" // HostProvider describes something which can yield hosts for transactions, // and record a given host's success/failure. type HostProvider interface { Get() (host string, err error) Put(host string, success bool) } // Proxying implements host proxying logic. func Proxying(p HostProvider, next Client) Client { return &proxying{ p: p, next: next, } } type proxying struct { p HostProvider next Client } func (p proxying) Do(req *stdhttp.Request) (*stdhttp.Response, error) { host, err := p.p.Get() if err != nil { return nil, err } req.Host = host resp, err := p.next.Do(req) if err == nil { p.p.Put(host, true) } else { p.p.Put(host, false) } return resp, err }
package http import stdhttp "net/http" // HostProvider describes something which can yield hosts for transactions, // and record transaction success against a yielded host. type HostProvider interface { Get() (host string, err error) Put(host string, success bool) } // Proxying implements host proxying logic. func Proxying(p HostProvider, next Client) Client { return &proxying{ p: p, next: next, } } type proxying struct { p HostProvider next Client } func (p proxying) Do(req *stdhttp.Request) (*stdhttp.Response, error) { host, err := p.p.Get() if err != nil { return nil, err } req.Host = host resp, err := p.next.Do(req) if err == nil { p.p.Put(host, true) } else { p.p.Put(host, false) } return resp, err }
Add domain to cookie to set cookie for PhantomJS
from importlib import import_module from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY def force_login(user, driver, base_url): from django.conf import settings SessionStore = import_module(settings.SESSION_ENGINE).SessionStore selenium_login_start_page = getattr(settings, 'SELENIUM_LOGIN_START_PAGE', '/page_404/') driver.get('{}{}'.format(base_url, selenium_login_start_page)) session = SessionStore() session[SESSION_KEY] = user.id session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0] session[HASH_SESSION_KEY] = user.get_session_auth_hash() session.save() domain = base_url.split(':')[-2].split('/')[-1] cookie = { 'name': settings.SESSION_COOKIE_NAME, 'value': session.session_key, 'path': '/', 'domain': domain } driver.add_cookie(cookie) driver.refresh()
from importlib import import_module from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY def force_login(user, driver, base_url): from django.conf import settings SessionStore = import_module(settings.SESSION_ENGINE).SessionStore selenium_login_start_page = getattr(settings, 'SELENIUM_LOGIN_START_PAGE', '/page_404/') driver.get('{}{}'.format(base_url, selenium_login_start_page)) session = SessionStore() session[SESSION_KEY] = user.id session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0] session[HASH_SESSION_KEY] = user.get_session_auth_hash() session.save() cookie = { 'name': settings.SESSION_COOKIE_NAME, 'value': session.session_key, 'path': '/' } driver.add_cookie(cookie) driver.refresh()
Add todo on verifying the version number on lock
package org.hibernate.ogm.dialect.infinispan; import java.io.Serializable; import org.infinispan.AdvancedCache; import org.hibernate.EntityMode; import org.hibernate.JDBCException; import org.hibernate.LockMode; import org.hibernate.StaleObjectStateException; import org.hibernate.dialect.lock.LockingStrategy; import org.hibernate.engine.SessionImplementor; import org.hibernate.ogm.grid.Key; import org.hibernate.ogm.metadata.GridMetadataManagerHelper; import org.hibernate.persister.entity.Lockable; /** * @author Emmanuel Bernard */ public class InfinispanPessimisticWriteLockingStrategy implements LockingStrategy { private final LockMode lockMode; private final Lockable lockable; public InfinispanPessimisticWriteLockingStrategy(Lockable lockable, LockMode lockMode) { this.lockMode = lockMode; this.lockable = lockable; } @Override public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session) throws StaleObjectStateException, JDBCException { AdvancedCache advCache = GridMetadataManagerHelper.getEntityCache( session.getFactory() ).getAdvancedCache(); advCache.lock( new Key( lockable.getRootTableName(), id ) ); //FIXME check the version number as well and raise an optimistic lock exception if there is an issue JPA 2 spec: 3.4.4.2 } }
package org.hibernate.ogm.dialect.infinispan; import java.io.Serializable; import org.infinispan.AdvancedCache; import org.hibernate.EntityMode; import org.hibernate.JDBCException; import org.hibernate.LockMode; import org.hibernate.StaleObjectStateException; import org.hibernate.dialect.lock.LockingStrategy; import org.hibernate.engine.SessionImplementor; import org.hibernate.ogm.grid.Key; import org.hibernate.ogm.metadata.GridMetadataManagerHelper; import org.hibernate.persister.entity.Lockable; /** * @author Emmanuel Bernard */ public class InfinispanPessimisticWriteLockingStrategy implements LockingStrategy { private final LockMode lockMode; private final Lockable lockable; public InfinispanPessimisticWriteLockingStrategy(Lockable lockable, LockMode lockMode) { this.lockMode = lockMode; this.lockable = lockable; } @Override public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session) throws StaleObjectStateException, JDBCException { AdvancedCache advCache = GridMetadataManagerHelper.getEntityCache( session.getFactory() ).getAdvancedCache(); advCache.lock( new Key( lockable.getRootTableName(), id ) ); } }
Fix package description according to golint reccomendation
/* Package httperr defines a simple HTTP error which has a message and status code. This can be useful for returning errors with relevant HTTP status codes, which the standard errors package allow for. Example: func Foo() httperr.Error { if err := Bar(); err != nil { return httperr.New(err.Error(), http.StatusInternalServerError) } return nil } func FooHandler(w http.ResponseWriter, r *http.Request) { if httpErr := Foo(); httpErr != nil { http.Error(w, httpErr.Error(), httpErr.Code()) } } */ package httperr // Error represents a simple HTTP error which has a message and status code. type Error interface { error // Code returns the error's HTTP status code. Code() int } type httpError struct { message string code int } // New returns a new Error with the given message and code. func New(message string, code int) Error { return &httpError{message, code} } // Error returns the error's message. func (e *httpError) Error() string { return e.message } // Code returns the error's HTTP status code. func (e *httpError) Code() int { return e.code }
/* httperr defines a simple HTTP error which has a message and status code. This can be useful for returning errors with relevant HTTP status codes, which the standard errors package allow for. Example: func Foo() httperr.Error { if err := Bar(); err != nil { return httperr.New(err.Error(), http.StatusInternalServerError) } return nil } func FooHandler(w http.ResponseWriter, r *http.Request) { if httpErr := Foo(); httpErr != nil { http.Error(w, httpErr.Error(), httpErr.Code()) } } */ package httperr // Error represents a simple HTTP error which has a message and status code. type Error interface { error // Code returns the error's HTTP status code. Code() int } type httpError struct { message string code int } // New returns a new Error with the given message and code. func New(message string, code int) Error { return &httpError{message, code} } // Error returns the error's message. func (e *httpError) Error() string { return e.message } // Code returns the error's HTTP status code. func (e *httpError) Code() int { return e.code }
Fix typo in header name
//+build !guidev package main import ( "fmt" "log" "mime" "net/http" "path/filepath" "time" "github.com/calmh/syncthing/auto" ) func embeddedStatic() interface{} { var modt = time.Now().UTC().Format(http.TimeFormat) return func(res http.ResponseWriter, req *http.Request, log *log.Logger) { file := req.URL.Path if file[0] == '/' { file = file[1:] } bs, ok := auto.Assets[file] if !ok { return } mtype := mime.TypeByExtension(filepath.Ext(req.URL.Path)) if len(mtype) != 0 { res.Header().Set("Content-Type", mtype) } res.Header().Set("Content-Length", fmt.Sprintf("%d", len(bs))) res.Header().Set("Last-Modified", modt) res.Write(bs) } }
//+build !guidev package main import ( "fmt" "log" "mime" "net/http" "path/filepath" "time" "github.com/calmh/syncthing/auto" ) func embeddedStatic() interface{} { var modt = time.Now().UTC().Format(http.TimeFormat) return func(res http.ResponseWriter, req *http.Request, log *log.Logger) { file := req.URL.Path if file[0] == '/' { file = file[1:] } bs, ok := auto.Assets[file] if !ok { return } mtype := mime.TypeByExtension(filepath.Ext(req.URL.Path)) if len(mtype) != 0 { res.Header().Set("Content-Type", mtype) } res.Header().Set("Content-Size", fmt.Sprintf("%d", len(bs))) res.Header().Set("Last-Modified", modt) res.Write(bs) } }
Fix bad test that sometimes fails on slow jenkins
package org.gbif.checklistbank.service.mybatis.model; import org.gbif.checklistbank.model.RawUsage; import org.junit.Assert; import org.junit.Test; import java.util.Date; import java.util.UUID; public class RawUsageTest { @Test public void testEquals() throws Exception { final int key = 100000001; final String json = "xeghwax542tgld@"; final UUID dkey = UUID.randomUUID(); final Date now = new Date(); RawUsage raw = new RawUsage(); raw.setUsageKey(key); raw.setDatasetKey(dkey); raw.setLastCrawled(now); raw.setJson(json); RawUsage raw2 = new RawUsage(); raw2.setUsageKey(key); raw2.setDatasetKey(dkey); raw2.setLastCrawled(now); raw2.setJson(json); Assert.assertEquals(raw, raw2); raw.setLastCrawled(null); Assert.assertNotEquals(raw, raw2); raw2.setLastCrawled(null); Assert.assertEquals(raw, raw2); } }
package org.gbif.checklistbank.service.mybatis.model; import org.gbif.checklistbank.model.RawUsage; import java.util.Date; import java.util.UUID; import org.junit.Assert; import org.junit.Test; public class RawUsageTest { @Test public void testEquals() throws Exception { final int key = 100000001; final String json = "xeghwax542tgld@"; final UUID dkey = UUID.randomUUID(); RawUsage raw = new RawUsage(); raw.setUsageKey(key); raw.setDatasetKey(dkey); raw.setLastCrawled(new Date()); raw.setJson(json); RawUsage raw2 = new RawUsage(); raw2.setUsageKey(key); raw2.setDatasetKey(dkey); raw2.setLastCrawled(new Date()); raw2.setJson(json); Assert.assertEquals(raw, raw2); raw.setLastCrawled(null); Assert.assertNotEquals(raw, raw2); raw2.setLastCrawled(null); Assert.assertEquals(raw, raw2); } }
Add minX and minY on widget template
import React from 'react'; const nbCol = 12; const nbRow = 6; var Widget = React.createClass({ render: function () { var xSize = $(window).width() / nbCol, ySize = $(window).height() / nbRow; var style = { width: "calc(100vw/" + nbCol + " * " + this.props.width + ")", height: "calc(100vh/" + nbRow + " * " + this.props.height + ")", } if (this.props.debug == "true") { style.background = "tomato"; } var posX = this.props.posX * xSize - xSize, posY = this.props.posY * ySize - ySize, minX = xSize * this.props.width, minY = ySize * this.props.height; style.transform = "translate("+ posX +"px, "+ posY +"px)"; return ( <div className="widget" data-posx={posX} data-posy={posY} data-minx={minX} data-miny={minY} style={style}> {this.props.render} </div> ); } }); export default Widget;
import React from 'react'; const nbCol = 12; const nbRow = 6; var Widget = React.createClass({ render: function () { var xSize = $(window).width() / nbCol, ySize = $(window).height() / nbRow; var style = { width: "calc(100vw/" + nbCol + " * " + this.props.width + ")", height: "calc(100vh/" + nbRow + " * " + this.props.height + ")", } if (this.props.debug == "true") { style.background = "tomato"; } var posX = this.props.posX * xSize - xSize, posY = this.props.posY * ySize - ySize; style.transform = "translate("+ posX +"px, "+ posY +"px)"; return ( <div className="widget" data-x={posX} data-y={posY} style={style}> {this.props.render} </div> ); } }); export default Widget;
Fix wrong rtol in adjointTest
''' These are tests to assist with creating :class:`.LinearOperator`. ''' import numpy as np from numpy.testing import assert_allclose def adjointTest(O, significant = 7): ''' Test for verifying forward and adjoint functions in LinearOperator. adjointTest verifies correctness for the forward and adjoint functions for an operator via asserting :math:`<A^H y, x> = <y, A x>` Parameters ---------- O : LinearOperator The LinearOperator to test. significant : int, optional Perform the test with a numerical accuracy of "significant" digits. Examples -------- >>> from pyop import LinearOperator >>> A = LinearOperator((4,4), lambda _, x: x, lambda _, x: x) >>> adjointTest(A) >>> B = LinearOperator((4,4), lambda _, x: x, lambda _, x: 2*x) >>> adjointTest(B) ... # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... AssertionError: ''' x = np.random.rand(O.shape[1]) y = np.random.rand(O.shape[0]) assert_allclose(O.T(y).dot(x), y.dot(O(x)), rtol = 10**(-significant))
''' These are tests to assist with creating :class:`.LinearOperator`. ''' import numpy as np from numpy.testing import assert_allclose def adjointTest(O, significant = 7): ''' Test for verifying forward and adjoint functions in LinearOperator. adjointTest verifies correctness for the forward and adjoint functions for an operator via asserting :math:`<A^H y, x> = <y, A x>` Parameters ---------- O : LinearOperator The LinearOperator to test. significant : int, optional Perform the test with a numerical accuracy of "significant" digits. Examples -------- >>> from pyop import LinearOperator >>> A = LinearOperator((4,4), lambda _, x: x, lambda _, x: x) >>> adjointTest(A) >>> B = LinearOperator((4,4), lambda _, x: x, lambda _, x: 2*x) >>> adjointTest(B) ... # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... AssertionError: ''' x = np.random.rand(O.shape[1]) y = np.random.rand(O.shape[0]) assert_allclose(O.T(y).dot(x), y.dot(O(x)), rtol = 10**significant)