text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Use irclib 0.4.6, which is available via pip
#!/usr/bin/env python # Require setuptools. See http://pypi.python.org/pypi/setuptools for # installation instructions, or run the ez_setup script found at # http://peak.telecommunity.com/dist/ez_setup.py from setuptools import setup, find_packages setup( name = "cobe", version = "2.0.0", author = "Peter Teichman", author_email = "[email protected]", url = "http://wiki.github.com/pteichman/cobe/", description = "A conversation simulator similar to MegaHAL", packages = ["cobe"], test_suite = "tests", setup_requires = [ "nose==1.1.2", "coverage==3.5" ], install_requires = [ "PyStemmer==1.2.0", "argparse==1.2.1", "python-irclib==0.4.6" ], classifiers = [ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Scientific/Engineering :: Artificial Intelligence" ], entry_points = { "console_scripts" : [ "cobe = cobe.control:main" ] } )
#!/usr/bin/env python # Require setuptools. See http://pypi.python.org/pypi/setuptools for # installation instructions, or run the ez_setup script found at # http://peak.telecommunity.com/dist/ez_setup.py from setuptools import setup, find_packages setup( name = "cobe", version = "2.0.0", author = "Peter Teichman", author_email = "[email protected]", url = "http://wiki.github.com/pteichman/cobe/", description = "A conversation simulator similar to MegaHAL", packages = ["cobe"], test_suite = "tests", setup_requires = [ "nose==1.1.2", "coverage==3.5" ], install_requires = [ "PyStemmer==1.2.0", "argparse==1.2.1", "python-irclib==0.4.8" ], classifiers = [ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Scientific/Engineering :: Artificial Intelligence" ], entry_points = { "console_scripts" : [ "cobe = cobe.control:main" ] } )
Set unit tests not depending on real profile file
<?php use Karma\Application; use Gaufrette\Adapter\InMemory; use Karma\Console; use Symfony\Component\Console\Tester\CommandTester; abstract class CommandTestCase extends PHPUnit_Framework_TestCase { protected $app, $commandTester; protected function setUp() { $masterContent = <<< CONFFILE [variables] foo: dev = value1 default = value2 bar: default = valueAll CONFFILE; $this->app = new Application(); $this->app['configuration.fileSystem.adapter'] = new InMemory(array( Application::DEFAULT_MASTER_FILE => $masterContent, )); $this->app['profile.fileSystem.adapter'] = function($c) { return new InMemory(); }; } protected function runCommand($commandName, array $commandArguments = array()) { $console = new Console($this->app); $command = $console ->getConsoleApplication() ->find($commandName); $this->commandTester = new CommandTester($command); $commandArguments = array_merge( array('command' => $command->getName()), $commandArguments ); $this->commandTester->execute($commandArguments); } protected function assertDisplay($regex) { $this->assertRegExp($regex, $this->commandTester->getDisplay()); } protected function assertNotDisplay($regex) { $this->assertNotRegExp($regex, $this->commandTester->getDisplay()); } }
<?php use Karma\Application; use Gaufrette\Adapter\InMemory; use Karma\Console; use Symfony\Component\Console\Tester\CommandTester; abstract class CommandTestCase extends PHPUnit_Framework_TestCase { protected $app, $commandTester; protected function setUp() { $masterContent = <<< CONFFILE [variables] foo: dev = value1 default = value2 bar: default = valueAll CONFFILE; $this->app = new Application(); $this->app['configuration.fileSystem.adapter'] = new InMemory(array( Application::DEFAULT_MASTER_FILE => $masterContent, )); } protected function runCommand($commandName, array $commandArguments = array()) { $console = new Console($this->app); $command = $console ->getConsoleApplication() ->find($commandName); $this->commandTester = new CommandTester($command); $commandArguments = array_merge( array('command' => $command->getName()), $commandArguments ); $this->commandTester->execute($commandArguments); } protected function assertDisplay($regex) { $this->assertRegExp($regex, $this->commandTester->getDisplay()); } protected function assertNotDisplay($regex) { $this->assertNotRegExp($regex, $this->commandTester->getDisplay()); } }
Use plum and shadow_plum from colors.xml
package mozilla.org.webmaker.activity; import android.app.ActionBar; import android.content.res.Resources; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.Menu; import android.view.Window; import android.view.WindowManager; import android.widget.RelativeLayout; import mozilla.org.webmaker.R; import mozilla.org.webmaker.WebmakerActivity; import mozilla.org.webmaker.view.WebmakerWebView; public class Tinker extends WebmakerActivity { public Tinker() { super("tinker", R.id.tinker_layout, R.layout.tinker_layout, R.menu.menu_tinker); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Custom styles Resources res = getResources(); int shadowPlum = res.getColor(R.color.shadow_plum); int plum = res.getColor(R.color.plum); ActionBar actionBar = getActionBar(); actionBar.setStackedBackgroundDrawable(plum); actionBar.setBackgroundDrawable(plum); Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.setStatusBarColor(shadowPlum); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } }
package mozilla.org.webmaker.activity; import android.app.ActionBar; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.Menu; import android.view.Window; import android.view.WindowManager; import android.widget.RelativeLayout; import mozilla.org.webmaker.R; import mozilla.org.webmaker.WebmakerActivity; import mozilla.org.webmaker.view.WebmakerWebView; public class Tinker extends WebmakerActivity { public Tinker() { super("tinker", R.id.tinker_layout, R.layout.tinker_layout, R.menu.menu_tinker); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Custom styles ActionBar actionBar = getActionBar(); ColorDrawable colorOne = new ColorDrawable(Color.parseColor("#ff303250")); ColorDrawable colorTwo = new ColorDrawable(Color.parseColor("#ff303250")); actionBar.setStackedBackgroundDrawable(colorOne); actionBar.setBackgroundDrawable(colorTwo); Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.setStatusBarColor(0xff282733); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } }
Replace 3rd and 4th panes
$(function() { "use strict"; window.AppConfig = { srcBase: 'https://graphite-phx.mozilla.org/render/?', globalGraphOptions: { hideLegend: false, from: '-24hour' }, defaultGraphs: { 'SUMOES': [ { target: ['stats.timers.sumo.view.search.views.search.GET.upper_90', 'stats.timers.sumo.view.search.views.search.GET.mean'], title: 'search view response' }, { target: ['stats.sumo.search.tasks.index_task.forums_thread', 'stats.sumo.search.tasks.index_task.wiki_document', 'stats.sumo.search.tasks.index_task.questions_question', 'stats.sumo.search.tasks.unindex_task.forums_thread', 'stats.sumo.search.tasks.unindex_task.wiki_document', 'stats.sumo.search.tasks.unindex_task.questions_question'], title: 'index and unindex counts' }, { target: ['sumSeries(stats.sumo.response.*)'], title: 'all responses' }, { target: ['stats.timers.sumo.view.landings.views.home.GET.mean'], title: 'home mean time' } ] } }; });
$(function() { "use strict"; window.AppConfig = { srcBase: 'https://graphite-phx.mozilla.org/render/?', globalGraphOptions: { hideLegend: false, from: '-24hour' }, defaultGraphs: { 'SUMOES': [ { target: ['stats.timers.sumo.view.search.views.search.GET.upper_90', 'stats.timers.sumo.view.search.views.search.GET.mean'], title: 'search view response' }, { target: ['stats.sumo.search.tasks.index_task.forums_thread', 'stats.sumo.search.tasks.index_task.wiki_document', 'stats.sumo.search.tasks.index_task.questions_question', 'stats.sumo.search.tasks.unindex_task.forums_thread', 'stats.sumo.search.tasks.unindex_task.wiki_document', 'stats.sumo.search.tasks.unindex_task.questions_question'], title: 'index and unindex counts' }, { target: ['stats.sumo.search.esunified.elasticsearchexception', 'stats.sumo.search.esunified.maxretryerror', 'stats.sumo.search.esunified.timeouterror'], title: 'ES errors' }, { target: ['sumSeries(stats.sumo.response.*)'], title: 'search view response' } ] } }; });
Fix integration tests on Mint 20
from . import * # MSBuild backend doesn't support generated_source yet. @skip_if_backend('msbuild') class TestQt(IntegrationTest): def run_executable(self, exe): if env.host_platform.genus == 'linux': output = self.assertPopen([exe], extra_env={'DISPLAY': ''}, returncode='fail') self.assertRegex(output, r'[Cc]ould not connect to display') def __init__(self, *args, **kwargs): env_vars = ({} if env.builder('c++').flavor == 'msvc' else {'CPPFLAGS': ('-Wno-inconsistent-missing-override ' + env.getvar('CPPFLAGS', ''))}) super().__init__(os.path.join(examples_dir, '13_qt'), *args, extra_env=env_vars, **kwargs) def test_designer(self): self.build(executable('qt-designer')) self.run_executable(executable('qt-designer')) def test_qml(self): self.build(executable('qt-qml')) self.run_executable(executable('qt-qml'))
from . import * # MSBuild backend doesn't support generated_source yet. @skip_if_backend('msbuild') class TestQt(IntegrationTest): def run_executable(self, exe): if env.host_platform.genus == 'linux': output = self.assertPopen([exe], extra_env={'DISPLAY': ''}, returncode='fail') self.assertRegex(output, r'QXcbConnection: Could not connect to display') def __init__(self, *args, **kwargs): env_vars = ({} if env.builder('c++').flavor == 'msvc' else {'CPPFLAGS': ('-Wno-inconsistent-missing-override ' + env.getvar('CPPFLAGS', ''))}) super().__init__(os.path.join(examples_dir, '13_qt'), *args, extra_env=env_vars, **kwargs) def test_designer(self): self.build(executable('qt-designer')) self.run_executable(executable('qt-designer')) def test_qml(self): self.build(executable('qt-qml')) self.run_executable(executable('qt-qml'))
Add some global variables. this will be handy when we change to production environment. just have to change a few variables.
angular.module('fleetonrails.services.login-service', []) .service('LoginService', ['$http', 'GlobalSettings', function ($http, GlobalSettings) { var loginWithPassword = function (email, password) { var params = { 'grant_type' : 'password', 'client_id' : GlobalSettings.api_client_id, 'client_secret' : GlobalSettings.api_client_secret, 'email' : email, 'password' : password }; return $http({ method : 'POST', url : GlobalSettings.api_base_url + '/oauth/token', params : params }) }; var loginWithRefreshToken = function () { var params = { 'grant_type' : 'refresh_token', 'client_id' : GlobalSettings.api_client_id, 'client_secret' : GlobalSettings.api_client_secret, 'refresh_token' : localStorage.getItem("refresh_token") }; return $http({ method : "POST", url : GlobalSettings.api_base_url + '/oauth/token', params : params }) }; var logout = function () { // TODO = implement a logout function } return { loginWithPassword : loginWithPassword, loginWithRefreshToken : loginWithRefreshToken, logout : logout }; }]);
angular.module('fleetonrails.services.login-service', []) .service('LoginService', ['$http', 'GlobalSettings', function ($http, GlobalSettings) { var loginWithPassword = function (email, password) { var params = { 'grant_type': 'password', 'client_id': GlobalSettings.api_client_id, 'client_secret': GlobalSettings.api_client_secret, 'email': email, 'password': password }; return $http({ method: 'POST', url: GlobalSettings.api_base_url + '/oauth/token', params: params }) }; var loginWithRefreshToken = function () { var params = { 'grant_type': 'refresh_token', 'client_id': '2abe8af97a1e45ee655b5f19d9fb4977990374c2a2895b4aaa6a9d80aa7edeeb', 'client_secret': '33d91b9efcea015b8acaff960ae49164c15da62ff895a253bbfd819b883ba5f6', 'refresh_token': localStorage.getItem("refresh_token") }; return $http({ method: "POST", url: GlobalSettings.api_base_url + '/oauth/token', params: params }) }; return { loginWithPassword: loginWithPassword, loginWithRefreshToken: loginWithRefreshToken }; }]);
Select search input on focus instead of click.
import React from 'react' import P from 'prop-types' export default class AppSearchInput extends React.Component { constructor(props) { super(props) this.state = {searchValue: null} } startTimeout() { this.clearTimeout() this.timeoutID = window.setTimeout(this.triggerLoad.bind(this), 400) } clearTimeout() { if (this.timeoutID) { window.clearTimeout(this.timeoutID) delete this.timeoutID } } triggerLoad() { const s = this.state.searchValue if (s !== null && s.length > 0) { this.props.onChange(this.state.searchValue) } } onInputChange(event, blah) { this.setState({searchValue: event.target.value}) this.startTimeout() } onInputFocus(event) { event.target.select() } onKeyPress(event) { if (event.key === 'Enter') { this.clearTimeout() this.triggerLoad() } } render() { return ( <input type="text" className="app-search-input" placeholder="Search" onChange={this.onInputChange.bind(this)} onKeyPress={this.onKeyPress.bind(this)} onFocus={this.onInputFocus} /> ) } } AppSearchInput.propTypes = { onChange: P.func.isRequired }
import React from 'react' import P from 'prop-types' export default class AppSearchInput extends React.Component { constructor(props) { super(props) this.state = {searchValue: null} } startTimeout() { this.clearTimeout() this.timeoutID = window.setTimeout(this.triggerLoad.bind(this), 400) } clearTimeout() { if (this.timeoutID) { window.clearTimeout(this.timeoutID) delete this.timeoutID } } triggerLoad() { const s = this.state.searchValue if (s !== null && s.length > 0) { this.props.onChange(this.state.searchValue) } } onInputChange(event, blah) { this.setState({searchValue: event.target.value}) this.startTimeout() } onInputClick(event) { event.target.select() } onKeyPress(event) { if (event.key === 'Enter') { this.clearTimeout() this.triggerLoad() } } render() { return ( <input type="text" className="app-search-input" placeholder="Search" onChange={this.onInputChange.bind(this)} onKeyPress={this.onKeyPress.bind(this)} onClick={this.onInputClick} /> ) } } AppSearchInput.propTypes = { onChange: P.func.isRequired }
Disable HTML entity encoding in some tests
<?php namespace Tests\Functional; use App\Models\User; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class NavigationTest extends \Tests\TestCase { use DatabaseMigrations; public function testGuestNavigation() { $this->get('/') ->assertSee('Log In') ->assertSee('href="/login"', false) ->assertDontSee('My List') ->assertDontSee('/list'); } public function testUserListNavigation() { $user = factory(User::class)->create(); $this->actingAs($user) ->get('/') ->assertSee('My List') ->assertSee('/list') ->assertDontSee('Login') ->assertDontSee('href="/login"', false); } public function testUserAccountNavigation() { $user = factory(User::class)->create(); $encodedUsername = htmlentities( $user->username, ENT_COMPAT | ENT_HTML401 | ENT_QUOTES ); $this->actingAs($user) ->get('/') ->assertSee($encodedUsername, false) ->assertSee('href="/account"', false); } public function testUserAccountLogOut() { $user = factory(User::class)->create(); $this->actingAs($user) ->get('/') ->assertSee('Log Out') ->assertSee('href="/logout"', false); } }
<?php namespace Tests\Functional; use App\Models\User; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class NavigationTest extends \Tests\TestCase { use DatabaseMigrations; public function testGuestNavigation() { $this->get('/') ->assertSee('Log In') ->assertSee('href="/login"', false) ->assertDontSee('My List') ->assertDontSee('/list'); } public function testUserListNavigation() { $user = factory(User::class)->create(); $this->actingAs($user) ->get('/') ->assertSee('My List') ->assertSee('/list') ->assertDontSee('Login') ->assertDontSee('href="/login"'); } public function testUserAccountNavigation() { $user = factory(User::class)->create(); $encodedUsername = htmlentities( $user->username, ENT_COMPAT | ENT_HTML401 | ENT_QUOTES ); $this->actingAs($user) ->get('/') ->assertSee($encodedUsername) ->assertSee('href="/account"', false); } public function testUserAccountLogOut() { $user = factory(User::class)->create(); $this->actingAs($user) ->get('/') ->assertSee('Log Out') ->assertSee('href="/logout"', false); } }
Remove site dependency from tagmeta; works cross-site now
from collections import OrderedDict import datetime import settings # Django from django import template from django.template import resolve_variable, NodeList from django.template.defaultfilters import stringfilter from django.contrib.auth.models import User, Group from django.utils.timesince import timesince # External from tagmeta.models import TagMeta register = template.Library() class TagMetaForTagNode(template.Node): def __init__(self, object, context_var): self.object = object self.context_var = context_var def render(self, context): try: object = template.resolve_variable(self.object, context) except template.VariableDoesNotExist: return '' try: context[self.context_var] = TagMeta.objects.get(tag=object) except: context[self.context_var] = None return '' def tagmeta_for_tag(parser, token): """ Example usage:: {% tagmeta_for_tag tag as tagmeta %} """ bits = token.contents.split() if len(bits) != 4: raise template.TemplateSyntaxError("'%s' tag takes exactly 4 arguments" % bits[0]) if bits[2] != 'as': raise template.TemplateSyntaxError("2nd argument to '%s' tag must be 'as'" % bits[0]) return TagMetaForTagNode(bits[1], bits[3]) register.tag('tagmeta_for_tag', tagmeta_for_tag)
from collections import OrderedDict import datetime import settings # Django from django import template from django.template import resolve_variable, NodeList from django.template.defaultfilters import stringfilter from django.contrib.auth.models import User, Group from django.utils.timesince import timesince # External from tagmeta.models import TagMeta register = template.Library() class TagMetaForTagNode(template.Node): def __init__(self, object, context_var): self.object = object self.context_var = context_var def render(self, context): try: object = template.resolve_variable(self.object, context) except template.VariableDoesNotExist: return '' try: context[self.context_var] = TagMeta.on_site.get(tag=object) except: context[self.context_var] = None return '' def tagmeta_for_tag(parser, token): """ Example usage:: {% tagmeta_for_tag tag as tagmeta %} """ bits = token.contents.split() if len(bits) != 4: raise template.TemplateSyntaxError("'%s' tag takes exactly 4 arguments" % bits[0]) if bits[2] != 'as': raise template.TemplateSyntaxError("2nd argument to '%s' tag must be 'as'" % bits[0]) return TagMetaForTagNode(bits[1], bits[3]) register.tag('tagmeta_for_tag', tagmeta_for_tag)
Fix typo in JSON property name.
package io.dropwizard.bundles.apikey; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Optional; import com.google.common.collect.Maps; import java.util.Map; import static com.google.common.base.Preconditions.checkNotNull; public class AuthConfiguration { private final String cacheSpec; private final String realm; private final Map<String, ApiKey> keys; @JsonCreator AuthConfiguration(@JsonProperty("cache-spec") String cacheSpec, @JsonProperty("realm") String realm, @JsonProperty("keys") Map<String, String> keys) { checkNotNull(cacheSpec); checkNotNull(realm); checkNotNull(keys); this.cacheSpec = cacheSpec; this.realm = realm; this.keys = Maps.transformEntries(keys, new Maps.EntryTransformer<String, String, ApiKey>() { @Override public ApiKey transformEntry(String key, String value) { return new ApiKey(key, value); } }); } /** * The configuration for how API keys should be cached. Can be missing. */ @JsonProperty("cache-spec") public Optional<String> getCacheSpec() { return Optional.fromNullable(cacheSpec); } /** * The realm to use. */ @JsonProperty("realm") public String getRealm() { return realm; } /** * Return the API keys that this application should support indexed by application. */ @JsonProperty("api-keys") public Map<String, ApiKey> getApiKeys() { return keys; } }
package io.dropwizard.bundles.apikey; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Optional; import com.google.common.collect.Maps; import java.util.Map; import static com.google.common.base.Preconditions.checkNotNull; public class AuthConfiguration { private final String cacheSpec; private final String realm; private final Map<String, ApiKey> keys; @JsonCreator AuthConfiguration(@JsonProperty("cacheSpec") String cacheSpec, @JsonProperty("realm") String realm, @JsonProperty("keys") Map<String, String> keys) { checkNotNull(cacheSpec); checkNotNull(realm); checkNotNull(keys); this.cacheSpec = cacheSpec; this.realm = realm; this.keys = Maps.transformEntries(keys, new Maps.EntryTransformer<String, String, ApiKey>() { @Override public ApiKey transformEntry(String key, String value) { return new ApiKey(key, value); } }); } /** * The configuration for how API keys should be cached. Can be missing. */ @JsonProperty("cache-spec") public Optional<String> getCacheSpec() { return Optional.fromNullable(cacheSpec); } /** * The realm to use. */ @JsonProperty("realm") public String getRealm() { return realm; } /** * Return the API keys that this application should support indexed by application. */ @JsonProperty("api-keys") public Map<String, ApiKey> getApiKeys() { return keys; } }
Update to turn down logging level of UUID Maven plugin
package info.freelibrary.maven; import java.util.UUID; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Mojo(name = "set-uuid-property", defaultPhase = LifecyclePhase.VALIDATE) public class UUIDGeneratingMojo extends AbstractMojo { private static final Logger LOGGER = LoggerFactory.getLogger(UUIDGeneratingMojo.class); /** * The Maven project directory. */ @Parameter(defaultValue = "${project}") protected MavenProject myProject; /** * An optional String value from which to construct the UUID. */ @Parameter(alias = "string") private String myString; /** * An optional build property name for the requested UUID. */ @Parameter(alias = "name", defaultValue = "uuid") private String myName; @Override public void execute() throws MojoExecutionException, MojoFailureException { final String uuid = myString == null ? UUID.randomUUID().toString() : UUID.fromString(myString).toString(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Setting a UUID property ({} = {}) for use in the Maven build", myName, uuid); } myProject.getProperties().setProperty(myName, uuid); } }
package info.freelibrary.maven; import java.util.UUID; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Mojo(name = "set-uuid-property", defaultPhase = LifecyclePhase.VALIDATE) public class UUIDGeneratingMojo extends AbstractMojo { private static final Logger LOGGER = LoggerFactory.getLogger(UUIDGeneratingMojo.class); /** * The Maven project directory. */ @Parameter(defaultValue = "${project}") protected MavenProject myProject; /** * An optional String value from which to construct the UUID. */ @Parameter(alias = "string") private String myString; /** * An optional build property name for the requested UUID. */ @Parameter(alias = "name", defaultValue = "uuid") private String myName; @Override public void execute() throws MojoExecutionException, MojoFailureException { final String uuid = myString == null ? UUID.randomUUID().toString() : UUID.fromString(myString).toString(); if (LOGGER.isInfoEnabled()) { LOGGER.info("Setting a UUID property ({} = {}) for use in the Maven build", myName, uuid); } myProject.getProperties().setProperty(myName, uuid); } }
Make sure the application doesn't continue without a config
import os from twisted.internet import reactor from heufybot import HeufyBot, HeufyBotFactory from config import Config class BotHandler(object): factories = {} globalConfig = None def __init__(self): print "--- Loading configs..." self.globalConfig = Config("globalconfig.yml") if not self.globalConfig.loadConfig(None): return configList = self.getConfigList() if len(configList) == 0: print "WARNING: No server configs found. Using the global config instead." else: for filename in self.getConfigList(): config = Config(filename, globalConfig.settings) def getConfigList(self): root = os.path.join("config") configs = [] for item in os.listdir(root): if not os.path.isfile(os.path.join(root, item)): continue if not item.endswith(".yml"): continue if item == "globalconfig.yml": continue configs.append(item) return configs if __name__ == "__main__": # Create folders if not os.path.exists(os.path.join("config")): os.makedirs("config") handler = BotHandler()
import os from twisted.internet import reactor from heufybot import HeufyBot, HeufyBotFactory from config import Config class BotHandler(object): factories = {} globalConfig = None def __init__(self): print "--- Loading configs..." self.globalConfig = Config("globalconfig.yml") self.globalConfig.loadConfig(None) configList = self.getConfigList() if len(configList) == 0: print "WARNING: No server configs found. Using the global config instead." else: for filename in self.getConfigList(): config = Config(filename, globalConfig.settings) def getConfigList(self): root = os.path.join("config") configs = [] for item in os.listdir(root): if not os.path.isfile(os.path.join(root, item)): continue if not item.endswith(".yml"): continue if item == "globalconfig.yml": continue configs.append(item) return configs if __name__ == "__main__": # Create folders if not os.path.exists(os.path.join("config")): os.makedirs("config") handler = BotHandler()
Fix the name on the package from brew to brewday
from setuptools import find_packages from setuptools import setup setup( name='brewday', version='0.0.1', author='Chris Gilmer', author_email='[email protected]', maintainer='Chris Gilmer', maintainer_email='[email protected]', description='Brew Day Tools', url='https://github.com/chrisgilmerproj/brewday', packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), scripts=['bin/abv', 'bin/sugar', 'bin/temp', 'bin/yeast'], include_package_data=True, zip_safe=True, tests_require=[ 'nose==1.3.1', 'pluggy==0.3.1', 'py==1.4.31', 'tox==2.3.1', ], classifiers=( "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "Intended Audience :: Other Audience", "License :: OSI Approved :: GNU General Public License (GPL)", "Operating System :: OS Independent", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", ), )
from setuptools import find_packages from setuptools import setup setup( name='brew', version='0.0.1', author='Chris Gilmer', author_email='[email protected]', maintainer='Chris Gilmer', maintainer_email='[email protected]', description='Brew Day Tools', url='https://github.com/chrisgilmerproj/brewday', packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), scripts=['bin/abv', 'bin/sugar', 'bin/temp', 'bin/yeast'], include_package_data=True, zip_safe=True, tests_require=[ 'nose==1.3.1', 'pluggy==0.3.1', 'py==1.4.31', 'tox==2.3.1', ], classifiers=( "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "Intended Audience :: Other Audience", "License :: OSI Approved :: GNU General Public License (GPL)", "Operating System :: OS Independent", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", ), )
Use updated corner plot API
import numpy as np import corner import astropy.io.ascii as ascii import matplotlib.pyplot as plt pyout = ascii.read('test.pyout') idlout = ascii.read('test.idlout') fig, axarr = plt.subplots(9, 9, figsize=(10, 10)) fig.suptitle("Black = python, red = IDL") corner.corner(np.array([pyout['alpha'], pyout['beta'], pyout['sigsqr'], pyout['mu0'], pyout['usqr'], pyout['wsqr'], pyout['ximean'], pyout['xisig'], pyout['corr']]).T, labels=[r"$\alpha$", r"$\beta$", r"$\sigma^2$", r"$\mu_0$", r"$u^2$", r"$w^2$", r"$\bar{\xi}$", r"$\sigma_\xi$", r"$\rho_{\xi\eta}$"], range=[0.99]*9, plot_datapoints=False, fig=fig) corner.corner(np.array([idlout['alpha'], idlout['beta'], idlout['sigsqr'], idlout['mu00'], idlout['usqr'], idlout['wsqr'], idlout['ximean'], idlout['xisig'], idlout['corr']]).T, range=[0.99]*9, plot_datapoints=False, fig=fig, color='r') fig.subplots_adjust(bottom=0.065, left=0.07) plt.show()
import numpy as np import triangle import astropy.io.ascii as ascii import matplotlib.pyplot as plt pyout = ascii.read('test.pyout') idlout = ascii.read('test.idlout') fig, axarr = plt.subplots(9, 9, figsize=(10, 10)) fig.suptitle("Black = python, red = IDL") triangle.corner(np.array([pyout['alpha'], pyout['beta'], pyout['sigsqr'], pyout['mu0'], pyout['usqr'], pyout['wsqr'], pyout['ximean'], pyout['xisig'], pyout['corr']]).T, labels=[r"$\alpha$", r"$\beta$", r"$\sigma^2$", r"$\mu_0$", r"$u^2$", r"$w^2$", r"$\bar{\xi}$", r"$\sigma_\xi$", r"$\rho_{\xi\eta}$"], extents=[0.99]*9, plot_datapoints=False, fig=fig) triangle.corner(np.array([idlout['alpha'], idlout['beta'], idlout['sigsqr'], idlout['mu00'], idlout['usqr'], idlout['wsqr'], idlout['ximean'], idlout['xisig'], idlout['corr']]).T, extents=[0.99]*9, plot_datapoints=False, fig=fig, color='r') fig.subplots_adjust(bottom=0.065, left=0.07) plt.show()
Change the command name of grunt to build
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-typescript'); grunt.loadNpmTasks('grunt-mocha-phantomjs'); grunt.initConfig({ typescript: { main: { src: ['src/mml2miku.ts'], dest: 'js/mml2miku.js', options: { comments: true, // target: 'es5', } }, test: { src: ['tests/testmml2miku.ts'], // dest: 'tests/testmml2miku.js', options: { module: 'commonjs', comments: true, // target: 'es5', } } }, mocha_phantomjs: { all: ['test.html'] } }); grunt.registerTask('build', ['typescript']); grunt.registerTask('test', ['mocha_phantomjs']); };
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-typescript'); grunt.loadNpmTasks('grunt-mocha-phantomjs'); grunt.initConfig({ typescript: { main: { src: ['src/mml2miku.ts'], dest: 'js/mml2miku.js', options: { comments: true, // target: 'es5', } }, test: { src: ['tests/testmml2miku.ts'], // dest: 'tests/testmml2miku.js', options: { module: 'commonjs', comments: true, // target: 'es5', } } }, mocha_phantomjs: { all: ['test.html'] } }); grunt.registerTask('compile', ['typescript']); grunt.registerTask('test', ['mocha_phantomjs']); };
Fix a :bug: due to changes in ipcActions from previosly
import React, {Component, PropTypes} from 'react'; import styles from './DatabaseDropdown.css'; import Select from 'react-select'; /* Displays in a dropdown menu all available databases/schemes using `ipc`. Permits to alter the `configuration` database parameter once user selects an option. Sends a preset query to show all tables within a database/ scheme that was chosen in the dropdown using `ipcActions`. */ export default class DatabaseDropdown extends Component { constructor(props) { super(props); } render() { const {configuration, ipc, ipcActions, merge} = this.props; const ipcDatabases = ipc.get('databases'); let databaseDropdownOptions; if (ipcDatabases) { databaseDropdownOptions = ipcDatabases.toJS().map(database => ( {value: database.Database, label: database.Database} )); } else { databaseDropdownOptions = [ {value: 'None', label: 'None Found', disabled: true} ]; } function onSelectDatabase(database) { merge({database: database.value}); ipcActions.selectDatabase(); } return ( <div className={styles.dropdown}> <Select name="form-field-name" placeholder="Select Your Database" options={databaseDropdownOptions} onChange={onSelectDatabase} value={configuration.get('database')} resetValue="null" matchPos="start" /> </div> ); } }
import React, {Component, PropTypes} from 'react'; import styles from './DatabaseDropdown.css'; import Select from 'react-select'; /* Displays in a dropdown menu all available databases/schemes using `ipc`. Permits to alter the `configuration` database parameter once user selects an option. Sends a preset query to show all tables within a database/ scheme that was chosen in the dropdown using `ipcActions`. */ export default class DatabaseDropdown extends Component { constructor(props) { super(props); } render() { const {configuration, ipc, ipcActions, merge} = this.props; const ipcDatabases = ipc.get('databases'); let databaseDropdownOptions; if (ipcDatabases) { databaseDropdownOptions = ipcDatabases.toJS().map(database => ( {value: database.Database, label: database.Database} )); } else { databaseDropdownOptions = [ {value: 'None', label: 'None Found', disabled: true} ]; } function onSelectDatabase(database) { merge({database: database.value}); ipcActions.useDatabase(); } return ( <div className={styles.dropdown}> <Select name="form-field-name" placeholder="Select Your Database" options={databaseDropdownOptions} onValueClick={onSelectDatabase} value={configuration.get('database')} resetValue="null" matchPos="start" /> </div> ); } }
Add preventDefault on clicks on the 'edit' button next to the theme toggle in the page action popup. Without it, clicking edit actually toggles whether or not the theme is enabled which is incorrect.
// Adds toggle for custom theme to Page Action. // // This file *only* controls that toggle, // the logic behind enabling/disabling the theme is found in // core/js/customThemeHandler.js var customThemeToggle = (function(){ var optionsLink = document.getElementById("options-link"); var enableTheme = document.getElementById("enable-theme"); chrome.storage.local.get("cmCustomThemeEnabled", function(response){ var themeIsEnabled = !!response.cmCustomThemeEnabled; enableTheme.checked = themeIsEnabled; setEventListeners(); }); function setEventListeners() { optionsLink.addEventListener("click", function(e){ // needed to prevent the click from propagating to the checkbox e.preventDefault(); //http://stackoverflow.com/a/16130739 var optionsUrl = chrome.extension.getURL('core/html/ces_options.html'); chrome.tabs.query({url: optionsUrl}, function(tabs) { if (tabs.length) { chrome.tabs.update(tabs[0].id, {active: true}); } else { chrome.tabs.create({url: optionsUrl}); } }); }); enableTheme.addEventListener("click", function(){ if (enableTheme.checked) { chrome.storage.local.set({"cmCustomThemeEnabled": true}, function(){ sendToActiveTab({method:"enable-custom-theme"}); }) } else { chrome.storage.local.set({"cmCustomThemeEnabled": false}, function(){ sendToActiveTab({method:"disable-custom-theme"}); }) } }); } })();
// Adds toggle for custom theme to Page Action. // // This file *only* controls that toggle, // the logic behind enabling/disabling the theme is found in // core/js/customThemeHandler.js var customThemeToggle = (function(){ var optionsLink = document.getElementById("options-link"); var enableTheme = document.getElementById("enable-theme"); chrome.storage.local.get("cmCustomThemeEnabled", function(response){ var themeIsEnabled = !!response.cmCustomThemeEnabled; enableTheme.checked = themeIsEnabled; setEventListeners(); }); function setEventListeners() { optionsLink.addEventListener("click", function(){ //http://stackoverflow.com/a/16130739 var optionsUrl = chrome.extension.getURL('core/html/ces_options.html'); chrome.tabs.query({url: optionsUrl}, function(tabs) { if (tabs.length) { chrome.tabs.update(tabs[0].id, {active: true}); } else { chrome.tabs.create({url: optionsUrl}); } }); }); enableTheme.addEventListener("click", function(){ if (enableTheme.checked) { chrome.storage.local.set({"cmCustomThemeEnabled": true}, function(){ sendToActiveTab({method:"enable-custom-theme"}); }) } else { chrome.storage.local.set({"cmCustomThemeEnabled": false}, function(){ sendToActiveTab({method:"disable-custom-theme"}); }) } }); } })();
Remove 'u' prefix from strings
import json import unittest import awacs.aws as aws import awacs.s3 as s3 class TestConditions(unittest.TestCase): def test_for_all_values(self): c = aws.Condition( aws.ForAllValuesStringLike( "dynamodb:requestedAttributes", ["PostDateTime", "Message", "Tags"] ) ) pd = aws.PolicyDocument( Statement=[ aws.Statement( Action=[s3.ListBucket], Effect=aws.Allow, Resource=[s3.ARN("myBucket")], Condition=c, ) ] ) self.assertEqual( { "Statement": [ { "Action": ["s3:ListBucket"], "Condition": { "ForAllValues:StringLike": { "dynamodb:requestedAttributes": [ "PostDateTime", "Message", "Tags", ] } }, "Effect": "Allow", "Resource": ["arn:aws:s3:::myBucket"], } ] }, json.loads(pd.to_json()), )
import json import unittest import awacs.aws as aws import awacs.s3 as s3 class TestConditions(unittest.TestCase): def test_for_all_values(self): c = aws.Condition( aws.ForAllValuesStringLike( "dynamodb:requestedAttributes", ["PostDateTime", "Message", "Tags"] ) ) pd = aws.PolicyDocument( Statement=[ aws.Statement( Action=[s3.ListBucket], Effect=aws.Allow, Resource=[s3.ARN("myBucket")], Condition=c, ) ] ) self.assertEqual( { u"Statement": [ { u"Action": [u"s3:ListBucket"], u"Condition": { u"ForAllValues:StringLike": { u"dynamodb:requestedAttributes": [ u"PostDateTime", u"Message", u"Tags", ] } }, u"Effect": u"Allow", u"Resource": [u"arn:aws:s3:::myBucket"], } ] }, json.loads(pd.to_json()), )
Add retry for opening RabbitMQ connection (cluster start)
import json import pika import time from twython import TwythonStreamer class TwitterConfiguration: def __init__(self): with open('twitter_key.json') as jsonData: data = json.load(jsonData) self.consumer_key = data['consumer_key'] self.consumer_secret = data['consumer_secret'] self.access_token = data['access_token'] self.access_token_secret = data['access_token_secret'] class MyStreamer(TwythonStreamer): def __init__(self, twitter_configuration): super().__init__(twitter_configuration.consumer_key, twitter_configuration.consumer_secret, twitter_configuration.access_token, twitter_configuration.access_token_secret) def on_success(self, data): if 'text' in data: output_data = { 'text': data['text'] } serialized_data = json.dumps(output_data) print(serialized_data) def on_error(self, status_code, data): print(status_code) pika_connection = None while pika_connection == None: try: pika_connection = pika.BlockingConnection(pika.ConnectionParameters('rabbitmq')) except pika.exceptions.ConnectionClosed: print("RabbitMQ connection still closed. Retrying.") time.sleep(5) pika_channel = pika_connection.channel() pika_channel.queue_declare(queue='tweets') configuration = TwitterConfiguration() while True: try: stream = MyStreamer(configuration) stream.statuses.filter(track='trump,clinton') except: print("Unexpected error: ", sys.exc_info()[0])
import json import pika from twython import TwythonStreamer class TwitterConfiguration: def __init__(self): with open('twitter_key.json') as jsonData: data = json.load(jsonData) self.consumer_key = data['consumer_key'] self.consumer_secret = data['consumer_secret'] self.access_token = data['access_token'] self.access_token_secret = data['access_token_secret'] class MyStreamer(TwythonStreamer): def __init__(self, twitter_configuration): super().__init__(twitter_configuration.consumer_key, twitter_configuration.consumer_secret, twitter_configuration.access_token, twitter_configuration.access_token_secret) def on_success(self, data): if 'text' in data: output_data = { 'text': data['text'] } serialized_data = json.dumps(output_data) print(serialized_data) def on_error(self, status_code, data): print(status_code) pika_connection = pika.BlockingConnection(pika.ConnectionParameters('rabbitmq')) pika_channel = pika_connection.channel() pika_channel.queue_declare(queue='tweets') configuration = TwitterConfiguration() while True: try: stream = MyStreamer(configuration) stream.statuses.filter(track='trump,clinton') except: print("Unexpected error: ", sys.exc_info()[0])
Use Type::hasType to check for existing type
<?php namespace Ident\Test\Doctrine; use Doctrine\DBAL\Types\Type; /** * Class AbstractUuidTypeTest */ abstract class AbstractUuidTypeTest extends \PHPUnit_Framework_TestCase { /** * @var mixed */ private $signature; /** * @var \Ident\IdentifiesObjects */ private $identifier; private $platform; /** * @var \Doctrine\DBAL\Types\Type */ private $type; abstract public function instanceProvider(); /** * {@inheritdoc} */ protected function setUp() { list($typeClass, $idClass, $this->signature) = $this->instanceProvider(); $this->identifier = $idClass::fromSignature($this->signature); $typeName = constant($typeClass . '::NAME'); if (!Type::hasType($typeName)) { Type::addType($typeName, $typeClass); } $this->type = Type::getType($typeName); $this->platform = $this->getMockBuilder('Doctrine\DBAL\Platforms\AbstractPlatform') ->disableOriginalConstructor() ->getMockForAbstractClass(); } /** * @test */ public function shouldGenerateFromIdentifier() { $signature = $this->type->convertToDatabaseValue($this->identifier, $this->platform); $this->assertEquals($this->signature, $signature); } /** * @test */ public function shouldGenerateFromSignature() { $identifier = $this->type->convertToPHPValue($this->signature, $this->platform); $this->assertEquals($this->identifier, $identifier); } }
<?php namespace Ident\Test\Doctrine; use Doctrine\DBAL\Types\Type; /** * Class AbstractUuidTypeTest */ abstract class AbstractUuidTypeTest extends \PHPUnit_Framework_TestCase { /** * @var mixed */ private $signature; /** * @var \Ident\IdentifiesObjects */ private $identifier; private $platform; /** * @var \Doctrine\DBAL\Types\Type */ private $type; abstract public function instanceProvider(); /** * {@inheritdoc} */ protected function setUp() { list($typeClass, $idClass, $this->signature) = $this->instanceProvider(); $this->identifier = $idClass::fromSignature($this->signature); $typeName = constant($typeClass . '::NAME'); try { Type::getType($typeName); } catch (\Exception $e) { Type::addType($typeName, $typeClass); } $this->type = Type::getType($typeName); $this->platform = $this->getMockBuilder('Doctrine\DBAL\Platforms\AbstractPlatform') ->disableOriginalConstructor() ->getMockForAbstractClass(); } /** * @test */ public function shouldGenerateFromIdentifier() { $signature = $this->type->convertToDatabaseValue($this->identifier, $this->platform); $this->assertEquals($this->signature, $signature); } /** * @test */ public function shouldGenerateFromSignature() { $identifier = $this->type->convertToPHPValue($this->signature, $this->platform); $this->assertEquals($this->identifier, $identifier); } }
Fix a bug where scheme with uppercase is not handled
<?php namespace HomoChecker\Model; use TrueBV\Punycode; class Status { public function __construct(HomoInterface $homo, string $icon = null, string $status = null, float $duration = null) { $this->homo = (object)[ 'screen_name' => $homo->screen_name, 'url' => $homo->url, 'display_url' => $this->createDisplayURL($homo->url), 'secure' => $this->isSecure($homo->url), ]; if (isset($icon)) { $this->homo->icon = $icon; } if (isset($status)) { $this->status = $status; } if (isset($duration)) { $this->duration = $duration; } } protected function createDisplayURL(string $url): string { $domain = parse_url($url, PHP_URL_HOST); if (!is_string($domain)) { return ''; } $path = (string)parse_url($url, PHP_URL_PATH); return (new Punycode)->decode($domain) . $path; } protected function isSecure(string $url): bool { return strtolower(parse_url($url, PHP_URL_SCHEME)) === 'https'; } }
<?php namespace HomoChecker\Model; use TrueBV\Punycode; class Status { public function __construct(HomoInterface $homo, string $icon = null, string $status = null, float $duration = null) { $this->homo = (object)[ 'screen_name' => $homo->screen_name, 'url' => $homo->url, 'display_url' => $this->createDisplayURL($homo->url), 'secure' => $this->isSecure($homo->url), ]; if (isset($icon)) { $this->homo->icon = $icon; } if (isset($status)) { $this->status = $status; } if (isset($duration)) { $this->duration = $duration; } } protected function createDisplayURL(string $url): string { $domain = parse_url($url, PHP_URL_HOST); if (!is_string($domain)) { return ''; } $path = (string)parse_url($url, PHP_URL_PATH); return (new Punycode)->decode($domain) . $path; } protected function isSecure(string $url): bool { return parse_url($url, PHP_URL_SCHEME) === 'https'; } }
Rename a variable in Matcher.__repr__() to make the code less confusing. Even though there is technically no name clash, the code is now less confusing.
# # Project: retdec-python # Copyright: (c) 2015 by Petr Zemek <[email protected]> and contributors # License: MIT, see the LICENSE file for more details # """Tests for the library and tools.""" import abc class Matcher(metaclass=abc.ABCMeta): """A base class of all matchers.""" @abc.abstractmethod def __eq__(self, other): raise NotImplementedError def __ne__(self, other): return not self == other def __repr__(self): name = self.__class__.__qualname__ attr_list = ', '.join( '{}={!r}'.format(key, value) for key, value in self.__dict__.items() ) return '{}({})'.format(name, attr_list) class Anything(Matcher): """A matcher that matches anything.""" def __eq__(self, other): return True class AnyDictWith(Matcher): """A matcher that matches and ``dict`` with the given keys and values. The ``dict`` may also have other keys and values, which are not considered during the matching. """ def __init__(self, **kwargs): self.__dict__ = kwargs def __eq__(self, other): if not isinstance(other, dict): return False for name, value in self.__dict__.items(): if name not in other or other[name] != value: return False return True
# # Project: retdec-python # Copyright: (c) 2015 by Petr Zemek <[email protected]> and contributors # License: MIT, see the LICENSE file for more details # """Tests for the library and tools.""" import abc class Matcher(metaclass=abc.ABCMeta): """A base class of all matchers.""" @abc.abstractmethod def __eq__(self, other): raise NotImplementedError def __ne__(self, other): return not self == other def __repr__(self): name = self.__class__.__qualname__ attr_list = ', '.join( '{}={!r}'.format(name, value) for name, value in self.__dict__.items() ) return '{}({})'.format(name, attr_list) class Anything(Matcher): """A matcher that matches anything.""" def __eq__(self, other): return True class AnyDictWith(Matcher): """A matcher that matches and ``dict`` with the given keys and values. The ``dict`` may also have other keys and values, which are not considered during the matching. """ def __init__(self, **kwargs): self.__dict__ = kwargs def __eq__(self, other): if not isinstance(other, dict): return False for name, value in self.__dict__.items(): if name not in other or other[name] != value: return False return True
Revert "adding 2013 to search query"
from haystack import indexes from respondants.models import Institution class InstitutionIndex(indexes.SearchIndex, indexes.Indexable): """Search Index associated with an institution. Allows for searching by name or lender id""" text = indexes.CharField(document=True, model_attr='name') text_auto = indexes.EdgeNgramField(model_attr='name') lender_id = indexes.CharField() assets = indexes.IntegerField(model_attr='assets') num_loans = indexes.IntegerField(model_attr='num_loans') def get_model(self): return Institution def index_queryset(self, using=None): """To account for the somewhat complicated count query, we need to add an "extra" annotation""" subquery_tail = """ FROM hmda_hmdarecord WHERE hmda_hmdarecord.lender = CAST(respondants_institution.agency_id AS VARCHAR(1)) || respondants_institution.ffiec_id""" return self.get_model().objects.extra( select={"num_loans": "SELECT COUNT(*) " + subquery_tail}, where=["SELECT COUNT(*) > 0 " + subquery_tail]) def read_queryset(self, using=None): """A more efficient query than the index query -- makes use of select related and does not include the num_loans calculation.""" return self.get_model().objects.select_related('zip_code', 'agency') def prepare_lender_id(self, institution): return str(institution.agency_id) + institution.ffiec_id
from haystack import indexes from respondants.models import Institution class InstitutionIndex(indexes.SearchIndex, indexes.Indexable): """Search Index associated with an institution. Allows for searching by name or lender id""" text = indexes.CharField(document=True, model_attr='name') text_auto = indexes.EdgeNgramField(model_attr='name') lender_id = indexes.CharField() assets = indexes.IntegerField(model_attr='assets') num_loans = indexes.IntegerField(model_attr='num_loans') def get_model(self): return Institution def index_queryset(self, using=None): """To account for the somewhat complicated count query, we need to add an "extra" annotation""" subquery_tail = """ FROM hmda_hmdarecord WHERE year = 2013 AND hmda_hmdarecord.lender = CAST(respondants_institution.agency_id AS VARCHAR(1)) || respondants_institution.ffiec_id""" return self.get_model().objects.extra( select={"num_loans": "SELECT COUNT(*) " + subquery_tail}, where=["SELECT COUNT(*) > 0 " + subquery_tail]) def read_queryset(self, using=None): """A more efficient query than the index query -- makes use of select related and does not include the num_loans calculation.""" return self.get_model().objects.select_related('zip_code', 'agency') def prepare_lender_id(self, institution): return str(institution.agency_id) + institution.ffiec_id
Fix missing semi-colon bug in javascript file
import 'jquery-ui-dist/jquery-ui'; $(() => { // Is there already one prefix section on this Phase? // // draggableSections - A jQuery object, the sortable element. // // Returns Boolean function prefixSectionExists(draggableSections) { return !!draggableSections .has('[data-modifiable=true]:nth-child(1)').length && !!draggableSections.has('[data-modifiable=true]:nth-child(2)').length; } // Initialize the draggable-sections element as a jQuery sortable. // Read the docs here for more info: http://api.jqueryui.com/sortable/ $('.draggable-sections').sortable({ handle: 'i.fa-bars', axis: 'y', cursor: 'move', beforeStop() { if (prefixSectionExists($(this))) { // Prevent the sort action from completing. Moves element back to source $(this).sortable('cancel'); // Display a wobble effec to signify error $(this).effect('shake'); } }, update() { // Collect the section-id from each section element on the page. const sectionIds = $('.section[data-section-id]') .map((i, element) => $(element).data('section-id')).toArray(); // Post the section IDs to the server in their new order on the page. $.rails.ajax({ url: $(this).data('url'), method: 'post', data: { sort_order: sectionIds }, }); }, }); });
import 'jquery-ui-dist/jquery-ui'; $(() => { // Is there already one prefix section on this Phase? // // draggableSections - A jQuery object, the sortable element. // // Returns Boolean function prefixSectionExists(draggableSections) { return !!draggableSections .has('[data-modifiable=true]:nth-child(1)').length && !!draggableSections.has('[data-modifiable=true]:nth-child(2)').length } // Initialize the draggable-sections element as a jQuery sortable. // Read the docs here for more info: http://api.jqueryui.com/sortable/ $('.draggable-sections').sortable({ handle: 'i.fa-bars', axis: 'y', cursor: 'move', beforeStop() { if (prefixSectionExists($(this))) { // Prevent the sort action from completing. Moves element back to source $(this).sortable('cancel'); // Display a wobble effec to signify error $(this).effect('shake'); } }, update() { // Collect the section-id from each section element on the page. const sectionIds = $('.section[data-section-id]') .map((i, element) => $(element).data('section-id')).toArray(); // Post the section IDs to the server in their new order on the page. $.rails.ajax({ url: $(this).data('url'), method: 'post', data: { sort_order: sectionIds }, }); }, }); });
Add finals to TestMethidFilter properties
package fi.vincit.multiusertest.util; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import org.junit.runners.model.FrameworkMethod; import fi.vincit.multiusertest.annotation.TestUsers; public class TestMethodFilter { private final UserIdentifier creatorIdentifier; private final UserIdentifier userIdentifier; public TestMethodFilter(UserIdentifier creatorIdentifier, UserIdentifier userIdentifier) { Objects.requireNonNull(creatorIdentifier); Objects.requireNonNull(userIdentifier); this.creatorIdentifier = creatorIdentifier; this.userIdentifier = userIdentifier; } public boolean shouldRun(FrameworkMethod frameworkMethod) { TestConfiguration configuration = TestConfiguration.fromTestUsers(frameworkMethod.getAnnotation(TestUsers.class)); Collection<UserIdentifier> creators = configuration.getCreatorIdentifiers(); Collection<UserIdentifier> users = configuration.getUserIdentifiers(); boolean shouldRun = true; if (!creators.isEmpty()) { shouldRun = creators.contains(creatorIdentifier); } if (!users.isEmpty()) { shouldRun = shouldRun && users.contains(userIdentifier); } return shouldRun; } public List<FrameworkMethod> filter(List<FrameworkMethod> methods) { List<FrameworkMethod> methodsToRun = new ArrayList<>(); for (FrameworkMethod frameworkMethod : methods) { if (shouldRun(frameworkMethod)) { methodsToRun.add(frameworkMethod); } } return methodsToRun; } }
package fi.vincit.multiusertest.util; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import org.junit.runners.model.FrameworkMethod; import fi.vincit.multiusertest.annotation.TestUsers; public class TestMethodFilter { private UserIdentifier creatorIdentifier; private UserIdentifier userIdentifier; public TestMethodFilter(UserIdentifier creatorIdentifier, UserIdentifier userIdentifier) { Objects.requireNonNull(creatorIdentifier); Objects.requireNonNull(userIdentifier); this.creatorIdentifier = creatorIdentifier; this.userIdentifier = userIdentifier; } public boolean shouldRun(FrameworkMethod frameworkMethod) { TestConfiguration configuration = TestConfiguration.fromTestUsers(frameworkMethod.getAnnotation(TestUsers.class)); Collection<UserIdentifier> creators = configuration.getCreatorIdentifiers(); Collection<UserIdentifier> users = configuration.getUserIdentifiers(); boolean shouldRun = true; if (!creators.isEmpty()) { shouldRun = creators.contains(creatorIdentifier); } if (!users.isEmpty()) { shouldRun = shouldRun && users.contains(userIdentifier); } return shouldRun; } public List<FrameworkMethod> filter(List<FrameworkMethod> methods) { List<FrameworkMethod> methodsToRun = new ArrayList<>(); for (FrameworkMethod frameworkMethod : methods) { if (shouldRun(frameworkMethod)) { methodsToRun.add(frameworkMethod); } } return methodsToRun; } }
Fix missing up button on settings page
package com.marverenic.music.ui.settings; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v7.app.ActionBar; import com.marverenic.music.R; import com.marverenic.music.ui.BaseActivity; public class SettingsActivity extends BaseActivity { public static Intent newIntent(Context context) { return new Intent(context, SettingsActivity.class); } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); setSupportActionBar(findViewById(R.id.toolbar)); ActionBar toolbar = getSupportActionBar(); toolbar.setDisplayShowHomeEnabled(true); toolbar.setDisplayHomeAsUpEnabled(true); toolbar.setHomeButtonEnabled(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { toolbar.setElevation(getResources().getDimension(R.dimen.header_elevation)); } if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .replace(R.id.pref_fragment_container, new PreferenceFragment()) .commit(); } } @Override public boolean onSupportNavigateUp() { if (!getSupportFragmentManager().popBackStackImmediate()) { finish(); } return true; } @Override public void onBackPressed() { if (!getSupportFragmentManager().popBackStackImmediate()) { super.onBackPressed(); } } }
package com.marverenic.music.ui.settings; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.MenuItem; import com.marverenic.music.R; import com.marverenic.music.ui.BaseActivity; public class SettingsActivity extends BaseActivity { public static Intent newIntent(Context context) { return new Intent(context, SettingsActivity.class); } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); if (getSupportActionBar() != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getSupportActionBar() .setElevation(getResources().getDimension(R.dimen.header_elevation)); } if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .replace(R.id.pref_fragment_container, new PreferenceFragment()) .commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (!getSupportFragmentManager().popBackStackImmediate()) { super.onOptionsItemSelected(item); } return true; default: return super.onOptionsItemSelected(item); } } @Override public void onBackPressed() { if (!getSupportFragmentManager().popBackStackImmediate()) { super.onBackPressed(); } } }
Make problemsets display as verticals rather than sequences
from setuptools import setup, find_packages setup( name="XModule", version="0.1", packages=find_packages(), install_requires=['distribute'], package_data={ '': ['js/*'] }, # See http://guide.python-distribute.org/creation.html#entry-points # for a description of entry_points entry_points={ 'xmodule.v1': [ "book = xmodule.translation_module:TranslateCustomTagDescriptor", "chapter = xmodule.seq_module:SequenceDescriptor", "course = xmodule.seq_module:SequenceDescriptor", "customtag = xmodule.template_module:CustomTagDescriptor", "discuss = xmodule.translation_module:TranslateCustomTagDescriptor", "html = xmodule.html_module:HtmlDescriptor", "image = xmodule.translation_module:TranslateCustomTagDescriptor", "problem = xmodule.capa_module:CapaDescriptor", "problemset = xmodule.vertical_module:VerticalDescriptor", "section = xmodule.translation_module:SemanticSectionDescriptor", "sequential = xmodule.seq_module:SequenceDescriptor", "slides = xmodule.translation_module:TranslateCustomTagDescriptor", "vertical = xmodule.vertical_module:VerticalDescriptor", "video = xmodule.video_module:VideoDescriptor", "videodev = xmodule.translation_module:TranslateCustomTagDescriptor", "videosequence = xmodule.seq_module:SequenceDescriptor", ] } )
from setuptools import setup, find_packages setup( name="XModule", version="0.1", packages=find_packages(), install_requires=['distribute'], package_data={ '': ['js/*'] }, # See http://guide.python-distribute.org/creation.html#entry-points # for a description of entry_points entry_points={ 'xmodule.v1': [ "book = xmodule.translation_module:TranslateCustomTagDescriptor", "chapter = xmodule.seq_module:SequenceDescriptor", "course = xmodule.seq_module:SequenceDescriptor", "customtag = xmodule.template_module:CustomTagDescriptor", "discuss = xmodule.translation_module:TranslateCustomTagDescriptor", "html = xmodule.html_module:HtmlDescriptor", "image = xmodule.translation_module:TranslateCustomTagDescriptor", "problem = xmodule.capa_module:CapaDescriptor", "problemset = xmodule.seq_module:SequenceDescriptor", "section = xmodule.translation_module:SemanticSectionDescriptor", "sequential = xmodule.seq_module:SequenceDescriptor", "slides = xmodule.translation_module:TranslateCustomTagDescriptor", "vertical = xmodule.vertical_module:VerticalDescriptor", "video = xmodule.video_module:VideoDescriptor", "videodev = xmodule.translation_module:TranslateCustomTagDescriptor", "videosequence = xmodule.seq_module:SequenceDescriptor", ] } )
Clear subtitles and display ip address when network settings are changed
package com.spaceout; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; public class MainActivity extends Activity { private static final int REQUEST_CODE = 1; private String ipAddress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void setNetwork(View view) { Intent networkIntent = new Intent(this, NetworkActivity.class); networkIntent.putExtra("ipAddress", this.ipAddress); startActivityForResult(networkIntent, REQUEST_CODE); } @Override public void onDestroy() { stopService(new Intent(this, NeuralAlertnessService.class)); super.onDestroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Check which request we're responding to if (requestCode == REQUEST_CODE) { // Make sure the request was successful if (resultCode == RESULT_OK) { this.ipAddress = data.getStringExtra("ipAddress"); Log.d("SPACEOUT", "ip address of server set to " + this.ipAddress); // restart the service with the new ip address stopService(new Intent(this, NeuralAlertnessService.class)); Intent serviceIntent = new Intent(this, NeuralAlertnessService.class); serviceIntent.putExtra("ipAddress", this.ipAddress); startService(serviceIntent); TextView subtitles = (TextView) findViewById(R.id.subtitles); subtitles.setText("IP address: " + ipAddress + "\n\n---\n\n"); } } } }
package com.spaceout; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; public class MainActivity extends Activity { private static final int REQUEST_CODE = 1; private String ipAddress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void setNetwork(View view) { Intent networkIntent = new Intent(this, NetworkActivity.class); networkIntent.putExtra("ipAddress", this.ipAddress); startActivityForResult(networkIntent, REQUEST_CODE); } @Override public void onDestroy() { stopService(new Intent(this, NeuralAlertnessService.class)); super.onDestroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Check which request we're responding to if (requestCode == REQUEST_CODE) { // Make sure the request was successful if (resultCode == RESULT_OK) { this.ipAddress = data.getStringExtra("ipAddress"); Log.d("SPACEOUT", "ip address of server set to " + this.ipAddress); // restart the service with the new ip address stopService(new Intent(this, NeuralAlertnessService.class)); Intent serviceIntent = new Intent(this, NeuralAlertnessService.class); serviceIntent.putExtra("ipAddress", this.ipAddress); startService(serviceIntent); } } } }
Fix bug where null images were generating collidable tiles
import Phaser from 'phaser' import Waypoint from './Waypoint' export default class MapTile extends Phaser.Sprite { constructor(game, x = 0, y = 0, key = null, frame = null, rotation = 0) { super(game, x, y, key, frame); this.game = game; this.angle = rotation; this.pivot.x = 256; this.pivot.y = 256; if (this.width === 512 && this.height === 512 && key !== 'waterTile') { let offset = 256; new Waypoint(x - offset, y - offset); new Waypoint(x - offset + this.width, y - offset); new Waypoint(x - offset, y - offset + this.height); new Waypoint(x - offset + this.width, y - offset + this.height); } else if (key) { this.collide = true; } } enableCollision() { let newWidth = this.width - 128, newHeight = this.height - 128; if (this.width === 32 && this.height === 32) { return; } this.body.immovable = true; if (this.width !== 512 && this.height !== 512) { this.body.setSize(newWidth, newHeight, 64, 64); } } }
import Phaser from 'phaser' import Waypoint from './Waypoint' export default class MapTile extends Phaser.Sprite { constructor(game, x = 0, y = 0, key = null, frame = null, rotation = 0) { super(game, x, y, key, frame); this.game = game; this.angle = rotation; this.pivot.x = 256; this.pivot.y = 256; if (this.width === 512 && this.height === 512 && key !== 'waterTile') { let offset = 256; new Waypoint(x - offset, y - offset); new Waypoint(x - offset + this.width, y - offset); new Waypoint(x - offset, y - offset + this.height); new Waypoint(x - offset + this.width, y - offset + this.height); } else { this.collide = true; } } enableCollision() { let newWidth = this.width - 128, newHeight = this.height - 128; if (this.width === 32 && this.height === 32) { return; } this.body.immovable = true; if (this.width !== 512 && this.height !== 512) { this.body.setSize(newWidth, newHeight, 64, 64); } } }
Create two promises per social media request. Heroku deployment.
module.exports = (function(){ // GET /users/:id/media?lat=<LAT>&lng=<LNG>&time=<TIME> return function* collection(id) { var Q = require('q'); var TwitterManager = require('../media/twitter'); var InstagramManager = require('../media/instagram'); // Twitter Requests var twitterDef = Q.defer(); var twitterGranuals = twitterDef.promise .then(TwitterManager.search) twitterDef.resolve(this.request.url) // Instagram Requests var instagramDef = Q.defer(); var instagramGranuals = instagramDef.promise .then(InstagramManager.search) instagramDef.resolve(this.request.url) // Flickr Requests // var FlickrManager = require('../media/flickr'); // var flickrGranuals = yield FlickrManager.search(this.request.url); // Creating a universal capsul object var capsul = { user_id: id, latitude: require('../../helpers').paramsForUrl(this.request.url).lat, longitude: require('../../helpers').paramsForUrl(this.request.url).lng, timestamp: require('../../helpers').paramsForUrl(this.request.url).time, data: [] } capsul.data.push(instagramGranuals); capsul.data.push(twitterGranuals); this.body = yield capsul; } })();
module.exports = (function(){ // GET /users/:id/media?lat=<LAT>&lng=<LNG>&time=<TIME> return function* collection(id) { var Q = require('q'); var TwitterManager = require('../media/twitter'); var InstagramManager = require('../media/instagram'); // Twitter Requests var twitterDef = Q.defer(); var twitterGranuals = twitterDef.promise .then(TwitterManager.search); // Instagram Requests var instagramDef = Q.defer(); var instagramGranuals = instagramDef.promise .then(InstagramManager.search); // Flickr Requests // var FlickrManager = require('../media/flickr'); // var flickrGranuals = yield FlickrManager.search(this.request.url); // Creating a universal capsul object var capsul = { "user_id": id, "latitude": require('../../helpers').paramsForUrl(this.request.url).lat, "longitude": require('../../helpers').paramsForUrl(this.request.url).lng, "timestamp": require('../../helpers').paramsForUrl(this.request.url).time, "data": [] } twitterDef.resolve(this.request.url) instagramDef.resolve(this.request.url) capsul.data.push(twitterGranuals); capsul.data.push(instagramGranuals); this.body = yield capsul; } })();
Remove code alignment, add trailing comma, add EOF newline
var gulp = require('gulp'), csslint = require('gulp-csslint'), jshint = require('gulp-jshint'), rename = require('gulp-rename'), uglify = require('gulp-uglify'), autoprefixer = require('gulp-autoprefixer'), minifyCSS = require('gulp-minify-css'), stylish = require('jshint-stylish'); gulp.task('csslint', function () { return gulp.src('src/imagelightbox.css') .pipe(csslint('.csslintrc')) .pipe(csslint.reporter()) }); gulp.task('minify:css', function () { return gulp.src('src/imagelightbox.css') .pipe(autoprefixer({ browsers: ['last 2 versions', 'ie >= 7', 'Firefox ESR', 'Android >= 2.3'], cascade: false, })) .pipe(minifyCSS()) .pipe(rename('imagelightbox.min.css')) .pipe(gulp.dest('dist/')); }); gulp.task('jshint', function () { return gulp.src('src/imagelightbox.js') .pipe(jshint()) .pipe(jshint.reporter(stylish)); }); gulp.task('minify:js', function () { return gulp.src('src/imagelightbox.js') .pipe(uglify()) .pipe(rename('imagelightbox.min.js')) .pipe(gulp.dest('dist/')); }); gulp.task('default', ['csslint', 'minify:css', 'jshint', 'minify:js']);
var gulp = require('gulp'), csslint = require('gulp-csslint'), jshint = require('gulp-jshint'), rename = require('gulp-rename'), uglify = require('gulp-uglify'), autoprefixer = require('gulp-autoprefixer'), minifyCSS = require('gulp-minify-css'), stylish = require('jshint-stylish'); gulp.task('csslint', function () { return gulp.src('src/imagelightbox.css') .pipe(csslint('.csslintrc')) .pipe(csslint.reporter()) }); gulp.task('minify:css', function () { return gulp.src('src/imagelightbox.css') .pipe(autoprefixer({ browsers: ['last 2 versions', 'ie >= 7', 'Firefox ESR', 'Android >= 2.3'], cascade: false })) .pipe(minifyCSS()) .pipe(rename('imagelightbox.min.css')) .pipe(gulp.dest('dist/')); }); gulp.task('jshint', function () { return gulp.src('src/imagelightbox.js') .pipe(jshint()) .pipe(jshint.reporter(stylish)); }); gulp.task('minify:js', function () { return gulp.src('src/imagelightbox.js') .pipe(uglify()) .pipe(rename('imagelightbox.min.js')) .pipe(gulp.dest('dist/')); }); gulp.task('default', ['csslint', 'minify:css', 'jshint', 'minify:js']);
Make spinner reappear on subsequent visits
Template.duplicates.onRendered(function() { Session.set('loadedDuplicates', false); var playlist_id = Router.current().params['_id'] Meteor.call('getDuplicateTracksFromPlaylist', playlist_id, function(err, response) { console.log(response); Session.set('duplicateTracks', response); Session.set('loadedDuplicates', true); }); }); Template.duplicates.events({ 'click .remove-dup': function (e) { var track_uri = e.currentTarget.id; var track_id = e.currentTarget.id.split(':')[2]; var playlist_id = e.currentTarget.baseURI.split('/')[4]; console.log(track_uri); console.log(playlist_id); Meteor.call('removeDuplicates', playlist_id, track_uri, function(err, response) { }); // Temporary hack, can't // remove more than 1 duplicate without // completely reloading window.location.reload() //$('#' + track_id).remove(); //Session.set('duplicateTracks', $.grep(Session.get('duplicateTracks'), function(e) { return e.uri != track_uri })); }, 'click .home': function(e) { Session.set('loadedPlaylists', true); Router.go('/'); } }); Template.duplicates.helpers({ duplicates: function() { return Session.get('duplicateTracks'); }, loadedDuplicates: function() { return Session.get('loadedDuplicates'); } });
Template.duplicates.onRendered(function() { var playlist_id = Router.current().params['_id'] Meteor.call('getDuplicateTracksFromPlaylist', playlist_id, function(err, response) { console.log(response); Session.set('duplicateTracks', response); Session.set('loadedDuplicates', true); }); }); Template.duplicates.events({ 'click .remove-dup': function (e) { var track_uri = e.currentTarget.id; var track_id = e.currentTarget.id.split(':')[2]; var playlist_id = e.currentTarget.baseURI.split('/')[4]; console.log(track_uri); console.log(playlist_id); Meteor.call('removeDuplicates', playlist_id, track_uri, function(err, response) { }); // Temporary hack, can't // remove more than 1 duplicate without // completely reloading window.location.reload() //$('#' + track_id).remove(); //Session.set('duplicateTracks', $.grep(Session.get('duplicateTracks'), function(e) { return e.uri != track_uri })); }, 'click .home': function(e) { Session.set('loadedPlaylists', true); Router.go('/'); } }); Template.duplicates.helpers({ duplicates: function() { return Session.get('duplicateTracks'); }, loadedDuplicates: function() { return Session.get('loadedDuplicates'); } });
Remove exception for mixin linting now that they've all been removed.
module.exports = { root: true, parser: 'babel-eslint', parserOptions: { ecmaVersion: 2018, sourceType: 'module', ecmaFeatures: { legacyDecorators: true } }, plugins: [ 'ember' ], extends: [ 'eslint:recommended', 'plugin:ember/recommended' ], env: { browser: true }, rules: { 'ember/no-jquery': 'error' }, overrides: [ // node files { files: [ '.eslintrc.js', '.template-lintrc.js', 'ember-cli-build.js', 'index.js', 'testem.js', 'blueprints/*/index.js', 'config/**/*.js', 'tests/dummy/config/**/*.js' ], excludedFiles: [ 'addon/**', 'addon-test-support/**', 'app/**', 'tests/dummy/app/**' ], parserOptions: { sourceType: 'script' }, env: { browser: false, node: true }, plugins: ['node'], rules: Object.assign({}, require('eslint-plugin-node').configs.recommended.rules, { // add your custom rules and overrides for node files here }) } ] };
module.exports = { root: true, parser: 'babel-eslint', parserOptions: { ecmaVersion: 2018, sourceType: 'module', ecmaFeatures: { legacyDecorators: true } }, plugins: [ 'ember' ], extends: [ 'eslint:recommended', 'plugin:ember/recommended' ], env: { browser: true }, rules: { 'ember/no-jquery': 'error', 'ember/no-new-mixins': 'off' }, overrides: [ // node files { files: [ '.eslintrc.js', '.template-lintrc.js', 'ember-cli-build.js', 'index.js', 'testem.js', 'blueprints/*/index.js', 'config/**/*.js', 'tests/dummy/config/**/*.js' ], excludedFiles: [ 'addon/**', 'addon-test-support/**', 'app/**', 'tests/dummy/app/**' ], parserOptions: { sourceType: 'script' }, env: { browser: false, node: true }, plugins: ['node'], rules: Object.assign({}, require('eslint-plugin-node').configs.recommended.rules, { // add your custom rules and overrides for node files here }) } ] };
Move step-by-step direction details into element
(function () { 'use strict'; /* ngInject */ function RowDetail($compile) { // TODO: Animate the row appearing var template = [ '<div class="block" ng-show="visible">', '<ul class="list-unstyled">', '<li ng-repeat="feature in item.directions.features">', '<img width="20px" height="20px" ng-src="{{ ::feature.img }}" /> {{ ::feature.note }}', '</li>', '<li ng-repeat="warning in item.directions.warnings">', '<img width="20px" height="20px" ng-src="{{ ::warning.img }}" /> {{ ::warning.note }}', '</li>', '</ul>', '</div>' ].join(''); var module = { restrict: 'A', scope: false, link: link, }; return module; function link(scope, element) { if (!hasDetails(scope.item)) { return; } scope.visible = false; var row = $compile(template)(scope); element.find('td:last-child').append(row); element.click(function () { scope.visible = !scope.visible; scope.$apply(); }); function hasDetails(item) { var directions = item.directions; return directions && (directions.features.length || directions.warnings.length); } } } angular.module('nih.views.routing') .directive('rowDetail', RowDetail); })();
(function () { 'use strict'; /* ngInject */ function RowDetail($compile) { // TODO: Animate the row appearing var template = [ '<tr ng-show="visible"><td colspan="2">', '<ul class="list-unstyled">', '<li ng-repeat="feature in item.directions.features">', '<img width="20px" height="20px" ng-src="{{ ::feature.img }}" />{{ ::feature.note }}', '</li>', '<li ng-repeat="warning in item.directions.warnings">', '<img width="20px" height="20px" ng-src="{{ ::warning.img }}" />{{ ::warning.note }}', '</li>', '</ul>', '</td></tr>' ].join(''); var module = { restrict: 'A', scope: false, link: link, }; return module; function link(scope, element) { if (!hasDetails(scope.item)) { return; } scope.visible = false; var row = $compile(template)(scope); element.after(row); element.click(function () { scope.visible = !scope.visible; scope.$apply(); }); function hasDetails(item) { var directions = item.directions; return directions && (directions.features.length || directions.warnings.length); } } } angular.module('nih.views.routing') .directive('rowDetail', RowDetail); })();
[AC-7743] Change the user role key from userv to name
# Generated by Django 2.2.10 on 2020-04-09 21:24 from django.db import migrations def add_deferred_user_role(apps, schema_editor): DEFERRED_MENTOR = 'Deferred Mentor' UserRole = apps.get_model('accelerator', 'UserRole') Program = apps.get_model('accelerator', 'Program') ProgramRole = apps.get_model('accelerator', 'ProgramRole') if UserRole.objects.filter(name=DEFERRED_MENTOR).exists(): user_role = UserRole.objects.filter(name=DEFERRED_MENTOR)[0] else: user_role = UserRole.objects.create(name=DEFERRED_MENTOR, sort_order=17) for program in Program.objects.all(): if not ProgramRole.objects.filter(user_role=user_role, program=program).exists(): name = "{} {} ({}-{})".format( (program.end_date.year if program.end_date else ""), DEFERRED_MENTOR, program.program_family.url_slug.upper(), program.pk) ProgramRole.objects.get_or_create( program=program, user_role=user_role, name=name) class Migration(migrations.Migration): dependencies = [ ('accelerator', '0018_make_location_nonrequired'), ] operations = [ migrations.RunPython(add_deferred_user_role, migrations.RunPython.noop) ]
# Generated by Django 2.2.10 on 2020-04-09 21:24 from django.db import migrations def add_deferred_user_role(apps, schema_editor): DEFERRED_MENTOR = 'Deferred Mentor' UserRole = apps.get_model('accelerator', 'UserRole') Program = apps.get_model('accelerator', 'Program') ProgramRole = apps.get_model('accelerator', 'ProgramRole') if UserRole.objects.filter(name=DEFERRED_MENTOR).exists(): user_role = UserRole.objects.filter(user=DEFERRED_MENTOR)[0] else: user_role = UserRole.objects.create(name=DEFERRED_MENTOR, sort_order=17) for program in Program.objects.all(): if not ProgramRole.objects.filter(user_role=user_role, program=program).exists(): name = "{} {} ({}-{})".format( (program.end_date.year if program.end_date else ""), DEFERRED_MENTOR, program.program_family.url_slug.upper(), program.pk) ProgramRole.objects.get_or_create( program=program, user_role=user_role, name=name) class Migration(migrations.Migration): dependencies = [ ('accelerator', '0018_make_location_nonrequired'), ] operations = [ migrations.RunPython(add_deferred_user_role, migrations.RunPython.noop) ]
Fix red highlighting in GitHub diff
import React, { Component } from 'react'; import { action } from '@kadira/storybook'; import { DraftJSEditor, Renderer, defaultBlocks } from '../../src'; const draftRenderer = new Renderer(defaultBlocks); class SetStateExample extends Component { state = { content: { entityMap: {}, blocks: [ { text: '', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], }, ], }, }; onChange = content => { action('onChange')(content); // Log to storybook's "action-logger" this.setState({ content }); }; render() { return ( <div> <h1>@synapsestudios/draftjs-editor</h1> <p className="p text-center"> {`A customized WYSIWYG editor utilizing Facebook's Draft.js library`} </p> <p className="p text-center"> View this project on {' '} <a href="https://github.com/synapsestudios/draftjs-editor" target="_blank">Github</a> </p> <DraftJSEditor content={this.state.content || null} onChange={this.onChange} placeholder="Tell a story..." customBlocks={defaultBlocks} customBlockControls={Object.keys(defaultBlocks)} /> {this.state.content ? <div dangerouslySetInnerHTML={{ __html: draftRenderer.convertRawToHTML(this.state.content), }} /> : null} </div> ); } } export default SetStateExample;
import React, { Component } from 'react'; import { action } from '@kadira/storybook'; import { DraftJSEditor, Renderer, defaultBlocks } from '../../src'; const draftRenderer = new Renderer(defaultBlocks); class SetStateExample extends Component { state = { content: { entityMap: {}, blocks: [ { text: '', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], }, ], }, }; onChange = content => { action('onChange')(content); // Log to storybook's "action-logger" this.setState({ content }); }; render() { return ( <div> <h1>@synapsestudios/draftjs-editor</h1> <p className="p text-center"> A customized WYSIWYG editor utilizing Facebook's Draft.js library </p> <p className="p text-center"> View this project on {' '} <a href="https://github.com/synapsestudios/draftjs-editor" target="_blank">Github</a> </p> <DraftJSEditor content={this.state.content || null} onChange={this.onChange} placeholder="Tell a story..." customBlocks={defaultBlocks} customBlockControls={Object.keys(defaultBlocks)} /> {this.state.content ? <div dangerouslySetInnerHTML={{ __html: draftRenderer.convertRawToHTML(this.state.content), }} /> : null} </div> ); } } export default SetStateExample;
[OW] Fix bad spelling of reaper and forgetting sombra - fixes #93
<?php namespace Onyx\Overwatch\Helpers\Game; /** * Class Character * @package Onyx\Overwatch\Helpers\Game */ class Character { public static function getValidCharacter(string $char) : string { switch ($char) { case 'reinhardt': case 'rein': return 'reinhardt'; case 'mcree': return 'mcree'; case 'winston': return 'winston'; case 'pharah': return 'pharah'; case 'roadhog': case 'road': return 'roadhog'; case 'zarya': return 'zarya'; case 'torbjorn': case 'torb': return 'torbjorn'; case 'ana': return 'ana'; case 'genji': return 'genji'; case 'symmetra': case 'sim': case 'sym': return 'symmetra'; case 'dva': return 'dva'; case 'lucio': return 'lucio'; case 'zen': case 'zenyatta': return 'zenyatta'; case 'junkrat': case 'junk': return 'junkrat'; case 'hanzo': return 'hanzo'; case 'mercy': return 'mercy'; case 'reaper': return 'reaper'; case 'soldier76': case '76': return 'soldier76'; case 'osira': return 'osira'; case 'sombra': return 'sombra'; default: return 'unknown'; } } }
<?php namespace Onyx\Overwatch\Helpers\Game; /** * Class Character * @package Onyx\Overwatch\Helpers\Game */ class Character { public static function getValidCharacter(string $char) : string { switch ($char) { case 'reinhardt': case 'rein': return 'reinhardt'; case 'mcree': return 'mcree'; case 'winston': return 'winston'; case 'pharah': return 'pharah'; case 'roadhog': case 'road': return 'roadhog'; case 'zarya': return 'zarya'; case 'torbjorn': case 'torb': return 'torbjorn'; case 'ana': return 'ana'; case 'genji': return 'genji'; case 'symmetra': case 'sim': case 'sym': return 'symmetra'; case 'dva': return 'dva'; case 'lucio': return 'lucio'; case 'zen': case 'zenyatta': return 'zenyatta'; case 'junkrat': case 'junk': return 'junkrat'; case 'hanzo': return 'hanzo'; case 'mercy': return 'mercy'; case 'repear': return 'repear'; case 'soldier76': case '76': return 'soldier76'; case 'osira': return 'osira'; default: return 'unknown'; } } }
Add the check for status
package org.vietabroader.controller; import org.vietabroader.model.GlobalState; import org.vietabroader.model.VASpreadsheet; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SpreadsheetConnectController implements Controller { private JButton btnConnect; private JTextField txtConnect; private static final Logger logger = LoggerFactory.getLogger(SpreadsheetConnectController.class); public SpreadsheetConnectController setConnectButton(JButton btn) { btnConnect = btn; return this; } public SpreadsheetConnectController setTextSpreadsheetID(JTextField txt) { txtConnect = txt; return this; } @Override public void control() { btnConnect.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GlobalState currentState = GlobalState.getInstance(); if (currentState.getStatus() == GlobalState.Status.SIGNED_IN || currentState.getStatus() == GlobalState.Status.CONNECTED) { try { VASpreadsheet spreadsheet = new VASpreadsheet(txtConnect.getText()); spreadsheet.connect(); currentState.setStatus(GlobalState.Status.CONNECTED); currentState.setSpreadsheet(spreadsheet); logger.info("Sheet " + spreadsheet.getSpreadsheetTitle() + "connected"); } catch (Exception ex) { currentState.setStatus(GlobalState.Status.SIGNED_IN); ex.printStackTrace(); } } } }); } }
package org.vietabroader.controller; import org.vietabroader.model.GlobalState; import org.vietabroader.model.VASpreadsheet; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SpreadsheetConnectController implements Controller { private JButton btnConnect; private JTextField txtConnect; private static final Logger logger = LoggerFactory.getLogger(SpreadsheetConnectController.class); public SpreadsheetConnectController setConnectButton(JButton btn) { btnConnect = btn; return this; } public SpreadsheetConnectController setTextSpreadsheetID(JTextField txt) { txtConnect = txt; return this; } @Override public void control() { btnConnect.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GlobalState currentState = GlobalState.getInstance(); try { VASpreadsheet spreadsheet = new VASpreadsheet(txtConnect.getText()); spreadsheet.connect(); currentState.setStatus(GlobalState.Status.CONNECTED); currentState.setSpreadsheet(spreadsheet); logger.info("Sheet " + spreadsheet.getSpreadsheetTitle() + "connected"); } catch (Exception ex) { currentState.setStatus(GlobalState.Status.SIGNED_IN); ex.printStackTrace(); } } }); } }
Revert "Fix lines in border backgrounds." This ended up not being the cause of the off-by-one issue I observed. This reverts commit 582d6ed113e5ad4df971008671a9d07220028bf0.
// // Triple Play - utilities for use in PlayN-based games // Copyright (c) 2011, Three Rings Design, Inc. - All rights reserved. // http://github.com/threerings/tripleplay/blob/master/LICENSE package tripleplay.ui.bgs; import playn.core.ImmediateLayer; import playn.core.PlayN; import playn.core.Surface; import pythagoras.f.IDimension; import tripleplay.ui.Background; /** * A background that shows a line around a solid color. */ public class BorderedBackground extends Background { public BorderedBackground (int bgColor, int borderColor, int thickness) { _bgColor = bgColor; _borderColor = borderColor; _thickness = thickness; } @Override protected Instance instantiate (final IDimension size) { return new LayerInstance(PlayN.graphics().createImmediateLayer(new ImmediateLayer.Renderer() { public void render (Surface surf) { float width = size.width(), height = size.height(); float bot = height-1, right = width-1; surf.setFillColor(_bgColor).fillRect(0, 0, width, height); surf.setFillColor(_borderColor). drawLine(0, 0, right, 0, _thickness). drawLine(right, 0, right, bot, _thickness). drawLine(right, bot, 0, bot, _thickness). drawLine(0, bot, 0, 0, _thickness); } })); } protected final int _bgColor, _borderColor, _thickness; }
// // Triple Play - utilities for use in PlayN-based games // Copyright (c) 2011, Three Rings Design, Inc. - All rights reserved. // http://github.com/threerings/tripleplay/blob/master/LICENSE package tripleplay.ui.bgs; import playn.core.ImmediateLayer; import playn.core.PlayN; import playn.core.Surface; import pythagoras.f.IDimension; import tripleplay.ui.Background; /** * A background that shows a line around a solid color. */ public class BorderedBackground extends Background { public BorderedBackground (int bgColor, int borderColor, int thickness) { _bgColor = bgColor; _borderColor = borderColor; _thickness = thickness; } @Override protected Instance instantiate (final IDimension size) { return new LayerInstance(PlayN.graphics().createImmediateLayer(new ImmediateLayer.Renderer() { public void render (Surface surf) { float width = size.width(), height = size.height(); float bot = height, right = width; surf.setFillColor(_bgColor).fillRect(0, 0, width, height); surf.setFillColor(_borderColor). drawLine(0, 0, right, 0, _thickness). drawLine(right, 0, right, bot, _thickness). drawLine(right, bot, 0, bot, _thickness). drawLine(0, bot, 0, 0, _thickness); } })); } protected final int _bgColor, _borderColor, _thickness; }
Add a change to method.
package ru.job4j.even.numbers.iterator; import java.util.Iterator; import java.util.NoSuchElementException; public class EvenNumbersIterator implements Iterator { private int[] numbers; private int index = 0; private int size; public EvenNumbersIterator(final int[] numbers) { this.numbers = numbers; this.size = numbers.length; } @Override public boolean hasNext() { int pointer = index; while (pointer < size) { if (isEvenNumber(numbers[pointer])) { return true; } else { pointer++; } } return false; } @Override public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } int tmp = numbers[index]; while (index < size) { if (isEvenNumber(tmp)) { index++; break; } else { tmp = numbers[++index]; } } return tmp; } private boolean isEvenNumber(int num) { return num % 2 == 0; } }
package ru.job4j.even.numbers.iterator; import java.util.Iterator; import java.util.NoSuchElementException; public class EvenNumbersIterator implements Iterator { private int[] numbers; private int index = 0; private int size; public EvenNumbersIterator(final int[] numbers) { this.numbers = numbers; this.size = numbers.length; } @Override public boolean hasNext() { int pointer = index; while (pointer < size) { if (isEvenNumber(numbers[pointer])) { return true; } else { pointer++; } } return false; } @Override public Object next() { // if (size == 0 || !hasNext() || index > size) { if (!hasNext()) { throw new NoSuchElementException(); } int tmp = numbers[index]; while (index < size) { if (isEvenNumber(tmp)) { index++; break; } else { tmp = numbers[++index]; } } return tmp; } private boolean isEvenNumber(int num) { return num % 2 == 0; } }
Update tests to use 0.14.0 modules
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'mocha-jsdom'; import expect from 'expect'; import Notification from '../src/notification'; const MOCK = { message: 'Test', action: 'Dismiss', onClick: function handleClick() { return; }, style: { bar: { background: '#bababa' }, action: { color: '#000' }, active: { left: '2rem' } } }; describe('Notification', () => { jsdom(); it('should render message and action text', done => { const tree = TestUtils.renderIntoDocument( <Notification message={MOCK.message} action={MOCK.action} onClick={MOCK.onClick} /> ); let message = TestUtils.findRenderedDOMComponentWithClass(tree, 'notification-bar-message'); let action = TestUtils.findRenderedDOMComponentWithClass(tree, 'notification-bar-action'); expect(message.props.children).toBe(MOCK.message); expect(action.props.children).toBe(MOCK.action); done(); }); it('should handle click events', done => { const tree = TestUtils.renderIntoDocument( <Notification message={MOCK.message} action={MOCK.action} onClick={MOCK.onClick} /> ); let wrapper = TestUtils.findRenderedDOMComponentWithClass(tree, 'notification-bar-wrapper'); TestUtils.Simulate.click(wrapper); done(); }); });
import React from 'react/addons'; import ExecutionEnvironment from 'react/lib/ExecutionEnvironment'; import jsdom from 'mocha-jsdom'; import expect from 'expect'; import Notification from '../src/notification'; let TestUtils = React.addons.TestUtils; const MOCK = { message: 'Test', action: 'Dismiss', onClick: function handleClick() { return; }, style: { bar: { background: '#bababa' }, action: { color: '#000' }, active: { left: '2rem' } } }; describe('Notification', () => { jsdom(); ExecutionEnvironment.canUseDOM = true; it('should render message and action text', done => { const tree = TestUtils.renderIntoDocument( <Notification message={MOCK.message} action={MOCK.action} onClick={MOCK.onClick} /> ); let message = TestUtils.findRenderedDOMComponentWithClass(tree, 'notification-bar-message'); let action = TestUtils.findRenderedDOMComponentWithClass(tree, 'notification-bar-action'); expect(message.props.children).toBe(MOCK.message); expect(action.props.children).toBe(MOCK.action); done(); }); it('should handle click events', done => { const tree = TestUtils.renderIntoDocument( <Notification message={MOCK.message} action={MOCK.action} onClick={MOCK.onClick} /> ); let wrapper = TestUtils.findRenderedDOMComponentWithClass(tree, 'notification-bar-wrapper'); TestUtils.Simulate.click(wrapper); done(); }); });
Use right result for determining success
<?php namespace Endroid\Tests\Sudoku; use Endroid\Sudoku\Puzzle; class PuzzleTest extends \PHPUnit_Framework_TestCase { public function testSolveEasy() { // An easy puzzle $values = ' 003020600 900305001 001806400 008102900 700000008 006708200 002609500 800203009 005010300'; // Create the object $sudoku = new Puzzle($values); $sudoku = $sudoku->solve(); // Check if the puzzle is solved $this->assertTrue($sudoku->isSolved()); } public function testSolveHard() { // A difficult puzzle $values = ' 800000000 003600000 070090200 050007000 000045700 000100030 001000068 008500010 090000400'; // Create the object $sudoku = new Puzzle($values); $sudoku = $sudoku->solve(); // Check if the puzzle is solved $this->assertTrue($sudoku->isSolved()); } }
<?php namespace Endroid\Tests\Sudoku; use Endroid\Sudoku\Puzzle; class PuzzleTest extends \PHPUnit_Framework_TestCase { public function testSolveEasy() { // An easy puzzle $values = ' 003020600 900305001 001806400 008102900 700000008 006708200 002609500 800203009 005010300'; // Create the object $sudoku = new Puzzle($values); $sudoku->solve(); // Check if the puzzle is solved $this->assertTrue($sudoku->isSolved()); } public function testSolveHard() { // A difficult puzzle $values = ' 800000000 003600000 070090200 050007000 000045700 000100030 001000068 008500010 090000400'; // Create the object $sudoku = new Puzzle($values); $sudoku->solve(); // Check if the puzzle is solved $this->assertTrue($sudoku->isSolved()); } }
Fix hljs reference not found in browser
const path = require('path'); const webpack = require('webpack'); module.exports = { entry: { app: path.resolve(__dirname, 'app/Resources/assets/js/app.js') }, output: { path: path.resolve(__dirname, 'web/builds'), filename: 'bundle.js', publicPath: '/builds/' }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: 'babel-loader' }, { test: /\.scss$/, use: [ { loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader" } ] }, { test: /\.woff2?$|\.ttf$|\.eot$|\.svg$/, use: "url-loader" } ] }, plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery", hljs: path.resolve(__dirname, 'app/Resources/assets/js/highlight.pack.js') }), new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), ], resolve: { alias: { fonts: path.resolve(__dirname, 'web/fonts'), jquery: path.resolve(__dirname, 'app/Resources/assets/js/jquery-2.1.4.min.js'), moment: path.resolve(__dirname, 'app/Resources/assets/js/moment.min.js') } } };
const path = require('path'); const webpack = require('webpack'); module.exports = { entry: { app: path.resolve(__dirname, 'app/Resources/assets/js/app.js') }, output: { path: path.resolve(__dirname, 'web/builds'), filename: 'bundle.js', publicPath: '/builds/' }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: 'babel-loader' }, { test: /\.scss$/, use: [ { loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader" } ] }, { test: /\.woff2?$|\.ttf$|\.eot$|\.svg$/, use: "url-loader" } ] }, plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery", }), new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), ], resolve: { alias: { fonts: path.resolve(__dirname, 'web/fonts'), jquery: path.resolve(__dirname, 'app/Resources/assets/js/jquery-2.1.4.min.js'), moment: path.resolve(__dirname, 'app/Resources/assets/js/moment.min.js') } } };
Update documentation link on PyPI to flask-script.readthedocs.org
""" Flask-Script -------------- Flask support for writing external scripts. Links ````` * `documentation <http://flask-script.readthedocs.org>`_ """ from setuptools import setup # Hack to prevent stupid TypeError: 'NoneType' object is not callable error on # exit of python setup.py test # in multiprocessing/util.py _exit_function when # running python setup.py test (see # https://github.com/pypa/virtualenv/pull/259) try: import multiprocessing except ImportError: pass setup( name='Flask-Script', version='0.4.0', url='http://github.com/techniq/flask-script', license='BSD', author='Dan Jacob', author_email='[email protected]', maintainer='Sean Lynch', maintainer_email='[email protected]', description='Scripting support for Flask', long_description=__doc__, py_modules=[ 'flask_script' ], test_suite='nose.collector', zip_safe=False, platforms='any', install_requires=[ 'Flask', 'argparse', ], tests_require=[ 'nose', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
""" Flask-Script -------------- Flask support for writing external scripts. Links ````` * `documentation <http://packages.python.org/Flask-Script>`_ """ from setuptools import setup # Hack to prevent stupid TypeError: 'NoneType' object is not callable error on # exit of python setup.py test # in multiprocessing/util.py _exit_function when # running python setup.py test (see # https://github.com/pypa/virtualenv/pull/259) try: import multiprocessing except ImportError: pass setup( name='Flask-Script', version='0.4.0', url='http://github.com/techniq/flask-script', license='BSD', author='Dan Jacob', author_email='[email protected]', maintainer='Sean Lynch', maintainer_email='[email protected]', description='Scripting support for Flask', long_description=__doc__, py_modules=[ 'flask_script' ], test_suite='nose.collector', zip_safe=False, platforms='any', install_requires=[ 'Flask', 'argparse', ], tests_require=[ 'nose', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Rename task callbacks to match Gulp standards
/* jshint bitwise: true, curly: true, eqeqeq: true, esversion: 6, forin: true, freeze: true, latedef: nofunc, noarg: true, nocomma: true, node: true, nonbsp: true, nonew: true, plusplus: true, singleGroups: true, strict: true, undef: true, unused: true */ 'use strict'; const gulp = require('gulp'); const BUILD_OUTPUT_DIR = 'build'; const NODE_MODULES_BIN_DIR = 'node_modules/.bin'; function exec(command, callback) { require('child_process').exec(command, (err) => { if (err) { return callback(err); } callback(); }); } function execJsDoc(configPath, callback) { exec(`${NODE_MODULES_BIN_DIR}/jsdoc -c ${configPath}`, callback); } gulp.task('clean', () => { const del = require('del'); return del([BUILD_OUTPUT_DIR]); }); gulp.task('docs:client', (done) => { execJsDoc('.jsdoc-client-conf.json', done); }); gulp.task('docs:server', (done) => { execJsDoc('.jsdoc-server-conf.json', done); }); gulp.task('docs', ['docs:client', 'docs:server']);
/* jshint bitwise: true, curly: true, eqeqeq: true, esversion: 6, forin: true, freeze: true, latedef: nofunc, noarg: true, nocomma: true, node: true, nonbsp: true, nonew: true, plusplus: true, singleGroups: true, strict: true, undef: true, unused: true */ 'use strict'; const gulp = require('gulp'); const BUILD_OUTPUT_DIR = 'build'; const NODE_MODULES_BIN_DIR = 'node_modules/.bin'; function exec(command, callback) { require('child_process').exec(command, (err) => { if (err) { return callback(err); } callback(); }); } function execJsDoc(configPath, callback) { exec(`${NODE_MODULES_BIN_DIR}/jsdoc -c ${configPath}`, callback); } gulp.task('clean', () => { const del = require('del'); return del([BUILD_OUTPUT_DIR]); }); gulp.task('docs:client', (callback) => { execJsDoc('.jsdoc-client-conf.json', callback); }); gulp.task('docs:server', (callback) => { execJsDoc('.jsdoc-server-conf.json', callback); }); gulp.task('docs', ['docs:client', 'docs:server']);
Test fix, remove invalid owner
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ({ //test icon background testIconBackgroundColorWithIcon: { test: function(cmp) { var pillIcons = $A.test.select('.pillIcon'); //there should only be one pill, because the other two pills doesnt have iconUrl $A.test.assertEquals( 1, pillIcons.length, 'There should be only one pill icon on the page' ); var elPillIcon = pillIcons[0]; //assert background color var stylePillIcon = $A.test.getStyle(elPillIcon,"background-color"); var expectedStyle = "rgb(255, 0, 255)"; $A.test.assertEquals(expectedStyle, stylePillIcon, '.pillIcon should have a background style. Found style: ' + stylePillIcon) } } })
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ({ owner:"sle", //test icon background testIconBackgroundColorWithIcon: { test: function(cmp) { var pillIcons = $A.test.select('.pillIcon'); //there should only be one pill, because the other two pills doesnt have iconUrl $A.test.assertEquals( 1, pillIcons.length, 'There should be only one pill icon on the page' ); var elPillIcon = pillIcons[0]; //assert background color var stylePillIcon = $A.test.getStyle(elPillIcon,"background-color"); var expectedStyle = "rgb(255, 0, 255)"; $A.test.assertEquals(expectedStyle, stylePillIcon, '.pillIcon should have a background style. Found style: ' + stylePillIcon) } } })
Use callback to display raw results * Move invariants out of request structure * Move request operation to dedicated sendRequest fn * TODO: Remove deprecated comment
'use strict'; var request = require('request'); var opts = parseOptions(process.argv[2]); sendRequest(opts, function (out) { console.log(out) }); /* * Verify param is present, and just return it. * TODO * Check for multiple params, and check validity * as well as presence. */ function parseParams(params) { if (! params) { console.log('Usage: nodejs gevents.js <user-name>'); process.exit(0); } return params; } function parseOptions(opts) { // org or users, resource, query topic var who = '/users' , where = '/' + opts , what = '/events' var options = { uri: 'https://api.github.com' + who + where + what, json: true, method: 'GET', headers: { 'User-Agent': 'nodejs script' } } return options; } function sendRequest(opts, callback) { var format = '[%s]: %s %s %s'; var bod = []; request(opts, function (error, res, body) { if (error) throw new Error(error); for (var i = 0; i < body.length; i++) { /* * TODO return something like this as JSON * for caller consumption (useful for servers). */ bod.push([ body[i].created_at , body[i].type , body[i].actor.login , body[i].repo.name]); } callback(bod); }); }
'use strict'; var request = require('request'); var opts = parseOptions(process.argv[2]); request(opts, function (err, res, body) { if (err) throw new Error(err); var format = '[%s]: %s %s %s'; for (var i = 0; i < body.length; i++) { /* * TODO return something like this as JSON * for caller consumption (useful for servers). */ console.log(format , body[i].created_at , body[i].type , body[i].actor.login , body[i].repo.name); } }); /* * Verify param is present, and just return it. * TODO * Check for multiple params, and check validity * as well as presence. */ function parseParams(params) { if (! params) { console.log('Usage: nodejs gevents.js <user-name>'); process.exit(0); } return params; } function parseOptions(opts) { // org or users, resource, query topic var who = '/users' , where = '/' + opts , what = '/events' var options = { uri: 'https://api.github.com' + who + where + what, json: true, method: 'GET', headers: { 'User-Agent': 'nodejs script' } } return options; }
Move hooks directory to a constant That way one could ask for the default directory from its code while still extend the class and change the path to another one.
<?php namespace PhpGitHooks\Module\Configuration\Infrastructure\Hook; use Symfony\Component\Process\Process; class HookCopier { public const DEFAULT_GIT_HOOKS_DIR = '.git/hooks'; protected $hookDir = self::DEFAULT_GIT_HOOKS_DIR; public function copyPreCommitHook(): void { $this->copyHookFile('pre-commit'); } public function copyCommitMsgHook(): void { $this->copyHookFile('commit-msg'); } public function copyPrePushHook(): void { $this->copyHookFile('pre-push'); } public function copyPrepareCommitMsgHook(): void { $this->copyHookFile('prepare-commit-msg'); } protected function hookExists(string $hookFile): bool { return file_exists(sprintf('%s%s', $this->hookDir, $hookFile)); } protected function copyFile(string $hookFile): void { $copy = new Process(sprintf("mkdir -p {$this->hookDir} && cp %s %s", $hookFile, $this->hookDir)); $copy->run(); } protected function setPermissions(string $hookFile): void { $permissions = new Process(sprintf('chmod 775 %s%s', $this->hookDir, $hookFile)); $permissions->run(); } protected function copyHookFile(string $file): void { if (false === $this->hookExists($file)) { $this->copyFile(sprintf('%s/%s', __DIR__ . '/../../../../Infrastructure/Hook', $file)); $this->setPermissions($file); } } }
<?php namespace PhpGitHooks\Module\Configuration\Infrastructure\Hook; use Symfony\Component\Process\Process; class HookCopier { protected $hookDir = '.git/hooks/'; public function copyPreCommitHook(): void { $this->copyHookFile('pre-commit'); } public function copyCommitMsgHook(): void { $this->copyHookFile('commit-msg'); } public function copyPrePushHook(): void { $this->copyHookFile('pre-push'); } public function copyPrepareCommitMsgHook(): void { $this->copyHookFile('prepare-commit-msg'); } protected function hookExists(string $hookFile): bool { return file_exists(sprintf('%s%s', $this->hookDir, $hookFile)); } protected function copyFile(string $hookFile): void { $copy = new Process(sprintf("mkdir -p {$this->hookDir} && cp %s %s", $hookFile, $this->hookDir)); $copy->run(); } protected function setPermissions(string $hookFile): void { $permissions = new Process(sprintf('chmod 775 %s%s', $this->hookDir, $hookFile)); $permissions->run(); } protected function copyHookFile(string $file): void { if (false === $this->hookExists($file)) { $this->copyFile(sprintf('%s/%s', __DIR__ . '/../../../../Infrastructure/Hook', $file)); $this->setPermissions($file); } } }
Adjust testapp migration dependency to be valid on 1.6.x
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-09-21 11:37 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wagtail.wagtailcore.blocks import wagtail.wagtailcore.fields import wagtail.wagtailimages.blocks class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0029_unicode_slugfield_dj19'), ('tests', '0008_inlinestreampage_inlinestreampagesection'), ] operations = [ migrations.CreateModel( name='DefaultStreamPage', fields=[ ('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')), ('body', wagtail.wagtailcore.fields.StreamField((('text', wagtail.wagtailcore.blocks.CharBlock()), ('rich_text', wagtail.wagtailcore.blocks.RichTextBlock()), ('image', wagtail.wagtailimages.blocks.ImageChooserBlock())), default='')), ], options={ 'abstract': False, }, bases=('wagtailcore.page',), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-09-21 11:37 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wagtail.wagtailcore.blocks import wagtail.wagtailcore.fields import wagtail.wagtailimages.blocks class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0030_index_on_pagerevision_created_at'), ('tests', '0008_inlinestreampage_inlinestreampagesection'), ] operations = [ migrations.CreateModel( name='DefaultStreamPage', fields=[ ('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')), ('body', wagtail.wagtailcore.fields.StreamField((('text', wagtail.wagtailcore.blocks.CharBlock()), ('rich_text', wagtail.wagtailcore.blocks.RichTextBlock()), ('image', wagtail.wagtailimages.blocks.ImageChooserBlock())), default='')), ], options={ 'abstract': False, }, bases=('wagtailcore.page',), ), ]
Hide header if no matches found
/* global browser:readonly */ "use strict"; function parseReceivedHeader(headerStr, regexp) { const capturedSubstr = headerStr.match(new RegExp(regexp)); if (capturedSubstr === null || typeof capturedSubstr[1] === "undefined") return null; return capturedSubstr[1]; } function parseReceivedHeaders(headers, regexp) { const received = []; headers.forEach(function (header) { const parsed = parseReceivedHeader(header, regexp); if (parsed !== null) received.push(parsed); }); return received; } browser.storage.local.get().then((res) => { if (!res.regexp) { browser.storage.local.set({regexp: "(.*)"}); } }); browser.messageDisplay.onMessageDisplayed.addListener((tab, message) => { browser.messages.getFull(message.id).then((messagepart) => { const headers = messagepart.headers.received; if (headers) { browser.storage.local.get().then((res) => { const parsed = parseReceivedHeaders(headers, res.regexp); browser.displayReceivedHeader.setReceivedHeaderValue(tab.id, parsed); browser.displayReceivedHeader.setReceivedHeaderHidden(tab.id, !parsed.length); }); } else { browser.displayReceivedHeader.setReceivedHeaderHidden(tab.id, true); } }); }); browser.displayReceivedHeader.init();
/* global browser:readonly */ "use strict"; function parseReceivedHeader(headerStr, regexp) { const capturedSubstr = headerStr.match(new RegExp(regexp)); if (capturedSubstr === null || typeof capturedSubstr[1] === "undefined") return null; return capturedSubstr[1]; } function parseReceivedHeaders(headers, regexp) { const received = []; headers.forEach(function (header) { const parsed = parseReceivedHeader(header, regexp); if (parsed !== null) received.push(parsed); }); return received; } browser.storage.local.get().then((res) => { if (!res.regexp) { browser.storage.local.set({regexp: "(.*)"}); } }); browser.messageDisplay.onMessageDisplayed.addListener((tab, message) => { browser.messages.getFull(message.id).then((messagepart) => { const headers = messagepart.headers.received; if (headers) { browser.storage.local.get().then((res) => { const parsed = parseReceivedHeaders(headers, res.regexp); browser.displayReceivedHeader.setReceivedHeaderValue(tab.id, parsed); browser.displayReceivedHeader.setReceivedHeaderHidden(tab.id, false); }); } else { browser.displayReceivedHeader.setReceivedHeaderHidden(tab.id, true); } }); }); browser.displayReceivedHeader.init();
Handle recreating soft deleted pages
<?php namespace Metrique\Building\Http\Requests; use Illuminate\Database\Eloquent\Builder; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; use Metrique\Building\Rules\AbsoluteUrlPathRule; class PageRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get custom attributes for validator errors. * * @return array */ public function attributes() { return [ 'path' => 'Path', 'published_at' => 'published date', ]; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'path' => [ 'required', 'string', new AbsoluteUrlPathRule, Rule::unique( 'pages', 'path' )->ignore( optional($this->page)->id )->where(function ($query) { return $query->whereNull('deleted_at'); }), ], 'title' => [ 'required', 'string', ], 'description' => [ 'required', 'string', ], 'image' => [ 'string', 'url' ], 'meta' => [ 'array', ], 'params' => [ 'array', ], 'published_at' => [ 'nullable', 'date', ], ]; } }
<?php namespace Metrique\Building\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; use Metrique\Building\Rules\AbsoluteUrlPathRule; class PageRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get custom attributes for validator errors. * * @return array */ public function attributes() { return [ 'path' => 'Path', 'published_at' => 'published date', ]; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'path' => [ 'required', 'string', new AbsoluteUrlPathRule, Rule::unique( 'pages', 'path' )->ignore( optional($this->page)->id ), ], 'title' => [ 'required', 'string', ], 'description' => [ 'required', 'string', ], 'image' => [ 'string', 'url' ], 'meta' => [ 'array', ], 'params' => [ 'array', ], 'published_at' => [ 'nullable', 'date', ], ]; } }
Improve test coverage of functional.py.
import unittest from transducer.functional import compose, true, identity, false class TestComposition(unittest.TestCase): def test_single(self): """ compose(f)(x) -> f(x) """ f = lambda x: x * 2 c = compose(f) # We can't test the equivalence of functions completely, so... self.assertSequenceEqual([f(x) for x in range(1000)], [c(x) for x in range(1000)]) def test_double(self): """ compose(f, g)(x) -> f(g(x)) """ f = lambda x: x * 2 g = lambda x: x + 1 c = compose(f, g) self.assertSequenceEqual([f(g(x)) for x in range(100)], [c(x) for x in range(100)]) def test_triple(self): """ compose(f, g, h)(x) -> f(g(h(x))) """ f = lambda x: x * 2 g = lambda x: x + 1 h = lambda x: x - 7 c = compose(f, g, h) self.assertSequenceEqual([f(g(h(x))) for x in range(100)], [c(x) for x in range(100)]) class TestFunctions(unittest.TestCase): def test_true(self): self.assertTrue(true()) def test_false(self): self.assertFalse(false()) def test_identity(self): self.assertEqual(identity(42), 42) if __name__ == '__main__': unittest.main()
import unittest from transducer.functional import compose class TestComposition(unittest.TestCase): def test_single(self): """ compose(f)(x) -> f(x) """ f = lambda x: x * 2 c = compose(f) # We can't test the equivalence of functions completely, so... self.assertSequenceEqual([f(x) for x in range(1000)], [c(x) for x in range(1000)]) def test_double(self): """ compose(f, g)(x) -> f(g(x)) """ f = lambda x: x * 2 g = lambda x: x + 1 c = compose(f, g) self.assertSequenceEqual([f(g(x)) for x in range(100)], [c(x) for x in range(100)]) def test_triple(self): """ compose(f, g, h)(x) -> f(g(h(x))) """ f = lambda x: x * 2 g = lambda x: x + 1 h = lambda x: x - 7 c = compose(f, g, h) self.assertSequenceEqual([f(g(h(x))) for x in range(100)], [c(x) for x in range(100)]) if __name__ == '__main__': unittest.main()
Fix implementation of overlapping rectangles
# -*- coding: utf-8 -*- from collections import namedtuple Size = namedtuple("Size", ["width", "height"]) class Rectangle(namedtuple("Rectangle", ["x0", "y0", "x1", "y1"])): def __contains__(self, other): """Check if this rectangle and `other` overlaps eachother. Essentially this is a bit of a hack to be able to write `rect1 in rect2`. """ if self.x0 < other.x1 and self.x1 > other.x0 and \ self.y0 < other.y1 and self.y1 > other.y0: return True return False class Point(namedtuple("Point", ["x", "y"])): """Point in a two-dimensional space. Named tuple implementation that allows for addition and subtraction. """ __slots__ = () def __add__(self, other): x = self.x + other.x y = self.y + other.y return Point(x, y) def __sub__(self, other): x = self.x - other.x y = self.y - other.y return Point(x, y) class Box(namedtuple("Box", ["point", "size"])): __slots__ = () @property def rectangle(self): return Rectangle( x0=self.point.x, y0=self.point.y, x1=self.point.x+self.size.width, y1=self.point.y+self.size.height )
# -*- coding: utf-8 -*- from collections import namedtuple Size = namedtuple("Size", ["width", "height"]) class Rectangle(namedtuple("Rectangle", ["x0", "y0", "x1", "y1"])): def __contains__(self, other): """Check if this rectangle and `other` overlaps eachother. Essentially this is a bit of a hack to be able to write `rect1 in rect2`. """ if self.x0 < other.x0 and self.x1 > other.x1 and \ self.y0 < other.y0 and self.y1 > other.y1: return True return False class Point(namedtuple("Point", ["x", "y"])): """Point in a two-dimensional space. Named tuple implementation that allows for addition and subtraction. """ __slots__ = () def __add__(self, other): x = self.x + other.x y = self.y + other.y return Point(x, y) def __sub__(self, other): x = self.x - other.x y = self.y - other.y return Point(x, y) class Box(namedtuple("Box", ["point", "size"])): __slots__ = () @property def rectangle(self): return Rectangle( x0=self.point.x, y0=self.point.y, x1=self.point.x+self.size.width, y1=self.point.y+self.size.height )
Implement the ypdate form controller
<?php namespace App\Http\Controllers; use App\mailingUsers; use Illuminate\Http\Request; use App\Http\Requests; class MailingController extends Controller { /** * MailingController constructor. * * Here the following middleware will be set. */ public function __construct() { $this->middleware('auth'); } /** * Get the index page for the mailing module. * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index() { $data['title'] = 'Mailing'; $data['query'] = mailingUsers::with('tag')->paginate(15); return view('backend.mailing.index', $data); } public function mail() { } public function mailGroup() { } public function send() { } public function insert() { } public function store() { } /** * Show the update form off the mailing module. * * @param int, $id, the user his id in the data table. * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function update($id) { $data['title'] = 'mailing'; $data['query'] = mailingUsers::find($id); return view('backend.mailing.update', $data); } /** * Delete a user out off the mailing module. * * @param int, $id, the user his id in the data table. * @return \Illuminate\Http\RedirectResponse */ public function deleteUser($id) { mailingUsers::find($id)->tag()->sync([]); mailingUsers::destroy($id); session()->flash('message', ''); return redirect()->back(302); } }
<?php namespace App\Http\Controllers; use App\mailingUsers; use Illuminate\Http\Request; use App\Http\Requests; class MailingController extends Controller { /** * MailingController constructor. * * Here the following middleware will be set. */ public function __construct() { $this->middleware('auth'); } /** * Get the index page for the mailing module. * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index() { $data['title'] = 'Mailing'; $data['query'] = mailingUsers::with('tag')->paginate(15); return view('backend.mailing.index', $data); } public function mail() { } public function mailGroup() { } public function send() { } public function insert() { } public function store() { } public function update($id) { } /** * Delete a user out off the mailing module. * * @param int, $id, the user his id in the data table. * @return \Illuminate\Http\RedirectResponse */ public function deleteUser($id) { mailingUsers::find($id)->tag()->sync([]); mailingUsers::destroy($id); session()->flash('message', ''); return redirect()->back(302); } }
Add createdAt when logging a message and sort results by createdAt date
$(document).ready(function () { $(document).on('keyloaded', function () { var hostname = $('#hostname').val(); $.ajax({ url: appConfig.getUrl('/log/' + hostname), dataType: 'jsonp', method: 'GET' }).done(function (data) { var hasHeader = false; var $table = $('<table class="table table-bordered table-hover dataTable"></table>'); var $tbody = $('<tbody></tbody>'); var $trh = $('<tr></tr>'); var nbCol = 0; var createdAtIndex = 0; for (var i in data) { var log = data[i]._source; var $tr = $('<tr></tr>').addClass(log['level']); for (var prop in log) { if (hasHeader == false) { $trh.append('<th>' + prop + '</th>'); } if (prop === 'createdAt' || prop === 'date') { createdAtIndex = nbCol; $tr.append('<td>' + moment(log[prop]).format('YYYY/MM/DD HH:MM:SS') + '</td>'); } else { $tr.append('<td>' + log[prop] + '</td>'); } nbCol++; } if (hasHeader == false) { var $thead = $('<thead></thead>').append($trh); $table.append($thead); hasHeader = true; } $tbody.append($tr); } $table.append($tbody); $('#dtContainer').append($table); $('#dtContainer table:eq(0)').dataTable({ "order": [[createdAtIndex, "desc"]] }); }); }); });
$(document).ready(function () { $(document).on('keyloaded', function () { var hostname = $('#hostname').val(); $.ajax({ url: appConfig.getUrl('/log/' + hostname), dataType: 'jsonp', method: 'GET' }).done(function (data) { var hasHeader = false; var $table = $('<table class="table table-bordered table-hover dataTable"></table>'); var $tbody = $('<tbody></tbody>'); var $trh = $('<tr></tr>'); for (var i in data) { var log = data[i]._source; var $tr = $('<tr></tr>').addClass(log['level']); for (var prop in log) { if (hasHeader == false) { $trh.append('<th>' + prop + '</th>'); } var value = (prop === 'date' ? moment(log[prop]).format('YYYY/MM/DD HH:MM:SS') : log[prop]); $tr.append('<td>' + value + '</td>'); } if (hasHeader == false) { var $thead = $('<thead></thead>').append($trh); $table.append($thead); hasHeader = true; } $tbody.append($tr); } $table.append($tbody); $('#dtContainer').append($table); $('#dtContainer table:eq(0)').dataTable(); }); }); });
Change the default __getattr_ value
class Card: """ A wrapper around a Scryfall json card object. """ def __init__(self, cardData): self._data = cardData def __getattr__(self, attr): """ A hack that makes all attributes inaccessible, and instead returns the stored json values """ if attr in self._data and isinstance(self._data[attr], str): return self._data[attr] else: return "{N/A}" def __contains__(self, arg): return arg in self._data def __str__(self): """ Returns the string representation of a magic card. The ** is the Discord way to bolden the text """ # Power/toughness, seen only if it's a creature pt = "" if "power" in self._data: pt = "{0}/{1}".format(self.power, self.toughness) return "**{0}** {1}\n{2} {3}\n{4}\n".format(self.name, self.mana_cost, self.type_line, pt, self.oracle_text)
class Card: """ A wrapper around a Scryfall json card object. """ def __init__(self, cardData): self._data = cardData def __getattr__(self, attr): """ A hack that makes all attributes inaccessible, and instead returns the stored json values """ if attr in self._data and isinstance(self._data[attr], str): return self._data[attr] else: return "Attribute not found." def __contains__(self, arg): return arg in self._data def __str__(self): """ Returns the string representation of a magic card. The ** is the Discord way to bolden the text """ # Power/toughness, seen only if it's a creature pt = "" if "power" in self._data: pt = "{0}/{1}".format(self.power, self.toughness) return "**{0}** {1}\n{2} {3}\n{4}\n".format(self.name, self.mana_cost, self.type_line, pt, self.oracle_text)
Add isNew function to determine if user is on news section
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { NavLink } from 'react-router-dom'; import './Sidenav.less'; const isNews = (match, location) => location.pathname !== '/'; const Sidenav = ({ username }) => (<div> {username && <ul className="Sidenav"> <li> <NavLink to={`/@${username}`} activeClassName="Sidenav__item--active"> <i className="iconfont icon-mine" /> <FormattedMessage id="my_profile" defaultMessage="My profile" /> </NavLink> </li> <li> <NavLink to="/" activeClassName="Sidenav__item--active" exact> <i className="iconfont icon-clock" /> <FormattedMessage id="feed" defaultMessage="Feed" /> </NavLink> </li> <li> <NavLink to="/trending" activeClassName="Sidenav__item--active" isActive={isNews}> <i className="iconfont icon-headlines" /> <FormattedMessage id="news" defaultMessage="News" /> </NavLink> </li> <li> <NavLink to="#wallet" activeClassName="Sidenav__item--active"> <i className="iconfont icon-wallet" /> <FormattedMessage id="wallet" defaultMessage="Wallet" /> </NavLink> </li> </ul>} </div>); Sidenav.propTypes = { username: PropTypes.string, }; Sidenav.defaultProps = { username: undefined, }; export default Sidenav;
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { NavLink } from 'react-router-dom'; import './Sidenav.less'; const Sidenav = ({ username }) => (<div> {username && <ul className="Sidenav"> <li> <NavLink to={`/@${username}`} activeClassName="Sidenav__item--active"> <i className="iconfont icon-mine" /> <FormattedMessage id="my_profile" defaultMessage="My profile" /> </NavLink> </li> <li> <NavLink to="/" activeClassName="Sidenav__item--active" exact> <i className="iconfont icon-clock" /> <FormattedMessage id="feed" defaultMessage="Feed" /> </NavLink> </li> <li> <NavLink to="/trending" activeClassName="Sidenav__item--active"> <i className="iconfont icon-headlines" /> <FormattedMessage id="news" defaultMessage="News" /> </NavLink> </li> <li> <NavLink to="#wallet" activeClassName="Sidenav__item--active"> <i className="iconfont icon-wallet" /> <FormattedMessage id="wallet" defaultMessage="Wallet" /> </NavLink> </li> </ul>} </div>); Sidenav.propTypes = { username: PropTypes.string, }; Sidenav.defaultProps = { username: undefined, }; export default Sidenav;
Add coveralls back to list of plugins
module.exports = function(config){ config.set({ basePath : './', files : [ 'app/bower_components/angular/angular.min.js', 'app/bower_components/angular-ui-router/release/angular-ui-router.min.js', 'app/bower_components/angular-resource/angular-resource.min.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/bower_components/ng-table/dist/ng-table.min.js', 'app/bower_components/spin.js/spin.js', 'app/bower_components/angular-loading/angular-loading.min.js', 'app/search/**/*.js', 'app/services/**/*.js' ], preprocessors: { 'app/search/*.js': ['coverage', 'coveralls'], 'app/services/*.js': ['coverage', 'coveralls'] }, reporters: ['progress', 'coverage'], coverageReporter: { type: 'lcov', dir: 'coverage/' }, autoWatch : true, frameworks: ['jasmine'], browsers : ['Chrome'], plugins : [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter', 'karma-coverage', 'coveralls', 'karma-coveralls' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
module.exports = function(config){ config.set({ basePath : './', files : [ 'app/bower_components/angular/angular.min.js', 'app/bower_components/angular-ui-router/release/angular-ui-router.min.js', 'app/bower_components/angular-resource/angular-resource.min.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/bower_components/ng-table/dist/ng-table.min.js', 'app/bower_components/spin.js/spin.js', 'app/bower_components/angular-loading/angular-loading.min.js', 'app/search/**/*.js', 'app/services/**/*.js' ], preprocessors: { 'app/search/*.js': ['coverage', 'coveralls'], 'app/services/*.js': ['coverage', 'coveralls'] }, reporters: ['progress', 'coverage'], coverageReporter: { type: 'lcov', dir: 'coverage/' }, autoWatch : true, frameworks: ['jasmine'], browsers : ['Chrome'], plugins : [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter', 'karma-coverage', 'karma-coveralls' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
Fix ordering bug in NGO edit Fix issue #126
class CmsNgosListController{ constructor(NgoService, $filter, $state, DialogService){ 'ngInject'; var vm = this; this.$filter = $filter; this.$state = $state; this.DialogService = DialogService; this.NgoService = NgoService; this.listOrderByColumn = '-organisation'; this.NgoService.fetchAll().then(function(ngos) { vm.ngos = vm.$filter('orderBy')(ngos, [vm.listOrderByColumn], true); }); this.listFilter = { search: '' }; this.listPagination = { limit: 10, page: 1 }; this.onOrderChange = (order) => { return vm.ngos = vm.$filter('orderBy')(vm.ngos, [order], true); }; } togglePublished(ngo) { this.NgoService.togglePublished(ngo); } add() { this.ngo = {}; this.DialogService.fromTemplate('ngo', { controller: () => this, controllerAs: 'vm' }); } edit(ngo) { this.ngo = ngo; this.ngo.editMode = true; this.DialogService.fromTemplate('ngo', { controller: () => this, controllerAs: 'vm' }); } $onInit(){ } } export const CmsNgosListComponent = { templateUrl: './views/app/components/cms-ngos-list/cms-ngos-list.component.html', controller: CmsNgosListController, controllerAs: 'vm', bindings: {} }
class CmsNgosListController{ constructor(NgoService, $filter, $state, DialogService){ 'ngInject'; var vm = this; this.$filter = $filter; this.$state = $state; this.DialogService = DialogService; this.NgoService = NgoService; this.NgoService.fetchAll().then(function(response) { vm.ngos = response; }); this.listFilter = { search: '' }; this.listPagination = { limit: 10, page: 1 }; this.listOrderByColumn = '-organisation'; this.onOrderChange = (order) => { return vm.ngos = this.$filter('orderBy')(vm.ngos, [order], true); }; } togglePublished(ngo) { this.NgoService.togglePublished(ngo); } add() { this.ngo = {}; this.DialogService.fromTemplate('ngo', { controller: () => this, controllerAs: 'vm' }); } edit(ngo) { this.ngo = ngo; this.ngo.editMode = true; this.DialogService.fromTemplate('ngo', { controller: () => this, controllerAs: 'vm' }); } $onInit(){ } } export const CmsNgosListComponent = { templateUrl: './views/app/components/cms-ngos-list/cms-ngos-list.component.html', controller: CmsNgosListController, controllerAs: 'vm', bindings: {} }
Add minimum target browser versions
/** * WSO2 NOTES: * Add targets -> node -> current for test config * as per this comment https://github.com/babel/babel/issues/5085#issuecomment-363242788 * Add minimum browser compatibility for production builds as per https://babeljs.io/docs/en/babel-preset-env#targets * Related github issue: https://github.com/wso2/product-apim/issues/2661 */ module.exports = { env: { test: { presets: [ [ '@babel/preset-env', { targets: { node: 'current', }, }, ], '@babel/preset-react', ], plugins: [ '@babel/plugin-syntax-dynamic-import', '@babel/plugin-proposal-class-properties', 'dynamic-import-node', ], }, production: { presets: [ [ '@babel/preset-env', { targets: { chrome: '58', ie: '11', }, }, ], '@babel/preset-react', ], plugins: ['@babel/plugin-proposal-class-properties', '@babel/plugin-syntax-dynamic-import'], }, development: { presets: ['@babel/preset-env', '@babel/preset-react'], plugins: ['@babel/plugin-proposal-class-properties', '@babel/plugin-syntax-dynamic-import'], }, }, };
/** * Add targets -> node -> current as per this comment https://github.com/babel/babel/issues/5085#issuecomment-363242788 */ module.exports = { env: { test: { presets: [ [ '@babel/preset-env', { targets: { node: 'current' } } ], '@babel/preset-react' ], plugins: [ '@babel/plugin-syntax-dynamic-import', '@babel/plugin-proposal-class-properties', 'dynamic-import-node' ] }, production: { presets: ['@babel/preset-env', '@babel/preset-react'], plugins: [ '@babel/plugin-proposal-class-properties', '@babel/plugin-syntax-dynamic-import' ] }, development: { presets: ['@babel/preset-env', '@babel/preset-react'], plugins: [ '@babel/plugin-proposal-class-properties', '@babel/plugin-syntax-dynamic-import', ] } } };
Use loop.create_future if it exists
import asyncio from .protocol import Protocol __all__ = ('connect',) class Connection: def __init__(self, protocol, transport, loop): self._protocol = protocol self._transport = transport self._loop = loop def get_settings(self): return self._protocol.get_settings() async def query(self, query): waiter = _create_future(self._loop) self._protocol.query(query, waiter) return await waiter async def prepare(self, query): waiter = _create_future(self._loop) self._protocol.prepare(None, query, waiter) state = await waiter return PreparedStatement(self, state) class PreparedStatement: def __init__(self, connection, state): self._connection = connection self._state = state async def execute(self, *args): protocol = self._connection._protocol waiter = _create_future(self._connection._loop) protocol.execute(self._state, args, waiter) return await waiter async def connect(host='localhost', port=5432, user='postgres', *, loop=None): if loop is None: loop = asyncio.get_event_loop() connected = asyncio.Future(loop=loop) tr, pr = await loop.create_connection( lambda: Protocol(connected, user, loop), host, port) await connected return Connection(pr, tr, loop) def _create_future(loop): try: create_future = loop.create_future except AttributeError: return asyncio.Future(loop=loop) else: return create_future()
import asyncio from .protocol import Protocol __all__ = ('connect',) class Connection: def __init__(self, protocol, transport, loop): self._protocol = protocol self._transport = transport self._loop = loop def get_settings(self): return self._protocol.get_settings() async def query(self, query): waiter = asyncio.Future(loop=self._loop) self._protocol.query(query, waiter) return await waiter async def prepare(self, query): waiter = asyncio.Future(loop=self._loop) self._protocol.prepare(None, query, waiter) state = await waiter return PreparedStatement(self, state) class PreparedStatement: def __init__(self, connection, state): self._connection = connection self._state = state async def execute(self, *args): protocol = self._connection._protocol waiter = asyncio.Future(loop=self._connection._loop) protocol.execute(self._state, args, waiter) return await waiter async def connect(host='localhost', port=5432, user='postgres', *, loop=None): if loop is None: loop = asyncio.get_event_loop() connected = asyncio.Future(loop=loop) tr, pr = await loop.create_connection( lambda: Protocol(connected, user, loop), host, port) await connected return Connection(pr, tr, loop)
Use brackets for array declaration
<?php namespace Emergence\People; use HandleBehavior; class Invitation extends \ActiveRecord { public static $tableName = 'invitations'; public static $singularNoun = 'invitation'; public static $pluralNoun = 'invitations'; public static $fields = [ 'RecipientID' => [ 'type' => 'uint', 'index' => true ], 'Handle' => [ 'unique' => true ], 'Status' => [ 'type' => 'enum', 'values' => ['Pending', 'Used', 'Revoked'], 'default' => 'Pending' ], 'Expires' => [ 'type' => 'timestamp', 'notnull' => false ], 'Used' => [ 'type' => 'timestamp', 'notnull' => false ] ]; public static $relationships = [ 'Recipient' => [ 'type' => 'one-one', 'class' => Person::class ] ]; public function save($deep = true) { // set handle if (!$this->Handle) { $this->Handle = HandleBehavior::generateRandomHandle($this); } // call parent parent::save($deep); } }
<?php namespace Emergence\People; use HandleBehavior; class Invitation extends \ActiveRecord { public static $tableName = 'invitations'; public static $singularNoun = 'invitation'; public static $pluralNoun = 'invitations'; public static $fields = array( 'RecipientID' => [ 'type' => 'uint', 'index' => true ], 'Handle' => [ 'unique' => true ], 'Status' => [ 'type' => 'enum', 'values' => ['Pending', 'Used', 'Revoked'], 'default' => 'Pending' ], 'Expires' => [ 'type' => 'timestamp', 'notnull' => false ], 'Used' => [ 'type' => 'timestamp', 'notnull' => false ] ); public static $relationships = [ 'Recipient' => [ 'type' => 'one-one', 'class' => Person::class ] ]; public function save($deep = true) { // set handle if (!$this->Handle) { $this->Handle = HandleBehavior::generateRandomHandle($this); } // call parent parent::save($deep); } }
Update base view tests to use Jasmine
define(['views/base_view'], function (baseView) { jasmine.getFixtures().fixturesPath = 'tests/html_fixtures'; describe("BaseView", function () { beforeEach(function() { loadFixtures('components/base_view.html'); }); it("Test BaseView rendering of compiled template", function () { var test_model = new Backbone.Model({name: "Test"}), TestView = baseView.extend({ template_selector: "#milestone-table-heading", el: "#qunit-fixture" }), tv; tv = new TestView({model: test_model}); since("Correct selector"); expect(tv.template_selector).toEqual("#milestone-table-heading"); tv.render(); since("Rendered element contains model's data"); expect(tv.el.firstChild.innerHTML).toEqual("Test"); }); it("Test getTemplateData", function () { var test_model = new Backbone.Model({name: "Test"}), TestView = baseView.extend({ template_selector: "#milestone-table-heading", el: "#qunit-fixture", getTemplateData: function (data) { data.name = "Changed test"; return data; } }), tv; tv = new TestView({model: test_model}); tv.render(); since("Rendered element contains getTemplateData changes"); expect(tv.el.firstChild.innerHTML).toEqual("Changed test"); }); }); });
define(['views/base_view'], function (baseView) { var run = function () { module("BaseView"); test("Test BaseView rendering of compiled template", function () { var test_model = new Backbone.Model({name: "Test"}), TestView = baseView.extend({ template_selector: "#milestone-table-heading", el: "#qunit-fixture" }), tv; tv = new TestView({model: test_model}); equal(tv.template_selector, "#milestone-table-heading", "Correct selector"); tv.render(); equal(tv.el.firstChild.innerHTML, "Test", "Rendered element contains model's data"); }); test("Test getTemplateData", function () { var test_model = new Backbone.Model({name: "Test"}), TestView = baseView.extend({ template_selector: "#milestone-table-heading", el: "#qunit-fixture", getTemplateData: function (data) { data.name = "Changed test"; return data; } }), tv; tv = new TestView({model: test_model}); tv.render(); equal(tv.el.firstChild.innerHTML, "Changed test", "Rendered element contains getTemplateData changes"); }); }; return run; });
Convert gulp coverage spawnSyncs to chained spawns.
const gulp = require('gulp'); const spawn = require('child_process').spawn; gulp.task('test', function(cb) { let command = [ 'run', 'python', 'manage.py', 'test' ]; let args = process.argv; if (args[3] == '--test' && args[4]) { command.push(args[4]); } spawn( 'pipenv', command, { stdio: 'inherit' } ).on('exit', (code) => { process.exit(code); }); }); gulp.task('coverage', function() { spawn( 'pipenv', [ 'run', 'coverage', 'run', '--source=core,api', 'manage.py', 'test' ], { stdio: 'inherit' } ).on('exit', (code) => { if (code != 0) { process.exit(code); } spawn( 'pipenv', [ 'run', 'coverage', 'report', '-m' ], { stdio: 'inherit' } ).on('exit', (code) => { process.exit(code); }); }); });
const gulp = require('gulp'); const spawn = require('child_process').spawn; const spawnSync = require('child_process').spawnSync; gulp.task('test', function(cb) { let command = [ 'run', 'python', 'manage.py', 'test' ]; let args = process.argv; if (args[3] == '--test' && args[4]) { command.push(args[4]); } spawn( 'pipenv', command, { stdio: 'inherit' } ).on('exit', (code) => { process.exit(code); }); }); gulp.task('coverage', function() { spawnSync( 'pipenv', [ 'run', 'coverage', 'run', '--source=core,api', 'manage.py', 'test' ], { stdio: 'inherit' } ).on('exit', (code) => { process.exit(code); }); spawnSync( 'pipenv', [ 'run', 'coverage', 'report', '-m' ], { stdio: 'inherit' } ).on('exit', (code) => { process.exit(code); }); });
Allow reading static resources from jars
package j2html.tags; import java.io.FileInputStream; import java.io.InputStream; import java.util.Scanner; import j2html.Config; import static j2html.TagCreator.*; public class InlineStaticResource { public enum TargetFormat {CSS_MIN, CSS, JS_MIN, JS} public static ContainerTag get(String path, TargetFormat format) { String fileString = getFileAsString(path); switch (format) { case CSS_MIN : return style().with(rawHtml(Config.cssMinifier.minify(fileString))); case JS_MIN : return script().with(rawHtml(Config.jsMinifier.minify((fileString)))); case CSS : return style().with(rawHtml(fileString)); case JS : return script().with(rawHtml(fileString)); default : throw new RuntimeException("Invalid target format"); } } public static String getFileAsString(String path) { try { return streamToString(InlineStaticResource.class.getResourceAsStream(path)); } catch (Exception expected) { // we don't ask users to specify classpath or file-system try { return streamToString(new FileInputStream(path)); } catch (Exception exception) { throw new RuntimeException("Couldn't find file with path='" + path + "'"); } } } private static String streamToString(InputStream inputStream) { Scanner s = new Scanner(inputStream).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } }
package j2html.tags; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import j2html.Config; import j2html.utils.CSSMin; import j2html.utils.JSMin; import static j2html.TagCreator.*; public class InlineStaticResource { public enum TargetFormat {CSS_MIN, CSS, JS_MIN, JS} public static ContainerTag get(String path, TargetFormat format) { String fileString = getFileAsString(path); switch (format) { case CSS_MIN : return style().with(rawHtml(Config.cssMinifier.minify(fileString))); case JS_MIN : return script().with(rawHtml(Config.jsMinifier.minify((fileString)))); case CSS : return style().with(rawHtml(fileString)); case JS : return script().with(rawHtml(fileString)); default : throw new RuntimeException("Invalid target format"); } } public static String getFileAsString(String path) { try { return readFileAsString(InlineStaticResource.class.getResource(path).getPath()); } catch (Exception e1) { try { return readFileAsString(path); } catch (Exception e2) { throw new RuntimeException("Couldn't find file with path='" + path + "'"); } } } /** * @author kjheimark <3 */ private static String readFileAsString(String path) throws IOException { BufferedReader bufferedReader = new BufferedReader(new FileReader(path)); StringBuilder sb = new StringBuilder(); int c; while ((c = bufferedReader.read()) >= 0 && c >= 0) { sb.append((char) c); } return sb.toString(); } }
Throw better exceptions on invalid data
<?php namespace GraphiteAlert; use Guzzle\Http\Client; class GraphiteData { protected $config; protected $client; public function __construct($config) { $this->config = $config; $this->client = new Client($config['url']); } public function fetch($target, $lookback) { $args = [ 'target' => $target, 'format' => 'json', 'from' => "-{$lookback}min" ]; $request = $this->client->get('/render?'.http_build_query($args)) ->setAuth($this->config['user'], $this->config['pass'], 'Digest'); $r = $request->send(); $data = $r->json(); try { return $this->reformat($data); } catch(\Exception $e) { throw new \Exception("Unable to reformat $target", 0, $e); } } protected function reformat($data) { $out = array(); if (!isset($data[0]['datapoints'])) { var_dump($data); throw new \Exception("Bad data from graphite"); } foreach($data[0]['datapoints'] as $point) { if (is_null($point[0])) continue; $out[$point[1]] = $point[0]; } return $out; } }
<?php namespace GraphiteAlert; use Guzzle\Http\Client; class GraphiteData { protected $config; protected $client; public function __construct($config) { $this->config = $config; $this->client = new Client($config['url']); } public function fetch($target, $lookback) { $args = [ 'target' => $target, 'format' => 'json', 'from' => "-{$lookback}min" ]; $request = $this->client->get('/render?'.http_build_query($args)) ->setAuth($this->config['user'], $this->config['pass'], 'Digest'); $r = $request->send(); $data = $r->json(); return $this->reformat($data); } protected function reformat($data) { $out = array(); if (!isset($data[0]['datapoints'])) { var_dump($data); throw new \Exception("Bad data from graphite"); } foreach($data[0]['datapoints'] as $point) { if (is_null($point[0])) continue; $out[$point[1]] = $point[0]; } return $out; } }
Remove commented out console.log lines
class MCWorkflowGraphComponentController { /*@ngInject*/ constructor(processGraph, cyGraph) { this.processGraph = processGraph; this.cyGraph = cyGraph; this.state = { processes: [], samples: [], cy: null, }; } $onChanges(changes) { if (changes.processes) { this.state.processes = angular.copy(changes.processes.currentValue); this.drawWorkflow(); } } drawWorkflow() { let graph = this.processGraph.build(this.state.processes, []); this.state.samples = graph.samples; this.cy = this.cyGraph.createGraph(graph.elements, 'processesGraph'); this.setupOnClick(); } setupOnClick() { this.cy.on('click', event => { let target = event.cyTarget; if (target.isNode()) { let process = target.data('details'); this.onSetCurrentProcess({process: process}); } }); } } angular.module('materialscommons').component('mcWorkflowGraph', { controller: MCWorkflowGraphComponentController, template: require('./workflow-graph.html'), bindings: { processes: '<', onSetCurrentProcess: '&' } });
class MCWorkflowGraphComponentController { /*@ngInject*/ constructor(processGraph, cyGraph) { this.processGraph = processGraph; this.cyGraph = cyGraph; this.state = { processes: [], samples: [], cy: null, }; } $onChanges(changes) { if (changes.processes) { this.state.processes = angular.copy(changes.processes.currentValue); this.drawWorkflow(); } } drawWorkflow() { let graph = this.processGraph.build(this.state.processes, []); this.state.samples = graph.samples; this.cy = this.cyGraph.createGraph(graph.elements, 'processesGraph'); this.setupOnClick(); } setupOnClick() { this.cy.on('click', event => { // console.log('click event'); let target = event.cyTarget; if (target.isNode()) { // console.log(' isNode'); let process = target.data('details'); // console.log(' process', process); this.onSetCurrentProcess({process: process}); } }); } } angular.module('materialscommons').component('mcWorkflowGraph', { controller: MCWorkflowGraphComponentController, template: require('./workflow-graph.html'), bindings: { processes: '<', onSetCurrentProcess: '&' } });
Add graph node ordering test
"use strict"; define([ 'knockout3', 'lib/knockout-dependency-graph' ], function(ko, KoDependencyGraph) { describe('Functional tests', function () { describe('Basic usage', function () { it('Should track observable creation', function () { var graph = new KoDependencyGraph(ko); var observable = ko.observable(); expect(graph.nodes.length).toEqual(1); expect(graph.nodes[0].subscribable).toEqual(observable); }); it('Should track computed creation', function () { var graph = new KoDependencyGraph(ko); var computed = ko.computed(function () { return 1; }); expect(graph.nodes.length).toEqual(1); expect(graph.nodes[0].subscribable).toEqual(computed); }); it('Should track nodes in order of creation time', function () { var graph = new KoDependencyGraph(ko); var observable1 = ko.observable(); var observable2 = ko.observable(); var observable3 = ko.observable(); expect(graph.nodes.length).toEqual(3); expect(graph.nodes[0].subscribable).toEqual(observable1); expect(graph.nodes[1].subscribable).toEqual(observable2); expect(graph.nodes[2].subscribable).toEqual(observable3); }); xit('Should track dependencies between observables', function () { var graph = new KoDependencyGraph(ko); var observable = ko.observable(); var computed = ko.computed(function () { return observable(); }); expect(graph.nodes[0].subscribers).toEqual([computed]); expect(graph.nodes[1].subscriptions).toEqual([observable]); }); }); }); });
"use strict"; define([ 'knockout3', 'lib/knockout-dependency-graph' ], function(ko, KoDependencyGraph) { describe('Functional tests', function () { describe('Basic usage', function () { it('Should track observable creation', function () { var graph = new KoDependencyGraph(ko); var observable = ko.observable(); expect(graph.nodes.length).toEqual(1); expect(graph.nodes[0].subscribable).toEqual(observable); }); it('Should track computed creation', function () { var graph = new KoDependencyGraph(ko); var computed = ko.computed(function () { return 1; }); expect(graph.nodes.length).toEqual(1); expect(graph.nodes[0].subscribable).toEqual(computed); }); xit('Should track dependencies between observables', function () { var graph = new KoDependencyGraph(ko); var observable = ko.observable(); var computed = ko.computed(function () { return observable(); }); expect(graph.nodes[0].subscribers).toEqual([computed]); expect(graph.nodes[1].subscriptions).toEqual([observable]); }); }); }); });
Check stopped torrents when cleaning
import datetime import textwrap import transmissionrpc from axel import config from axel import pb_notify def clean(): transmission_client = transmissionrpc.Client( config['transmission']['host'], port=config['transmission']['port'] ) torrents = transmission_client.get_torrents() now = datetime.datetime.now() time_threshold = config['transmission']['time_threshold'] for torrent in torrents: if torrent.status in ('seeding', 'stopped'): done = torrent.date_done diff = now - done if diff.days >= time_threshold: pb_notify( textwrap.dedent( ''' Torrent {torrent} older than {days} days: removing (with data) '''.format(torrent=torrent.name, days=time_threshold) ).strip() ) transmission_client.remove_torrent( torrent.id, delete_data=True ) elif torrent.ratio >= config['transmission']['ratio_threshold']: pb_notify( textwrap.dedent( ''' Torrent {0} reached threshold ratio or higher: removing (with data) '''.format(torrent.name) ).strip() ) transmission_client.remove_torrent( torrent.id, delete_data=True )
import datetime import textwrap import transmissionrpc from axel import config from axel import pb_notify def clean(): transmission_client = transmissionrpc.Client( config['transmission']['host'], port=config['transmission']['port'] ) torrents = transmission_client.get_torrents() now = datetime.datetime.now() time_threshold = config['transmission']['time_threshold'] for torrent in torrents: if torrent.status == 'seeding': done = torrent.date_done diff = now - done if diff.days >= time_threshold: # TODO: Use pb_notify instead pb_notify( textwrap.dedent( ''' Torrent {torrent} older than {days} days: removing (with data) '''.format(torrent=torrent.name, days=time_threshold) ).strip() ) transmission_client.remove_torrent( torrent.id, delete_data=True ) elif torrent.ratio >= config['transmission']['ratio_threshold']: pb_notify( textwrap.dedent( ''' Torrent {0} reached threshold ratio or higher: removing (with data) '''.format(torrent.name) ).strip() ) transmission_client.remove_torrent( torrent.id, delete_data=True )
Remove header from top 500 domains in examples
<?php require __DIR__ . "/../vendor/autoload.php"; use Amp\Dns; use Amp\Loop; print "Downloading top 500 domains..." . PHP_EOL; $domains = file_get_contents("https://moz.com/top500/domains/csv"); $domains = array_map(function ($line) { return trim(explode(",", $line)[1], '"/'); }, array_filter(explode("\n", $domains))); // Remove "URL" header array_shift($domains); Loop::run(function () use ($domains) { print "Starting sequential queries..." . PHP_EOL; $timings = []; for ($i = 0; $i < 10; $i++) { $start = microtime(1); $domain = $domains[mt_rand(0, count($domains) - 1)]; print $domain . ": "; try { $records = yield Dns\resolve($domain); $records = array_map(function ($record) { return $record->getValue(); }, $records); print implode(", ", $records); } catch (Dns\ResolutionException $e) { print get_class($e); } $time = round(microtime(1) - $start, 2); $timings[] = $time; print " in " . $time . " ms" . PHP_EOL; } print PHP_EOL; print (array_sum($timings) / count($timings)) . " ms for an average query." . PHP_EOL; });
<?php require __DIR__ . "/../vendor/autoload.php"; use Amp\Dns; use Amp\Loop; print "Downloading top 500 domains..." . PHP_EOL; $domains = file_get_contents("https://moz.com/top500/domains/csv"); $domains = array_map(function ($line) { return trim(explode(",", $line)[1], '"/'); }, array_filter(explode("\n", $domains))); Loop::run(function () use ($domains) { print "Starting sequential queries..." . PHP_EOL; $timings = []; for ($i = 0; $i < 10; $i++) { $start = microtime(1); $domain = $domains[mt_rand(0, count($domains) - 1)]; print $domain . ": "; try { $records = yield Dns\resolve($domain); $records = array_map(function ($record) { return $record->getValue(); }, $records); print implode(", ", $records); } catch (Dns\ResolutionException $e) { print get_class($e); } $time = round(microtime(1) - $start, 2); $timings[] = $time; print " in " . $time . " ms" . PHP_EOL; } print PHP_EOL; print (array_sum($timings) / count($timings)) . " ms for an average query." . PHP_EOL; });
Hide preferences button for now.
from gi.repository import Gio, Gtk from rsr.commands import commands class HeaderBar(Gtk.HeaderBar): def __init__(self, win): super(HeaderBar, self).__init__() self.win = win self.set_show_close_button(True) self.set_title('RunSQLRun') self.set_subtitle('Database query tool') self.pack_start(self._btn_from_command('app', 'neweditor')) self.pack_start(self._btn_from_command('editor', 'run')) # btn = Gtk.Button() # icon = Gio.ThemedIcon(name="preferences-system-symbolic") # image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON) # btn.add(image) # self.pack_end(btn) def _btn_from_command(self, group, name): btn = Gtk.Button() btn.set_action_name('app.{}_{}'.format(group, name)) data = commands[group]['actions'][name] icon = Gio.ThemedIcon(name=data['icon']) image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON) btn.add(image) btn.set_tooltip_text('{} [{}]'.format( data['description'], data['shortcut'])) return btn def on_button_add_clicked(self, *args): self.win.docview.add_worksheet()
from gi.repository import Gio, Gtk from rsr.commands import commands class HeaderBar(Gtk.HeaderBar): def __init__(self, win): super(HeaderBar, self).__init__() self.win = win self.set_show_close_button(True) self.set_title('RunSQLRun') self.set_subtitle('Database query tool') self.pack_start(self._btn_from_command('app', 'neweditor')) self.pack_start(self._btn_from_command('editor', 'run')) btn = Gtk.Button() icon = Gio.ThemedIcon(name="preferences-system-symbolic") image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON) btn.add(image) self.pack_end(btn) def _btn_from_command(self, group, name): btn = Gtk.Button() btn.set_action_name('app.{}_{}'.format(group, name)) data = commands[group]['actions'][name] icon = Gio.ThemedIcon(name=data['icon']) image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON) btn.add(image) btn.set_tooltip_text('{} [{}]'.format( data['description'], data['shortcut'])) return btn def on_button_add_clicked(self, *args): self.win.docview.add_worksheet()
Set the route for text wallposts to the model passed as a parameter
App.WallRouteMixin = Em.Mixin.create({ parentId: Em.K(), parentType: Em.K(), // This way the ArrayController won't hold an immutable array thus it can be extended with more wallposts. setupController: function(controller, model) { // Only reload wall-posts if switched to another project. var parentId = this.get('parentId'); var parentType = this.get('parentType'); if (controller.get('parentId') != parentId){ controller.set('page', 1); controller.set('parentId', parentId); var route = this; var mediaWallPostNewController = this.controllerFor('mediaWallPostNew'); var textWallPostNewController = this.controllerFor('textWallPostNew'); var store = this.get('store'); store.find('wallPost', {'parent_type': parentType, 'parent_id': parentId}).then(function(items){ controller.set('meta', items.get('meta')); controller.set('model', items.toArray()); // Set some variables for WallPostNew controllers model = controller.get('model'); mediaWallPostNewController.set('parentId', parentId); mediaWallPostNewController.set('parentType', parentType); mediaWallPostNewController.set('wallPostList', model); textWallPostNewController.set('parentId', parentId); textWallPostNewController.set('parentType', parentType); textWallPostNewController.set('wallPostList', model); }); } } });
App.WallRouteMixin = Em.Mixin.create({ parentId: Em.K(), parentType: Em.K(), // This way the ArrayController won't hold an immutable array thus it can be extended with more wallposts. setupController: function(controller, model) { // Only reload wall-posts if switched to another project. var parentId = this.get('parentId'); var parentType = this.get('parentType'); if (controller.get('parentId') != parentId){ controller.set('page', 1); controller.set('parentId', parentId); var route = this; var mediaWallPostNewController = this.controllerFor('mediaWallPostNew'); var textWallPostNewController = this.controllerFor('textWallPostNew'); var store = this.get('store'); store.find('wallPost', {'parent_type': parentType, 'parent_id': parentId}).then(function(items){ controller.set('meta', items.get('meta')); controller.set('model', items.toArray()); // Set some variables for WallPostNew controllers model = controller.get('model'); mediaWallPostNewController.set('parentId', parentId); mediaWallPostNewController.set('parentType', parentType); mediaWallPostNewController.set('wallPostList', model); textWallPostNewController.set('parentId', parentId); textWallPostNewController.set('parentType', 'task'); textWallPostNewController.set('wallPostList', model); }); } } });
Change code to use array_helper
<?php namespace Laravel\Socialite\Two; use Symfony\Component\HttpFoundation\RedirectResponse; class GithubProvider extends AbstractProvider implements ProviderInterface { /** * The scopes being requested. * * @var array */ protected $scopes = ['user:email']; /** * {@inheritdoc} */ protected function getAuthUrl($state) { return $this->buildAuthUrlFromBase('https://github.com/login/oauth/authorize', $state); } /** * {@inheritdoc} */ protected function getTokenUrl() { return 'https://github.com/login/oauth/access_token'; } /** * {@inheritdoc} */ protected function getUserByToken($token) { $response = $this->getHttpClient()->get('https://api.github.com/user?access_token='.$token, [ 'headers' => [ 'Accept' => 'application/vnd.github.v3+json', ], ]); return json_decode($response->getBody(), true); } /** * {@inheritdoc} */ protected function mapUserToObject(array $user) { return (new User)->setRaw($user)->map([ 'id' => $user['id'], 'nickname' => $user['login'], 'name' => array_get($user, 'name'), 'email' => array_get($user, 'email'), 'avatar' => $user['avatar_url'], ]); } }
<?php namespace Laravel\Socialite\Two; use Symfony\Component\HttpFoundation\RedirectResponse; class GithubProvider extends AbstractProvider implements ProviderInterface { /** * The scopes being requested. * * @var array */ protected $scopes = ['user:email']; /** * {@inheritdoc} */ protected function getAuthUrl($state) { return $this->buildAuthUrlFromBase('https://github.com/login/oauth/authorize', $state); } /** * {@inheritdoc} */ protected function getTokenUrl() { return 'https://github.com/login/oauth/access_token'; } /** * {@inheritdoc} */ protected function getUserByToken($token) { $response = $this->getHttpClient()->get('https://api.github.com/user?access_token='.$token, [ 'headers' => [ 'Accept' => 'application/vnd.github.v3+json', ], ]); return json_decode($response->getBody(), true); } /** * {@inheritdoc} */ protected function mapUserToObject(array $user) { return (new User)->setRaw($user)->map([ 'id' => $user['id'], 'nickname' => $user['login'], 'name' => array_get($user, 'name'), 'email' => isset($user['email']) ? $user['email'] : null, 'avatar' => $user['avatar_url'], ]); } }
Remove referencing Backbone.Model's attributes internal structure We should *never* use `attributes` as it violates the contract Models: http://backbonejs.org/#Model-attributes The contract of a Backbone.Model is that you access the properties held in it via `.get('attr-name')` Here, I mean for properties & attributes to be synomyms. You can see the Backbone docs warn about this in relate to setting an attribute for a Model: ``` Please use set to update the attributes instead of modifying them directly. ``` source: http://backbonejs.org/#Model-attributes
import React from 'react/addons'; import Backbone from 'backbone'; import Router from 'react-router'; import stores from 'stores'; import Stats from './Stats.react'; export default React.createClass({ displayName: "ProvidersList", render: function () { let providers = this.props.providers; let ProviderCards = providers.map(function(provider) { return ( <li key={provider.get('id')}> <div className="media card" > <Router.Link to="provider" params={{id: provider.get('id')}}> <div className="media__content"> <h2 className="title-3"> {provider.get('name')} </h2> <p className="media__description"> {provider.get('description')} </p> <hr/> <Stats provider={provider} /> </div> </Router.Link> </div> </li> ); }); return ( <ul className="app-card-list"> {ProviderCards} </ul> ); } });
import React from 'react/addons'; import Backbone from 'backbone'; import Router from 'react-router'; import stores from 'stores'; import Stats from './Stats.react'; export default React.createClass({ displayName: "ProvidersList", render: function () { let providers = this.props.providers; let ProviderCards = providers.map(function(item) { let provider = item.attributes; return ( <li key={provider.id}> <div className="media card" > <Router.Link to = "provider" params = {{id: provider.id}} > <div className="media__content" > <h2 className="title-3" > {provider.name} </h2> <p className="media__description" > {provider.description} </p> <hr/> <Stats provider={provider} /> </div> </Router.Link> </div> </li> ); }); return ( <ul className="app-card-list" > {ProviderCards} </ul> ); } });
Hide splash when needed (when running install)
<?php namespace Bluora\LaravelDatasets\Traits; trait CommandTrait { public function splash($text, $hide_splash = false) { if (!$hide_splash) { $this->line(''); $this->line(' ___ _ _ _ _ __ _ '); $this->line(' / \ __ _ | |_ __ _ ___ ___ | |_ ___ | || | / / __ _ _ __ __ _ __ __ ___ | |'); $this->line(" / /\ // _` || __|/ _` |/ __| / _ \| __|/ __|| || |_ / / / _` || '__|/ _` |\ \ / // _ \| |"); $this->line(' / /_//| (_| || |_| (_| |\__ \| __/| |_ \__ \|__ _|/ /___| (_| || | | (_| | \ V /| __/| |'); $this->line("/___,' \__,_| \__|\__,_||___/ \___| \__||___/ |_| \____/ \__,_||_| \__,_| \_/ \___||_|"); $this->line(''); $this->line(' By H&H|Digital'); $this->line(''); $this->line($text); $this->line(''); } } }
<?php namespace Bluora\LaravelDatasets\Traits; trait CommandTrait { public function splash($text) { $this->line(''); $this->line(' ___ _ _ _ _ __ _ '); $this->line(' / \ __ _ | |_ __ _ ___ ___ | |_ ___ | || | / / __ _ _ __ __ _ __ __ ___ | |'); $this->line(" / /\ // _` || __|/ _` |/ __| / _ \| __|/ __|| || |_ / / / _` || '__|/ _` |\ \ / // _ \| |"); $this->line(' / /_//| (_| || |_| (_| |\__ \| __/| |_ \__ \|__ _|/ /___| (_| || | | (_| | \ V /| __/| |'); $this->line("/___,' \__,_| \__|\__,_||___/ \___| \__||___/ |_| \____/ \__,_||_| \__,_| \_/ \___||_|"); $this->line(''); $this->line(' By H&H|Digital'); $this->line(''); $this->line($text.'.'); $this->line(''); } }
Enable HTTPS for localhost dev
const gulp = require('gulp'), browserSync = require('browser-sync').get('PGR2015'), inject = require('gulp-inject'), modRewrite = require('connect-modrewrite'), wiredep = require('wiredep').stream; module.exports = function () { browserSync.init({ server: { baseDir: ['./.tmp'], middleware: [ modRewrite([ '^[^\\.]*$ /index.html [L]' ]) ] }, open: false, https: true }); gulp.src('app/components/**/*').pipe(gulp.dest('.tmp/components')); gulp.src('app/index.html') .pipe(inject(gulp.src('.tmp/*.js'), { ignorePath: '.tmp/' })) .pipe(wiredep()) .pipe(gulp.dest('.tmp')); gulp.watch(['app/*.ts', 'app/modules/**/*.ts'], ['ts-watch:serve']); gulp.watch(['app/modules/**/*.html'], ['html-watch:serve']); gulp.watch(['app/styles/*.scss', 'app/modules/**/*.scss'], ['scss-watch:serve']); gulp.watch(['.tmp/*.js', '.tmp/**/*.html'], function () { browserSync.reload(); }); };
const gulp = require('gulp'), browserSync = require('browser-sync').get('PGR2015'), inject = require('gulp-inject'), modRewrite = require('connect-modrewrite'), wiredep = require('wiredep').stream; module.exports = function () { browserSync.init({ server: { baseDir: ['./.tmp'], middleware: [ modRewrite([ '^[^\\.]*$ /index.html [L]' ]) ] }, open: false }); gulp.src('app/components/**/*').pipe(gulp.dest('.tmp/components')); gulp.src('app/index.html') .pipe(inject(gulp.src('.tmp/*.js'), { ignorePath: '.tmp/' })) .pipe(wiredep()) .pipe(gulp.dest('.tmp')); gulp.watch(['app/*.ts', 'app/modules/**/*.ts'], ['ts-watch:serve']); gulp.watch(['app/modules/**/*.html'], ['html-watch:serve']); gulp.watch(['app/styles/*.scss', 'app/modules/**/*.scss'], ['scss-watch:serve']); gulp.watch(['.tmp/*.js', '.tmp/**/*.html'], function () { browserSync.reload(); }); };
Paste job definition to clipboard as text and not as HTML. Change-Id: I158ee4527d74d8cbd03c90d83398c9a6b5a9e2dd
create_tmp_element = function (text) { // create temporary textarea in order to copy it's contents. var tmp_element = $('<textarea />'); tmp_element.css("fontSize", "12pt"); tmp_element.css("border", "0"); tmp_element.css("padding", "0"); tmp_element.css("margin", "0"); // Move element out of screen tmp_element.css("position", "absolute"); tmp_element.css("left", "-9999px"); var yPosition = window.pageYOffset || document.documentElement.scrollTop; tmp_element.on("focus", window.scrollTo(0, yPosition)); tmp_element.css("top", yPosition + "px"); tmp_element.attr("readonly", ""); tmp_element.val(text); $("body").append(tmp_element); return tmp_element; } $(document).ready( function() { $("#copy_link").on("click", function() { tmp_element = create_tmp_element($("#job_definition_text").text()); tmp_element.select(); try { var success = document.execCommand('copy'); if (!success) { console.log('Copying job definition was unsuccessful'); } } catch (error) { console.log( 'Not able to copy job definition to clipboard. ' + error); } finally { tmp_element.remove(); } }); } );
create_tmp_element = function (text) { // create temporary textarea in order to copy it's contents. var tmp_element = $('<textarea />'); tmp_element.css("fontSize", "12pt"); tmp_element.css("border", "0"); tmp_element.css("padding", "0"); tmp_element.css("margin", "0"); // Move element out of screen tmp_element.css("position", "absolute"); tmp_element.css("left", "-9999px"); var yPosition = window.pageYOffset || document.documentElement.scrollTop; tmp_element.on("focus", window.scrollTo(0, yPosition)); tmp_element.css("top", yPosition + "px"); tmp_element.attr("readonly", ""); tmp_element.val(text); $("body").append(tmp_element); return tmp_element; } $(document).ready( function() { $("#copy_link").on("click", function() { tmp_element = create_tmp_element($("#job_definition_text").html()); tmp_element.select(); try { var success = document.execCommand('copy'); if (!success) { console.log('Copying job definition was unsuccessful'); } } catch (error) { console.log( 'Not able to copy job definition to clipboard. ' + error); } finally { tmp_element.remove(); } }); } );
BAP-10874: Apply select2-autocomplete component for field Organization Structure of form create/edit user
<?php namespace Oro\Bundle\OrganizationBundle\EventListener; use Oro\Bundle\SearchBundle\Event\IndexerPrepareQueryEvent; use Oro\Bundle\SecurityBundle\SecurityFacade; class IndexerPrepareQueryListener { const BUSINESS_UNIT_STRUCTURE_ORGANIZATION = 'business_units_search_handler'; /** @var SecurityFacade */ protected $securityFacade; /** * IndexerPrepareQueryListener constructor. * * @param SecurityFacade $securityFacade */ public function __construct( SecurityFacade $securityFacade ) { $this->securityFacade = $securityFacade; } /** * @param IndexerPrepareQueryEvent $event */ public function updateQuery(IndexerPrepareQueryEvent $event) { if ($event->getSearchHandlerState() === static::BUSINESS_UNIT_STRUCTURE_ORGANIZATION) { $user = $this->securityFacade->getLoggedUser(); if ($user) { $organizations = $user->getOrganizations(); $organizationsId = []; foreach ($organizations as $organization) { $organizationsId[] = $organization->getId(); } $query = $event->getQuery(); $expr = $query->getCriteria()->expr(); $query->getCriteria()->andWhere( $expr->in('integer.organization', $organizationsId) ); } } } }
<?php namespace Oro\Bundle\OrganizationBundle\EventListener; use Oro\Bundle\SearchBundle\Event\IndexerPrepareQueryEvent; use Oro\Bundle\SecurityBundle\SecurityFacade; class IndexerPrepareQueryListener { const BUSINESS_UNIT_STRUCTURE_ORGANIZATION = 'business_units_search_handler'; /** @var SecurityFacade */ protected $securityFacade; public function __construct( SecurityFacade $securityFacade ) { $this->securityFacade = $securityFacade; } public function updateQuery(IndexerPrepareQueryEvent $event) { if ($event->getSearchHandlerState() === static::BUSINESS_UNIT_STRUCTURE_ORGANIZATION) { $user = $this->securityFacade->getLoggedUser(); if ($user) { $organizations = $user->getOrganizations(); $organizationsId = []; foreach ($organizations as $organization) { $organizationsId[] = $organization->getId(); } $query = $event->getQuery(); $expr = $query->getCriteria()->expr(); $query->getCriteria()->andWhere( $expr->in('integer.organization', $organizationsId) ); } } } }
Fix default values of Argument Parser
# -*- coding: utf-8 -*- from queries import Grok def print_monthly_views(site, pages, year, month): grok = Grok(site) for page in pages: result = grok.get_views_for_month(page, year, month) print result['daily_views'] def main(): """ main script. """ from argparse import ArgumentParser description = 'Extract traffic statistics of Wikipedia articles.' parser = ArgumentParser(description=description) parser.add_argument("-l", "--lang", type=str, dest="lang", default="en", required=False, help="Language code for Wikipedia") parser.add_argument("-y", "--year", type=int, dest="year", required=False, help="Year") parser.add_argument("-m", "--month", type=int, dest="month", required=False, help="Month") parser.add_argument("page", nargs='*', metavar="PAGE", help='A list of pages') args = parser.parse_args() print_monthly_views(args.lang, args.page, args.year, args.month) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- from queries import Grok def print_monthly_views(site, pages, year, month): grok = Grok(site) for page in pages: result = grok.get_views_for_month(page, year, month) print result['daily_views'] def main(): """ main script. """ from argparse import ArgumentParser description = 'Extract traffic statistics of Wikipedia articles.' parser = ArgumentParser(description=description) parser.add_argument("-l", "--lang", type=str, dest="lang", default="en", required=True, help="Language code for Wikipedia") parser.add_argument("-y", "--year", type=int, dest="year", default="en", required=True, help="Year") parser.add_argument("-m", "--month", type=int, dest="month", default="en", required=True, help="Month") parser.add_argument("page", nargs='*', metavar="PAGE", help='A list of pages') args = parser.parse_args() print_monthly_views(args.lang, args.page, args.year, args.month) if __name__ == '__main__': main()
Fix the displayed error message in V2 API Change-Id: I07c3f1ed79fa507dbe9b76eb8f5964475516754c
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from designate.objects import base class ValidationError(base.DesignateObject): FIELDS = { 'path': {}, 'message': {}, 'validator': {}, 'validator_value': {}, 'raw': {}, } @classmethod def from_js_error(cls, js_error): """Convert a JSON Schema ValidationError instance into a ValidationError instance. """ e = cls() e.path = list(getattr(js_error, 'releative_path', js_error.path)) e.message = js_error.message e.validator = js_error.validator e.validator_value = js_error.validator_value e.raw = js_error._contents() return e class ValidationErrorList(base.ListObjectMixin, base.DesignateObject): LIST_ITEM_TYPE = ValidationError
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import six from designate.objects import base class ValidationError(base.DesignateObject): FIELDS = { 'path': {}, 'message': {}, 'validator': {}, 'validator_value': {}, 'raw': {}, } @classmethod def from_js_error(cls, js_error): """Convert a JSON Schema ValidationError instance into a ValidationError instance. """ e = cls() e.path = list(getattr(js_error, 'releative_path', js_error.path)) e.message = six.text_type(js_error) e.validator = js_error.validator e.validator_value = js_error.validator_value e.raw = js_error._contents() return e class ValidationErrorList(base.ListObjectMixin, base.DesignateObject): LIST_ITEM_TYPE = ValidationError
Return `value` as `null` when done. Closes #75.
module.exports = function (paginator, filter) { const iterator = paginator[Symbol.asyncIterator]() let done = false return { [Symbol.asyncIterator]: function () { return this }, next: async function () { if (done) { return { done: true, value: null } } const next = await iterator.next() if (next.done) { return { done: true, value: null } } const gathered = [] ITEMS: for (const item of next.value) { switch (filter(item)) { case -1: break case 0: gathered.push(item) break case 1: done = true break ITEMS } } return { done: false, value: gathered } } } }
module.exports = function (paginator, filter) { const iterator = paginator[Symbol.asyncIterator]() let done = false return { [Symbol.asyncIterator]: function () { return this }, next: async function () { if (done) { return { done: true } } const next = await iterator.next() if (next.done) { return { done: true } } const gathered = [] ITEMS: for (const item of next.value) { switch (filter(item)) { case -1: break case 0: gathered.push(item) break case 1: done = true break ITEMS } } return { done: false, value: gathered } } } }
Remove Risky warning in Tests
<?php /** * Novactive Collection. * * @author Luke Visinoni <[email protected], [email protected]> * @author Sébastien Morel <[email protected], [email protected]> * @copyright 2017 Novactive * @license MIT */ declare(strict_types=1); namespace Novactive\Tests; use Novactive\Collection\Factory; class ZipCollectionTest extends UnitTestCase { public function testZipCollection(): void { $names = Factory::create($this->fixtures['names'])->keep(0, 3); if (!$names instanceof Perfs\ArrayMethodCollection) { $zip = $names->zip(Factory::create($this->fixtures['array'])); $expected = [ ['Chelsea', 'first'], ['Adella', 'second'], ['Monte', 'third'], ]; $this->assertEquals($expected, $zip->toArray()); } $this->assertTrue(true); } public function testNotZipCollection(): void { $names = Factory::create($this->fixtures['names'])->keep(0, 3); if (!$names instanceof Perfs\ArrayMethodCollection) { $zip = $names->zip(Factory::create($this->fixtures['array'])); $expected = [ ['Chelsea', 'firdst'], ['Adella', 'secodnd'], ['Monte', 'thidrd'], ]; $this->assertNotEquals($expected, $zip->toArray()); } $this->assertTrue(true); } }
<?php /** * Novactive Collection. * * @author Luke Visinoni <[email protected], [email protected]> * @author Sébastien Morel <[email protected], [email protected]> * @copyright 2017 Novactive * @license MIT */ declare(strict_types=1); namespace Novactive\Tests; use Novactive\Collection\Factory; class ZipCollectionTest extends UnitTestCase { public function testZipCollection(): void { $names = Factory::create($this->fixtures['names'])->keep(0, 3); if (!$names instanceof Perfs\ArrayMethodCollection) { $zip = $names->zip(Factory::create($this->fixtures['array'])); $expected = [ ['Chelsea', 'first'], ['Adella', 'second'], ['Monte', 'third'], ]; $this->assertEquals($expected, $zip->toArray()); } } public function testNotZipCollection(): void { $names = Factory::create($this->fixtures['names'])->keep(0, 3); if (!$names instanceof Perfs\ArrayMethodCollection) { $zip = $names->zip(Factory::create($this->fixtures['array'])); $expected = [ ['Chelsea', 'firdst'], ['Adella', 'secodnd'], ['Monte', 'thidrd'], ]; $this->assertNotEquals($expected, $zip->toArray()); } } }
Clear queries list instead of overwriting it.
import functools import unicodedata from django.core.cache import get_cache from django.conf import settings def normalize_unicode(u): """Replace non-ASCII characters with closest ASCII equivalents where possible. """ return unicodedata.normalize('NFKD', u).encode('ascii', 'ignore') def cache_result(cache_key, timeout): """A decorator for caching the result of a function.""" def decorator(f): cache_name = settings.WAFER_CACHE @functools.wraps(f) def wrapper(*args, **kw): # replace this with cache.caches when we drop Django 1.6 # compatibility cache = get_cache(cache_name) result = cache.get(cache_key) if result is None: result = f(*args, **kw) cache.set(cache_key, result, timeout) return result def invalidate(): cache = get_cache(cache_name) cache.delete(cache_key) wrapper.invalidate = invalidate return wrapper return decorator class QueryTracker(object): """ Track queries to database. """ def __enter__(self): from django.conf import settings from django.db import connection self._debug = settings.DEBUG settings.DEBUG = True del connection.queries[:] return self def __exit__(self, *args, **kw): from django.conf import settings settings.DEBUG = self._debug @property def queries(self): from django.db import connection return connection.queries[:]
import functools import unicodedata from django.core.cache import get_cache from django.conf import settings def normalize_unicode(u): """Replace non-ASCII characters with closest ASCII equivalents where possible. """ return unicodedata.normalize('NFKD', u).encode('ascii', 'ignore') def cache_result(cache_key, timeout): """A decorator for caching the result of a function.""" def decorator(f): cache_name = settings.WAFER_CACHE @functools.wraps(f) def wrapper(*args, **kw): # replace this with cache.caches when we drop Django 1.6 # compatibility cache = get_cache(cache_name) result = cache.get(cache_key) if result is None: result = f(*args, **kw) cache.set(cache_key, result, timeout) return result def invalidate(): cache = get_cache(cache_name) cache.delete(cache_key) wrapper.invalidate = invalidate return wrapper return decorator class QueryTracker(object): """ Track queries to database. """ def __enter__(self): from django.conf import settings from django.db import connection self._debug = settings.DEBUG settings.DEBUG = True connection.queries = [] return self def __exit__(self, *args, **kw): from django.conf import settings settings.DEBUG = self._debug @property def queries(self): from django.db import connection return connection.queries[:]
Fix diffing on Py3 by comparing unicode strings
# coding=utf-8 from __future__ import unicode_literals from io import BytesIO from .marc import Record from .util import etree, parse_xml, show_diff class Bib(object): """ An Alma Bib record """ def __init__(self, alma, xml): self.alma = alma self.orig_xml = xml self.init(xml) def init(self, xml): self.doc = parse_xml(xml) self.mms_id = self.doc.findtext('mms_id') self.marc_record = Record(self.doc.find('record')) self.cz_link = self.doc.findtext('linked_record_id[@type="CZ"]') or None def save(self, diff=False, dry_run=False): # Save record back to Alma post_data = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' + etree.tounicode(self.doc)) if diff: show_diff(self.orig_xml, post_data) if not dry_run: response = self.alma.put('/bibs/{}'.format(self.mms_id), data=BytesIO(post_data.encode('utf-8')), headers={'Content-Type': 'application/xml'}) self.init(response) def dump(self, filename): # Dump record to file with open(filename, 'wb') as f: f.write(etree.tostring(self.doc, pretty_print=True))
# coding=utf-8 from __future__ import unicode_literals from io import BytesIO from .marc import Record from .util import etree, parse_xml, show_diff class Bib(object): """ An Alma Bib record """ def __init__(self, alma, xml): self.alma = alma self.orig_xml = xml.encode('utf-8') self.init(xml) def init(self, xml): self.doc = parse_xml(xml) self.mms_id = self.doc.findtext('mms_id') self.marc_record = Record(self.doc.find('record')) self.cz_link = self.doc.findtext('linked_record_id[@type="CZ"]') or None def save(self, diff=False, dry_run=False): # Save record back to Alma post_data = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'.encode('utf-8') + etree.tostring(self.doc, encoding='UTF-8')) if diff: show_diff(self.orig_xml, post_data) if not dry_run: response = self.alma.put('/bibs/{}'.format(self.mms_id), data=BytesIO(post_data), headers={'Content-Type': 'application/xml'}) self.init(response) def dump(self, filename): # Dump record to file with open(filename, 'wb') as f: f.write(etree.tostring(self.doc, pretty_print=True))
Fix required value prop failing on null values
import AdvancedSelect, { propTypes as advancedSelectPropTypes } from "components/advancedSelectWidget/AdvancedSelect" import { AdvancedSingleSelectOverlayTable } from "components/advancedSelectWidget/AdvancedSelectOverlayTable" import * as FieldHelper from "components/FieldHelper" import _isEmpty from "lodash/isEmpty" import PropTypes from "prop-types" import React from "react" import REMOVE_ICON from "resources/delete.png" const AdvancedSingleSelect = props => { return ( <AdvancedSelect {...props} handleAddItem={handleAddItem} handleRemoveItem={handleRemoveItem} closeOverlayOnAdd selectedValueAsString={ !_isEmpty(props.value) ? props.value[props.valueKey] : "" } extraAddon={ props.showRemoveButton && !_isEmpty(props.value) ? ( <img style={{ cursor: "pointer" }} src={REMOVE_ICON} height={16} alt="" onClick={handleRemoveItem} /> ) : null } /> ) function handleAddItem(newItem) { FieldHelper.handleSingleSelectAddItem(newItem, props.onChange) } function handleRemoveItem(oldItem) { FieldHelper.handleSingleSelectRemoveItem(oldItem, props.onChange) } } AdvancedSingleSelect.propTypes = { ...advancedSelectPropTypes, value: PropTypes.object, valueKey: PropTypes.string } AdvancedSingleSelect.defaultProps = { value: {}, overlayTable: AdvancedSingleSelectOverlayTable, showRemoveButton: true // whether to display a remove button in the input field to allow removing the selected value } export default AdvancedSingleSelect
import AdvancedSelect, { propTypes as advancedSelectPropTypes } from "components/advancedSelectWidget/AdvancedSelect" import { AdvancedSingleSelectOverlayTable } from "components/advancedSelectWidget/AdvancedSelectOverlayTable" import * as FieldHelper from "components/FieldHelper" import _isEmpty from "lodash/isEmpty" import PropTypes from "prop-types" import React from "react" import REMOVE_ICON from "resources/delete.png" const AdvancedSingleSelect = props => { return ( <AdvancedSelect {...props} handleAddItem={handleAddItem} handleRemoveItem={handleRemoveItem} closeOverlayOnAdd selectedValueAsString={ !_isEmpty(props.value) ? props.value[props.valueKey] : "" } extraAddon={ props.showRemoveButton && !_isEmpty(props.value) ? ( <img style={{ cursor: "pointer" }} src={REMOVE_ICON} height={16} alt="" onClick={handleRemoveItem} /> ) : null } /> ) function handleAddItem(newItem) { FieldHelper.handleSingleSelectAddItem(newItem, props.onChange) } function handleRemoveItem(oldItem) { FieldHelper.handleSingleSelectRemoveItem(oldItem, props.onChange) } } AdvancedSingleSelect.propTypes = { ...advancedSelectPropTypes, value: PropTypes.object.isRequired, valueKey: PropTypes.string } AdvancedSingleSelect.defaultProps = { value: {}, overlayTable: AdvancedSingleSelectOverlayTable, showRemoveButton: true // whether to display a remove button in the input field to allow removing the selected value } export default AdvancedSingleSelect
Add first pass at "none" koan. One test left.
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Based on AboutNil in the Ruby Koans # from runner.koan import * class AboutNone(Koan): def test_none_is_an_object(self): "Unlike NULL in a lot of languages" self.assertEqual(True, isinstance(None, object)) def test_none_is_universal(self): "There is only one None" self.assertEqual(True, None is None) def test_what_exception_do_you_get_when_calling_nonexistent_methods(self): """ What is the Exception that is thrown when you call a method that does not exist? Hint: launch python command console and try the code in the block below. Don't worry about what 'try' and 'except' do, we'll talk about this later """ try: None.some_method_none_does_not_know_about() except Exception as ex: ex2 = ex # What exception has been caught? # # Need a recap on how to evaluate __class__ attributes? # # http://bit.ly/__class__ self.assertEqual(__, ex2.__class__) # What message was attached to the exception? # (HINT: replace __ with part of the error message.) self.assertRegexpMatches(ex2.args[0], __) def test_none_is_distinct(self): """ None is distinct from other things which are False. """ self.assertEqual(True, None is not 0) self.assertEqual(True, None is not False)
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Based on AboutNil in the Ruby Koans # from runner.koan import * class AboutNone(Koan): def test_none_is_an_object(self): "Unlike NULL in a lot of languages" self.assertEqual(__, isinstance(None, object)) def test_none_is_universal(self): "There is only one None" self.assertEqual(____, None is None) def test_what_exception_do_you_get_when_calling_nonexistent_methods(self): """ What is the Exception that is thrown when you call a method that does not exist? Hint: launch python command console and try the code in the block below. Don't worry about what 'try' and 'except' do, we'll talk about this later """ try: None.some_method_none_does_not_know_about() except Exception as ex: ex2 = ex # What exception has been caught? # # Need a recap on how to evaluate __class__ attributes? # # http://bit.ly/__class__ self.assertEqual(__, ex2.__class__) # What message was attached to the exception? # (HINT: replace __ with part of the error message.) self.assertRegexpMatches(ex2.args[0], __) def test_none_is_distinct(self): """ None is distinct from other things which are False. """ self.assertEqual(__, None is not 0) self.assertEqual(__, None is not False)
Remove if(this.viewHeight){} since block is empty.
class MCShowSampleComponentController { /*@ngInject*/ constructor($stateParams, samplesService, toast, $mdDialog) { this.projectId = $stateParams.project_id; this.samplesService = samplesService; this.toast = toast; this.$mdDialog = $mdDialog; this.viewHeight = this.viewHeight ? this.viewHeight : "40vh"; } $onInit() { this.samplesService.getProjectSample(this.projectId, this.sampleId) .then( (sample) => this.sample = sample, () => this.toast.error('Unable to retrieve sample') ) } showProcess(process) { this.$mdDialog.show({ templateUrl: 'app/project/experiments/experiment/components/dataset/components/show-process-dialog.html', controllerAs: '$ctrl', controller: ShowProcessDialogController, bindToController: true, locals: { process: process } }); } } class ShowProcessDialogController { /*@ngInject*/ constructor($mdDialog) { this.$mdDialog = $mdDialog; } done() { this.$mdDialog.cancel(); } } angular.module('materialscommons').component('mcShowSample', { templateUrl: 'app/global.components/mc-show-sample.html', controller: MCShowSampleComponentController, bindings: { sampleId: '<', viewHeight: '@' } });
class MCShowSampleComponentController { /*@ngInject*/ constructor($stateParams, samplesService, toast, $mdDialog) { this.projectId = $stateParams.project_id; this.samplesService = samplesService; this.toast = toast; this.$mdDialog = $mdDialog; this.viewHeight = this.viewHeight ? this.viewHeight : "40vh"; } $onInit() { if (this.viewHeight) { } this.samplesService.getProjectSample(this.projectId, this.sampleId) .then( (sample) => this.sample = sample, () => this.toast.error('Unable to retrieve sample') ) } showProcess(process) { this.$mdDialog.show({ templateUrl: 'app/project/experiments/experiment/components/dataset/components/show-process-dialog.html', controllerAs: '$ctrl', controller: ShowProcessDialogController, bindToController: true, locals: { process: process } }); } } class ShowProcessDialogController { /*@ngInject*/ constructor($mdDialog) { this.$mdDialog = $mdDialog; } done() { this.$mdDialog.cancel(); } } angular.module('materialscommons').component('mcShowSample', { templateUrl: 'app/global.components/mc-show-sample.html', controller: MCShowSampleComponentController, bindings: { sampleId: '<', viewHeight: '@' } });
Change wording of nomination submit
// @flow import * as React from 'react'; import HouseholdForm from './form/head-of-household'; import AddressForm from './form/address'; import PhoneNumbers from './form/phone-numbers'; import ChildForm from './form/child'; import { Row, Col, Button } from 'react-bootstrap'; import { Form } from 'neoform'; import { FormValidation } from 'neoform-validation'; const Household = ({ onSubmit, onInvalid, validate, data, addChild, removeChild, affiliations, saved }) => { return ( <form onSubmit={e => { e.preventDefault(); validate(onSubmit, onInvalid); }} > <HouseholdForm /> <AddressForm /> <PhoneNumbers /> <ChildForm nominations={data.nominations} addChild={addChild} removeChild={removeChild} affiliations={affiliations} /> <Row> <Col xs={12}> <Button type="submit">Save Draft</Button> {saved && <Button type="submit">Submit Nomination</Button>} </Col> </Row> </form> ); }; export default Form(FormValidation(Household));
// @flow import * as React from 'react'; import HouseholdForm from './form/head-of-household'; import AddressForm from './form/address'; import PhoneNumbers from './form/phone-numbers'; import ChildForm from './form/child'; import { Row, Col, Button } from 'react-bootstrap'; import { Form } from 'neoform'; import { FormValidation } from 'neoform-validation'; const Household = ({ onSubmit, onInvalid, validate, data, addChild, removeChild, affiliations, saved }) => { return ( <form onSubmit={e => { e.preventDefault(); validate(onSubmit, onInvalid); }} > <HouseholdForm /> <AddressForm /> <PhoneNumbers /> <ChildForm nominations={data.nominations} addChild={addChild} removeChild={removeChild} affiliations={affiliations} /> <Row> <Col xs={12}> <Button type="submit">Save Draft</Button> {saved && <Button type="submit">Publish</Button>} </Col> </Row> </form> ); }; export default Form(FormValidation(Household));
Fix travis by removing abc metaclass.
import sublime import sublime_plugin from ..helpers import is_js_source class BaseCommand(sublime_plugin.TextCommand): """Common properties and methods for children commands.""" def get_content(self): """Return file content.""" return self.view.substr(sublime.Region(0, self.view.size())) def get_cmd(self): """Construct cli command.""" raise NotImplementedError('get_cmd method must be defined') def handle_process(self, returncode, stdout, error): """Handle the output from the threaded process.""" raise NotImplementedError('handle_process method must be defined') def check_thread(self, thread, i=0, dir=1): """Check if the thread is still running.""" before = i % 8 after = (7) - before if not after: dir = -1 if not before: dir = 1 i += dir self.view.set_status( 'flow_type', 'FlowType [%s=%s]' % (' ' * before, ' ' * after) ) if thread.is_alive(): return sublime.set_timeout(lambda: self.check_thread( thread, i, dir), 100) self.view.erase_status('flow_type') self.handle_process(thread.returncode, thread.stdout, thread.stderr) def is_enabled(self): """Enable the command only on Javascript files.""" return is_js_source(self.view)
import abc import sublime import sublime_plugin from ..helpers import is_js_source class BaseCommand(sublime_plugin.TextCommand, metaclass=abc.ABCMeta): """Common properties and methods for children commands.""" def get_content(self): """Return file content.""" return self.view.substr(sublime.Region(0, self.view.size())) @abc.abstractmethod def get_cmd(self): """Construct cli command.""" raise NotImplementedError('get_cmd method must be defined') @abc.abstractmethod def handle_process(self, returncode, stdout, error): """Handle the output from the threaded process.""" raise NotImplementedError('handle_process method must be defined') def check_thread(self, thread, i=0, dir=1): """Check if the thread is still running.""" before = i % 8 after = (7) - before if not after: dir = -1 if not before: dir = 1 i += dir self.view.set_status( 'flow_type', 'FlowType [%s=%s]' % (' ' * before, ' ' * after) ) if thread.is_alive(): return sublime.set_timeout(lambda: self.check_thread( thread, i, dir), 100) self.view.erase_status('flow_type') self.handle_process(thread.returncode, thread.stdout, thread.stderr) def is_enabled(self): """Enable the command only on Javascript files.""" return is_js_source(self.view)
Improve indented code block parsing.
<?php namespace FluxBB\CommonMark\Parser\Block; use FluxBB\CommonMark\Common\Text; use FluxBB\CommonMark\Node\CodeBlock; use FluxBB\CommonMark\Node\Container; use FluxBB\CommonMark\Parser\AbstractBlockParser; class CodeBlockParser extends AbstractBlockParser { /** * Parse the given content. * * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser * in the chain. * * @param Text $content * @param Container $target * @return void */ public function parseBlock(Text $content, Container $target) { $content->handle( '{ ^ (?:(?<=\n\n)|\A) # Ensure blank line before (or beginning of subject) [ ]{4} # four leading spaces .+ (?: # optionally more spaces (?: # blank lines in between are okay \n[ ]* )* \n [ ]{4} .+ )* $ }mx', function (Text $code) use ($target) { // Remove indent $code->replace('/^[ ]{1,4}/m', ''); $code->append("\n"); $target->acceptCodeBlock(new CodeBlock($code)); }, function(Text $part) use ($target) { $this->next->parseBlock($part, $target); } ); } }
<?php namespace FluxBB\CommonMark\Parser\Block; use FluxBB\CommonMark\Common\Text; use FluxBB\CommonMark\Node\CodeBlock; use FluxBB\CommonMark\Node\Container; use FluxBB\CommonMark\Parser\AbstractBlockParser; class CodeBlockParser extends AbstractBlockParser { /** * Parse the given content. * * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser * in the chain. * * @param Text $content * @param Container $target * @return void */ public function parseBlock(Text $content, Container $target) { $content->handle( '{ (?:\n\n|\A) ( # $1 = the code block -- one or more lines, starting with at least four spaces (?: (?:[ ]{4}) # Lines must start with four spaces .*\n+ )+ ) (?:(?=^[ ]{0,4}\S)|\Z) # Lookahead for non-space at line-start, or end of doc }mx', function (Text $whole, Text $code) use ($target) { // TODO: Prepare contents // Remove indent $code->replace('/^(\t|[ ]{1,4})/m', ''); $target->acceptCodeBlock(new CodeBlock($code)); }, function(Text $part) use ($target) { $this->next->parseBlock($part, $target); } ); } }
Fix workshop loading spinner not showing properly
import React, { Component } from 'react' import Radium from 'radium' import Helmet from 'react-helmet' import Axios from 'axios' import { NavBar, LoadingSpinner } from '../../components' import { NotFound } from '../../containers' const baseUrl = 'https://api.hackclub.com/v1/workshops/' class WorkshopWrapper extends Component { constructor(props) { super(props) Axios.get(baseUrl + (props.routeParams.splat || '')) .then(resp => { this.setState({ notFound: false, workshopContent: resp.data }) }) .catch(e => { console.log(e) this.setState({ notFound: true }) }) } getInitialState() { return { notFound: null } } createWorkshop() { return {__html: this.state.workshopContent} } content() { if (this.state.notFound === null) { return <LoadingSpinner /> } else if(this.state.notFound === false) { return <div dangerouslySetInnerHTML={this.createWorkshop()} /> } else { return <NotFound /> } } render() { return( <div> <Helmet title={this.state.path || 'Workshops'} /> <NavBar /> {this.content()} </div> ) } } export default Radium(WorkshopWrapper)
import React, { Component } from 'react' import Radium from 'radium' import Helmet from 'react-helmet' import Axios from 'axios' import { NavBar, LoadingSpinner } from '../../components' import { NotFound } from '../../containers' const baseUrl = 'https://api.hackclub.com/v1/workshops/' class WorkshopWrapper extends Component { constructor(props) { super(props) Axios.get(baseUrl + (props.routeParams.splat || '')) .then(resp => { this.setState({ workshopContent: resp.data, }) }) .catch(e => { console.log(e) this.setState({ notFound: true }) }) } getInitialState() { return { notFound: false, } } createWorkshop() { return {__html: this.state.workshopContent} } content() { if (this.state.notFound === undefined) { return <LoadingSpinner /> } else if(this.state.notFound === false) { return <div dangerouslySetInnerHTML={this.createWorkshop()} /> } else { return <NotFound /> } } render() { return( <div> <Helmet title={this.state.path || 'Workshops'} /> <NavBar /> {this.content()} </div> ) } } export default Radium(WorkshopWrapper)
Update comments to be clearer
'use strict'; var glimpse = require('glimpse'); var requestRepository = require('../repository/request-repository'); // TODO: Not sure I need to store the requests var _requests = {}; var _viewModel = { selectedId: null, request: null }; function requestChanged(targetRequests) { glimpse.emit('shell.request.detail.changed', targetRequests); } // Clear Request (function () { function clearRequest() { _viewModel.selectedId = null; _viewModel.request = null; requestChanged(_viewModel); } glimpse.on('shell.request.detail.closed', clearRequest); })(); // Found Request (function () { function dataFound(payload) { var newRequest = payload.newRequest; _requests[newRequest.id] = newRequest; if (_viewModel.selectedId === newRequest.id) { _viewModel.request = newRequest; requestChanged(_viewModel); } } // External data coming in glimpse.on('data.request.detail.found', dataFound); })(); // Get Request (function () { function triggerRequest(payload) { var requestId = payload.requestId; _viewModel.selectedId = requestId; _viewModel.request = null; requestChanged(_viewModel); requestRepository.triggerGetDetailsFor(requestId); } glimpse.on('data.request.detail.requested', triggerRequest); })();
'use strict'; var glimpse = require('glimpse'); var requestRepository = require('../repository/request-repository'); // TODO: Not sure I need to store the requests var _requests = {}; var _viewModel = { selectedId: null, request: null }; function requestChanged(targetRequests) { glimpse.emit('shell.request.detail.changed', targetRequests); } // Clear Request (function () { function clearRequest() { _viewModel.selectedId = null; _viewModel.request = null; requestChanged(_viewModel); } glimpse.on('shell.request.detail.closed', clearRequest); })(); // Found Data (function () { function dataFound(payload) { var newRequest = payload.newRequest; _requests[newRequest.id] = newRequest; if (_viewModel.selectedId === newRequest.id) { _viewModel.request = newRequest; requestChanged(_viewModel); } } // External data coming in glimpse.on('data.request.detail.found', dataFound); })(); // Trigger Requests (function () { function triggerRequest(payload) { var requestId = payload.requestId; _viewModel.selectedId = requestId; _viewModel.request = null; requestChanged(_viewModel); requestRepository.triggerGetDetailsFor(requestId); } glimpse.on('data.request.detail.requested', triggerRequest); })();
Add missing bucket for local fs
<?php return function (CM_Config_Node $config) { $awsBucket = '<%= @aws_bucket %>'; $awsRegion = '<%= @aws_region %>'; $awsKey = '<%= @aws_key %>'; $awsSecret = '<%= @aws_secret %>'; $config->services['s3export-filesystem-original'] = array( 'class' => 'CM_File_Filesystem_Factory', 'method' => array( 'name' => 'createFilesystem', 'arguments' => array( 'CM_File_Filesystem_Adapter_AwsS3', array( 'bucket' => $awsBucket, 'region' => $awsRegion, 'key' => $awsKey, 'secret' => $awsSecret, ), ), )); $config->services['s3export-backup-manager'] = [ 'class' => 'S3Export_BackupManager', 'arguments' => [ [ 'bucket' => $awsBucket, 'key' => $awsKey, 'secret' => $awsSecret, ] ] ]; };
<?php return function (CM_Config_Node $config) { $awsBucket = '<%= @aws_bucket %>'; $awsRegion = '<%= @aws_region %>'; $awsKey = '<%= @aws_key %>'; $awsSecret = '<%= @aws_secret %>'; $config->services['s3export-filesystem-original'] = array( 'class' => 'CM_File_Filesystem_Factory', 'method' => array( 'name' => 'createFilesystem', 'arguments' => array( 'CM_File_Filesystem_Adapter_AwsS3', array( 'bucket' => $awsBucket, 'region' => $awsRegion, 'key' => $awsKey, 'secret' => $awsSecret, ), ), )); $config->services['s3export-backup-manager'] = [ 'class' => 'S3Export_BackupManager', 'arguments' => [ [ 'key' => $awsKey, 'secret' => $awsSecret, ] ] ]; };
Fix jshint and jscs errors.
/*jshint node: true*/ 'use strict'; module.exports = { options: { indent: ' ' }, npm: { src: '<%= meta.cwd %>package.json', dest: '<%= meta.build %>package.json', fields: { 'name': null, 'version': null, 'description': null, 'license': null, 'author': null, 'homepage': null, 'repository': null, 'keywords': null, 'main': null, 'dependencies': null } }, bower: { src: '<%= meta.cwd %>package.json', dest: '<%= meta.build %>bower.json', fields: { 'name': null, 'version': null, 'description': null, 'license': null, 'author': 'authors', 'homepage': null, 'repository': null, 'keywords': null, 'main': null, 'dependencies': null } } };
/*jshint node: true*/ 'use strict'; module.exports = { options: { indent: ' ' }, npm: { src: '<%= meta.cwd %>package.json', dest: '<%= meta.build %>package.json', fields: { 'name': null, 'version': null, 'description': null, 'license': null, 'author': null, 'homepage': null, 'repository': null, 'keywords': null, 'main': null, 'dependencies': null, } }, bower: { src: '<%= meta.cwd %>package.json', dest: '<%= meta.build %>bower.json', fields: { 'name': null, 'version': null, 'description': null, 'license': null, 'author': 'authors', 'homepage': null, 'repository': null, 'keywords': null, 'main': null, 'dependencies': null, } } };
Fix logic error in request handler Was rejecting in simple mode if the response was a valid status code, instead of when it wasn't.
var Promise = require('bluebird'), request = require('request'); function rp(options) { var statusCodes = { 'GET' : [200], 'HEAD' : [200], 'PUT' : [200, 201], 'POST' : [200, 201], 'DELETE' : [200, 201] }, c = {simple: true}, i; if (typeof options === 'string') { c.uri = options; c.method = 'GET'; } if (typeof options === 'object') { for (i in options) { if (options.hasOwnProperty(i)) { c[i] = options[i]; } } } c.method = c.method || 'GET'; return new Promise(function (resolve, reject) { request(c, function (error, response, body) { if (error) { reject(error); } else if (c.simple && (statusCodes[c.method].indexOf(response.statusCode) === -1)) { reject(response.statusCode); } else { if (c.transform && typeof c.transform === 'function') { resolve(c.transform(body)); } else { resolve(body); } } }); }); } module.exports = function (a) { if (a) return rp(a); };
var Promise = require('bluebird'), request = require('request'); function rp(options) { var statusCodes = { 'GET' : [200], 'HEAD' : [200], 'PUT' : [200, 201], 'POST' : [200, 201], 'DELETE' : [200, 201] }, c = {simple: true}, i; if (typeof options === 'string') { c.uri = options; c.method = 'GET'; } if (typeof options === 'object') { for (i in options) { if (options.hasOwnProperty(i)) { c[i] = options[i]; } } } c.method = c.method || 'GET'; return new Promise(function (resolve, reject) { request(c, function (error, response, body) { if (error) { reject(error); } else if (c.simple && (statusCodes[c.method].indexOf(response.statusCode) > -1)) { reject(response.statusCode); } else { if (c.transform && typeof c.transform === 'function') { resolve(c.transform(body)); } else { resolve(body); } } }); }); } module.exports = function (a) { if (a) return rp(a); };
Change Sphinx dependency to 1.1 According to @nyergler 1.1 should be sufficient, I hadn't thought to check travis or tox's conf files for the information.
from setuptools import setup, find_packages import os here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() NEWS = open(os.path.join(here, 'NEWS.txt')).read() version = '0.7' install_requires = [ "Sphinx >= 1.1", "six", ] setup(name='hieroglyph', version=version, description="", long_description=README + '\n\n' + NEWS, classifiers=[ 'License :: OSI Approved :: BSD License', 'Topic :: Documentation', 'Topic :: Text Processing', "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", ], keywords='', author='Nathan Yergler', author_email='[email protected]', url='https://github.com/nyergler/hieroglyph', license='BSD', packages=find_packages('src'), package_dir={'': 'src'}, include_package_data=True, zip_safe=False, install_requires=install_requires, entry_points={ 'console_scripts': [ 'hieroglyph=hieroglyph.quickstart:main', 'hieroglyph-quickstart=hieroglyph.quickstart:compatibility', ], }, test_suite='hieroglyph.tests', tests_require=[ 'beautifulsoup4', 'mock', ], )
from setuptools import setup, find_packages import os here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() NEWS = open(os.path.join(here, 'NEWS.txt')).read() version = '0.7' install_requires = [ "Sphinx >= 1.2", "six", ] setup(name='hieroglyph', version=version, description="", long_description=README + '\n\n' + NEWS, classifiers=[ 'License :: OSI Approved :: BSD License', 'Topic :: Documentation', 'Topic :: Text Processing', "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", ], keywords='', author='Nathan Yergler', author_email='[email protected]', url='https://github.com/nyergler/hieroglyph', license='BSD', packages=find_packages('src'), package_dir={'': 'src'}, include_package_data=True, zip_safe=False, install_requires=install_requires, entry_points={ 'console_scripts': [ 'hieroglyph=hieroglyph.quickstart:main', 'hieroglyph-quickstart=hieroglyph.quickstart:compatibility', ], }, test_suite='hieroglyph.tests', tests_require=[ 'beautifulsoup4', 'mock', ], )
Fix typo causing error in imports.
from __future__ import absolute_import from ._version import __version__ from . import styles from . import examples from . import datasets from . import embed from .widgets import (Mesh, Scatter, Volume, Figure, quickquiver, quickscatter, quickvolshow) from .transferfunction import (TransferFunction, TransferFunctionJsBumps, TransferFunctionWidgetJs3, TransferFunctionWidget3) from .pylab import (current, clear, controls_light, figure, gcf, xlim, ylim, zlim, xyzlim, squarelim, plot_trisurf, plot_surface, plot_wireframe, plot_mesh, plot, scatter, quiver, show, animate_glyphs, animation_control, gcc, transfer_function, plot_isosurface, volshow, save, movie, screenshot, savefig, xlabel, ylabel, zlabel, xyzlabel, view, style, plot_plane, selector_default) def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'static', 'dest': 'ipyvolume', 'require': 'ipyvolume/extension' }]
from __future__ import absolute_import from ._version import __version__ from . import styles from . import examples from . import datasets from . import embed from .widgets import (Mesh, Scatter, Volume, Figure, quickquiver, quickscatter, quickvolshow) from .transferfunction import (TransferFunction, TransferFunctionJsBumps, TransferFunctionWidgetJs3, TransferFunctionWidget3) from .pylab import (current, clear, controls_light, figure, gcf, xlim, ylim, zlim, xyzlim, squarelim, plot_trisurf, plot_surface, plot_wireframe, plot_mesh, plot, scatter, quiver, show, animate_glyphs, animation_control, gcc, transfer_function, plot_isosurface, volshow, save, movie, screenshot, savefig, xlabel, ylabel, zlabel, xyzlabel, view, style, plot_plane', selector_default) def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'static', 'dest': 'ipyvolume', 'require': 'ipyvolume/extension' }]
Fix distance for margin title on layout
/* * Code to display coderwall.com badges */ $(document).ready(function(){ var member = $('#github_user').text(); var coderwallJSONurl ="http://www.coderwall.com/" + member + ".json?callback=?"; var height = 75; var width = 75; $.getJSON(coderwallJSONurl, function(data) { $("<p><a href='http://coderwall.com/" + member + "' id='coderwall_link'>Coderwall Achievements</a></p> <br /><br />").appendTo("#coderwall"); $.each(data.data.badges, function(i, item) { $("<img/>").attr("src", item.badge) .attr("float", "left") .attr("title", item.name + ": " + item.description) .attr("alt", item.name) .attr("height", height) .attr("width", width) .appendTo("#coderwall") .hover( function(){ $(this).css("opacity","0.6"); }, function(){ $(this).css("opacity","1.0"); } ) }); }); });
/* * Code to display coderwall.com badges */ $(document).ready(function(){ var member = $('#github_user').text(); var coderwallJSONurl ="http://www.coderwall.com/" + member + ".json?callback=?"; var height = 75; var width = 75; $.getJSON(coderwallJSONurl, function(data) { $("<a href='http://coderwall.com/" + member + "' id='coderwall_link'>Coderwall Achievements</a> <br /><br />").appendTo("#coderwall"); $.each(data.data.badges, function(i, item) { $("<img/>").attr("src", item.badge) .attr("float", "left") .attr("title", item.name + ": " + item.description) .attr("alt", item.name) .attr("height", height) .attr("width", width) .appendTo("#coderwall") .hover( function(){ $(this).css("opacity","0.6"); }, function(){ $(this).css("opacity","1.0"); } ) }); }); });
Remove default arguments for user_id, client_id and type
from .rest import RestClient class DeviceCredentials(object): """Auth0 connection endpoints Args: domain (str): Your Auth0 domain, e.g: 'username.auth0.com' jwt_token (str): An API token created with your account's global keys. You can create one by using the token generator in the API Explorer: https://auth0.com/docs/api/v2 """ def __init__(self, domain, jwt_token): self.domain = domain self.client = RestClient(jwt=jwt_token) def _url(self, id=None): url = 'https://%s/api/v2/device-credentials' % self.domain if id is not None: return url + '/' + id return url def get(self, user_id, client_id, type, fields=[], include_fields=True): params = { 'fields': ','.join(fields) or None, 'include_fields': str(include_fields).lower(), 'user_id': user_id, 'client_id': client_id, 'type': type, } return self.client.get(self._url(), params=params) def create(self, body): return self.client.post(self._url(), data=body) def delete(self, id): return self.client.delete(self._url(id))
from .rest import RestClient class DeviceCredentials(object): """Auth0 connection endpoints Args: domain (str): Your Auth0 domain, e.g: 'username.auth0.com' jwt_token (str): An API token created with your account's global keys. You can create one by using the token generator in the API Explorer: https://auth0.com/docs/api/v2 """ def __init__(self, domain, jwt_token): self.domain = domain self.client = RestClient(jwt=jwt_token) def _url(self, id=None): url = 'https://%s/api/v2/device-credentials' % self.domain if id is not None: return url + '/' + id return url def get(self, user_id=None, client_id=None, type=None, fields=[], include_fields=True): params = { 'fields': ','.join(fields) or None, 'include_fields': str(include_fields).lower(), 'user_id': user_id, 'client_id': client_id, 'type': type, } return self.client.get(self._url(), params=params) def create(self, body): return self.client.post(self._url(), data=body) def delete(self, id): return self.client.delete(self._url(id))
Fix recursive deep merge of context data
'use strict'; const _ = require('lodash'); const utils = require('../utils'); const Log = require('../log'); const mix = require('../mixins/mix'); const Heritable = require('../mixins/heritable'); const EntityMixin = require('../mixins/entity'); module.exports = class Entity extends mix(Heritable, EntityMixin) { constructor(name, config, parent) { super(); this.isEntity = true; this._contextData = {}; this.initEntity(name, config, parent); this.setHeritable(parent); Object.defineProperty(this, 'status', { enumerable: true, get() { return this.source.statusInfo(this.getProp('status')); }, }); this.setProps(config); } getResolvedContext() { return this.source.resolve(this.context); } hasContext() { return this.getResolvedContext().then(context => Object.keys(context).length); } getContext() { return _.clone(this._contextData); } toJSON() { const self = super.toJSON(); self.isEntity = true; return self; } static defineProperty(key, opts) { if (_.isPlainObject(opts)) { Object.defineProperty(this.prototype, key, opts); } else { Object.defineProperty(this.prototype, key, { enumerable: true, writable: true, value: opts }); } } };
'use strict'; const _ = require('lodash'); const utils = require('../utils'); const Log = require('../log'); const mix = require('../mixins/mix'); const Heritable = require('../mixins/heritable'); const EntityMixin = require('../mixins/entity'); module.exports = class Entity extends mix(Heritable, EntityMixin) { constructor(name, config, parent) { super(); this.isEntity = true; this._contextData = {}; this.initEntity(name, config, parent); this.setHeritable(parent); Object.defineProperty(this, 'status', { enumerable: true, get() { return this.source.statusInfo(this.getProp('status')); }, }); this.setProps(config); } getResolvedContext() { return this.source.resolve(this.context); } hasContext() { return this.getResolvedContext().then(context => Object.keys(context).length); } getContext() { return this._contextData; } toJSON() { const self = super.toJSON(); self.isEntity = true; return self; } static defineProperty(key, opts) { if (_.isPlainObject(opts)) { Object.defineProperty(this.prototype, key, opts); } else { Object.defineProperty(this.prototype, key, { enumerable: true, writable: true, value: opts }); } } };