text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix lint checks in migration recipes/0045.
# -*- coding: utf-8 -*- from __future__ import unicode_literals import hashlib from base64 import urlsafe_b64encode from django.db import migrations def make_hashes_urlsafe_sri(apps, schema_editor): Action = apps.get_model('recipes', 'Action') for action in Action.objects.all(): data = action.implementation.encode() digest = hashlib.sha384(data).digest() data_hash = urlsafe_b64encode(digest) action.implementation_hash = 'sha384-' + data_hash.decode() action.save() def make_hashes_sha1(apps, schema_editor): Action = apps.get_model('recipes', 'Action') for action in Action.objects.all(): data = action.implementation.encode() data_hash = hashlib.sha1(data).hexdigest() action.implementation_hash = data_hash action.save() class Migration(migrations.Migration): dependencies = [ ('recipes', '0044_auto_20170801_0010'), ] operations = [ migrations.RunPython(make_hashes_urlsafe_sri, make_hashes_sha1), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals import hashlib from base64 import b64encode, urlsafe_b64encode from django.db import migrations def make_hashes_urlsafe_sri(apps, schema_editor): Action = apps.get_model('recipes', 'Action') for action in Action.objects.all(): data = action.implementation.encode() digest = hashlib.sha384(data).digest() data_hash = urlsafe_b64encode(digest) action.implementation_hash = 'sha384-' + data_hash.decode() action.save() def make_hashes_sha1(apps, schema_editor): Action = apps.get_model('recipes', 'Action') for action in Action.objects.all(): data = action.implementation.encode() data_hash = hashlib.sha1(data).hexdigest() action.implementation_hash = data_hash action.save() class Migration(migrations.Migration): dependencies = [ ('recipes', '0044_auto_20170801_0010'), ] operations = [ migrations.RunPython(make_hashes_urlsafe_sri, make_hashes_sha1), ]
Disable new test from r1779 for the android generator. BUG=gyp:379 TBR=torne@chromium.org Review URL: https://codereview.chromium.org/68333002
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that copying files preserves file attributes. """ import TestGyp import os import stat import sys def check_attribs(path, expected_exec_bit): out_path = test.built_file_path(path, chdir='src') in_stat = os.stat(os.path.join('src', path)) out_stat = os.stat(out_path) if out_stat.st_mode & stat.S_IXUSR != expected_exec_bit: test.fail_test() # Doesn't pass with the android generator, see gyp bug 379. test = TestGyp.TestGyp(formats=['!android']) test.run_gyp('copies-attribs.gyp', chdir='src') test.build('copies-attribs.gyp', chdir='src') if sys.platform != 'win32': out_path = test.built_file_path('executable-file.sh', chdir='src') test.must_contain(out_path, '#!/bin/bash\n' '\n' 'echo echo echo echo cho ho o o\n') check_attribs('executable-file.sh', expected_exec_bit=stat.S_IXUSR) test.pass_test()
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that copying files preserves file attributes. """ import TestGyp import os import stat import sys def check_attribs(path, expected_exec_bit): out_path = test.built_file_path(path, chdir='src') in_stat = os.stat(os.path.join('src', path)) out_stat = os.stat(out_path) if out_stat.st_mode & stat.S_IXUSR != expected_exec_bit: test.fail_test() test = TestGyp.TestGyp() test.run_gyp('copies-attribs.gyp', chdir='src') test.build('copies-attribs.gyp', chdir='src') if sys.platform != 'win32': out_path = test.built_file_path('executable-file.sh', chdir='src') test.must_contain(out_path, '#!/bin/bash\n' '\n' 'echo echo echo echo cho ho o o\n') check_attribs('executable-file.sh', expected_exec_bit=stat.S_IXUSR) test.pass_test()
Add is_active() method to the Library class
class Library: """This class represents a simaris target and is initialized with data in JSON format """ def __init__(self, data): if 'CurrentTarget' in data: self.target = data['CurrentTarget']['EnemyType'] self.scans = data['CurrentTarget']['PersonalScansRequired'] self.progress = data['CurrentTarget']['ProgressPercent'] self.active = True else: self.active = False def __str__(self): """Returns a string with all the information about this alert """ if not self.is_active(): return None library_string = ('Target: {0}\n' 'Scans needed: {1}\n' 'Progress: {2:.2f}%' ) return library_string.format(self.target, self.scans, self.progress) def is_active(self): """ Returns True if there is a currently active target, False otherwise """ return self.active
class Library: """This class represents a simaris target and is initialized with data in JSON format """ def __init__(self, data): self.target = data['CurrentTarget']['EnemyType'] self.scans = data['CurrentTarget']['PersonalScansRequired'] self.progress = data['CurrentTarget']['ProgressPercent'] def __str__(self): """Returns a string with all the information about this alert """ library_string = ('Target: {0}\n' 'Scans needed: {1}\n' 'Progress: {2:.2f}%' ) return library_string.format(self.target, self.scans, self.progress)
Reorder import in slack service
package services import ( "os" "fmt" "net/http" "encoding/json" "strconv" "github.com/jmoiron/jsonq" ) const ( slackUserListURL = "https://slack.com/api/users.list" ) func SlackUserList() (map[string]string, error){ token := os.Getenv("SLACK_API_TOKEN") if token == "" { return nil, fmt.Errorf("You need to pass SLACK_API_TOKEN as environment variable") } requestURL := slackUserListURL + "?token=" + token resp, err := http.Get(requestURL) if err != nil { return nil, err } defer resp.Body.Close() data := map[string]interface{}{} dec := json.NewDecoder(resp.Body) dec.Decode(&data) jq := jsonq.NewQuery(data) arr, err := jq.Array("members") users := make(map[string]string) for i := 0; i < len(arr); i++ { id, _ := jq.String("members", strconv.Itoa(i), "id") name, _ := jq.String("members", strconv.Itoa(i), "name") users[name] = id } return users, err }
package services import ( "os" "fmt" "net/http" "encoding/json" "github.com/jmoiron/jsonq" "strconv" ) const ( slackUserListURL = "https://slack.com/api/users.list" ) func SlackUserList() (map[string]string, error){ token := os.Getenv("SLACK_API_TOKEN") if token == "" { return nil, fmt.Errorf("You need to pass SLACK_API_TOKEN as environment variable") } requestURL := slackUserListURL + "?token=" + token resp, err := http.Get(requestURL) if err != nil { return nil, err } defer resp.Body.Close() data := map[string]interface{}{} dec := json.NewDecoder(resp.Body) dec.Decode(&data) jq := jsonq.NewQuery(data) arr, err := jq.Array("members") users := make(map[string]string) for i := 0; i < len(arr); i++ { id, _ := jq.String("members", strconv.Itoa(i), "id") name, _ := jq.String("members", strconv.Itoa(i), "name") users[name] = id } return users, err }
Fix incorrect string 'event' in place of var
'use strict'; var EventEmitter = require('events').EventEmitter; var Promise = require('bluebird'); var emitThen = function (event) { var args = Array.prototype.slice.call(arguments, 1); return Promise .bind(this) .return(this) .call('listeners', event) .map(function (listener) { var a1 = args[0], a2 = args[1]; switch (args.length) { case 0: return listener.call(this); case 1: return listener.call(this, a1) case 2: return listener.call(this, a1, a2); default: return listener.apply(this, args); } }); }; emitThen.register = function () { EventEmitter.prototype.emitThen = emitThen; }; module.exports = emitThen;
'use strict'; var EventEmitter = require('events').EventEmitter; var Promise = require('bluebird'); var emitThen = function (event) { var args = Array.prototype.slice.call(arguments, 1); return Promise .bind(this) .return(this) .call('listeners', 'event') .map(function (listener) { var a1 = args[0], a2 = args[1]; switch (args.length) { case 0: return listener.call(this); case 1: return listener.call(this, a1) case 2: return listener.call(this, a1, a2); default: return listener.apply(this, args); } }); }; emitThen.register = function () { EventEmitter.prototype.emitThen = emitThen; }; module.exports = emitThen;
Set value to annotation @WebAppConfiguration in tests.
package access; import config.MvcConfiguration; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Created by Vladyslav Dovhopol on 4/27/17. * Test Greeting Controller. */ @RunWith(SpringRunner.class) @WebAppConfiguration(value = "source/config") @ContextConfiguration(classes = MvcConfiguration.class) public class AccessControllerTest { private MockMvc mockMvc; @Autowired private WebApplicationContext webApplicationContext; @Before public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void GET_NoPayload_Success() throws Exception { ResultActions result = mockMvc.perform(get("/greeting")); result.andExpect(status().isOk()); } }
package access; import config.MvcConfiguration; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Created by Vladyslav Dovhopol on 4/27/17. * Test Greeting Controller. */ @RunWith(SpringRunner.class) @WebAppConfiguration @ContextConfiguration(classes = MvcConfiguration.class) public class AccessControllerTest { private MockMvc mockMvc; @Autowired private WebApplicationContext webApplicationContext; @Before public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void GET_NoPayload_Success() throws Exception { ResultActions result = mockMvc.perform(get("/greeting")); result.andExpect(status().isOk()); } }
Switch to class based generic views.
from django.conf import settings from django.conf.urls.defaults import patterns, url, include from django.views.generic.base import RedirectView from sumo import views services_patterns = patterns('', url('^/monitor$', views.monitor, name='sumo.monitor'), url('^/version$', views.version_check, name='sumo.version'), url('^/error$', views.error, name='sumo.error'), ) urlpatterns = patterns('', url(r'^robots.txt$', views.robots, name='robots.txt'), ('^services', include(services_patterns)), url('^locales$', views.locales, name='sumo.locales'), # Shortcuts: url('^contribute/?$', RedirectView.as_view(url='/kb/superheroes-wanted', permanent=False)), url(r'^windows7-support(?:\\/)?$', RedirectView.as_view(url='/home/?as=u', permanent=False)), ) if 'django_qunit' in settings.INSTALLED_APPS: urlpatterns += patterns('', url(r'^qunit/(?P<path>.*)', views.kitsune_qunit), url(r'^_qunit/', include('django_qunit.urls')), )
from django.conf import settings from django.conf.urls.defaults import patterns, url, include from django.views.generic.simple import redirect_to from sumo import views services_patterns = patterns('', url('^/monitor$', views.monitor, name='sumo.monitor'), url('^/version$', views.version_check, name='sumo.version'), url('^/error$', views.error, name='sumo.error'), ) urlpatterns = patterns('', url(r'^robots.txt$', views.robots, name='robots.txt'), ('^services', include(services_patterns)), url('^locales$', views.locales, name='sumo.locales'), # Shortcuts: url('^contribute/?$', redirect_to, {'url': '/kb/superheroes-wanted', 'permanent': False}), url(r'^windows7-support(?:\\/)?$', redirect_to, {'url': '/home/?as=u', 'permanent': False}), ) if 'django_qunit' in settings.INSTALLED_APPS: urlpatterns += patterns('', url(r'^qunit/(?P<path>.*)', views.kitsune_qunit), url(r'^_qunit/', include('django_qunit.urls')), )
Make context output behavior overridable
from .settings import env class AutoAPIBase(object): language = 'base' type = 'base' def __init__(self, obj): self.obj = obj def render(self, ctx=None): if not ctx: ctx = {} template = env.get_template( '{language}/{type}.rst'.format(language=self.language, type=self.type) ) ctx.update(**self.get_context_data()) return template.render(**ctx) def get_absolute_path(self): return "/autoapi/{type}/{name}".format( type=self.type, name=self.name, ) def get_context_data(self): return self.__dict__ class UnknownType(AutoAPIBase): def render(self, ctx=None): print "Unknown Type: %s" % (self.obj['type']) super(UnknownType, self).render(ctx=ctx)
from .settings import env class AutoAPIBase(object): language = 'base' type = 'base' def __init__(self, obj): self.obj = obj def render(self, ctx=None): if not ctx: ctx = {} template = env.get_template( '{language}/{type}.rst'.format(language=self.language, type=self.type) ) ctx.update(**self.__dict__) return template.render(**ctx) def get_absolute_path(self): return "/autoapi/{type}/{name}".format( type=self.type, name=self.name, ) class UnknownType(AutoAPIBase): def render(self, ctx=None): print "Unknown Type: %s" % (self.obj['type']) super(UnknownType, self).render(ctx=ctx)
Add PyHamcrest as a unit test dependency
import os import platform from setuptools import setup requirements = [ "pycurl", "pyyaml >= 3.09", "tornado >= 1.1, <2.0", "testify == 0.3.10", "PyHamcrest >= 1.8", ] # python-rrdtool doesn't install cleanly out of the box on OS X if not (os.name == "posix" and platform.system() == "Darwin"): requirements.append("python-rrdtool >= 1.4.7") setup( name='firefly', version='1.0', provides=['firefly'], author='Yelp', description='A multi-datacenter graphing tool', packages=['firefly'], long_description="""Firefly provides graphing of performance metrics from multiple data centers and sources. Firefly works with both the Ganglia and Statmonster data sources. """, install_requires=requirements )
import os import platform from setuptools import setup requirements = [ "pycurl", "pyyaml >= 3.09", "tornado >= 1.1, <2.0", "testify == 0.3.10", ] # python-rrdtool doesn't install cleanly out of the box on OS X if not (os.name == "posix" and platform.system() == "Darwin"): requirements.append("python-rrdtool >= 1.4.7") setup( name='firefly', version='1.0', provides=['firefly'], author='Yelp', description='A multi-datacenter graphing tool', packages=['firefly'], long_description="""Firefly provides graphing of performance metrics from multiple data centers and sources. Firefly works with both the Ganglia and Statmonster data sources. """, install_requires=requirements )
Remove console log with errors
'use strict' const jsonPatch = require('fast-json-patch') const getValue = require('./../fn/getValue') const nestingPatches = require('./../fn/nestingPatches') const decomposePath = require('./../fn/decomposePath') const uniq = require('uniq') const flatten = require('./../fn/flatten') const triggerListener = require('./../fn/triggerListener') /** * patch * * Applies a patch */ module.exports = db => patch => { if (patch instanceof Array === false) { patch = [patch] } // Check if root exists for add operations patch.forEach(x => { let path = x.path.split('/') path = path.slice(0, path.length - 1).join('/') if (x.op === 'add' && getValue(db.static, path) === undefined) { let patches = nestingPatches(db.static, x.path) jsonPatch.apply(db.static, patches) } }) let errors = jsonPatch.apply(db.static, patch) let trigger = [] patch.forEach(x => { let parts = decomposePath(x.path) parts.push(x.path) parts.forEach(y => { if (db.updates.triggers[y]) { trigger.push(db.updates.triggers[y]) } }) }) trigger = flatten(trigger) trigger = uniq(trigger) trigger.map(x => { triggerListener(db, x) }) }
'use strict' const jsonPatch = require('fast-json-patch') const getValue = require('./../fn/getValue') const nestingPatches = require('./../fn/nestingPatches') const decomposePath = require('./../fn/decomposePath') const uniq = require('uniq') const flatten = require('./../fn/flatten') const triggerListener = require('./../fn/triggerListener') /** * patch * * Applies a patch */ module.exports = db => patch => { if (patch instanceof Array === false) { patch = [patch] } // Check if root exists for add operations patch.forEach(x => { let path = x.path.split('/') path = path.slice(0, path.length - 1).join('/') if (x.op === 'add' && getValue(db.static, path) === undefined) { let patches = nestingPatches(db.static, x.path) jsonPatch.apply(db.static, patches) } }) let errors = jsonPatch.apply(db.static, patch) console.log(errors) let trigger = [] patch.forEach(x => { let parts = decomposePath(x.path) parts.push(x.path) parts.forEach(y => { if (db.updates.triggers[y]) { trigger.push(db.updates.triggers[y]) } }) }) trigger = flatten(trigger) trigger = uniq(trigger) trigger.map(x => { triggerListener(db, x) }) }
Fix usage of `version_info` on Python 2.
# vim: fileencoding=utf-8 from __future__ import print_function, absolute_import, unicode_literals import sys class VersionError (ValueError): pass def check_ex (): v = sys.version_info if v.major == 3: if v.minor < 3 or (v.minor == 3 and v.micro < 4): raise VersionError("Error: this is Python 3.{}.{}, not 3.3.4+".format(v.minor, v.micro)) elif v.major == 2: if v.minor < 7: raise VersionError("Error: this is Python 2.{}, not 2.7".format(v.minor)) else: raise VersionError("Error: this is Python {}, not 2.7 nor 3.x".format(v.major)) def check (): try: check_ex() except VersionError as e: print(e.args, file=sys.stderr) print("Python 2.7 or 3.3+ is required.", file=sys.stderr) sys.exit(2)
# vim: fileencoding=utf-8 from __future__ import print_function, absolute_import, unicode_literals import sys class VersionError (ValueError): pass def check_ex (): major, minor, patch = sys.version_info[0:2] if major == 3: if minor < 3 or (minor == 3 and patch < 4): raise VersionError("Error: this is Python 3.{}.{}, not 3.3.4+".format(minor, patch)) elif major == 2: if minor < 7: raise VersionError("Error: this is Python 2.{}, not 2.7".format(minor)) else: raise VersionError("Error: this is Python {}, not 2.7 nor 3.x".format(major)) def check (): try: check_ex() except VersionError as e: print(e.args, file=sys.stderr) print("Python 2.7 or 3.3+ is required.", file=sys.stderr) sys.exit(2)
Add templates, bump version number
from setuptools import setup, find_packages setup( name='icecake', version='0.2.0', py_modules=['icecake', 'templates'], url="https://github.com/cbednarski/icecake", author="Chris Bednarski", author_email="banzaimonkey@gmail.com", description="An easy and cool static site generator", license="MIT", install_requires=[ 'Click', 'Jinja2', 'Markdown', 'Pygments', 'python-dateutil', 'Werkzeug', ], entry_points=''' [console_scripts] icecake=icecake:cli ''', keywords="static site generator builder icecake" )
from setuptools import setup, find_packages setup( name='icecake', version='0.1.0', py_modules=['icecake'], url="https://github.com/cbednarski/icecake", author="Chris Bednarski", author_email="banzaimonkey@gmail.com", description="An easy and cool static site generator", license="MIT", install_requires=[ 'Click', 'Jinja2', 'Markdown', 'Pygments', 'python-dateutil', 'Werkzeug', ], entry_points=''' [console_scripts] icecake=icecake:cli ''', keywords="static site generator builder icecake" )
chore(karma): Update adapter selection to 0.9.x
// Karma configuration // base path, that will be used to resolve files and exclude basePath = ''; // list of files / patterns to load in the browser files = [ 'node_modules/chai/chai.js', 'node_modules/sinon/pkg/sinon.js', 'dist/sinon-doublist.js', 'lib/jquery.js', 'test/lib/sinon-doublist-fs/index.js', 'test/mocha.js' ]; frameworks = ['mocha']; // test results reporter to use // possible values: 'dots', 'progress', 'junit' reporters = ['progress']; // web server port port = 9876; // cli runner port runnerPort = 9100; // enable / disable colors in the output (reporters and logs) colors = true; // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel = LOG_WARN; // enable / disable watching file and executing tests whenever any file changes autoWatch = false; // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers = []; // If browser does not capture in given timeout [ms], kill it captureTimeout = 60000; // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun = false;
// Karma configuration // base path, that will be used to resolve files and exclude basePath = ''; // list of files / patterns to load in the browser files = [ MOCHA, MOCHA_ADAPTER, 'node_modules/chai/chai.js', 'node_modules/sinon/pkg/sinon.js', 'dist/sinon-doublist.js', 'lib/jquery.js', 'test/lib/sinon-doublist-fs/index.js', 'test/mocha.js' ]; // test results reporter to use // possible values: 'dots', 'progress', 'junit' reporters = ['progress']; // web server port port = 9876; // cli runner port runnerPort = 9100; // enable / disable colors in the output (reporters and logs) colors = true; // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel = LOG_WARN; // enable / disable watching file and executing tests whenever any file changes autoWatch = false; // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers = []; // If browser does not capture in given timeout [ms], kill it captureTimeout = 60000; // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun = false;
Use a light version of parent to instance in proto.
/* * InheritJS * https://github.com/Techniv/inheritjs * * Released under the MIT License. * https://github.com/Techniv/inheritjs/blob/master/LICENSE */ (function(){ /** * @param parent The parent constructor. * @param constructor The child constructor. * @param prototype The child prototype. [not implement yet] * @returns {Function} The inherit constructor. */ function ineritjs(parent, constructor, prototype){ //TODO external prototype. var lightParent = function(){}; lightParent.prototype = parent.prototype; constructor.prototype.__proto__ = new lightParent; return function(){ this.__proto__ = constructor.prototype; this.constructor = constructor; parent.apply(this, arguments); constructor.apply(this,arguments); } }; // Exporting module. if( typeof module == "object" && typeof module.exports == "object" ){ module.exports = ineritjs; } else if( typeof window == "object" ) { window.inherit = ineritjs; } })();
/* * InheritJS * https://github.com/Techniv/inheritjs * * Released under the MIT License. * https://github.com/Techniv/inheritjs/blob/master/LICENSE */ (function(){ /** * @param parent The parent constructor. * @param constructor The child constructor. * @param prototype The child prototype. [not implement yet] * @returns {Function} The inherit constructor. */ function ineritjs(parent, constructor, prototype){ //TODO external prototype. constructor.prototype.__proto__ = new parent; return function(){ this.__proto__ = constructor.prototype; this.constructor = constructor; parent.apply(this, arguments); constructor.apply(this,arguments); } }; // Exporting module. if( typeof module == "object" && typeof module.exports == "object" ){ module.exports = ineritjs; } else if( typeof window == "object" ) { window.inherit = ineritjs; } })();
Fix typo in `ticketed_events` migration
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class MakeTicketedEventImageUrlLonger extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('ticketed_events', function (Blueprint $table) { $table->text('image_url')->nullable()->change(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('ticketed_events', function (Blueprint $table) { $table->string('image_url')->nullable()->change(); }); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class MakeTicketedEventImageUrlLonger extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('ticketed_events', function (Blueprint $table) { $table->text('image_url')->nbullable()->change(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('ticketed_events', function (Blueprint $table) { $table->string('image_url')->nbullable()->change(); }); } }
Comment out initial solution, include faster course solution
// Reverse Array In Place /*RULES: Take array as parameter Reverse array Return reversed array NOTES: Can't create new empty array to push in Must modify given array Can't use array.reverse(); */ /*PSEUDOCODE 1) Find array length 2) Create variable "stopper" for last element in array 2) (array.length - 1) times do: 2a) Push element previous to "stopper" to the end of the array 2b) Splice that same element out from in front of 'stopper' 3) When done, return reversed array */ // This is the solution I came up with and it works! But, will add the course solution underneath. Considerably faster, since it only loops through half of the array rather than the whole array like mine does. // function reverseArray(arr){ // var count = arr.length; // var stopper = arr[count - 1]; // for (var i = 0; i < count; i++){ // arr.push(arr[arr.indexOf(stopper) - 1]); // arr.splice((arr.indexOf(stopper) - 1), 1); // } // return arr; // } function reverseArrayInPlace(arr) { for (var i = 0; i < arr.length / 2; i++) { var tempVar = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = tempVar; } return arr; }
// Reverse Array In Place /*RULES: Take array as parameter Reverse array Return reversed array NOTES: Can't create new empty array to push in Must modify given array Can't use array.reverse(); */ /*PSEUDOCODE 1) Find array length 2) Create variable "stopper" for last element in array 2) (array.length - 1) times do: 2a) Push element previous to "stopper" to the end of the array 2b) Splice that same element out from in front of 'stopper' 3) When done, return reversed array */ function reverseArray(arr){ var count = arr.length; var stopper = arr[count - 1]; for (var i = 0; i < count; i++){ arr.push(arr[arr.indexOf(stopper) - 1]); arr.splice((arr.indexOf(stopper) - 1), 1); } return arr; }
Increase base menu count in e2e tests
'use strict'; describe('Navigation', function () { var baseMenuCount = 6; it('should cope with a list with menu options', function () { browser().navigateTo('/#!/b_using_options'); expect(repeater('.dropdown-option').count()).toEqual(1 + baseMenuCount); }); it('should cope with a list without menu options', function () { browser().navigateTo('/#!/d_array_example'); expect(repeater('.dropdown-option').count()).toEqual(0 + baseMenuCount); }); it('should cope with an edit screen with menu options', function () { browser().navigateTo('/#!/b_using_options/519a6075b320153869b175e0/edit'); expect(repeater('.dropdown-option').count()).toEqual(2 + baseMenuCount); }); it('should cope with an edit screen with menu options', function () { browser().navigateTo('/#!/a_unadorned_mongoose/519a6075b320153869b17599/edit'); expect(repeater('.dropdown-option').count()).toEqual(0 + baseMenuCount); }); });
'use strict'; describe('Navigation', function () { var baseMenuCount = 5; it('should cope with a list with menu options', function () { browser().navigateTo('/#!/b_using_options'); expect(repeater('.dropdown-option').count()).toEqual(1 + baseMenuCount); }); it('should cope with a list without menu options', function () { browser().navigateTo('/#!/d_array_example'); expect(repeater('.dropdown-option').count()).toEqual(0 + baseMenuCount); }); it('should cope with an edit screen with menu options', function () { browser().navigateTo('/#!/b_using_options/519a6075b320153869b175e0/edit'); expect(repeater('.dropdown-option').count()).toEqual(2 + baseMenuCount); }); it('should cope with an edit screen with menu options', function () { browser().navigateTo('/#!/a_unadorned_mongoose/519a6075b320153869b17599/edit'); expect(repeater('.dropdown-option').count()).toEqual(0 + baseMenuCount); }); });
Add read only functionnality on published node
<?php namespace PHPOrchestra\ModelBundle\EventListener; use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs; use Doctrine\ODM\MongoDB\Event\PostFlushEventArgs; use PHPOrchestra\ModelBundle\Model\StatusInterface; use PHPOrchestra\ModelBundle\Model\StatusableInterface; /** * Class SavePublishedDocumentListener */ class SavePublishedDocumentListener { /** * @param LifecycleEventArgs $eventArgs */ public function preUpdate(LifecycleEventArgs $eventArgs) { $document = $eventArgs->getDocument(); if ($document instanceof StatusableInterface) { $status = $document->getStatus(); if (!empty($status) && $status->isPublished() && (!method_exists($document, 'isDeleted') || ! $document->isDeleted()) ) { $documentManager = $eventArgs->getDocumentManager(); $documentManager->getUnitOfWork()->detach($document); } } } }
<?php namespace PHPOrchestra\ModelBundle\EventListener; use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs; use Doctrine\ODM\MongoDB\Event\PostFlushEventArgs; use PHPOrchestra\ModelBundle\Model\StatusInterface; use PHPOrchestra\ModelBundle\Model\StatusableInterface; /** * Class SavePublishedDocumentListener */ class SavePublishedDocumentListener { /** * @param LifecycleEventArgs $eventArgs */ public function preUpdate(LifecycleEventArgs $eventArgs) { $document = $eventArgs->getDocument(); if ($document instanceof StatusableInterface) { $status = $document->getStatus(); if (! empty($status) && $status->isPublished() && (!method_exists($document, 'isDeleted') || ! $document->isDeleted()) ) { $documentManager = $eventArgs->getDocumentManager(); $documentManager->getUnitOfWork()->detach($document); } } } }
Fix package name to match PyPI
from setuptools import setup import os from appkit import __version__ data = list() for d in os.walk('appkit/'): if len(d[2]) > 0: path_list = [str.join('/', os.path.join(d[0], x).split('/')[1:]) for x in d[2]] data.extend(path_list) requires = ['flask', 'pygobject',] requires.append('beautifulsoup4') # v0_2_4 backward compatibility setup( name='AppKit', version=__version__, description='Desktop application framework based on Webkit' + ' HTML5, CSS3, Javascript and Python', author='Nitipit Nontasuwan', author_email='nitipit@gmail.com', url='http://nitipit.github.com/appkit/', license='MIT', platforms=['Linux', ], keywords=['framework, html5, gnome, ui'], package_dir={'appkit': 'appkit'}, packages=['appkit'], package_data={'appkit': data}, install_requires=requires, )
from setuptools import setup import os from appkit import __version__ data = list() for d in os.walk('appkit/'): if len(d[2]) > 0: path_list = [str.join('/', os.path.join(d[0], x).split('/')[1:]) for x in d[2]] data.extend(path_list) requires = ['flask', 'pygobject',] requires.append('beautifulsoup4') # v0_2_4 backward compatibility setup( name='appkit', version=__version__, description='Desktop application framework based on Webkit' + ' HTML5, CSS3, Javascript and Python', author='Nitipit Nontasuwan', author_email='nitipit@gmail.com', url='http://nitipit.github.com/appkit/', license='MIT', platforms=['Linux', ], keywords=['framework, html5, gnome, ui'], package_dir={'appkit': 'appkit'}, packages=['appkit'], package_data={'appkit': data}, install_requires=requires, )
Make doc and naming consistent.
/* * Copyright 2018, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.command; /** * A pre-processed {@link HandledError}. * * <p>Performs no action on {@link #rethrowOnce()} and always returns * {@link java.util.Optional#empty() Optional.empty()} on {@link #asRejection()}. * * @author Dmytro Dashenkov */ enum PreProcessedError implements HandledError { INSTANCE }
/* * Copyright 2018, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.command; /** * A preprocessed {@link HandledError}. * * <p>Performs no action on {@link #rethrowOnce()} and always returns * {@link java.util.Optional#empty() Optional.empty()} on {@link #asRejection()}. * * @author Dmytro Dashenkov */ enum PreProcessedError implements HandledError { INSTANCE }
Fix HTML unescape issue for messages
import Ember from "ember"; const { getOwner } = Ember; export default Ember.Service.extend({ i18n: Ember.inject.service(), convert: function(values) { var offerId = values.offer.id; values.body = values.body.trim(); values.body = Ember.Handlebars.Utils.escapeExpression(values.body || ""); values.body = values.body.replace(/(\r\n|\n|\r)/gm, "<br>"); var msg = values.body; var url_with_text = msg.slice(msg.indexOf("[") + 1, msg.indexOf("]")); var url_text_begin = url_with_text.indexOf("|"); var url_text = url_with_text.slice(0, url_text_begin); var url_for = url_with_text.slice(url_text_begin + 1).trim(); if (url_for === "transport_page") { values.body = msg.replace( "[" + url_with_text + "]", `<a href='/offers/${offerId}/plan_delivery'>${url_text}</a>` ); } if (url_for === "feedback_form") { values.body = msg.replace( "[" + url_with_text + "]", `<a href=' https://crossroads-foundation.formstack.com/forms/goodcity_feedback?OfferId=${offerId}'>${url_text}</a>` ); } } });
import Ember from "ember"; const { getOwner } = Ember; export default Ember.Service.extend({ i18n: Ember.inject.service(), convert: function(values) { var offerId = values.offer.id; var msg = values.body.trim(); msg = Ember.Handlebars.Utils.escapeExpression(msg || ""); msg = msg.replace(/(\r\n|\n|\r)/gm, "<br>"); var url_with_text = msg.slice(msg.indexOf("[") + 1, msg.indexOf("]")); var url_text_begin = url_with_text.indexOf("|"); var url_text = url_with_text.slice(0, url_text_begin); var url_for = url_with_text.slice(url_text_begin + 1); if (url_for === "transport_page") { values.body = msg.replace( "[" + url_with_text + "]", `<a href='/offers/${offerId}/plan_delivery'>${url_text}</a>` ); } if (url_for === "feedback_form") { values.body = msg.replace( "[" + url_with_text + "]", `<a href=' https://crossroads-foundation.formstack.com/forms/goodcity_feedback?OfferId=${offerId}'>${url_text}</a>` ); } } });
Make hashes that are not valid redirect to DEFAULT_PAGE
var DEFAULT_PAGE = 'about'; // Given an HTML string response, set it as the page content. var onChangePage = function(/*string*/ response) { var body = document.getElementById('body'); body.innerHTML = response; } // Given a URL, load the contents into the body of the page. var loadPage = function(/*string*/ url) { var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (request.readyState === 4) { onChangePage(request.responseText); } }; request.open('GET', url, true); request.send(); }; var loadPageAndUpdateNavFromCurrentHash = function() { var links = { about: document.getElementById('nav-about'), projects: document.getElementById('nav-projects') }; var hash = window.location.hash.replace('#', ''); hash = hash in links ? hash : DEFAULT_PAGE; for (var link_name in links) { if (links.hasOwnProperty(link_name)) { if (link_name === hash) { links[link_name].classList.add('selected'); } else { links[link_name].classList.remove('selected'); } } } loadPage(hash + '.html'); } window.onhashchange = loadPageAndUpdateNavFromCurrentHash; window.onload = loadPageAndUpdateNavFromCurrentHash;
var DEFAULT_PAGE = 'about'; // Given an HTML string response, set it as the page content. var onChangePage = function(/*string*/ response) { var body = document.getElementById('body'); body.innerHTML = response; } // Given a URL, load the contents into the body of the page. var loadPage = function(/*string*/ url) { var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (request.readyState === 4) { onChangePage(request.responseText); } }; request.open('GET', url, true); request.send(); }; var loadPageAndUpdateNavFromCurrentHash = function() { var hash = window.location.hash.replace('#', '') || DEFAULT_PAGE; var links = { about: document.getElementById('nav-about'), projects: document.getElementById('nav-projects') }; for (var link_name in links) { if (links.hasOwnProperty(link_name)) { if (link_name === hash) { links[link_name].classList.add('selected'); } else { links[link_name].classList.remove('selected'); } } } loadPage(hash + '.html'); } window.onhashchange = loadPageAndUpdateNavFromCurrentHash; window.onload = loadPageAndUpdateNavFromCurrentHash;
Fix missing resume file extension
<?php namespace App\Http\Controllers; use App\Mail\ResumeDownloaded; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; class DownloadResumeController extends Controller { public function __invoke(Request $request) { $this->validate($request, [ 'email' => 'required|email', ], [ 'email.required' => 'To be fair, you could enter any valid email and you would still be able to download my resume. <br>So if you really want it that badly then here, use <code>gimme@example.com</code>', 'email.email' => 'To be fair, you could enter any valid email and you would still be able to download my resume. <br>So if you really want it that badly then here, use <code>gimme@example.com</code>', ]); Mail::to(config('mail.from.address')) ->send(new ResumeDownloaded($request->input('email'))); return response()->download(storage_path('app/resume.pdf'), 'Tonning, Kristoffer - Resume.pdf'); } }
<?php namespace App\Http\Controllers; use App\Mail\ResumeDownloaded; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; class DownloadResumeController extends Controller { public function __invoke(Request $request) { $this->validate($request, [ 'email' => 'required|email', ], [ 'email.required' => 'To be fair, you could enter any valid email and you would still be able to download my resume. <br>So if you really want it that badly then here, use <code>gimme@example.com</code>', 'email.email' => 'To be fair, you could enter any valid email and you would still be able to download my resume. <br>So if you really want it that badly then here, use <code>gimme@example.com</code>', ]); Mail::to(config('mail.from.address')) ->send(new ResumeDownloaded($request->input('email'))); return response()->download(storage_path('app/resume.pdf'), 'Tonning, Kristoffer - Resume'); } }
Add sun and moon to list of interesting objects
import ephem INTERESTING_OBJECTS = [ ephem.Sun, ephem.Moon, ephem.Mercury, ephem.Venus, ephem.Mars, ephem.Jupiter, ephem.Saturn, ephem.Uranus, ephem.Neptune, ] MIN_ALT = 5.0 * ephem.degree class AstroObject(): def __init__(self, ephem_object, observer): self.altitude = round(ephem_object.alt / ephem.degree) self.azimuth = round(ephem_object.az / ephem.degree) self.ephem_object = ephem_object self.name = ephem_object.name self.observer = observer def get_visible_objects(lat, lon): """ Get interesting objects currently visible from the given latitude and longitude. TODO: add other things besides planets """ visible = [] observer = ephem.Observer() observer.lat = str(lat) observer.lon = str(lon) for object_class in INTERESTING_OBJECTS: obj = object_class() obj.compute(observer) if obj.alt >= MIN_ALT: visible.append(AstroObject(obj, observer)) return visible
import ephem INTERESTING_PLANETS = [ ephem.Mercury, ephem.Venus, ephem.Mars, ephem.Jupiter, ephem.Saturn, ephem.Uranus, ephem.Neptune, ] MIN_ALT = 5.0 * ephem.degree class AstroObject(): def __init__(self, ephem_object, observer): self.altitude = round(ephem_object.alt / ephem.degree) self.azimuth = round(ephem_object.az / ephem.degree) self.ephem_object = ephem_object self.name = ephem_object.name self.observer = observer def get_visible_objects(lat, lon): """ Get interesting objects currently visible from the given latitude and longitude. TODO: add other things besides planets """ visible = [] observer = ephem.Observer() observer.lat = str(lat) observer.lon = str(lon) for Planet in INTERESTING_PLANETS: planet = Planet() planet.compute(observer) if planet.alt >= MIN_ALT: visible.append(AstroObject(planet, observer)) return visible
Fix a bug while clicking the first button to show the lesson
BustinBash.Directory.View = function() {} BustinBash.Directory.View.prototype = { hideAndShowDOM: function(data) { if(data != undefined){ $(data.Hide).hide(); $(data.Show).show(); this.clearDom(); } }, clearDom: function() { $('#directory-template li').hide(); }, appendCurrentFolder: function(data) { $('.current-folder').text(data) } } BustinBash.Directory.Controller = function(view) { this.view = view; } BustinBash.Directory.Controller.prototype = { init: function() { this.bindListeners(); }, bindListeners: function() { $(document).on('changeLevel', function(event, data) { this.data = data; this.clickLevel(this.data) }.bind(this)); $(document).on('success', function() { if(this.data.ID <= 12 ){ this.checkLevel(this.data) } }.bind(this)); }, checkLevel: function(data) { this.view.hideAndShowDOM(data); }, clickLevel: function(data){ $(document).on('clickLevel', function(event, data){ this.view.hideAndShowDOM(data); }.bind(this)) } }
BustinBash.Directory.View = function() {} BustinBash.Directory.View.prototype = { hideAndShowDOM: function(data) { $(data.Hide).hide(); $(data.Show).show(); this.clearDom(); }, clearDom: function() { $('#directory-template li').hide(); }, appendCurrentFolder: function(data) { $('.current-folder').text(data) } } BustinBash.Directory.Controller = function(view) { this.view = view; } BustinBash.Directory.Controller.prototype = { init: function() { this.bindListeners(); }, bindListeners: function() { $(document).on('changeLevel', function(event, data) { this.data = data; this.clickLevel(this.data) }.bind(this)); $(document).on('success', function() { if(this.data.ID <= 12 ){ this.checkLevel(this.data) } }.bind(this)); }, checkLevel: function(data) { this.view.hideAndShowDOM(data); }, clickLevel: function(data){ $(document).on('clickLevel', function(event, data){ this.view.hideAndShowDOM(data); }.bind(this)) } }
Add viewBox attr to top level <svg>
<?php namespace Bitverse\Identicon\SVG; class Svg extends SvgNode { private $width; private $height; private $children = []; /** * @param integer $width * @param integer $height */ public function __construct($width, $height) { $this->width = $width; $this->height = $height; } /** * @param SvgNode $node * * @return Svg */ public function addChild(SvgNode $node = null) { $this->children[] = $node; return $this; } public function __toString() { return sprintf( '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" ' . 'width="%d" height="%d" viewBox="0 0 %d %d">%s</svg>', $this->width, $this->height, $this->width, $this->height, implode('', array_map(function ($node) { return (string) $node; }, $this->children)) ); } }
<?php namespace Bitverse\Identicon\SVG; class Svg extends SvgNode { private $width; private $height; private $children = []; /** * @param integer $width * @param integer $height */ public function __construct($width, $height) { $this->width = $width; $this->height = $height; } /** * @param SvgNode $node * * @return Svg */ public function addChild(SvgNode $node = null) { $this->children[] = $node; return $this; } public function __toString() { return sprintf( '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" ' . 'width="%d" height="%d">%s</svg>', $this->width, $this->height, implode('', array_map(function ($node) { return (string) $node; }, $this->children)) ); } }
Fix issue with latest changes in haystack A merge into haystack has resulted in an additional argument for ``index_queryset``, I updated the search index for Oscar's product to fix the issue.
from haystack import indexes from django.db.models import get_model class ProductIndex(indexes.SearchIndex, indexes.Indexable): """ Base class for products solr index definition. Overide by creating your own copy of oscar.search_indexes.py """ text = indexes.EdgeNgramField(document=True, use_template=True, template_name='oscar/search/indexes/product/item_text.txt') title = indexes.EdgeNgramField(model_attr='title', null=True) upc = indexes.CharField(model_attr="upc", null=True) date_created = indexes.DateTimeField(model_attr='date_created') date_updated = indexes.DateTimeField(model_attr='date_updated') def get_model(self): return get_model('catalogue', 'Product') def index_queryset(self, using=None): """ Used when the entire index for model is updated. Orders by the most recently updated so that new objects are indexed first """ return self.get_model().objects.order_by('-date_updated') def get_updated_field(self): """ Used to specify the field used to determine if an object has been updated Can be used to filter the query set when updating the index """ return 'date_updated'
from haystack import indexes from django.db.models import get_model class ProductIndex(indexes.SearchIndex, indexes.Indexable): """ Base class for products solr index definition. Overide by creating your own copy of oscar.search_indexes.py """ text = indexes.EdgeNgramField(document=True, use_template=True, template_name='oscar/search/indexes/product/item_text.txt') title = indexes.EdgeNgramField(model_attr='title', null=True) upc = indexes.CharField(model_attr="upc", null=True) date_created = indexes.DateTimeField(model_attr='date_created') date_updated = indexes.DateTimeField(model_attr='date_updated') def get_model(self): return get_model('catalogue', 'Product') def index_queryset(self): """ Used when the entire index for model is updated. Orders by the most recently updated so that new objects are indexed first """ return self.get_model().objects.order_by('-date_updated') def get_updated_field(self): """ Used to specify the field used to determine if an object has been updated Can be used to filter the query set when updating the index """ return 'date_updated'
Add missing tests dependency pycodestyle.
import re import sys from setuptools import setup from setuptools.command.test import test as TestCommand # Parse the version from the file. verstrline = open('git_archive_all.py', "rt").read() VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]" mo = re.search(VSRE, verstrline, re.M) if mo: verstr = mo.group(1) else: raise RuntimeError("Unable to find version string in git_archive_all.py") class PyTest(TestCommand): user_options = [("pytest-args=", "a", "Arguments to pass to pytest")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = "" def run_tests(self): import shlex # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(shlex.split(self.pytest_args)) sys.exit(errno) setup( version=verstr, py_modules=['git_archive_all'], entry_points={'console_scripts': 'git-archive-all=git_archive_all:main'}, tests_require=['pytest', 'pytest-cov', 'pycodestyle'], cmdclass={"test": PyTest}, )
import re import sys from setuptools import setup from setuptools.command.test import test as TestCommand # Parse the version from the file. verstrline = open('git_archive_all.py', "rt").read() VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]" mo = re.search(VSRE, verstrline, re.M) if mo: verstr = mo.group(1) else: raise RuntimeError("Unable to find version string in git_archive_all.py") class PyTest(TestCommand): user_options = [("pytest-args=", "a", "Arguments to pass to pytest")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = "" def run_tests(self): import shlex # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(shlex.split(self.pytest_args)) sys.exit(errno) setup( version=verstr, py_modules=['git_archive_all'], entry_points={'console_scripts': 'git-archive-all=git_archive_all:main'}, tests_require=['pytest', 'pytest-cov'], cmdclass={"test": PyTest}, )
Increase length of logged request responses in `HTTPException`
<?php namespace wcf\util\exception; use wcf\system\exception\IExtraInformationException; use wcf\system\exception\SystemException; use wcf\util\HTTPRequest; use wcf\util\StringUtil; /** * Denotes failure to perform a HTTP request. * * @author Tim Duesterhus * @copyright 2001-2018 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Util\Exception * @since 3.0 */ class HTTPException extends SystemException implements IExtraInformationException { /** * The HTTP request that lead to this Exception. * * @param HTTPRequest */ protected $http = null; /** * @inheritDoc */ public function __construct(HTTPRequest $http, $message, $code = 0, $previous = null) { parent::__construct($message, $code, '', $previous); $this->http = $http; } /** * @inheritDoc */ public function getExtraInformation() { $reply = $this->http->getReply(); $body = StringUtil::truncate(preg_replace('/[\x00-\x1F\x80-\xFF]/', '.', $reply['body']), 2048, StringUtil::HELLIP, true); return [ ['Body', $body], ['Status Code', $reply['statusCode']] ]; } }
<?php namespace wcf\util\exception; use wcf\system\exception\IExtraInformationException; use wcf\system\exception\SystemException; use wcf\util\HTTPRequest; use wcf\util\StringUtil; /** * Denotes failure to perform a HTTP request. * * @author Tim Duesterhus * @copyright 2001-2018 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Util\Exception * @since 3.0 */ class HTTPException extends SystemException implements IExtraInformationException { /** * The HTTP request that lead to this Exception. * * @param HTTPRequest */ protected $http = null; /** * @inheritDoc */ public function __construct(HTTPRequest $http, $message, $code = 0, $previous = null) { parent::__construct($message, $code, '', $previous); $this->http = $http; } /** * @inheritDoc */ public function getExtraInformation() { $reply = $this->http->getReply(); $body = StringUtil::truncate(preg_replace('/[\x00-\x1F\x80-\xFF]/', '.', $reply['body']), 512, StringUtil::HELLIP, true); return [ ['Body', $body], ['Status Code', $reply['statusCode']] ]; } }
Fix url to rest api in GWTP example
/* * Copyright 2014 Nicolas Morel * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.nmorel.gwtjackson.hello.client; import com.google.gwt.inject.client.AbstractGinModule; import com.gwtplatform.dispatch.rest.client.RestApplicationPath; import com.gwtplatform.dispatch.rest.client.gin.RestDispatchAsyncModule; /** * @author Nicolas Morel. */ public class HelloModule extends AbstractGinModule { @Override protected void configure() { RestDispatchAsyncModule.Builder dispatchBuilder = new RestDispatchAsyncModule.Builder(); install( dispatchBuilder.build() ); bindConstant().annotatedWith( RestApplicationPath.class ).to( "api" ); } }
/* * Copyright 2014 Nicolas Morel * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.nmorel.gwtjackson.hello.client; import com.google.gwt.inject.client.AbstractGinModule; import com.gwtplatform.dispatch.rest.client.RestApplicationPath; import com.gwtplatform.dispatch.rest.client.gin.RestDispatchAsyncModule; /** * @author Nicolas Morel. */ public class HelloModule extends AbstractGinModule { @Override protected void configure() { RestDispatchAsyncModule.Builder dispatchBuilder = new RestDispatchAsyncModule.Builder(); install( dispatchBuilder.build() ); bindConstant().annotatedWith( RestApplicationPath.class ).to( "/api" ); } }
Fix to support path substitution with 0 value.
/** * Module dependencies. */ var utils = require('./utils'); /** * `Entry` constructor. * * An entry is conceptually a reverse route, used to map from a controller * action to the URL pattern which dispatches to it. * * @api private */ function Entry(controller, action, pattern) { this.controller = controller; this.action = action; this.pattern = pattern; utils.pathRegexp(pattern, this.keys = []); }; /** * Build path. * * Builds a path for the entry, substituting any placeholders with the * corresponding value from `options`. * * @param {Object} options * @return {String} * @api protected */ Entry.prototype.path = function(options) { options = options || {}; var self = this , path = this.pattern; this.keys.forEach(function(key) { if (!key.optional) { if (!options[key.name] && options[key.name] !== 0) { throw new Error('Unable to substitute value for ":' + key.name + '" in URL pattern "' + self.pattern + '"'); } path = path.replace(':' + key.name, options[key.name]); } else { var replacement = options[key.name] ? '$1' + options[key.name] : ''; path = path.replace(new RegExp('(\\.?\\/?):' + key.name + '\\?'), replacement); } }); return path; } /** * Expose `Entry`. */ module.exports = Entry;
/** * Module dependencies. */ var utils = require('./utils'); /** * `Entry` constructor. * * An entry is conceptually a reverse route, used to map from a controller * action to the URL pattern which dispatches to it. * * @api private */ function Entry(controller, action, pattern) { this.controller = controller; this.action = action; this.pattern = pattern; utils.pathRegexp(pattern, this.keys = []); }; /** * Build path. * * Builds a path for the entry, substituting any placeholders with the * corresponding value from `options`. * * @param {Object} options * @return {String} * @api protected */ Entry.prototype.path = function(options) { options = options || {}; var self = this , path = this.pattern; this.keys.forEach(function(key) { if (!key.optional) { if (!options[key.name]) { throw new Error('Unable to substitute value for ":' + key.name + '" in URL pattern "' + self.pattern + '"'); } path = path.replace(':' + key.name, options[key.name]); } else { var replacement = options[key.name] ? '$1' + options[key.name] : ''; path = path.replace(new RegExp('(\\.?\\/?):' + key.name + '\\?'), replacement); } }); return path; } /** * Expose `Entry`. */ module.exports = Entry;
ci: Exit with error if dist upload fails
import os import sys import xmlrpclib from shutil import rmtree from subprocess import check_call TEMP_DIR = 'tmp' PROJECT_NAME = 'cctrl' DIST_DIR = os.path.join(TEMP_DIR, 'dist') def main(): if is_current_version(): sys.exit("Version is not updated. Aborting release.") dist() cleanup() def is_current_version(): pypi = xmlrpclib.ServerProxy('http://pypi.python.org/pypi') return pypi.package_releases('cctrl')[0] == __version__ def dist(): try: check_call(['python', 'setup.py', 'sdist', '--dist-dir={0}'.format(DIST_DIR), '--formats=gztar', 'upload']) except OSError as e: cleanup() sys.exit(e) def cleanup(): rmtree(TEMP_DIR) if __name__ == '__main__': execfile(os.path.join(PROJECT_NAME, 'version.py')) main()
import os import sys import xmlrpclib from shutil import rmtree from subprocess import check_call TEMP_DIR = 'tmp' PROJECT_NAME = 'cctrl' DIST_DIR = os.path.join(TEMP_DIR, 'dist') def main(): if is_current_version(): sys.exit("Version is not updated. Aborting release.") dist() cleanup() def is_current_version(): pypi = xmlrpclib.ServerProxy('http://pypi.python.org/pypi') return pypi.package_releases('cctrl')[0] == __version__ def dist(): try: check_call(['python', 'setup.py', 'sdist', '--dist-dir={0}'.format(DIST_DIR), '--formats=gztar', 'upload']) except OSError as e: print e def cleanup(): rmtree(TEMP_DIR) if __name__ == '__main__': execfile(os.path.join(PROJECT_NAME, 'version.py')) main()
Fix item method arguements and replace item string
/** * */ var battleNetApiRequest = require('../common/battleNetApiRequest'); module.exports = (function() { 'use strict'; return { item: function (params, callback) { var origin = params.origin, item = params.item.replace(/^item\//, ''); battleNetApiRequest({ origin: origin, path: '/d3/data/item/' + item }, callback); }, follower: function(params, callback) { var origin = params.origin, follower = params.follower; battleNetApiRequest({ origin: origin, path: '/d3/data/follower/' + follower }, callback); }, artisan: function(params, callback) { var origin = params.origin, artisan = params.artisan; battleNetApiRequest({ origin: origin, path: '/d3/data/artisan/' + artisan }, callback); } }; })();
/** * */ var battleNetApiRequest = require('../common/battleNetApiRequest'); module.exports = (function() { 'use strict'; return { item: function () { var origin = params.origin, item = params.item; battleNetApiRequest({ origin: origin, path: '/d3/data/item/' + item }, callback); }, follower: function(params, callback) { var origin = params.origin, follower = params.follower; battleNetApiRequest({ origin: origin, path: '/d3/data/follower/' + follower }, callback); }, artisan: function(params, callback) { var origin = params.origin, artisan = params.artisan; battleNetApiRequest({ origin: origin, path: '/d3/data/artisan/' + artisan }, callback); } }; })();
Allow splitting of samples if sample all checkbox is checked.
import React from 'react'; import {ButtonGroup} from 'react-bootstrap'; import UIStore from './../stores/UIStore'; import ElementActions from './../actions/ElementActions'; import SplitButton from './SplitButton'; import CreateButton from './CreateButton'; export default class ContextActions extends React.Component { constructor(props) { super(props); const uiState = UIStore.getState(); this.state = { uiState } } componentDidMount() { UIStore.listen(state => this.onChange(state)); } componentWillUnmount() { UIStore.unlisten(state => this.onChange(state)); } onChange(state) { const uiState = state; this.setState({ uiState }); } isAllCollection() { const {currentCollection} = this.state.uiState; return currentCollection && currentCollection.label == 'All'; } noSampleSelected() { const {sample} = this.state.uiState; return sample.checkedIds.size == 0 && sample.checkedAll == false; } render() { return ( <ButtonGroup> <SplitButton isDisabled={this.noSampleSelected() || this.isAllCollection()}/> <CreateButton isDisabled={this.isAllCollection()}/> </ButtonGroup> ) } }
import React from 'react'; import {ButtonGroup} from 'react-bootstrap'; import UIStore from './../stores/UIStore'; import ElementActions from './../actions/ElementActions'; import SplitButton from './SplitButton'; import CreateButton from './CreateButton'; export default class ContextActions extends React.Component { constructor(props) { super(props); const uiState = UIStore.getState(); this.state = { uiState } } componentDidMount() { UIStore.listen(state => this.onChange(state)); } componentWillUnmount() { UIStore.unlisten(state => this.onChange(state)); } onChange(state) { const uiState = state; this.setState({ uiState }); } isAllCollection() { const {currentCollection} = this.state.uiState; return currentCollection && currentCollection.label == 'All'; } noSampleSelected() { const {sample} = this.state.uiState; return sample.checkedIds.size == 0; } render() { return ( <ButtonGroup> <SplitButton isDisabled={this.noSampleSelected() || this.isAllCollection()}/> <CreateButton isDisabled={this.isAllCollection()}/> </ButtonGroup> ) } }
Fix Android compilation on versions 47+ * removes `@Override` declaration on `ReactNativeContacts.createJSModlues` method * fixes https://github.com/rt2zz/react-native-contacts/issues/236
package com.rt2zz.reactnativecontacts; import android.support.annotation.NonNull; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import com.facebook.react.bridge.JavaScriptModule; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ReactNativeContacts implements ReactPackage { @Override public List<NativeModule> createNativeModules( ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new ContactsManager(reactContext)); return modules; } public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Arrays.<ViewManager>asList(); } public static void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { ContactsManager.onRequestPermissionsResult(requestCode, permissions, grantResults); } }
package com.rt2zz.reactnativecontacts; import android.support.annotation.NonNull; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import com.facebook.react.bridge.JavaScriptModule; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ReactNativeContacts implements ReactPackage { @Override public List<NativeModule> createNativeModules( ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new ContactsManager(reactContext)); return modules; } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Arrays.<ViewManager>asList(); } public static void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { ContactsManager.onRequestPermissionsResult(requestCode, permissions, grantResults); } }
Fix detection of primitive boolean parameter type on set method
package org.bootstrapjsp.util; import java.lang.reflect.Method; import org.bootstrapjsp.tags.Component; public class ComponentUtil { public static String getComponentName(Component component) { final Class<? extends Component> clazz = component.getClass(); final String packageName = clazz.getPackage().getName(); final String componentName = clazz.getName().replace(packageName + ".", ""); return componentName.toLowerCase(); } public static boolean setProperty(Component component, String property, String value) { final StringBuilder methodNameBuilder = new StringBuilder("set"); methodNameBuilder.append(property.substring(0, 1).toUpperCase()); methodNameBuilder.append(property.substring(1)); final String setMethodName = methodNameBuilder.toString(); try { for (Method setMethod :component.getClass().getMethods()) { if (setMethod.getName().equals(setMethodName)) { final Class<?> parameterType = setMethod.getParameterTypes()[0]; if (String.class.equals(parameterType)) { setMethod.invoke(component, new Object[] {value}); } else if (Boolean.class.equals(parameterType) || Boolean.TYPE.equals(parameterType)) { final Boolean bool = Boolean.valueOf(value); setMethod.invoke(component, new Object[] {bool}); } return true; } } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } return false; } }
package org.bootstrapjsp.util; import java.lang.reflect.Method; import org.bootstrapjsp.tags.Component; public class ComponentUtil { public static String getComponentName(Component component) { final Class<? extends Component> clazz = component.getClass(); final String packageName = clazz.getPackage().getName(); final String componentName = clazz.getName().replace(packageName + ".", ""); return componentName.toLowerCase(); } public static boolean setProperty(Component component, String property, String value) { final StringBuilder methodNameBuilder = new StringBuilder("set"); methodNameBuilder.append(property.substring(0, 1).toUpperCase()); methodNameBuilder.append(property.substring(1)); final String setMethodName = methodNameBuilder.toString(); try { for (Method setMethod :component.getClass().getMethods()) { if (setMethod.getName().equals(setMethodName)) { final Class<?> parameterType = setMethod.getParameterTypes()[1]; if (String.class.equals(parameterType)) { setMethod.invoke(component, new Object[] {value}); } else if (Boolean.class.equals(parameterType)) { final Boolean bool = Boolean.valueOf(value); setMethod.invoke(component, new Object[] {bool}); } return true; } } } catch (Exception e) { throw new RuntimeException(e); } return false; } }
Remove dispatch check since there is none for store array
let id = 0; const identity = arg => arg; export default function createAction(name, mapper = identity) { if (typeof name === 'function') { mapper = name; name = undefined; } if (typeof mapper !== 'function') { mapper = identity; } const action = { id: ++id, type: `[${id}]${name ? ' ' + name : ''}` }; let actionStores = undefined; function setupPayload(payload) { return { id: action.id, type: action.type, payload: payload }; } function actionCreator(...args) { const payloaded = setupPayload(mapper.apply(undefined, args)); if (Array.isArray(actionStores)) { return actionStores.map(store=> store.dispatch(payloaded)); } else if (actionStores) { return actionStores.dispatch(payloaded); } else { return payloaded; } } actionCreator.toString = ()=> action.id; actionCreator.bindTo = (stores)=> { actionStores = stores; return actionCreator; }; return actionCreator; };
let id = 0; const identity = arg => arg; export default function createAction(name, mapper = identity) { if (typeof name === 'function') { mapper = name; name = undefined; } if (typeof mapper !== 'function') { mapper = identity; } const action = { id: ++id, type: `[${id}]${name ? ' ' + name : ''}` }; let actionStores = undefined; function setupPayload(payload) { return { id: action.id, type: action.type, payload: payload }; } function actionCreator(...args) { const payloaded = setupPayload(mapper.apply(undefined, args)); if (Array.isArray(actionStores)) { return actionStores.map(store=> store.dispatch(payloaded)); } else if (actionStores && actionStores.dispatch) { return actionStores.dispatch(payloaded); } else { return payloaded; } } actionCreator.toString = ()=> action.id; actionCreator.bindTo = (stores)=> { actionStores = stores; return actionCreator; }; return actionCreator; }
Check for new version on load. We should probably do this even earlier and force reload immediately.
// We don't want everyone to be synchronized, so add a random amount to the interval const NEW_VERSION_INTERVAL = (10 + Math.random() * 5) * 60 * 1000; module.exports = ['$interval', '$http', '$rootScope', ($interval, $http, $rootScope) => { let ignoreNewVersion = false; $rootScope.ignoreNewVersion = () => { ignoreNewVersion = true; $rootScope.newVersionAvailable = false; $interval.cancel(versionCheck); }; let versionCheck = $interval(checkForNewVersion, NEW_VERSION_INTERVAL); function checkForNewVersion() { $http .get('currentVersion?' + new Date().getTime()) .success(version => { // clVersion is generate at build time and injected into index.html // it is a global value! $rootScope.newVersionAvailable = !ignoreNewVersion && clVersion != version; }) .error(error => { }); } }];
// We don't want everyone to be synchronized, so add a random amount to the interval const NEW_VERSION_INTERVAL = (10 + Math.random() * 5) * 60 * 1000; module.exports = ['$interval', '$http', '$rootScope', ($interval, $http, $rootScope) => { let ignoreNewVersion = false; $rootScope.ignoreNewVersion = () => { ignoreNewVersion = true; $rootScope.newVersionAvailable = false; $interval.cancel(versionCheck); }; let versionCheck = $interval(() => { $http .get('currentVersion?' + new Date().getTime()) .success(version => { // clVersion is generate at build time and injected into index.html // it is a global value! $rootScope.newVersionAvailable = !ignoreNewVersion && clVersion != version; }) .error(error => { }); }, NEW_VERSION_INTERVAL); }];
Use href rather than construct url for last cookie
(function () { 'use strict'; function getExpires() { var d = new Date(); // expires in 1 hour from now d.setTime(+d + 1000 * 60 * 60); return d.toUTCString(); } function save() { var url = window.location.href; if (url) { document.cookie = 'last=' + encodeURIComponent(url) + '; expires=' + getExpires() + '; path=/'; } else { // expire cookie document.cookie = 'last=""; expires=-1; path=/'; } } function readCookie(name) { var nameEQ = name + '='; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function updateBackButton() { var el = document.getElementById('back'); var back = readCookie('last'); if (el && back !== null && back !== '%2Fedit') { el.href = decodeURIComponent(back); } } // save the bin url when the bin is saved, changed and when we load first time if (jsbin && jsbin.getURL) { $document.on('saved', save); save(); } else { updateBackButton(); } })();
(function () { 'use strict'; function getExpires() { var d = new Date(); // expires in 1 hour from now d.setTime(+d + 1000 * 60 * 60); return d.toUTCString(); } function save() { var url = jsbin.getURL({ withRevision: true }) + '/edit'; if (url) { document.cookie = 'last=' + encodeURIComponent(url) + '; expires=' + getExpires() + '; path=/'; } else { // expire cookie document.cookie = 'last=""; expires=-1; path=/'; } } function readCookie(name) { var nameEQ = name + '='; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function updateBackButton() { var el = document.getElementById('back'); var back = readCookie('last'); if (el && back !== null && back !== '%2Fedit') { el.href = decodeURIComponent(back); } } // save the bin url when the bin is saved, changed and when we load first time if (jsbin && jsbin.getURL) { $document.on('saved', save); save(); } else { updateBackButton(); } })();
Fix storage manager returning wrong level result
function StorageManager(storageMethod) { this.storageMethod = storageMethod; } StorageManager.prototype.setCurrentLevel = function(level) { this.storageMethod.setItem('currentLevel', level); }; StorageManager.prototype.incrementCurrentLevel = function() { this.setCurrentLevel(this.getCurrentLevel() + 1); }; StorageManager.prototype.getCurrentLevel = function() { return parseInt(this.storageMethod.getItem('currentLevel')) || 1; }; StorageManager.prototype.setCurrentLevelHistory = function(history) { this.history = history; }; StorageManager.prototype.updateCurrentLevelHistory = function() { if(typeof this.history === 'undefined' ) { throw "Cannot update history without history object"; } this.storageMethod.setItem('currentLevelHistory', JSON.stringify(this.history)); }; StorageManager.prototype.getCurrentLevelHistory = function(history) { var history = this.storageMethod.getItem('currentLevelHistory'); return history ? JSON.parse(history) : []; }; StorageManager.prototype.getLevelResults = function() { var results = this.storageMethod.getItem('levelResults'); return results ? JSON.parse(results) : []; }; StorageManager.prototype.setLevelResult = function(level, result) { var results = this.getLevelResults(); results[level - 1] = result; this.storageMethod.setItem('levelResults', JSON.stringify(results)); }; StorageManager.prototype.getLevelResult = function(level) { return this.getLevelResults()[level - 1]; };
function StorageManager(storageMethod) { this.storageMethod = storageMethod; } StorageManager.prototype.setCurrentLevel = function(level) { this.storageMethod.setItem('currentLevel', level); }; StorageManager.prototype.incrementCurrentLevel = function() { this.setCurrentLevel(this.getCurrentLevel() + 1); }; StorageManager.prototype.getCurrentLevel = function() { return parseInt(this.storageMethod.getItem('currentLevel')) || 1; }; StorageManager.prototype.setCurrentLevelHistory = function(history) { this.history = history; }; StorageManager.prototype.updateCurrentLevelHistory = function() { if(typeof this.history === 'undefined' ) { throw "Cannot update history without history object"; } this.storageMethod.setItem('currentLevelHistory', JSON.stringify(this.history)); }; StorageManager.prototype.getCurrentLevelHistory = function(history) { var history = this.storageMethod.getItem('currentLevelHistory'); return history ? JSON.parse(history) : []; }; StorageManager.prototype.getLevelResults = function() { var results = this.storageMethod.getItem('levelResults'); return results ? JSON.parse(results) : []; }; StorageManager.prototype.setLevelResult = function(level, result) { var results = this.getLevelResults(); results[level - 1] = result; this.storageMethod.setItem('levelResults', JSON.stringify(results)); }; StorageManager.prototype.getLevelResult = function(level) { return this.getLevelResults()[level]; };
Use regexp for checking the line
#!/usr/bin/env python # # igcollect - Memcached # # Copyright (c) 2016, InnoGames GmbH # import telnetlib import sys import socket import time import re def main(host='127.0.0.1', port='11211'): hostname = socket.gethostname().replace('.', '_') ts = str(int(time.time())) template = 'servers.' + hostname + '.software.memcached.{1} {2} ' + ts pattern = re.compile('STAT \w+ \d+(.\d+)?$') for line in command(host, port, 'stats').splitlines(): if pattern.match(line): header, key, value = line.split() print(template.format(hostname, key, value)) def command(host, port, cmd): """Write a command to telnet and return the response""" client = telnetlib.Telnet(host, port) client.write(cmd + '\n') return client.read_until('END') def is_float(value): try: float(value) except ValueError: return False else: return True if __name__ == '__main__': main(*sys.argv[1:])
#!/usr/bin/env python # # igcollect - Memcached # # Copyright (c) 2016, InnoGames GmbH # import telnetlib import sys import socket import time def main(host='127.0.0.1', port='11211'): hostname = socket.gethostname().replace('.', '_') ts = str(int(time.time())) template = 'servers.' + hostname + '.software.memcached.{1} {2} ' + ts for line in command(host, port, 'stats').splitlines(): if line.startswith('STAT '): header, key, value = line.split() if key.replace('_', '').isalpha() and is_float(value): print(template.format(hostname, key, value)) def command(host, port, cmd): """Write a command to telnet and return the response""" client = telnetlib.Telnet(host, port) client.write(cmd + '\n') return client.read_until('END') def is_float(value): try: float(value) except ValueError: return False else: return True if __name__ == '__main__': main(*sys.argv[1:])
Replace Boom variable in createUser()
'use strict'; const Boom = require('boom'); const Errors = require('../lib/errors'); const Formatters = require('../lib/formatters'); exports.listUsers = function({ headers }, reply) { let authParts = []; if (headers.authorization) { authParts = headers.authorization.split(' '); } const token = (authParts.length === 2) ? authParts[1] : ''; return this.helpers.verifyJWT(token) .then(({ sub }) => this.models.User.getUser(sub)) .then((user) => { const options = {}; if (!user) { options.onlyViewPublic = true; } else if (!user.isAdministrator()) { options.selfId = user.id; } return this.models.User.listUsers(options); }) .then((users) => { return reply(Formatters.users(users)).code(200); }) .catch(this.helpers.errorHandler.bind(this, reply)); }; exports.createUser = function({ payload }, reply) { return this.models.User.createUser(payload) .then((user) => { return reply(Formatters.user(user)).code(201); }) .catch(Errors.ExistingUserError, () => { return reply(Boom.conflict('User already exist')); }) .catch(this.helpers.errorHandler.bind(this, reply)); };
'use strict'; const Boom = require('boom'); const Errors = require('../lib/errors'); const Formatters = require('../lib/formatters'); const EXISTING_USER = Boom.conflict('User already exist'); exports.listUsers = function({ headers }, reply) { let authParts = []; if (headers.authorization) { authParts = headers.authorization.split(' '); } const token = (authParts.length === 2) ? authParts[1] : ''; return this.helpers.verifyJWT(token) .then(({ sub }) => this.models.User.getUser(sub)) .then((user) => { const options = {}; if (!user) { options.onlyViewPublic = true; } else if (!user.isAdministrator()) { options.selfId = user.id; } return this.models.User.listUsers(options); }) .then((users) => { return reply(Formatters.users(users)).code(200); }) .catch(this.helpers.errorHandler.bind(this, reply)); }; exports.createUser = function({ payload }, reply) { return this.models.User.createUser(payload) .then((user) => { return reply(Formatters.user(user)).code(201); }) .catch(Errors.ExistingUserError, () => reply(EXISTING_USER)) .catch(this.helpers.errorHandler.bind(this, reply)); };
Use our own llama mp3 on Netlify
import llamaAudio from "../mp3/llama-2.91.mp3"; /* global SENTRY_DSN */ const { hash } = window.location; let config = {}; if (hash) { try { config = JSON.parse(decodeURIComponent(hash).slice(1)); } catch (e) { console.error("Failed to decode config from hash: ", hash); } } // Backwards compatibility with the old syntax if (config.audioUrl && !config.initialTracks) { config.initialTracks = [{ url: config.audioUrl }]; } export const skinUrl = config.skinUrl === undefined ? null : config.skinUrl; export const initialTracks = config.initialTracks || [ { metaData: { artist: "DJ Mike Llama", title: "Llama Whippin' Intro" }, url: llamaAudio, duration: 5.322286 } ]; export const hideAbout = config.hideAbout || false; export const disableMarquee = config.disableMarquee || false; export const initialState = config.initialState || undefined; export const milkdrop = config.milkdrop || false; export const sentryDsn = SENTRY_DSN;
// eslint-disable-next-line no-unused-vars import llamaAudio from "../mp3/llama-2.91.mp3"; /* global SENTRY_DSN */ const { hash } = window.location; let config = {}; if (hash) { try { config = JSON.parse(decodeURIComponent(hash).slice(1)); } catch (e) { console.error("Failed to decode config from hash: ", hash); } } // Backwards compatibility with the old syntax if (config.audioUrl && !config.initialTracks) { config.initialTracks = [{ url: config.audioUrl }]; } export const skinUrl = config.skinUrl === undefined ? null : config.skinUrl; export const initialTracks = config.initialTracks || [ { metaData: { artist: "DJ Mike Llama", title: "Llama Whippin' Intro" }, // This seems to include the `accept-ranges` header, which GitHub Pages does not, and // Safari on iOS requires. url: "https://raw.githubusercontent.com/captbaritone/webamp/master/mp3/llama-2.91.mp3", duration: 5.322286 } ]; export const hideAbout = config.hideAbout || false; export const disableMarquee = config.disableMarquee || false; export const initialState = config.initialState || undefined; export const milkdrop = config.milkdrop || false; export const sentryDsn = SENTRY_DSN;
Fix JS issue to let users post questions and answers
$(document).ready(function () { $(".new-question").click(function() { $(this).addClass("hidden"); $("#new-question").removeClass("hidden"); }); $("#new-question").submit(function(event) { event.preventDefault(); var ajaxRequest = $.ajax({ url: '/questions', method: 'POST', data: $(this).serialize() }); ajaxRequest.done(function(response) { $("ul.questions").prepend(response); $("form#new-question")[0].reset(); $(".new-question").removeClass("hidden"); $("form#new-question").addClass("hidden"); }); }); $('#answer-form').on('submit', function(event){ event.preventDefault(); var route = $(this).attr("action"); var answerData = $(this).find("textarea").serialize(); $.ajax({ url: route, method: "post", data: answerData }).done(function(serverResponse) { $(".answer-box").find(".answers").append(serverResponse) $('#answer-form').find('textarea').val('') }); }); });
$(document).ready(function () { $(".new-question").click(function() { $(this).addClass("hidden"); $("#new-question").removeClass("hidden"); }); $("#new-question").submit(function(event) { event.preventDefault(); var ajaxRequest = $.ajax({ url: '/questions', method: 'POST', data: $(this).serialize() }); ajaxRequest.done(function(response) { $("ul.questions").prepend(response); $("form#new-question")[0].reset(); $(".new-question").removeClass("hidden"); $("form#new-question").addClass("hidden"); $('#answer-form').on('submit', function(event){ event.preventDefault(); var route = $(this).attr("action"); var answerData = $(this).find("textarea").serialize(); // debugger; $.ajax({ url: route, method: "post", data: answerData }).done(function(serverResponse) { // debugger; $(".answer-box").find(".answers").append(serverResponse) }); }); });
[BUGFIX] Add a missing 'use strict;' statement
/** * Grunt-Contrib-copy * @description Copy files and folders. * @docs https://github.com/gruntjs/grunt-contrib-copy */ var config = require("../Config"), createNodeMdulesTargets = function() { "use strict"; var nodeModulesFiles = []; for(var key in config.nodeModuleDists) { if (config.nodeModuleDists.hasOwnProperty(key)) { nodeModulesFiles.push({ expand: true, cwd: "./node_modules/" + key, src: "**", dest: config.nodeModuleDists[key] }) } } return nodeModulesFiles; }; module.exports = { imagesDir: { files: [{ expand: true, cwd: config.Images.distDir + '/', src: "**", dest: config.Images.tempDir }] }, nodeModules: { files: createNodeMdulesTargets() } };
/** * Grunt-Contrib-copy * @description Copy files and folders. * @docs https://github.com/gruntjs/grunt-contrib-copy */ var config = require("../Config"), createNodeMdulesTargets = function() { var nodeModulesFiles = []; for(var key in config.nodeModuleDists) { if (config.nodeModuleDists.hasOwnProperty(key)) { nodeModulesFiles.push({ expand: true, cwd: "./node_modules/" + key, src: "**", dest: config.nodeModuleDists[key] }) } } return nodeModulesFiles; }; module.exports = { imagesDir: { files: [{ expand: true, cwd: config.Images.distDir + '/', src: "**", dest: config.Images.tempDir }] }, nodeModules: { files: createNodeMdulesTargets() } };
Make sure solenoid fully retracts pin
package org.usfirst.frc.team236.robot.commands; import org.usfirst.frc.team236.robot.Robot; import edu.wpi.first.wpilibj.command.Command; /** * */ public class Shoot extends Command { public Shoot() { // Use requires() here to declare subsystem dependencies requires(Robot.shooter); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { Robot.shooter.setSol(1); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return true; } // Called once after isFinished returns true protected void end() { Robot.shooter.setSol(-1); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
package org.usfirst.frc.team236.robot.commands; import org.usfirst.frc.team236.robot.Robot; import edu.wpi.first.wpilibj.command.Command; /** * */ public class Shoot extends Command { public Shoot() { // Use requires() here to declare subsystem dependencies requires(Robot.shooter); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { Robot.shooter.setSol(1); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return true; } // Called once after isFinished returns true protected void end() { Robot.shooter.setSol(0); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
Set log level to 2 when migrating so there is some indication it is running
#!/usr/bin/python # Copyright (c) 2006 rPath, Inc # All rights reserved import sys import os import pwd from conary.server import schema from conary.lib import cfgtypes, tracelog from conary.repository.netrepos.netserver import ServerConfig from conary import dbstore cnrPath = '/srv/conary/repository.cnr' cfg = ServerConfig() tracelog.initLog(filename='stdout', level=2) try: cfg.read(cnrPath) except cfgtypes.CfgEnvironmentError: print "Error reading %s" % cnrPath sys.exit(1) db = dbstore.connect(cfg.repositoryDB[1], cfg.repositoryDB[0]) schema.loadSchema(db, doMigrate=True) if cfg.repositoryDB[0] == 'sqlite': os.chown(cfg.repositoryDB[1], pwd.getpwnam('apache')[2], pwd.getpwnam('apache')[3])
#!/usr/bin/python # Copyright (c) 2006 rPath, Inc # All rights reserved import sys import os import pwd from conary.server import schema from conary.lib import cfgtypes from conary.repository.netrepos.netserver import ServerConfig from conary import dbstore cnrPath = '/srv/conary/repository.cnr' cfg = ServerConfig() try: cfg.read(cnrPath) except cfgtypes.CfgEnvironmentError: print "Error reading %s" % cnrPath sys.exit(1) db = dbstore.connect(cfg.repositoryDB[1], cfg.repositoryDB[0]) schema.loadSchema(db, doMigrate=True) if cfg.repositoryDB[0] == 'sqlite': os.chown(cfg.repositoryDB[1], pwd.getpwnam('apache')[2], pwd.getpwnam('apache')[3])
Convert ContentLength of storage to number
const AWS = require('aws-sdk'); const s3 = new AWS.S3(); class S3Storage { constructor(config, log) { this.bucket = config.s3_bucket; this.log = log; } async length(id) { const result = await s3 .headObject({ Bucket: this.bucket, Key: id }) .promise(); return Number(result.ContentLength); } getStream(id) { return s3.getObject({ Bucket: this.bucket, Key: id }).createReadStream(); } async set(id, file) { let hitLimit = false; const upload = s3.upload({ Bucket: this.bucket, Key: id, Body: file }); file.on('limit', () => { hitLimit = true; upload.abort(); }); try { await upload.promise(); } catch (e) { if (hitLimit) { throw new Error('limit'); } throw e; } } del(id) { return s3.deleteObject({ Bucket: this.bucket, Key: id }).promise(); } ping() { return s3.headBucket({ Bucket: this.bucket }).promise(); } } module.exports = S3Storage;
const AWS = require('aws-sdk'); const s3 = new AWS.S3(); class S3Storage { constructor(config, log) { this.bucket = config.s3_bucket; this.log = log; } async length(id) { const result = await s3 .headObject({ Bucket: this.bucket, Key: id }) .promise(); return result.ContentLength; } getStream(id) { return s3.getObject({ Bucket: this.bucket, Key: id }).createReadStream(); } async set(id, file) { let hitLimit = false; const upload = s3.upload({ Bucket: this.bucket, Key: id, Body: file }); file.on('limit', () => { hitLimit = true; upload.abort(); }); try { await upload.promise(); } catch (e) { if (hitLimit) { throw new Error('limit'); } throw e; } } del(id) { return s3.deleteObject({ Bucket: this.bucket, Key: id }).promise(); } ping() { return s3.headBucket({ Bucket: this.bucket }).promise(); } } module.exports = S3Storage;
Move transliterator to Transliteratable namespace.
<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\ContentBundle\Sluggable; use Darvin\Utils\Transliteratable\TransliteratorInterface; /** * Sluggable transliterator */ class SluggableTransliterator { /** * @var \Darvin\Utils\Transliteratable\TransliteratorInterface */ private $transliterator; /** * @param \Darvin\Utils\Transliteratable\TransliteratorInterface $transliterator Transliterator */ public function __construct(TransliteratorInterface $transliterator) { $this->transliterator = $transliterator; } /** * @param string $string String to transliterate * * @return string */ public function transliterate($string) { return $this->transliterator->transliterate($string); } }
<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\ContentBundle\Sluggable; use Darvin\Utils\Strings\Transliterator\TransliteratorInterface; /** * Sluggable transliterator */ class SluggableTransliterator { /** * @var \Darvin\Utils\Strings\Transliterator\TransliteratorInterface */ private $transliterator; /** * @param \Darvin\Utils\Strings\Transliterator\TransliteratorInterface $transliterator Transliterator */ public function __construct(TransliteratorInterface $transliterator) { $this->transliterator = $transliterator; } /** * @param string $string String to transliterate * * @return string */ public function transliterate($string) { return $this->transliterator->transliterate($string); } }
Remove concepts link and rename try it to Homepage.
import React from 'react' import styled from 'styled-components' import rem from '../../utils/rem' import { navbarHeight } from '../../utils/sizes' import NavSeparator from './NavSeparator' import Link from '../Link' const Wrapper = styled.nav` display: flex; align-items: center; flex: 0 0 auto; ` const NavLink = styled(Link).attrs({ unstyled: true, })` flex: 0 0 auto; display: inline-block; line-height: ${rem(navbarHeight)}; transition: opacity 0.2s, transform 0.2s; cursor: pointer; letter-spacing: ${rem(.4)}; color: currentColor; &:hover, &:focus { opacity: 0.8; } &:active { transform: scale(0.95); opacity: 0.6; } ` const NavLinks = () => ( <Wrapper> <NavLink href="/">Homepage</NavLink> <NavSeparator /> <NavLink href="/docs">Documentation</NavLink> </Wrapper> ) export default NavLinks
import React from 'react' import styled from 'styled-components' import rem from '../../utils/rem' import { navbarHeight } from '../../utils/sizes' import NavSeparator from './NavSeparator' import Link from '../Link' const Wrapper = styled.nav` display: flex; align-items: center; flex: 0 0 auto; ` const NavLink = styled(Link).attrs({ unstyled: true, })` flex: 0 0 auto; display: inline-block; line-height: ${rem(navbarHeight)}; transition: opacity 0.2s, transform 0.2s; cursor: pointer; letter-spacing: ${rem(.4)}; color: currentColor; &:hover, &:focus { opacity: 0.8; } &:active { transform: scale(0.95); opacity: 0.6; } ` const NavLinks = () => ( <Wrapper> <NavLink href="/docs/basics#motivation">Concepts</NavLink> <NavSeparator /> <NavLink href="/">Try it out</NavLink> <NavSeparator /> <NavLink href="/docs">Documentation</NavLink> </Wrapper> ) export default NavLinks
Change owner of saved file
package main import ( "net/http" "io/ioutil" "os" ) func saveHandler(w http.ResponseWriter, r *http.Request) { folder := "/PRODUCTION/EXPERIMENT/web/savedfiles/" filename := generateRandomURL() path := folder + filename if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { http.Error(w, err.Error(), http.StatusInternalServerError) return } } r.ParseForm() text := r.Form.Get("text") ioutil.WriteFile(path, []byte(text), 0400) os.Chown(path, 995, 994) http.Redirect(w, r, "http://experiment.safkanyazilim.com/"+filename, http.StatusTemporaryRedirect) } func generateRandomURL() string { return "1234556" } func main() { http.HandleFunc("/save", saveHandler) http.ListenAndServe(":8080", nil) }
package main import ( "net/http" "io/ioutil" "os" ) func saveHandler(w http.ResponseWriter, r *http.Request) { folder := "/PRODUCTION/EXPERIMENT/web/savedfiles/" filename := generateRandomURL() path := folder + filename if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { http.Error(w, err.Error(), http.StatusInternalServerError) return } } r.ParseForm() text := r.Form.Get("text") ioutil.WriteFile(path, []byte(text), 0400) http.Redirect(w, r, "http://experiment.safkanyazilim.com/"+filename, http.StatusTemporaryRedirect) } func generateRandomURL() string { return "1234556" } func main() { http.HandleFunc("/save", saveHandler) http.ListenAndServe(":8080", nil) }
Fix for Android change events
package com.mapbox.rctmgl.components.mapview.helpers; import android.util.Log; /** * Created by nickitaliano on 12/12/17. */ public class CameraChangeTracker { public static final int USER_GESTURE = 1; public static final int DEVELOPER_ANIMATION = 2; public static final int SDK_ANIMATION = 3; public static final int EMPTY = -1; private int reason = EMPTY; private boolean isAnimating; public void setReason(int reason) { this.reason = reason; } public void setIsAnimating(boolean isAnimating) { this.isAnimating = isAnimating; } public boolean isUserInteraction() { return reason == USER_GESTURE || reason == DEVELOPER_ANIMATION; } public boolean isAnimated() { return reason == DEVELOPER_ANIMATION || reason == SDK_ANIMATION; } public boolean isAnimating() { return this.isAnimating; } public boolean isEmpty() { return reason == EMPTY; } }
package com.mapbox.rctmgl.components.mapview.helpers; import android.util.Log; /** * Created by nickitaliano on 12/12/17. */ public class CameraChangeTracker { public static final int USER_GESTURE = 1; public static final int USER_ANIMATION = 2; public static final int SDK = 3; public static final int EMPTY = -1; private int reason; private boolean isRegionChangeAnimated; public void setReason(int reason) { this.reason = reason; } public void setRegionChangeAnimated(boolean isRegionChangeAnimated) { this.isRegionChangeAnimated = isRegionChangeAnimated; } public boolean isUserInteraction() { return reason == USER_GESTURE || reason == USER_ANIMATION; } public boolean isAnimated() { return isRegionChangeAnimated; } public boolean isEmpty() { return reason == EMPTY; } }
Add function for retrieving team name from URL
function retrieveGetParameters(){ let parameters = {} window.location.search .substring(1) //Remove '?' at beginning .split('&') //Split key-value pairs .map((currentElement) => { //Fill parameters object with key-value pairs const key = currentElement.split('=')[0]; const value = currentElement.split('=')[1]; parameters[key] = value; }) return parameters; } function getTeamname(){ const parameters = retrieveGetParameters(); return parameters["teamname"]; }
function retrieveGetParameters(){ let parameters = {} window.location.search .substring(1) //Remove '?' at beginning .split('&') //Split key-value pairs .map((currentElement) => { //Fill parameters object with key-value pairs const key = currentElement.split('=')[0]; const value = currentElement.split('=')[1]; parameters[key] = value; }) return parameters; }
Add aliase for primary and secondary AMP modes.
/** * WordPress dependencies */ import { activatePlugin, visitAdminPage } from '@wordpress/e2e-test-utils'; /** * The allow list of AMP modes. */ export const allowedAMPModes = { primary: 'standard', secondary: 'transitional', standard: 'standard', transitional: 'transitional', reader: 'disabled', }; /** * Activate AMP and set it to the correct mode. * * @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader. */ export const activateAMPWithMode = async ( mode ) => { await activatePlugin( 'amp' ); await setAMPMode( mode ); }; /** * Set AMP Mode * * @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader. */ export const setAMPMode = async ( mode ) => { // Test to be sure that the passed mode is known. expect( allowedAMPModes ).toHaveProperty( mode ); // Set the AMP mode await visitAdminPage( 'admin.php', 'page=amp-options' ); await expect( page ).toClick( `#theme_support_${ allowedAMPModes[ mode ] }` ); await expect( page ).toClick( '#submit' ); await page.waitForNavigation(); };
/** * WordPress dependencies */ import { activatePlugin, visitAdminPage } from '@wordpress/e2e-test-utils'; /** * The allow list of AMP modes. */ export const allowedAMPModes = { standard: 'standard', transitional: 'transitional', reader: 'disabled', }; /** * Activate AMP and set it to the correct mode. * * @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader. */ export const activateAMPWithMode = async ( mode ) => { await activatePlugin( 'amp' ); await setAMPMode( mode ); }; /** * Set AMP Mode * * @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader. */ export const setAMPMode = async ( mode ) => { // Test to be sure that the passed mode is known. expect( allowedAMPModes ).toHaveProperty( mode ); // Set the AMP mode await visitAdminPage( 'admin.php', 'page=amp-options' ); await expect( page ).toClick( `#theme_support_${ allowedAMPModes[ mode ] }` ); await expect( page ).toClick( '#submit' ); await page.waitForNavigation(); };
Remove man pages post-install (for now)
import xyz import os import shutil class Binutils(xyz.BuildProtocol): pkg_name = 'binutils' supported_targets = ['arm-none-eabi'] def check(self, builder): if builder.target not in self.supported_targets: raise xyz.UsageError("Invalid target ({}) for {}".format(builder.target, self.pkg_name)) def configure(self, builder, config): builder.cross_configure('--disable-nls', '--enable-lto', '--enable-ld=yes', '--without-zlib', config=config) def install(self, builder, config): super().install(builder, config) # For some reason binutils plonks libiberty.a in the output directory libdir = builder.j('{install_dir_abs}', config['eprefix'][1:], 'lib', config=config) if os.path.exists(libdir): shutil.rmtree(libdir) # For now we strip the man pages. # man pages created on different systems are (for no good reason) different! man_dir = builder.j('{install_dir}', config['prefix'][1:], 'share', 'man', config=config) shutil.rmtree(man_dir) rules = Binutils()
import xyz import os import shutil class Binutils(xyz.BuildProtocol): pkg_name = 'binutils' supported_targets = ['arm-none-eabi'] def check(self, builder): if builder.target not in self.supported_targets: raise xyz.UsageError("Invalid target ({}) for {}".format(builder.target, self.pkg_name)) def configure(self, builder, config): builder.cross_configure('--disable-nls', '--enable-lto', '--enable-ld=yes', '--without-zlib', config=config) def install(self, builder, config): super().install(builder, config) # For some reason binutils plonks libiberty.a in the output directory libdir = builder.j('{install_dir_abs}', config['eprefix'][1:], 'lib', config=config) if os.path.exists(libdir): shutil.rmtree(libdir) rules = Binutils()
Add two additional Movements: DEAD & HIDDEN
package edu.agh.tunev.model; import java.awt.geom.Point2D; /** * Reprezentuje stan przypisany do danego PersonProfile w jakiejś chwili czasu, * niezależny od wybranego konkretnego modelu. * * Obiekty tej klasy używane są głównie do rysowania przebiegu symulacji. * * Obiekty tej klasy w postaci przekazanej interpolatorowi są w nim pamiętane, * więc klasa ta musi być niezmienna (wszystkie jej pola). Gdyby zmienić jedno * pole już zapisanego obiektu, to zmieniłby się też w pamięci Interpolatora, a * tego nie chcemy. * */ public final class PersonState { public static enum Movement { STANDING, SQUATTING, CRAWLING, DEAD, HIDDEN } public final Point2D.Double position; public final double orientation; public final Movement movement; public PersonState(Point2D.Double position, double orientation, Movement movement) { this.position = position; this.orientation = orientation; this.movement = movement; } }
package edu.agh.tunev.model; import java.awt.geom.Point2D; /** * Reprezentuje stan przypisany do danego PersonProfile w jakiejś chwili czasu, * niezależny od wybranego konkretnego modelu. * * Obiekty tej klasy używane są głównie do rysowania przebiegu symulacji. * * Obiekty tej klasy w postaci przekazanej interpolatorowi są w nim pamiętane, * więc klasa ta musi być niezmienna (wszystkie jej pola). Gdyby zmienić jedno * pole już zapisanego obiektu, to zmieniłby się też w pamięci Interpolatora, a * tego nie chcemy. * */ public final class PersonState { public static enum Movement { STANDING, SQUATTING, CRAWLING } public final Point2D.Double position; public final double orientation; public final Movement movement; public PersonState(Point2D.Double position, double orientation, Movement movement) { this.position = position; this.orientation = orientation; this.movement = movement; } }
Fix a test on travis
'use strict'; const { expect } = require('chai'); const SshTransport = require('./ssh'); class NoExceptionSshTransport extends SshTransport { normalizeOptions() { try { super.normalizeOptions(); } catch (e) { this.error = e; } } } describe('SshTransport', () => { it('should not use a private key if password is specified', () => { const options = getTransportOptions({ password: 'pass' }); expect(options.usePrivateKey).to.be.false; expect(options.privateKeyPath).to.be.undefined; }); it('should use a private key if password is not specified', () => { const options = getTransportOptions(); expect(options.usePrivateKey).to.be.true; expect(options.privateKeyPath).not.to.be.undefined; }); }); function getTransportOptions(config) { const options = Object.assign({ remoteUrl: '/', remotePath: '/' }, config); const ssh = new NoExceptionSshTransport({ transport: options }); return ssh.options; }
'use strict'; const { expect } = require('chai'); const SshTransport = require('./ssh'); describe('SshTransport', () => { it('should not use a private key if password is specified', () => { const options = getTransportOptions({ password: 'pass' }); expect(options.usePrivateKey).to.be.false; expect(options.privateKeyPath).to.be.undefined; }); it('should use a private key if password is not specified', () => { const options = getTransportOptions(); expect(options.usePrivateKey).to.be.true; expect(options.privateKeyPath).not.to.be.undefined; }); }); function getTransportOptions(config) { const options = Object.assign({ remoteUrl: '/', remotePath: '/' }, config); const ssh = new SshTransport({ transport: options }); return ssh.options; }
Adjust the order of TTY restoration on Windows. Normal commands no longer produce unsupported escape sequences. This addresses #798.
package tty import ( "os" "github.com/elves/elvish/util" "golang.org/x/sys/windows" ) const ( wantedInMode = windows.ENABLE_WINDOW_INPUT | windows.ENABLE_MOUSE_INPUT | windows.ENABLE_PROCESSED_INPUT wantedOutMode = windows.ENABLE_PROCESSED_OUTPUT | windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING ) func setup(in, out *os.File) (func() error, error) { hIn := windows.Handle(in.Fd()) hOut := windows.Handle(out.Fd()) var oldInMode, oldOutMode uint32 err := windows.GetConsoleMode(hIn, &oldInMode) if err != nil { return nil, err } err = windows.GetConsoleMode(hOut, &oldOutMode) if err != nil { return nil, err } errSetIn := windows.SetConsoleMode(hIn, wantedInMode) errSetOut := windows.SetConsoleMode(hOut, wantedOutMode) errVT := setupVT(out) return func() error { return util.Errors( restoreVT(out), windows.SetConsoleMode(hOut, oldOutMode), windows.SetConsoleMode(hIn, oldInMode)) }, util.Errors(errSetIn, errSetOut, errVT) }
package tty import ( "os" "github.com/elves/elvish/util" "golang.org/x/sys/windows" ) const ( wantedInMode = windows.ENABLE_WINDOW_INPUT | windows.ENABLE_MOUSE_INPUT | windows.ENABLE_PROCESSED_INPUT wantedOutMode = windows.ENABLE_PROCESSED_OUTPUT | windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING ) func setup(in, out *os.File) (func() error, error) { hIn := windows.Handle(in.Fd()) hOut := windows.Handle(out.Fd()) var oldInMode, oldOutMode uint32 err := windows.GetConsoleMode(hIn, &oldInMode) if err != nil { return nil, err } err = windows.GetConsoleMode(hOut, &oldOutMode) if err != nil { return nil, err } errSetIn := windows.SetConsoleMode(hIn, wantedInMode) errSetOut := windows.SetConsoleMode(hOut, wantedOutMode) errVT := setupVT(out) return func() error { return util.Errors( windows.SetConsoleMode(hIn, oldInMode), windows.SetConsoleMode(hOut, oldOutMode), restoreVT(out)) }, util.Errors(errSetIn, errSetOut, errVT) }
Make a tsv instead of a long string
# Graciously adopted from https://github.com/ucscXena/xenaH5 # # Generates a tsv compatible for making a create table statement from a # 10xgenomics HDF5 file. # # Usage # # python maketsv.py fname 0 # # Will generate a tsv file with the 0th slice of the h5 file named # `out0.tsv`. import string, sys import h5py import numpy as np hF = h5py.File(sys.argv[1]) group = "mm10" indptr = hF[group +"/indptr"] indices = hF[group + "/indices"] data = hF[group + "/data"] genes = hF[group + "/genes"] gene_names = hF[group + "/gene_names"] barcodes = hF[group + "/barcodes"] shape = hF[group + "/shape"] rowN = shape[0] colN = shape[1] counter_indptr_size = rowN fout = open("features.tsv",'w') fout.write("index\tfeature\tfeature_name\n") for i in range (0, len(genes)): fout.write("{}\t{}\t{}\n".format(i, genes[i], gene_names[i]))
# Graciously adopted from https://github.com/ucscXena/xenaH5 # # Generates a tsv compatible for making a create table statement from a # 10xgenomics HDF5 file. # # Usage # # python maketsv.py fname 0 # # Will generate a tsv file with the 0th slice of the h5 file named # `out0.tsv`. import string, sys import h5py import numpy as np hF = h5py.File(sys.argv[1]) group = "mm10" indptr = hF[group +"/indptr"] indices = hF[group + "/indices"] data = hF[group + "/data"] genes = hF[group + "/genes"] gene_names = hF[group + "/gene_names"] barcodes = hF[group + "/barcodes"] shape = hF[group + "/shape"] rowN = shape[0] colN = shape[1] counter_indptr_size = rowN fout = open("features.tsv",'w') for i in range (0, len(genes)): fout.write("{} {} {}".format(i, genes[i], gene_names[i]))
Change test function as existing method deprecated
import pytest @pytest.mark.parametrize("name", [ ("apt-file"), ("apt-transport-https"), ("atom"), ("blktrace"), ("ca-certificates"), ("chromium-browser"), ("cron"), ("curl"), ("diod"), ("docker-ce"), ("fonts-font-awesome"), ("git"), ("gnupg"), ("gnupg2"), ("gnupg-agent"), ("handbrake"), ("handbrake-cli"), ("haveged"), ("htop"), ("i3"), ("iotop"), ("language-pack-en-base"), ("laptop-mode-tools"), ("nfs-common"), ("ntop"), ("ntp"), ("openssh-client"), ("openssh-server"), ("openssh-sftp-server"), ("openssl"), ("pinta"), ("python"), ("python-pip"), ("scrot"), ("software-properties-common"), ("suckless-tools"), ("sysstat"), ("tree"), ("vagrant"), ("vim"), ("virtualbox"), ("vlc"), ("wget"), ("whois"), ("x264"), ("xfce4-terminal"), ("xfonts-terminus"), ("xinit"), ]) def test_packages(host, name): pkg = host.package(name) assert pkg.is_installed
import pytest @pytest.mark.parametrize("name", [ ("apt-file"), ("apt-transport-https"), ("atom"), ("blktrace"), ("ca-certificates"), ("chromium-browser"), ("cron"), ("curl"), ("diod"), ("docker-ce"), ("fonts-font-awesome"), ("git"), ("gnupg"), ("gnupg2"), ("gnupg-agent"), ("handbrake"), ("handbrake-cli"), ("haveged"), ("htop"), ("i3"), ("iotop"), ("language-pack-en-base"), ("laptop-mode-tools"), ("nfs-common"), ("ntop"), ("ntp"), ("openssh-client"), ("openssh-server"), ("openssh-sftp-server"), ("openssl"), ("pinta"), ("python"), ("python-pip"), ("scrot"), ("software-properties-common"), ("suckless-tools"), ("sysstat"), ("tree"), ("vagrant"), ("vim"), ("virtualbox"), ("vlc"), ("wget"), ("whois"), ("x264"), ("xfce4-terminal"), ("xfonts-terminus"), ("xinit"), ]) def test_packages(Package, name): assert Package(name).is_installed
Allow 0-dimensional arrays for tensor meshgrids
"""The WaveBlocks Project Various small utility functions. @author: R. Bourquin @copyright: Copyright (C) 2012, 2013 R. Bourquin @license: Modified BSD License """ from numpy import squeeze, asarray, atleast_1d def meshgrid_nd(arrays): """Like 'meshgrid()' but for arbitrary number of dimensions. :param arrays: A list of arrays to form the tensor grid. All arrays have to be 1 oder 0 dimensional. :return: The full tensor product mesh grid. """ arrays = map(squeeze, arrays) arrays = tuple(map(atleast_1d, arrays)) if not len([ None for a in arrays if a.ndim != 1 ]) == 0: raise ValueError("Arrays must be 1-dimensional") # The dimension D = len(arrays) # The number of elements in each array nelements = map(len, arrays) result = [] for d, a in enumerate(arrays): # The new shape shape = D * [1] shape[d] = nelements[d] # Reshape A = asarray(a).reshape(shape) # And repeat as many times as necessary for ax, n in enumerate(nelements): if not ax == d: A = A.repeat(n, axis=ax) result.append(A) return tuple(result)
"""The WaveBlocks Project Various small utility functions. @author: R. Bourquin @copyright: Copyright (C) 2012 R. Bourquin @license: Modified BSD License """ from numpy import squeeze, asarray def meshgrid_nd(arrays): """Like 'meshgrid()' but for arbitrary number of dimensions. """ arrays = tuple(map(squeeze, arrays)) if not len([ None for a in arrays if a.ndim != 1 ]) == 0: raise ValueError("Arrays must be 1-dimensional") # TODO: Handle one-element arrays! # The dimension D = len(arrays) # The number of elements in each array nelements = map(len, arrays) result = [] for d, a in enumerate(arrays): # The new shape shape = D * [1] shape[d] = nelements[d] # Reshape A = asarray(a).reshape(shape) # And repeat as many times as necessary for ax, n in enumerate(nelements): if not ax == d: A = A.repeat(n, axis=ax) result.append(A) return tuple(result)
Fix Username Password setting making new rows
<?php namespace App\Listeners; use App\Events\NewIP; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use App\Models\DeviceIPs; use App\Models\SSHCredentials; class FindSSH { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param NewIP $event * @return void */ public function handle(NewIP $event) { $address = $event->address; $ip = $address['address']; $addressid = $address['id']; exec("nmap -p22 $ip",$ping); $ping = implode("", $ping); if(str_contains($ping,'22/tcp open ssh')){ SSHCredentials::firstOrCreate([ 'device_IP_id' => $addressid, ]); } } }
<?php namespace App\Listeners; use App\Events\NewIP; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use App\Models\DeviceIPs; use App\Models\SSHCredentials; class FindSSH { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param NewIP $event * @return void */ public function handle(NewIP $event) { $address = $event->address; $ip = $address['address']; $addressid = $address['id']; exec("nmap -p22 $ip",$ping); $ping = implode("", $ping); if(str_contains($ping,'22/tcp open ssh')){ SSHCredentials::firstOrCreate([ 'username' => NULL, 'password' => NULL, 'device_IP_id' => $addressid, ]); } } }
Stop adding data-ember-extension to body
(function() { "use strict"; window.addEventListener('message', function(event) { if (event.data === 'debugger-client') { var port = event.ports[0]; listenToPort(port); } else if (event.data.type) { chrome.extension.sendMessage(event.data); } }); function listenToPort(port) { port.addEventListener('message', function(event) { chrome.extension.sendMessage(event.data); }); chrome.extension.onMessage.addListener(function(message) { if (message.from === 'devtools') { port.postMessage(message); } }); port.start(); } // let ember-debug know that content script has executed document.documentElement.dataset.emberExtension = 1; // clear a possible previous Ember icon chrome.extension.sendMessage({ type: 'resetEmberIcon' }); // inject JS into the page to check for an app on domready var script = document.createElement('script'); script.type = "text/javascript"; script.src = chrome.extension.getURL("in-page-script.js"); if (document.body) document.body.appendChild(script); }());
(function() { "use strict"; window.addEventListener('message', function(event) { if (event.data === 'debugger-client') { var port = event.ports[0]; listenToPort(port); } else if (event.data.type) { chrome.extension.sendMessage(event.data); } }); function listenToPort(port) { port.addEventListener('message', function(event) { chrome.extension.sendMessage(event.data); }); chrome.extension.onMessage.addListener(function(message) { if (message.from === 'devtools') { port.postMessage(message); } }); port.start(); } // let ember-debug know that content script has executed document.documentElement.dataset.emberExtension = 1; // Allow older versions of Ember (< 1.4) to detect the extension. if (document.body) { document.body.dataset.emberExtension = 1; } // clear a possible previous Ember icon chrome.extension.sendMessage({ type: 'resetEmberIcon' }); // inject JS into the page to check for an app on domready var script = document.createElement('script'); script.type = "text/javascript"; script.src = chrome.extension.getURL("in-page-script.js"); if (document.body) document.body.appendChild(script); }());
Fix long-description reader, make it fail silently
# -*- coding: utf8 -*- import os from setuptools import setup, find_packages os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' def _read_long_description(): try: import pypandoc return pypandoc.convert('README.md', 'rst', format='markdown') except Exception: return None setup( name="django-basis", version='0.3.2', url='http://github.com/frecar/django-basis', author='Fredrik Carlsen', author_email='fredrik@carlsen.io', description='Simple reusable django app for basic model functionality', long_description=_read_long_description(), packages=find_packages(exclude='tests'), tests_require=[ 'django>=1.4', ], license='MIT', test_suite='runtests.runtests', include_package_data=True, classifiers=[ "Programming Language :: Python", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', "Topic :: Software Development :: Libraries :: Python Modules", "Framework :: Django", "Environment :: Web Environment", "Operating System :: OS Independent", "Natural Language :: English", ] )
# -*- coding: utf8 -*- import os from setuptools import setup, find_packages os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' def _read_long_description(): try: import pypandoc return pypandoc.convert('README.md', 'rst') except ImportError: return None setup( name="django-basis", version='0.3.2', url='http://github.com/frecar/django-basis', author='Fredrik Carlsen', author_email='fredrik@carlsen.io', description='Simple reusable django app for basic model functionality', long_description=_read_long_description(), packages=find_packages(exclude='tests'), tests_require=[ 'django>=1.4', ], license='MIT', test_suite='runtests.runtests', include_package_data=True, classifiers=[ "Programming Language :: Python", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', "Topic :: Software Development :: Libraries :: Python Modules", "Framework :: Django", "Environment :: Web Environment", "Operating System :: OS Independent", "Natural Language :: English", ] )
[Readability] Fix indentation; Shorter line length
<?php /** * @title Helper PDO Database Class * * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Install / Library */ namespace PH7; defined('PH7') or die('Restricted access'); use PDO; class Db extends PDO { const DBMS_MYSQL_NAME = 'MySQL'; const DBMS_POSTGRESQL_NAME = 'PostgreSQL'; const DSN_MYSQL_PREFIX = 'mysql'; const DSN_POSTGRESQL_PREFIX = 'pgsql'; public function __construct(array $aParams) { $aDriverOptions[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $aParams['db_charset']; parent::__construct( "{$aParams['db_type']}:host={$aParams['db_hostname']};dbname={$aParams['db_name']};", $aParams['db_username'], $aParams['db_password'], $aDriverOptions ); $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } }
<?php /** * @title Helper PDO Database Class * * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Install / Library */ namespace PH7; defined('PH7') or die('Restricted access'); use PDO; class Db extends PDO { const DBMS_MYSQL_NAME = 'MySQL'; const DBMS_POSTGRESQL_NAME = 'PostgreSQL'; const DSN_MYSQL_PREFIX = 'mysql'; const DSN_POSTGRESQL_PREFIX = 'pgsql'; public function __construct(array $aParams) { $aDriverOptions[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $aParams['db_charset']; parent::__construct("{$aParams['db_type']}:host={$aParams['db_hostname']};dbname={$aParams['db_name']};", $aParams['db_username'], $aParams['db_password'], $aDriverOptions); $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } }
Add support for DriverManager and JDBC URL-based pool configuration.
/* * Copyright (C) 2014 Brett Wooldridge * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zaxxer.hikari; import java.sql.Connection; import java.sql.SQLException; import org.junit.Test; public class JdbcDriverTest { @Test public void driverTest1() throws SQLException { HikariConfig config = new HikariConfig(); config.setMinimumPoolSize(1); config.setMaximumPoolSize(1); config.setAcquireIncrement(1); config.setConnectionTestQuery("VALUES 1"); config.setDriverClassName("com.zaxxer.hikari.mocks.StubDriver"); config.setJdbcUrl("jdbc:stub"); config.addDataSourceProperty("user", "bart"); config.addDataSourceProperty("password", "simpson"); HikariDataSource ds = new HikariDataSource(config); Connection connection = ds.getConnection(); connection.close(); ds.shutdown(); } }
/* * Copyright (C) 2014 Brett Wooldridge * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zaxxer.hikari; import java.sql.SQLException; import org.junit.Test; public class JdbcDriverTest { @Test public void driverTest1() throws SQLException { HikariConfig config = new HikariConfig(); config.setMinimumPoolSize(1); config.setMaximumPoolSize(1); config.setAcquireIncrement(1); config.setConnectionTestQuery("VALUES 1"); config.setDriverClassName("com.zaxxer.hikari.mocks.StubDriver"); config.setJdbcUrl("jdbc:stub"); config.addDataSourceProperty("user", "bart"); config.addDataSourceProperty("password", "simpson"); HikariDataSource ds = new HikariDataSource(config); ds.shutdown(); } }
Add 'print_unit' to the default environment
package env; import types.*; public class Env { public Table<Type> tenv; public Table<Type> venv; public Env() { tenv = new Table<Type>(); put(tenv, "unit", UNIT.T); put(tenv, "int", INT.T); put(tenv, "real", REAL.T); venv = new Table<Type>(); put(venv, "print_int", new FUNCTION(UNIT.T, INT.T)); put(venv, "print_real", new FUNCTION(UNIT.T, REAL.T)); put(venv, "print_unit", new FUNCTION(UNIT.T, UNIT.T)); put(venv, "round", new FUNCTION(INT.T, REAL.T)); put(venv, "ceil", new FUNCTION(INT.T, REAL.T)); put(venv, "floor", new FUNCTION(INT.T, REAL.T)); put(venv, "real", new FUNCTION(REAL.T, INT.T)); } @Override public String toString() { return "Env{" + "tenv=" + tenv + ", venv=" + venv + '}'; } private static <E> void put(Table<E> table, String name, E value) { table.put(name.intern(), value); } }
package env; import types.*; public class Env { public Table<Type> tenv; public Table<Type> venv; public Env() { tenv = new Table<Type>(); put(tenv, "unit", UNIT.T); put(tenv, "int", INT.T); put(tenv, "real", REAL.T); venv = new Table<Type>(); put(venv, "print_int", new FUNCTION(UNIT.T, INT.T)); put(venv, "print_real", new FUNCTION(UNIT.T, REAL.T)); put(venv, "round", new FUNCTION(INT.T, REAL.T)); put(venv, "ceil", new FUNCTION(INT.T, REAL.T)); put(venv, "floor", new FUNCTION(INT.T, REAL.T)); put(venv, "real", new FUNCTION(REAL.T, INT.T)); } @Override public String toString() { return "Env{" + "tenv=" + tenv + ", venv=" + venv + '}'; } private static <E> void put(Table<E> table, String name, E value) { table.put(name.intern(), value); } }
Change access denied http code to 401
<?php namespace OpenOrchestra\BaseApi\Exceptions\HttpException; /** * Class ClientAccessDeniedHttpException */ class ClientAccessDeniedHttpException extends ApiException { const DEVELOPER_MESSAGE = 'client.access_denied'; const HUMAN_MESSAGE = 'api.exception.client_access_denied'; const STATUS_CODE = '401'; const ERROR_CODE = 'x'; const ERROR_SUPPORT = 'global_platform_main_contact_contact'; const REDIRECTION = 'logout'; /** * Constructor */ public function __construct() { $developerMessage = self::DEVELOPER_MESSAGE; $humanMessage = self::HUMAN_MESSAGE; $statusCode = self::STATUS_CODE; $errorCode = self::ERROR_CODE; $errorSupport = self::ERROR_SUPPORT; $redirection = self::REDIRECTION; parent::__construct($statusCode, $errorCode, $errorSupport, $developerMessage, $humanMessage, $redirection); } }
<?php namespace OpenOrchestra\BaseApi\Exceptions\HttpException; /** * Class ClientAccessDeniedHttpException */ class ClientAccessDeniedHttpException extends ApiException { const DEVELOPER_MESSAGE = 'client.access_denied'; const HUMAN_MESSAGE = 'api.exception.client_access_denied'; const STATUS_CODE = '404'; const ERROR_CODE = 'x'; const ERROR_SUPPORT = 'global_platform_main_contact_contact'; const REDIRECTION = 'logout'; /** * Constructor */ public function __construct() { $developerMessage = self::DEVELOPER_MESSAGE; $humanMessage = self::HUMAN_MESSAGE; $statusCode = self::STATUS_CODE; $errorCode = self::ERROR_CODE; $errorSupport = self::ERROR_SUPPORT; $redirection = self::REDIRECTION; parent::__construct($statusCode, $errorCode, $errorSupport, $developerMessage, $humanMessage, $redirection); } }
Fix order of TournamentLevel on games site
package de.bettinggame.adapter; import de.bettinggame.domain.Game; import de.bettinggame.domain.TournamentLevel; import de.bettinggame.domain.repository.GameRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.function.Function; import java.util.stream.Collectors; @Controller public class GameController implements AbstractController { @Autowired private GameRepository gameRepository; @GetMapping("/game") public ModelAndView list() { ModelAndView mav = new ModelAndView("game/all-games"); List<Game> games = gameRepository.findByOrderByStarttime(); Map<TournamentLevel, List<Game>> matchesByLevel = games.stream() .collect(Collectors.groupingBy(Game::getLevel, TreeMap::new, Collectors.mapping(Function.identity(), Collectors.toList()))); mav.addObject("gamesByLevel", matchesByLevel); return mav; } }
package de.bettinggame.adapter; import de.bettinggame.domain.Game; import de.bettinggame.domain.TournamentLevel; import de.bettinggame.domain.repository.GameRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Controller public class GameController implements AbstractController { @Autowired private GameRepository gameRepository; @GetMapping("/game") public ModelAndView list() { ModelAndView mav = new ModelAndView("game/all-games"); List<Game> games = gameRepository.findByOrderByStarttime(); Map<TournamentLevel, List<Game>> matchesByLevel = games.stream() .collect(Collectors.groupingBy(Game::getLevel)); mav.addObject("gamesByLevel", matchesByLevel); return mav; } }
Add title attributes to buttons
var yaja = typeof yaja === 'undefined' ? {} : yaja; (function (window, yaja, $) { function App(config) { this.config = $.extend({ // Define default config values here. "shortcuts": { "run": "F5" } }, config); this.input = $('.yaja-input')[0]; this.output = $('.yaja-output')[0]; this.interpreter = new yaja.Interpreter(); this._bindListeners(); } App.prototype.run = function () { this.output.value = ''; this.interpreter.run(this.input.value); this.output.value = this.interpreter.buffer.join(''); this.output.scrollTop = this.output.scrollHeight; }; App.prototype._bindListeners = function () { var self = this, shortcuts = this.config.shortcuts, actions = { "run": { func: function () { self.run(); }, htmlClass: '.yaja-run' } }; for (var name in actions) { var act = actions[name]; $(act.htmlClass).click(act.func).attr('title', function () { return $(this).text().trim() + ' [' + shortcuts[name] + ']'; }); $(window).add('textarea').bind('keydown', shortcuts[name], act.func); } }; yaja.App = App; })(window, yaja, jQuery);
var yaja = typeof yaja === 'undefined' ? {} : yaja; (function (window, yaja, $) { function App(config) { this.config = $.extend({ // Define default config values here. "shortcuts": { "run": "F5" } }, config); this.input = $('.yaja-input')[0]; this.output = $('.yaja-output')[0]; this.interpreter = new yaja.Interpreter(); this._bindListeners(); } App.prototype.run = function () { this.output.value = ''; this.interpreter.run(this.input.value); this.output.value = this.interpreter.buffer.join(''); this.output.scrollTop = this.output.scrollHeight; }; App.prototype._bindListeners = function () { var self = this, shortcuts = this.config.shortcuts, actions = { "run": { func: function () { self.run(); }, htmlClass: '.yaja-run' } }; for (var name in actions) { var act = actions[name]; $(act.htmlClass).click(act.func); $(window).add('textarea').bind('keydown', shortcuts[name], act.func); } }; yaja.App = App; })(window, yaja, jQuery);
Fix link to user page and contribs Bug: T107681 Change-Id: I59d749afe282c7b06a0f9a5a391a72a8bd29fb19
angular .module('crosswatch') .directive('user', user); function user() { var directive = { link: link, scope: true, template: '<a stop-event dir="auto" href="{{::event.projecturl}}/wiki/User:{{::user | urlEncode}}" target="_blank">{{::user}}</a> ' + '<span dir="auto" ng-if="event.showDiff">' + '(<a stop-event href="{{::event.projecturl}}/wiki/Special:Contributions/{{::user | urlEncode}}" target="_blank" translate="CONTRIBS"></a>)' + '</span>&#32;', restrict: 'E' }; return directive; function link(scope, element, attrs) { if (typeof attrs.name !== 'undefined') { scope.user = attrs.name; } else { scope.user = scope.event.user; } var split = scope.user.split(':'); scope.user = split[split.length - 1] } }
angular .module('crosswatch') .directive('user', user); function user() { var directive = { link: link, scope: true, template: '<a stop-event dir="auto" href="{{::event.projecturl}}/wiki/User:{{::user | urlEncode}}" target="_blank">{{::user}}</a> ' + '<span dir="auto" ng-if="event.showDiff">' + '(<a stop-event href="{{::event.projecturl}}/wiki/Special:Contributions/{{::user | urlEncode}}" target="_blank" translate="CONTRIBS"></a>)' + '</span>&#32;', restrict: 'E' }; return directive; function link(scope, element, attrs) { if (typeof attrs.name !== 'undefined') { scope.user = attrs.name; } else { scope.user = scope.event.user; } } }
Fix typo in website script.
/* * Copyright 2011 Twitter, 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. */ var Hogan = require(__dirname + '/../lib/hogan.js'); var fs = require('fs'); var path = require('path'); // Substitute variables in the homepage with values from package.json var homeTemplatePath = __dirname + '/../build/gh-pages/index.html.mustache'; var contextPath = __dirname + '/../build/gh-pages/package.json'; var homepage = fs.readFileSync(homeTemplatePath).toString(); var context = JSON.parse(fs.readFileSync(contextPath).toString()); var template = Hogan.compile(homepage); fs.writeFileSync(path.dirname(homeTemplatePath) + '/index.html', template.render(context)); fs.unlinkSync(homeTemplatePath);
/* * Copyright 2011 Twitter, 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. */ var Hogan = require(__dirname + '/../lib/hogan.js'); var fs = require('fs'); var path = require('path'); // Substitute variables in the homepage with values from package.json var homeTemplatePath = __dirname + '/../build/gh-pages/index.html.mustache'; var contextPath = __dirname + '/../build/gh-pages/package.json'; var homepage = fs.readFileSync(homeTemplatePath).toString(); var context = JSON.parse(fs.readFileSync(contextPath).toString()); var template = Hogan.compile(homepage); fs.writeFileSync(path.dirname(homeTemplatePath) + '/index.html', template.render(context)); fs.unlinkSync(homepateTemplatePath);
Use the Authorization request header field to send the token. Per http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-14#section-2.1 this is the recommended approach which must be supported by all servers.
var TokenCache = require('./token-cache'), tokens = new TokenCache(); /** * Returns a JWT-enabled request module. * @param request The request instance to modify to enable JWT. * @returns {Function} The JWT-enabled request module. */ exports.requestWithJWT = function (request) { if (!request) { // use the request module from our dependency request = require('request'); } return function (uri, options, callback) { if (typeof uri === 'undefined') throw new Error('undefined is not a valid uri or options object.'); if ((typeof options === 'function') && !callback) callback = options; if (options && typeof options === 'object') { options.uri = uri; } else if (typeof uri === 'string') { options = {uri: uri}; } else { options = uri; } if (callback) options.callback = callback; // look for a request with JWT requirement if (options.jwt) { return tokens.get(options.jwt, function (err, token) { if (err) return callback(err); options.headers = options.headers || {}; options.headers.authorization = 'Bearer ' + token; return request(uri, options, callback); }); } else { return request(uri, options, callback); } }; }; /** * Resets the token cache, clearing previously requested tokens. */ exports.resetCache = function () { tokens.clear(); };
var TokenCache = require('./token-cache'), tokens = new TokenCache(); /** * Returns a JWT-enabled request module. * @param request The request instance to modify to enable JWT. * @returns {Function} The JWT-enabled request module. */ exports.requestWithJWT = function (request) { if (!request) { // use the request module from our dependency request = require('request'); } return function (uri, options, callback) { if (typeof uri === 'undefined') throw new Error('undefined is not a valid uri or options object.'); if ((typeof options === 'function') && !callback) callback = options; if (options && typeof options === 'object') { options.uri = uri; } else if (typeof uri === 'string') { options = {uri: uri}; } else { options = uri; } if (callback) options.callback = callback; // look for a request with JWT requirement if (options.jwt) { return tokens.get(options.jwt, function (err, token) { if (err) return callback(err); // TODO: for now the token is only passed using the query string options.qs = options.qs || {}; options.qs.access_token = token; return request(uri, options, callback); }); } else { return request(uri, options, callback); } }; }; /** * Resets the token cache, clearing previously requested tokens. */ exports.resetCache = function () { tokens.clear(); };
Sort todos by creation time
'use babel'; import React from 'react'; import TodoItem from './TodoItem'; const TodoListBackgroundMessage = () => ( <background-tips> <ul className="centered background-message"> <li className="message fade-in"> Newly added todos will be listed here </li> </ul> </background-tips> ); const TodoList = ({ todos, setTodoStatus, deleteTodo, onTitleClick }) => { return ( <div> { _.sortBy(todos, ['createdAt']).map(todo => ( <TodoItem key={todo._id} todo={todo} setTodoStatus={setTodoStatus} deleteTodo={deleteTodo} onTitleClick={onTitleClick} /> )) } { (!todos || todos.length==0) && <TodoListBackgroundMessage /> } </div> ); }; export default TodoList;
'use babel'; import React from 'react'; import TodoItem from './TodoItem'; const TodoListBackgroundMessage = () => ( <background-tips> <ul className="centered background-message"> <li className="message fade-in"> Newly added todos will be listed here </li> </ul> </background-tips> ); const TodoList = ({ todos, setTodoStatus, deleteTodo, onTitleClick }) => { return ( <div> { todos.map(todo => ( <TodoItem key={todo._id} todo={todo} setTodoStatus={setTodoStatus} deleteTodo={deleteTodo} onTitleClick={onTitleClick} /> )) } { (!todos || todos.length==0) && <TodoListBackgroundMessage /> } </div> ); }; export default TodoList;
Mark internal tick API as final to discourage external usage
<?php namespace React\EventLoop\Tick; use SplQueue; /** * A tick queue implementation that can hold multiple callback functions * * This class should only be used internally, see LoopInterface instead. * * @see LoopInterface * @internal */ final class FutureTickQueue { private $queue; public function __construct() { $this->queue = new SplQueue(); } /** * Add a callback to be invoked on a future tick of the event loop. * * Callbacks are guaranteed to be executed in the order they are enqueued. * * @param callable $listener The callback to invoke. */ public function add(callable $listener) { $this->queue->enqueue($listener); } /** * Flush the callback queue. */ public function tick() { // Only invoke as many callbacks as were on the queue when tick() was called. $count = $this->queue->count(); while ($count--) { call_user_func( $this->queue->dequeue() ); } } /** * Check if the next tick queue is empty. * * @return boolean */ public function isEmpty() { return $this->queue->isEmpty(); } }
<?php namespace React\EventLoop\Tick; use SplQueue; class FutureTickQueue { private $queue; public function __construct() { $this->queue = new SplQueue(); } /** * Add a callback to be invoked on a future tick of the event loop. * * Callbacks are guaranteed to be executed in the order they are enqueued. * * @param callable $listener The callback to invoke. */ public function add(callable $listener) { $this->queue->enqueue($listener); } /** * Flush the callback queue. */ public function tick() { // Only invoke as many callbacks as were on the queue when tick() was called. $count = $this->queue->count(); while ($count--) { call_user_func( $this->queue->dequeue() ); } } /** * Check if the next tick queue is empty. * * @return boolean */ public function isEmpty() { return $this->queue->isEmpty(); } }
Use native DOM commands for screenshot ready expression Instead of using jQuery, use document.querySelector. This avoids warning messages in screenshot-as-a-service.
define([ 'http', 'url' ], function (http, url) { var renderPng = function (req, res) { var options = url.parse(renderPng.getScreenshotPath(req.url)); http.get(options, function (screenshot) { res.status(screenshot.statusCode); for (var i in screenshot.headers) { res.setHeader(i, screenshot.headers[i]); } screenshot.on("data", function(chunk) { res.write(chunk); }); screenshot.on("end", function () { res.end(); }); }).on('error', function (e) { res.status(500); res.send("Got error: " + e.message); }); }; if (global.config) { renderPng.screenshotServiceUrl = config.screenshotServiceUrl; renderPng.screenshotTargetUrl = config.screenshotTargetUrl; } renderPng.getScreenshotPath = function (url) { return [ renderPng.screenshotServiceUrl, '?readyExpression=!!document.querySelector(".ready")', '&forwardCacheHeaders=true', '&clipSelector=.visualisation', '&url=', renderPng.screenshotTargetUrl, url.replace(/.png|\?raw/g, "?raw") ].join(''); }; return renderPng; });
define([ 'http', 'url' ], function (http, url) { var renderPng = function (req, res) { var options = url.parse(renderPng.getScreenshotPath(req.url)); http.get(options, function (screenshot) { res.status(screenshot.statusCode); for (var i in screenshot.headers) { res.setHeader(i, screenshot.headers[i]); } screenshot.on("data", function(chunk) { res.write(chunk); }); screenshot.on("end", function () { res.end(); }); }).on('error', function (e) { res.status(500); res.send("Got error: " + e.message); }); }; if (global.config) { renderPng.screenshotServiceUrl = config.screenshotServiceUrl; renderPng.screenshotTargetUrl = config.screenshotTargetUrl; } renderPng.getScreenshotPath = function (url) { return [ renderPng.screenshotServiceUrl, '?readyExpression=$("body").hasClass("ready")', '&forwardCacheHeaders=true', '&clipSelector=.visualisation', '&url=', renderPng.screenshotTargetUrl, url.replace(/.png|\?raw/g, "?raw") ].join(''); }; return renderPng; });
Use multiline string to make test for InputStreamAXT.readToString() fail
package org.ligi.axt.test; import android.os.Environment; import org.apache.tools.ant.filters.StringInputStream; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.axt.AXT; import org.robolectric.RobolectricTestRunner; import java.io.File; import java.io.IOException; import static org.fest.assertions.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) public class TheInputStreamAXT { private static final String STRING_PROBE = "first line\nsecond line"; private File ROOT = Environment.getExternalStorageDirectory(); @Test public void should_write_file_correctly() throws IOException { File file = new File(ROOT, "foo1"); AXT.at(new StringInputStream(STRING_PROBE)).toFile(file); assertThat(STRING_PROBE).isEqualTo(AXT.at(file).readToString()); } @Test public void should_read_to_string_correctly() throws IOException { String readFromStream = AXT.at(new StringInputStream(STRING_PROBE)).readToString(); assertThat(readFromStream).isEqualTo(STRING_PROBE); } }
package org.ligi.axt.test; import android.os.Environment; import org.apache.tools.ant.filters.StringInputStream; import org.junit.Test; import org.junit.runner.RunWith; import org.ligi.axt.AXT; import org.robolectric.RobolectricTestRunner; import java.io.File; import java.io.IOException; import static org.fest.assertions.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) public class TheInputStreamAXT { public static final String STRING_PROBE = "132QWE"; private File ROOT = Environment.getExternalStorageDirectory(); @Test public void should_write_file_correctly() throws IOException { File file = new File(ROOT, "foo1"); AXT.at(new StringInputStream(STRING_PROBE)).toFile(file); assertThat(STRING_PROBE).isEqualTo(AXT.at(file).readToString()); } @Test public void should_read_to_string_correctly() throws IOException { String readFromStream = AXT.at(new StringInputStream(STRING_PROBE)).readToString(); assertThat(readFromStream).isEqualTo(STRING_PROBE); } }
Change version number for release
from setuptools import setup setup( name='mdf_forge', version='0.4.1', packages=['mdf_forge'], description='Materials Data Facility python package', long_description="Forge is the Materials Data Facility Python package to interface and leverage the MDF Data Discovery service. Forge allows users to perform simple queries and facilitiates moving and synthesizing results.", install_requires=[ "globus-sdk>=1.1.1", "requests>=2.18.1", "tqdm>=4.14.0", "six>=1.10.0" ], python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Science/Research", "License :: OSI Approved :: Apache Software License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 2", "Topic :: Scientific/Engineering" ], keywords=[ "MDF", "Materials Data Facility", "materials science", "dft", "data discovery", "supercomputing", "light sources" ], license="Apache License, Version 2.0", url="https://github.com/materials-data-facility/forge" )
from setuptools import setup setup( name='mdf_forge', version='0.5.0', packages=['mdf_forge'], description='Materials Data Facility python package', long_description="Forge is the Materials Data Facility Python package to interface and leverage the MDF Data Discovery service. Forge allows users to perform simple queries and facilitiates moving and synthesizing results.", install_requires=[ "globus-sdk>=1.1.1", "requests>=2.18.1", "tqdm>=4.14.0", "six>=1.10.0" ], python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Science/Research", "License :: OSI Approved :: Apache Software License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 2", "Topic :: Scientific/Engineering" ], keywords=[ "MDF", "Materials Data Facility", "materials science", "dft", "data discovery", "supercomputing", "light sources" ], license="Apache License, Version 2.0", url="https://github.com/materials-data-facility/forge" )
Add empty tagName to typeahead component
import Ember from 'ember'; import layout from '../templates/components/power-select-typeahead'; const { computed } = Ember; export default Ember.Component.extend({ tagName: '', layout: layout, tabindex: -1, triggerComponent: 'power-select-typeahead/trigger', beforeOptionsComponent: null, searchEnabled: false, loadingMessage: false, // CPs concatenatedTriggerClasses: computed('triggerClass', function() { const classes = ['ember-power-select-typeahead-trigger']; const passedClass = this.get('triggerClass'); if (passedClass) { classes.push(passedClass); } return classes.join(' '); }), concatenatedDropdownClasses: computed('dropdownClass', function() { const classes = ['ember-power-select-typeahead-dropdown']; const passedClass = this.get('dropdownClass'); if (passedClass) { classes.push(passedClass); } return classes.join(' '); }) });
import Ember from 'ember'; import layout from '../templates/components/power-select-typeahead'; const { computed } = Ember; export default Ember.Component.extend({ layout: layout, tabindex: -1, triggerComponent: 'power-select-typeahead/trigger', beforeOptionsComponent: null, searchEnabled: false, loadingMessage: false, // CPs concatenatedTriggerClasses: computed('triggerClass', function() { const classes = ['ember-power-select-typeahead-trigger']; const passedClass = this.get('triggerClass'); if (passedClass) { classes.push(passedClass); } return classes.join(' '); }), concatenatedDropdownClasses: computed('dropdownClass', function() { const classes = ['ember-power-select-typeahead-dropdown']; const passedClass = this.get('dropdownClass'); if (passedClass) { classes.push(passedClass); } return classes.join(' '); }) });
Change start-weblogic-server using jdk as default. Code reviewed by Edwin Tang Former-commit-id: 6e2cbb2da770d73e12dfae7d36fd6f1ef00c4ed7
############################################################################ # Generic script applicable on any Operating Environments (Unix, Windows) # ScriptName : wls_start.py # Properties : weblogic.properties # Author : Kevin Yuan ############################################################################ #=========================================================================== # Start server using wlst command #=========================================================================== #startServer('%%TARGET_SERVER%%', 'eclipselink', url='t3://%%WL_HOST%%:%%WL_PORT%%', username='%%WL_USR%%', password='%%WL_PWD%%', domainDir='%%WL_DOMAIN%%', jvmArgs='-Xms256m -Xmx960m -Dweblogic.Stdout=stdout.log -Dweblogic.Stderr=stderr.log') #=========================================================================== # Using the following instead of above "jvmarg" setting when using SUN jdk # because jrockit doesn't support PermSize when the server run on SUN jdk #=========================================================================== startServer('%%TARGET_SERVER%%', 'eclipselink', url='t3://%%WL_HOST%%:%%WL_PORT%%', username='%%WL_USR%%', password='%%WL_PWD%%', domainDir='%%WL_DOMAIN%%', jvmArgs='-XX:PermSize=128m -XX:MaxPermSize=256m -Dweblogic.Stdout=stdout.log -Dweblogic.Stderr=stderr.log') #=========================================================================== # Add the following jvmarg(s) into wlst command when you try to debug #=========================================================================== #-Xdebug #-Xnoagent #-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=4000
############################################################################ # Generic script applicable on any Operating Environments (Unix, Windows) # ScriptName : wls_start.py # Properties : weblogic.properties # Author : Kevin Yuan ############################################################################ #=========================================================================== # Start server using wlst command #=========================================================================== startServer('%%TARGET_SERVER%%', 'eclipselink', url='t3://%%WL_HOST%%:%%WL_PORT%%', username='%%WL_USR%%', password='%%WL_PWD%%', domainDir='%%WL_DOMAIN%%', jvmArgs='-Xms256m -Xmx960m -Dweblogic.Stdout=stdout.log -Dweblogic.Stderr=stderr.log') #=========================================================================== # Using the following instead of above "jvmarg" setting when using SUN jdk # because jrockit doesn't support PermSize when the server run on SUN jdk #=========================================================================== #startServer('%%TARGET_SERVER%%', 'eclipselink', url='t3://%%WL_HOST%%:%%WL_PORT%%', username='%%WL_USR%%', password='%%WL_PWD%%', domainDir='%%WL_DOMAIN%%', jvmArgs='-XX:PermSize=128m -XX:MaxPermSize=256m -Dweblogic.Stdout=stdout.log -Dweblogic.Stderr=stderr.log') #=========================================================================== # Add the following jvmarg(s) into wlst command when you try to debug #=========================================================================== #-Xdebug #-Xnoagent #-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=4000
Add median/avg response time stats functions.
var _ = require('underscore'), moment = require('moment'); function Stats() { this.outstandingPings = {}; this.responseTimes = []; } Stats.prototype.makeKey = function(channelID, version) { return channelID + version.toString(); }; Stats.prototype.addOutstanding = function(channelID, version) { this.outstandingPings[this.makeKey(channelID, version)] = moment(); }; Stats.prototype.clearPing = function(channelID, version) { var key = this.makeKey(channelID, version); var start = this.outstandingPings[key]; delete this.outstandingPings[key]; this.responseTimes.push(moment().diff(start)); }; function StatsCollector() { this.stats = new Stats(); } StatsCollector.prototype.pingSent = function(channelID, version) { this.stats.addOutstanding(channelID, version); }; StatsCollector.prototype.pingReceived = function(channelID, version) { this.stats.clearPing(channelID, version); }; StatsCollector.prototype.medianRespTime = function() { var responseTimes = this.stats.responseTimes; if(_.isEmpty(responseTimes)) return; responseTimes.sort(function(a, b) {return a - b;}); var medIdx = Math.floor(_.size(responseTimes) / 2); return responseTimes[medIdx]; }; StatsCollector.prototype.avgRespTime = function() { var responseTimes = this.stats.responseTimes; if(_.isEmpty(responseTimes)) return; return _.reduce(responseTimes, function(m, n) { return n + m; }, 0) / _.size(responseTimes); }; module.exports = StatsCollector;
var _ = require('underscore'), moment = require('moment'); function Stats() { this.outstandingPings = {}; this.responseTimes = []; } Stats.prototype.makeKey = function(channelID, version) { return channelID + version.toString(); }; Stats.prototype.addOutstanding = function(channelID, version) { this.outstandingPings[this.makeKey(channelID, version)] = moment(); }; Stats.prototype.clearPing = function(channelID, version) { var key = this.makeKey(channelID, version); var start = this.outstandingPings[key]; delete this.outstandingPings[key]; this.responseTimes.push(moment().diff(start)); }; function StatsCollector() { this.stats = new Stats(); } StatsCollector.prototype.pingSent = function(channelID, version) { this.stats.addOutstanding(channelID, version); }; StatsCollector.prototype.pingReceived = function(channelID, version) { this.stats.clearPing(channelID, version); }; module.exports = StatsCollector;
Use the attribute getter, not the property. Declare the getter abstract.
<?php /** * This file is part of the LdapTools package. * * (c) Chad Sikorra <Chad.Sikorra@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace LdapTools\AttributeConverter; /** * Intended to be used with attribute converters that utilize options and current attributes to do some of their work. * * @author Chad Sikorra <Chad.Sikorra@gmail.com> */ trait ConverterUtilitiesTrait { /** * {@inheritdoc} */ abstract public function getAttribute(); /** * If the current attribute does not exist in the array, then throw an error. * * @param $options */ protected function validateCurrentAttribute(array $options) { if (!array_key_exists(strtolower($this->getAttribute()), array_change_key_case($options))) { throw new \RuntimeException( sprintf('You must first define "%s" in the options for this converter.', $this->getAttribute()) ); } } /** * Get the value of an array key in a case-insensitive way. * * @param array $options * @param string $key */ protected function getArrayValue(array $options, $key) { return array_change_key_case($options)[strtolower($key)]; } }
<?php /** * This file is part of the LdapTools package. * * (c) Chad Sikorra <Chad.Sikorra@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace LdapTools\AttributeConverter; /** * Intended to be used with attribute converters that utilize options and current attributes to do some of their work. * * @author Chad Sikorra <Chad.Sikorra@gmail.com> */ trait ConverterUtilitiesTrait { /** * If the current attribute does not exist in the array, then throw an error. * * @param $options */ protected function validateCurrentAttribute(array $options) { if (!array_key_exists(strtolower($this->getAttribute()), array_change_key_case($options))) { throw new \RuntimeException( sprintf('You must first define "%s" in the options for this converter.', $this->attribute) ); } } /** * Get the value of an array key in a case-insensitive way. * * @param array $options * @param string $key */ protected function getArrayValue(array $options, $key) { return array_change_key_case($options)[strtolower($key)]; } }
Update server example to match client example
import React, { Component, PropTypes } from 'react'; import {connect} from 'react-redux'; import {Link} from 'react-router'; @connect(state => ({ routerState: state.router })) export const App = class App extends Component { static propTypes = { children: PropTypes.node } render() { const links = [ '/', '/parent?foo=bar', '/parent/child?bar=baz', '/parent/child/123?baz=foo' ].map((l, i) => <p key={i}> <Link to={l}>{l}</Link> </p> ); return ( <div> <h1>App Container</h1> {links} {this.props.children} </div> ); } }; export const Parent = class Parent extends Component { static propTypes = { children: PropTypes.node } render() { return ( <div> <h2>Parent</h2> {this.props.children} </div> ); } }; export const Child = class Child extends Component { render() { const { params: { id }} = this.props; return ( <div> <h2>Child</h2> {id && <p>{id}</p>} </div> ); } };
import React, { Component, PropTypes } from 'react'; import {connect} from 'react-redux'; import {Link} from 'react-router'; @connect(state => ({ routerState: state.router })) export const App = class App extends Component { static propTypes = { children: PropTypes.node } render() { const links = [ '/', '/parent?foo=bar', '/parent/child?bar=baz', '/parent/child/123?baz=foo' ].map((l, i) => <p key={i}> <Link to={l}>{l}</Link> </p> ); return ( <div> <h1>App Container</h1> {links} {this.props.children} </div> ); } }; export const Parent = class Parent extends Component { static propTypes = { children: PropTypes.node } render() { return ( <div> <h2>Parent</h2> {this.props.children} </div> ); } }; export const Child = class Child extends Component { render() { return ( <div> <h2>Child</h2> </div> ); } };
Comment out buggy encoding detection.
<?php function is_utf8 ($str) { $converted = iconv('utf-8', 'utf-8', $str); if ($converted == $str) { return true; } else { return false; } } require_once('lib/FileLog.class.php'); $data = new FileLog('data/data.tsv', array('id', 'page_path', 'page_url', 'category', 'element', 'pass', 'comment')); $page_path = $_REQUEST['path']; $page_url = $_REQUEST['url']; // if (!is_utf8($page_path)) { // $page_path = iconv('euc-kr', 'utf-8', $page_path); // } $count = 0; foreach ($_REQUEST['result'] as $category => $seq) { foreach ($seq as $item) { if (isset($item['pass'])) { $data->save(array(uniqid(), $page_path, $page_url, $category, $item['data'], $item['pass'], $item['comment'])); $count++; } } } header('Content-Type: text/plain'); ?> Saved <?php echo($count); ?> items.
<?php function is_utf8 ($str) { $converted = iconv('utf-8', 'utf-8', $str); if ($converted == $str) { return true; } else { return false; } } require_once('lib/FileLog.class.php'); $data = new FileLog('data/data.tsv', array('id', 'page_path', 'page_url', 'category', 'element', 'pass', 'comment')); $page_path = $_REQUEST['path']; $page_url = $_REQUEST['url']; if (!is_utf8($page_path)) { $page_path = iconv('euc-kr', 'utf-8', $page_path); } $count = 0; foreach ($_REQUEST['result'] as $category => $seq) { foreach ($seq as $item) { if (isset($item['pass'])) { $data->save(array(uniqid(), $page_path, $page_url, $category, $item['data'], $item['pass'], $item['comment'])); $count++; } } } header('Content-Type: text/plain'); ?> Saved <?php echo($count); ?> items.
Fix the version string generation when not a final or RC release.
# The version of Review Board. # # This is in the format of: # # (Major, Minor, Micro, alpha/beta/rc/final, Release Number, Released) # VERSION = (1, 0, 1, 'alpha', 1, False) def get_version_string(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version += ".%s" % VERSION[2] if VERSION[3] != 'final': if VERSION[3] == 'rc': version += ' RC%s' % VERSION[4] else: version += ' %s %s' % (VERSION[3], VERSION[4]) if not is_release(): version += " (dev)" return version def get_package_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version += ".%s" % VERSION[2] if VERSION[3] != 'final': version += '%s%s' % (VERSION[3], VERSION[4]) return version def is_release(): return VERSION[5]
# The version of Review Board. # # This is in the format of: # # (Major, Minor, Micro, alpha/beta/rc/final, Release Number, Released) # VERSION = (1, 0, 1, 'alpha', 1, False) def get_version_string(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version += ".%s" % VERSION[2] if VERSION[3] != 'final': if VERSION[3] == 'rc': version += ' RC%s' % VERSION[4] else: version += ' %s %s' % (release_tag, VERSION[4]) if not is_release(): version += " (dev)" return version def get_package_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version += ".%s" % VERSION[2] if VERSION[3] != 'final': version += '%s%s' % (VERSION[3], VERSION[4]) return version def is_release(): return VERSION[5]
BUG: Fix test which appeared to not be run
# This file is part of h5py, a Python interface to the HDF5 library. # # http://www.h5py.org # # Copyright 2008-2018 Andrew Collette and contributors # # License: Standard 3-clause BSD; see "license.txt" for full license terms # and contributor agreement. """ Tests that deprecations work correctly """ from __future__ import absolute_import import h5py from h5py.h5py_warnings import H5pyDeprecationWarning from ..common import ut, TestCase class TestDeprecations(TestCase): def test_highlevel_access(self): warning_message = ( "The h5py.highlevel module is deprecated, code should import " "directly from h5py, e.g. 'from h5py import File'." ) with self.assertWarnsRegex(H5pyDeprecationWarning, warning_message) as warning: File = h5py.highlevel.File
# This file is part of h5py, a Python interface to the HDF5 library. # # http://www.h5py.org # # Copyright 2008-2018 Andrew Collette and contributors # # License: Standard 3-clause BSD; see "license.txt" for full license terms # and contributor agreement. """ Tests that deprecations work correctly """ from __future__ import absolute_import import h5py from ..common import ut, TestCase class TestDeprecations(TestCase): def test_highlevel_access(self): warning_message = ( "The h5py.highlevel module is deprecated, code should import " "directly from h5py, e.g. 'from h5py import File'." ) with self.assertWarnsRegex(H5pyDeprecationWarning, warning_message) as warning: hl = h5py.highlevel
Fix bug al actualizar perfil
<?php namespace Tecnocreaciones\Vzla\GovernmentBundle\Form\Type; use FOS\UserBundle\Form\Type\ProfileFormType as BaseProfileFormType; use Symfony\Component\Form\FormBuilderInterface; class ProfileFormType extends BaseProfileFormType { public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); $builder ->add('firstName',null,array( 'label' => 'form.first_name', 'translation_domain' => 'TecnocreacionesVzlaGovernmentBundle', )) ->add('lastName',null,array( 'label' => 'form.last_name', 'translation_domain' => 'TecnocreacionesVzlaGovernmentBundle', )) ; } public function getName() { return 'tecnocreaciones_vzla_government_user_profile'; } }
<?php namespace Tecnocreaciones\Vzla\GovernmentBundle\Form\Type; use FOS\UserBundle\Form\Type\ProfileFormType; use Symfony\Component\Form\FormBuilderInterface; class ProfileFormType extends ProfileFormType { public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); $builder ->add('firstName',null,array( 'label' => 'form.first_name', 'translation_domain' => 'TecnocreacionesVzlaGovernmentBundle', )) ->add('lastName',null,array( 'label' => 'form.last_name', 'translation_domain' => 'TecnocreacionesVzlaGovernmentBundle', )) ; } public function getName() { return 'tecnocreaciones_vzla_government_user_profile'; } }
Remove yes/no answer check after submitted once
//hide and show answers $(document).ready(function(e){ function provide_feedback(is_correct, notice_text) { $.ajax({ url: window.location.pathname + "/feedback", type: "POST", data: { correct: is_correct } }) .done(function( data ) { if ( console && console.log ) { console.log( "Sample of data:", data.slice( 0, 100 ) ); } $('#alert_text').text(notice_text); $('.alert').slideDown(); }); }; //if you wish to keep both the divs hidden by default then dont forget to hide //them $("#answers").hide(); $("#response").hide(); $("#submit_answer").click(function(){ $("#answers").fadeIn(); $("#submit_answer").hide("slow"); $("#response").fadeIn(); }); $('#respond-yes').click(function(e) { provide_feedback("yes", "Great! Congrats! Try another question."); $('#response').addClass('hidden'); }); $('#respond-no').click(function(e) { provide_feedback("no", "No worries. You'll get it next time. Onwards!"); $('#response').addClass('hidden'); }); });
//hide and show answers $(document).ready(function(e){ function provide_feedback(is_correct, notice_text) { $.ajax({ url: window.location.pathname + "/feedback", type: "POST", data: { correct: is_correct } }) .done(function( data ) { if ( console && console.log ) { console.log( "Sample of data:", data.slice( 0, 100 ) ); } $('#alert_text').text(notice_text); $('.alert').slideDown(); }); }; //if you wish to keep both the divs hidden by default then dont forget to hide //them $("#answers").hide(); $("#response").hide(); $("#submit_answer").click(function(){ $("#answers").fadeIn(); $("#submit_answer").hide("slow"); $("#response").fadeIn(); }); $('#respond-yes').click(function(e) { provide_feedback("yes", "Great! Congrats! Try another question."); }); $('#respond-no').click(function(e) { provide_feedback("no", "No worries. You'll get it next time. Onwards!"); }); });
Add basic GTM tracking for user collections
const defaultState = { items: [], } const store = { state: JSON.parse(localStorage.getItem('userCollections')) || defaultState, getItems() { return this.state.items }, addItem(itemId) { this.state.items.push({id: itemId}) this._saveState() this._track('addItem', itemId) }, removeItem(itemId) { this.state.items = this.state.items.filter(({id}) => id !== itemId) this._saveState() this._track('removeItem', itemId) }, hasItem(itemId) { return this.state.items.findIndex(({id}) => id === itemId) > -1 }, toggleItem(itemId) { this.hasItem(itemId) ? this.removeItem(itemId) : this.addItem(itemId) }, clearAllItems() { this.state.items = [] this._saveState() this._track('clearAllItems', null) }, _saveState() { localStorage.setItem('userCollections', JSON.stringify(this.state)) }, // GTM Tracking _track(actionName, itemId) { if (!window.dataLayer) return window.dataLayer.push({ 'event': 'UserCollectionEvent', 'eventCategory': 'UserCollection', 'eventAction': actionName, 'eventLabel': itemId, 'userCollection': this.state.items }) } } module.exports = store
const defaultState = { items: [], } const store = { state: JSON.parse(localStorage.getItem('userCollections')) || defaultState, getItems() { return this.state.items }, addItem(itemId) { this.state.items.push({id: itemId}) this._saveState() }, removeItem(itemId) { this.state.items = this.state.items.filter(({id}) => id !== itemId) this._saveState() }, hasItem(itemId) { return this.state.items.findIndex(({id}) => id === itemId) > -1 }, toggleItem(itemId) { this.hasItem(itemId) ? this.removeItem(itemId) : this.addItem(itemId) }, clearAllItems() { this.state.items = [] this._saveState() }, _saveState() { localStorage.setItem('userCollections', JSON.stringify(this.state)) }, } module.exports = store
Update test for DeterLabProjectEntity in adapter-deterlab
package sg.ncl.adapter.deterlab.dtos.entities; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat; /** * Created by Tran Ly Vu on 10/3/2016. */ public class DeterLabProjectEntityTest { private DeterLabProjectEntity deterLabUserEntity; @Before public void setup(){ deterLabUserEntity=new DeterLabProjectEntity(); } @Test public void getterAndSetterTest(){ deterLabUserEntity.setId("test1"); deterLabUserEntity.setNclTeamId("test2"); deterLabUserEntity.setDeterProjectId("test3"); String actual1=deterLabUserEntity.getId(); String actual2=deterLabUserEntity.getNclTeamId(); String actual3=deterLabUserEntity.getDeterProjectId(); assertThat(actual1).isNotNull(); assertThat(actual2).isNotNull(); assertThat(actual3).isNotNull(); assertEquals("test1",actual1); assertEquals("test2",actual2); assertEquals("test3",actual3); } }
package sg.ncl.adapter.deterlab.dtos.entities; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Created by Tran Ly Vu on 10/3/2016. */ public class DeterLabProjectEntityTest { private DeterLabProjectEntity deterLabUserEntity; @Before public void setup(){ deterLabUserEntity=new DeterLabProjectEntity(); } @Test public void getterAndSetterTest(){ deterLabUserEntity.setId("test1"); deterLabUserEntity.setNclTeamId("test2"); deterLabUserEntity.setDeterProjectId("test3"); String actual1=deterLabUserEntity.getId(); String actual2=deterLabUserEntity.getNclTeamId(); String actual3=deterLabUserEntity.getDeterProjectId(); assertEquals("test1",actual1); assertEquals("test2",actual2); assertEquals("test3",actual3); } }
Fix compilation error of Windows binary
// +build windows package util import ( "fmt" "os" "os/exec" "syscall" ) // ExecCommand executes the given command with cmd func ExecCommand(command string) *exec.Cmd { return ExecCommandWith("cmd", command) } // ExecCommandWith executes the given command with cmd. _shell parameter is // ignored on Windows. func ExecCommandWith(_shell string, command string) *exec.Cmd { cmd := exec.Command("cmd") cmd.SysProcAttr = &syscall.SysProcAttr{ HideWindow: false, CmdLine: fmt.Sprintf(` /s /c "%s"`, command), CreationFlags: 0, } return cmd } // IsWindows returns true on Windows func IsWindows() bool { return true } // SetNonBlock executes syscall.SetNonblock on file descriptor func SetNonblock(file *os.File, nonblock bool) { syscall.SetNonblock(syscall.Handle(file.Fd()), nonblock) } // Read executes syscall.Read on file descriptor func Read(fd int, b []byte) (int, error) { return syscall.Read(syscall.Handle(fd), b) }
// +build windows package util import ( "os" "os/exec" "syscall" ) // ExecCommand executes the given command with cmd func ExecCommand(command string) *exec.Cmd { return ExecCommandWith("cmd", command) } // ExecCommandWith executes the given command with cmd. _shell parameter is // ignored on Windows. func ExecCommandWith(_shell string, command string) *exec.Cmd { cmd := exec.Command("cmd") cmd.SysProcAttr = &syscall.SysProcAttr{ HideWindow: false, CmdLine: fmt.Sprintf(` /s /c "%s"`, command), CreationFlags: 0, } return cmd } // IsWindows returns true on Windows func IsWindows() bool { return true } // SetNonBlock executes syscall.SetNonblock on file descriptor func SetNonblock(file *os.File, nonblock bool) { syscall.SetNonblock(syscall.Handle(file.Fd()), nonblock) } // Read executes syscall.Read on file descriptor func Read(fd int, b []byte) (int, error) { return syscall.Read(syscall.Handle(fd), b) }
Fix issues from merge conflict
var passport = require('passport'); var middleware = require('./middleware.js'); module.exports = function(app, io, dbConfig) { app.use(passport.initialize()); app.use(passport.session()); app.use(middleware.redirectBasedOnLoggedInStatus); app.use(app.router); var poetsRepo = require('../repositories/poets_repository')(dbConfig); var auth = require('../services/authentication_service')(poetsRepo); var login = require('./login')(dbConfig); var register = require('./register')(dbConfig); var poems = require('./poems')(dbConfig); var poets = require('./poets')(dbConfig); var lines = require('./lines')(io, dbConfig); app.get('/', login.get); app.get('/login', login.get); app.post('/login', login.login); app.get('/logout', login.logout); app.get('/register', register.get); app.post('/register', register.create); app.get('/poems', poems.list); app.get('/poems/new', poems.createForm); app.get('/poems/:id', auth.verifyPoetAccess('id'), poems.edit); app.post('/poems', poems.create); app.post('/lines', auth.verifyPoetAccess('poemId'), lines.create); app.get('/poets', poets.search); };
var passport = require('passport'); var middleware = require('./middleware.js'); module.exports = function(app, io, dbConfig) { app.use(passport.initialize()); app.use(passport.session()); app.use(middleware.redirectBasedOnLoggedInStatus); app.use(app.router); var poetsRepo = require('../repositories/poets_repository')(dbConfig); var auth = require('../services/authentication_service')(poetsRepo); var login = require('./login')(dbConfig); var register = require('./register')(dbConfig); var poems = require('./poems')(dbConfig); var poets = require('./poets')(dbConfig); var lines = require('./lines')(io, dbConfig); app.get('/', login.get); app.get('/login', login.get); app.post('/login', login.login); app.get('/logout', login.logout); app.get('/register', register.get); app.post('/register', register.create); app.get('/poem', poem.list); app.get('/poems/new', poem.createForm); app.get('/poems/:id', auth.verifyPoetAccess('id'), poem.edit); app.post('/poem', poem.create); app.post('/line', auth.verifyPoetAccess('poemId'), line.create); app.get('/poets', poets.search); };
Fix compatibility intent name string for Actions on Google
const BotkitGActionsBot = require(__dirname + '/botkit'); const BaseController = require('../base-controler'); module.exports = class GActionsController extends BaseController { get botkitType() { return 'google'; } get hearsMentionEvents() { return []; } get hearsTriggerEvents() { return [ 'actions.intent.MAIN' ]; } get triggerEventsNLPMap() { return { 'actions.intent.MAIN': 'WELCOME' }; } get hearsMessageEvents() { return [ 'actions.intent.TEXT' ]; } constructor(abbottCore) { super('gactions', abbottCore, { __dirname: __dirname }); if (this.abbottCore.options.storage) { this.config.storage = this.abbottCore.options.storage; } this.initializeGActionsBot(); } getBotkitOptions() { let botOpt = super.getBotkitOptions(); return botOpt; } initializeGActionsBot() { this.controller = BotkitGActionsBot(this.getBotkitOptions()); this.controller.webserver = this.webserver; this.controller.startTicking(); this.controller.createWebhookEndpoints(this.webserver); } };
const BotkitGActionsBot = require(__dirname + '/botkit'); const BaseController = require('../base-controler'); module.exports = class GActionsController extends BaseController { get botkitType() { return 'google'; } get hearsMentionEvents() { return []; } get hearsTriggerEvents() { return [ 'assistant.intent.action.MAIN' ]; } get triggerEventsNLPMap() { return { 'assistant.intent.action.MAIN': 'WELCOME' }; } get hearsMessageEvents() { return [ 'assistant.intent.action.TEXT' ]; } constructor(abbottCore) { super('gactions', abbottCore, { __dirname: __dirname }); if (this.abbottCore.options.storage) { this.config.storage = this.abbottCore.options.storage; } this.initializeGActionsBot(); } getBotkitOptions() { let botOpt = super.getBotkitOptions(); return botOpt; } initializeGActionsBot() { this.controller = BotkitGActionsBot(this.getBotkitOptions()); this.controller.webserver = this.webserver; this.controller.startTicking(); this.controller.createWebhookEndpoints(this.webserver); } };
Fix url of sample sound
var context; window.addEventListener('load', init, false); function init() { try { var dogBarkingUrl = 'https://upload.wikimedia.org/wikipedia/commons/c/ce/Sound-of-dog.ogg'; var dogBarkingBuffer = null; // Fix up prefixing window.AudioContext = window.AudioContext || window.webkitAudioContext; context = new AudioContext(); loadDogSound(dogBarkingUrl); alert('Sound Loaded'); playSound(dogBarkingBuffer); } catch(e) { alert('Web Audio API is not supported in this browser'); } } function loadDogSound(url) { var request = new XMLHttpRequest(); request.open('GET', url, true); request.responseType = 'arraybuffer'; // Decode asynchronously request.onload = function() { context.decodeAudioData( request.response, function(buffer) { dogBarkingBuffer = buffer; }, onError ); } request.send(); } function playSound(buffer) { var source = context.createBufferSource(); // creates a sound source source.buffer = buffer; // tell the source which sound to play source.connect(context.destination); // connect the source to the context's destination (the speakers) source.start(0); // play the source now // note: on older systems, may have to use deprecated noteOn(time); }
var context; window.addEventListener('load', init, false); function init() { try { var dogBarkingUrl = 'https://commons.wikimedia.org/wiki/File:Sound-of-dog.ogg'; var dogBarkingBuffer = null; // Fix up prefixing window.AudioContext = window.AudioContext || window.webkitAudioContext; context = new AudioContext(); loadDogSound(dogBarkingUrl); alert('Sound Loaded'); playSound(dogBarkingBuffer); } catch(e) { alert('Web Audio API is not supported in this browser'); } } function loadDogSound(url) { var request = new XMLHttpRequest(); request.open('GET', url, true); request.responseType = 'arraybuffer'; // Decode asynchronously request.onload = function() { context.decodeAudioData( request.response, function(buffer) { dogBarkingBuffer = buffer; }, onError ); } request.send(); } function playSound(buffer) { var source = context.createBufferSource(); // creates a sound source source.buffer = buffer; // tell the source which sound to play source.connect(context.destination); // connect the source to the context's destination (the speakers) source.start(0); // play the source now // note: on older systems, may have to use deprecated noteOn(time); }
Fix to use pip style ==
from argparse import RawDescriptionHelpFormatter from copy import copy import yaml from conda.cli import common from conda.cli import main_list from conda import install description = """ Export a given environment """ example = """ examples: conda env export conda env export --file SOME_FILE """ def configure_parser(sub_parsers): p = sub_parsers.add_parser( 'export', formatter_class=RawDescriptionHelpFormatter, description=description, help=description, epilog=example, ) common.add_parser_prefix(p) p.set_defaults(func=execute) def execute(args, parser): prefix = common.get_prefix(args) installed = install.linked(prefix) conda_pkgs = copy(installed) # json=True hides the output, data is added to installed main_list.add_pip_installed(prefix, installed, json=True) pip_pkgs = sorted(installed - conda_pkgs) dependencies = ['='.join(a.rsplit('-', 2)) for a in sorted(conda_pkgs)] dependencies.append({'pip': ['=='.join(a.rsplit('-', 2)[:2]) for a in pip_pkgs]}) print(yaml.dump({'dependencies': dependencies}, default_flow_style=False))
from argparse import RawDescriptionHelpFormatter from copy import copy import yaml from conda.cli import common from conda.cli import main_list from conda import install description = """ Export a given environment """ example = """ examples: conda env export conda env export --file SOME_FILE """ def configure_parser(sub_parsers): p = sub_parsers.add_parser( 'export', formatter_class=RawDescriptionHelpFormatter, description=description, help=description, epilog=example, ) common.add_parser_prefix(p) p.set_defaults(func=execute) def execute(args, parser): prefix = common.get_prefix(args) installed = install.linked(prefix) conda_pkgs = copy(installed) # json=True hides the output, data is added to installed main_list.add_pip_installed(prefix, installed, json=True) pip_pkgs = sorted(installed - conda_pkgs) dependencies = ['='.join(a.rsplit('-', 2)) for a in sorted(conda_pkgs)] dependencies.append({'pip': ['='.join(a.rsplit('-', 2)[:2]) for a in pip_pkgs]}) print(yaml.dump({'dependencies': dependencies}, default_flow_style=False))
Add static server middleware that is active in non-production environments only.
// Server startup script // ===================== // Responsible for configuring the server, // inserting middleware, and starting the // app up. // // Note: this was written on my iPhone, please excuse typos 'use strict' let express = require('express'), exphbs = require('express-handlebars'), app = express(), _ = require('lodash'), config = _.merge(require(__dirname + '/config/app').common, require(__dirname + '/config/app')[process.env.NODE_ENV]); // App configuration // ----------------- // Configure views and other settings app.engine('hbs', exphbs(config.handlebars)); app.set('view engine', 'hbs'); app.set('views', __dirname + '/views'); // Middleware // ---------- // Insert, configure, update middleware if (_.includes(['development', 'test'], process.env.NODE_ENV)) { // DEVELOPMENT/TEST MIDDLEWARE app.use(express.static(__dirname + '/public')); } // Routes // ------ // Initialize user facing routes require('./controllers')(app); // Start server // ------------ // Start the server let server = app.listen(process.env.PORT, () => { console.log('Started app on localhost:' + server.address().port); });
// Server startup script // ===================== // Responsible for configuring the server, // inserting middleware, and starting the // app up. // // Note: this was written on my iPhone, please excuse typos 'use strict' let express = require('express'), exphbs = require('express-handlebars'), app = express(), _ = require('lodash'), config = _.merge(require(__dirname + '/config/app').common, require(__dirname + '/config/app')[process.env.NODE_ENV]); // App configuration // ----------------- // Configure views and other settings app.engine('hbs', exphbs(config.handlebars)); app.set('view engine', 'hbs'); app.set('views', __dirname + '/views'); // Middleware // ---------- // Insert, configure, update middleware // Routes // ------ // Initialize user facing routes require('./controllers')(app); // Start server // ------------ // Start the server let server = app.listen(process.env.PORT, () => { console.log('Started app on localhost:' + server.address().port); });
Disable rei.com on oopif benchmarks. CQ_EXTRA_TRYBOTS=tryserver.chromium.perf:linux_perf_bisect BUG=522870 Review URL: https://codereview.chromium.org/1334733002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#348251}
# Copyright 2015 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. from telemetry.page import page from telemetry import story class OopifBasicPageSet(story.StorySet): """ Basic set of pages used to measure performance of out-of-process iframes. """ def __init__(self): super(OopifBasicPageSet, self).__init__( archive_data_file='data/oopif_basic.json', cloud_storage_bucket=story.PARTNER_BUCKET) urls = [ 'http://www.cnn.com', 'http://www.ebay.com', 'http://booking.com', # Disabled because it causes flaky runs https://crbug.com/522870 #'http://www.rei.com/', 'http://www.fifa.com/', # Disabled because it is flaky on Windows and Android #'http://arstechnica.com/', 'http://www.nationalgeographic.com/', # Cross-site heavy! Enable them once they render without crashing. #'http://www.nba.com/', #'http://www.phonearena.com/', #'http://slickdeals.net/', #'http://www.163.com/', ] for url in urls: self.AddStory(page.Page(url, self))
# Copyright 2015 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. from telemetry.page import page from telemetry import story class OopifBasicPageSet(story.StorySet): """ Basic set of pages used to measure performance of out-of-process iframes. """ def __init__(self): super(OopifBasicPageSet, self).__init__( archive_data_file='data/oopif_basic.json', cloud_storage_bucket=story.PARTNER_BUCKET) urls = [ 'http://www.cnn.com', 'http://www.ebay.com', 'http://booking.com', 'http://www.rei.com/', 'http://www.fifa.com/', # Disabled because it is flaky on Windows and Android #'http://arstechnica.com/', 'http://www.nationalgeographic.com/', # Cross-site heavy! Enable them once they render without crashing. #'http://www.nba.com/', #'http://www.phonearena.com/', #'http://slickdeals.net/', #'http://www.163.com/', ] for url in urls: self.AddStory(page.Page(url, self))
Send error messages back to Slack We send HTTP status 200, along with a message (non-200 are not shown in the Slack views..)
var config = require('config'); var express = require('express'); var bodyParser = require('body-parser'); var ircdispatcher = require('./lib/ircdispatcher'); var messageparser = require('./lib/messageparser'); var l = require('./lib/log')('Server'); var db = require('./lib/db'); var app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.post('/toirc', function(req, res){ l.debug('Got incoming msg to IRC: ', req.body); messageparser.parseIrcMessage(req.body) .then(function(message) { return ircdispatcher.postMessage(message); }) .then(function(result) { if (result && result.sent) l.verbose('IRC message sent to IRC server'); res.status(200).end(); }, function error (e) { if (e.name === 'HttpError') { // Send 200 so that Slack will display the message res.status(200).json({text: 'Error: ' + e.message}); } else { l.error('%s\nStack: "%s"', e.toString(), e.stack); res.status(500); } }) .done(); }); var server = app.listen(config.server.port, function() { db.load(); l.info('Listening on port ' + config.server.port); });
var config = require('config'); var express = require('express'); var bodyParser = require('body-parser'); var ircdispatcher = require('./lib/ircdispatcher'); var messageparser = require('./lib/messageparser'); var l = require('./lib/log')('Server'); var db = require('./lib/db'); var app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.post('/toirc', function(req, res){ l.debug('Got incoming msg to IRC: ', req.body); messageparser.parseIrcMessage(req.body) .then(function(message) { return ircdispatcher.postMessage(message); }) .then(function(result) { if (result && result.sent) l.verbose('IRC message sent to IRC server'); res.status(200).end(); }, function error (e) { if (e.name !== 'HttpError') l.error('%s\nStack: "%s"', e.toString(), e.stack); res.status(e.statusCode); }) .done(); }); var server = app.listen(config.server.port, function() { db.load(); l.info('Listening on port ' + config.server.port); });
refactor: Split code in separate function
'use babel'; import { CompositeDisposable } from 'atom'; import fs from 'fs'; export default { modalPanel: null, subscriptions: null, config: { shouldCreateFile: { type: 'boolean', default: true, }, testExtension: { type: 'string', default: '.spec', }, }, activate(state) { this.subscriptions = new CompositeDisposable(); this.subscriptions.add(atom.commands.add('atom-workspace', { 'open-tests:open': () => this.open() })); }, deactivate() { this.subscriptions.dispose(); }, getTestPath() { const testExtension = atom.config.get('open-tests.testExtension') const filePath = atom.workspace.getActivePaneItem().buffer.file.path const index = filePath.lastIndexOf('.') const fileExtension = filePath.substring(index) const fileWithoutExt = filePath.substring(0,index) return (fileWithoutExt + testExtension + fileExtension) }, open() { const shouldCreate = atom.config.get('open-tests.shouldCreateFile') const testPath = getTestPath() if (!fs.existsSync(path) && !shouldCreate) { atom.notifications.addError('File not found') return } atom.open({ pathsToOpen: testPath }) } };
'use babel'; import { CompositeDisposable } from 'atom'; import fs from 'fs'; export default { modalPanel: null, subscriptions: null, config: { shouldCreateFile: { type: 'boolean', default: true, }, testExtension: { type: 'string', default: '.spec', }, }, activate(state) { this.subscriptions = new CompositeDisposable(); this.subscriptions.add(atom.commands.add('atom-workspace', { 'open-tests:open': () => this.open() })); }, deactivate() { this.subscriptions.dispose(); }, open() { const testExtension = atom.config.get('open-tests.testExtension') const shouldCreate = atom.config.get('open-tests.shouldCreateFile') const filePath = atom.workspace.getActivePaneItem().buffer.file.path const index = filePath.lastIndexOf('.') const fileExtension = filePath.substring(index) const fileWithoutExt = filePath.substring(0,index) const testPath = fileWithoutExt + testExtension + fileExtension if (!fs.existsSync(path) && !shouldCreate) { atom.notifications.addError('File not found') return } atom.open({ pathsToOpen: testPath }) } };
Fix IMPALA-122: Lzo scanner with small scan ranges. Change-Id: I5226fd1a1aa368f5b291b78ad371363057ef574e Reviewed-on: http://gerrit.ent.cloudera.com:8080/140 Reviewed-by: Skye Wanderman-Milne <6d4b168ab637b0a20cc9dbf96abb2537f372f946@cloudera.com> Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com> Tested-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # Validates running with different scan range length values # import pytest from copy import copy from tests.common.test_vector import TestDimension from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY # We use very small scan ranges to exercise corner cases in the HDFS scanner more # thoroughly. In particular, it will exercise: # 1. scan range with no tuple # 2. tuple that span across multiple scan ranges MAX_SCAN_RANGE_LENGTHS = [1, 2, 5] class TestScanRangeLengths(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestScanRangeLengths, cls).add_test_dimensions() cls.TestMatrix.add_dimension( TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS)) def test_scan_ranges(self, vector): if vector.get_value('table_format').file_format != 'text': pytest.xfail(reason='IMP-636') vector.get_value('exec_option')['max_scan_range_length'] =\ vector.get_value('max_scan_range_length') self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # Validates running with different scan range length values # import pytest from copy import copy from tests.common.test_vector import TestDimension from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY # We use very small scan ranges to exercise corner cases in the HDFS scanner more # thoroughly. In particular, it will exercise: # 1. scan range with no tuple # 2. tuple that span across multiple scan ranges MAX_SCAN_RANGE_LENGTHS = [1, 2, 5] class TestScanRangeLengths(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestScanRangeLengths, cls).add_test_dimensions() cls.TestMatrix.add_dimension( TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS)) def test_scan_ranges(self, vector): if vector.get_value('table_format').file_format != 'text': pytest.xfail(reason='IMP-636') elif vector.get_value('table_format').compression_codec != 'none': pytest.xfail(reason='IMPALA-122') vector.get_value('exec_option')['max_scan_range_length'] =\ vector.get_value('max_scan_range_length') self.run_test_case('QueryTest/hdfs-tiny-scan', vector)