text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add roboto to google fonts
module.exports = { siteMetadata: { title: 'Gatsby Default Starter', }, plugins: [ 'gatsby-plugin-react-helmet', { resolve: `gatsby-plugin-google-analytics`, options: { trackingId: 'UA-93011585-1', // Puts tracking script in the head instead of the body head: false, // Setting this parameter is optional anonymize: true, // Setting this parameter is also optional respectDNT: true, // Avoids sending pageview hits from custom paths exclude: ['/preview/**', '/do-not-track/me/too/'], }, }, { resolve: 'gatsby-plugin-google-fonts', options: { fonts: ['Lora', 'Raleway:400,700', 'Roboto'], }, }, ], };
module.exports = { siteMetadata: { title: 'Gatsby Default Starter', }, plugins: [ 'gatsby-plugin-react-helmet', { resolve: `gatsby-plugin-google-analytics`, options: { trackingId: 'UA-93011585-1', // Puts tracking script in the head instead of the body head: false, // Setting this parameter is optional anonymize: true, // Setting this parameter is also optional respectDNT: true, // Avoids sending pageview hits from custom paths exclude: ['/preview/**', '/do-not-track/me/too/'], }, }, { resolve: 'gatsby-plugin-google-fonts', options: { fonts: ['Lora', 'Raleway:400,700'], }, }, ], };
Remove auto insertion of test card number.
import React from 'react'; import bukovelAPI from './dataAccess/bukovelApi'; import CardNumberInput from './CardNumberInput'; const TEST_CARD_NUMBER = '01-2167-30-92545'; export default class App extends React.Component { constructor() { super(); this.state = { html: '', cardNumber: '' }; this.handleCardNumberChange = this.handleCardNumberChange.bind(this); } handleCardNumberChange(event) { if (event.isValid) { bukovelAPI .getCardBalance(event.text) .then(data => { this.setState({ html: JSON.stringify(data, null, '\t') }); }) } } render() { return ( <div> <CardNumberInput onChange={this.handleCardNumberChange} value={this.state.cardNumber} /> <p>{`Test card number: ${TEST_CARD_NUMBER}`}</p> <pre>{this.state.html}</pre> </div> ); } }
import React from 'react'; import bukovelAPI from './dataAccess/bukovelApi'; import CardNumberInput from './CardNumberInput'; const TEST_CARD_NUMBER = '01-2167-30-92545'; export default class App extends React.Component { constructor() { super(); this.state = { html: '', cardNumber: TEST_CARD_NUMBER }; this.handleCardNumberChange = this.handleCardNumberChange.bind(this); } handleCardNumberChange(event) { if (event.isValid) { bukovelAPI .getCardBalance(event.text) .then(data => { this.setState({ html: JSON.stringify(data, null, '\t') }); }) } } render() { return ( <div> <CardNumberInput onChange={this.handleCardNumberChange} value={this.state.cardNumber} /> <pre>{this.state.html}</pre> </div> ); } }
Swap parse call for synchronous_parse
import logging import typing from typing import Optional, Text from rasa.shared.utils.cli import print_info, print_success from rasa.shared.nlu.interpreter import RegexInterpreter from rasa.shared.constants import INTENT_MESSAGE_PREFIX from rasa.nlu.model import Interpreter from rasa.shared.utils.io import json_to_string import asyncio if typing.TYPE_CHECKING: from rasa.nlu.components import ComponentBuilder logger = logging.getLogger(__name__) def run_cmdline( model_path: Text, component_builder: Optional["ComponentBuilder"] = None ) -> None: interpreter = Interpreter.load(model_path, component_builder) regex_interpreter = RegexInterpreter() print_success("NLU model loaded. Type a message and press enter to parse it.") while True: print_success("Next message:") try: message = input().strip() except (EOFError, KeyboardInterrupt): print_info("Wrapping up command line chat...") break if message.startswith(INTENT_MESSAGE_PREFIX): result = regex_interpreter.synchronous_parse(message) else: result = interpreter.parse(message) print(json_to_string(result))
import logging import typing from typing import Optional, Text from rasa.shared.utils.cli import print_info, print_success from rasa.shared.nlu.interpreter import RegexInterpreter from rasa.shared.constants import INTENT_MESSAGE_PREFIX from rasa.nlu.model import Interpreter from rasa.shared.utils.io import json_to_string import asyncio if typing.TYPE_CHECKING: from rasa.nlu.components import ComponentBuilder logger = logging.getLogger(__name__) def run_cmdline( model_path: Text, component_builder: Optional["ComponentBuilder"] = None ) -> None: interpreter = Interpreter.load(model_path, component_builder) regex_interpreter = RegexInterpreter() print_success("NLU model loaded. Type a message and press enter to parse it.") while True: print_success("Next message:") try: message = input().strip() except (EOFError, KeyboardInterrupt): print_info("Wrapping up command line chat...") break if message.startswith(INTENT_MESSAGE_PREFIX): result = asyncio.run(regex_interpreter.parse(message)) else: result = interpreter.parse(message) print(json_to_string(result))
Add percentage to CLI output
#!/usr/bin/env node 'use strict'; var meow = require('meow'); var w3counter = require('./'); var cli = meow({ help: [ 'Usage', ' $ w3counter <type>', '', 'Example', ' $ w3counter browser', ' $ w3counter country', ' $ w3counter os', ' $ w3counter res' ].join('\n') }); if (!cli.input.length) { console.error([ 'Provide a type', '', 'Example', ' $ w3counter browser', ' $ w3counter country', ' $ w3counter os', ' $ w3counter res' ].join('\n')); process.exit(1); } w3counter(cli.input, function (err, types) { if (err) { console.error(err.message); process.exit(1); } types.forEach(function (type, i) { i = i + 1; console.log(i + '. ' + type.item + ' (' + type.percent + ')'); }); });
#!/usr/bin/env node 'use strict'; var meow = require('meow'); var w3counter = require('./'); var cli = meow({ help: [ 'Usage', ' $ w3counter <type>', '', 'Example', ' $ w3counter browser', ' $ w3counter country', ' $ w3counter os', ' $ w3counter res' ].join('\n') }); if (!cli.input.length) { console.error([ 'Provide a type', '', 'Example', ' $ w3counter browser', ' $ w3counter country', ' $ w3counter os', ' $ w3counter res' ].join('\n')); process.exit(1); } w3counter(cli.input, function (err, types) { if (err) { console.error(err.message); process.exit(1); } types.forEach(function (type, i) { i = i + 1; console.log(i + '. ' + type.item); }); });
Remove .only() call for tests. Sorry
'use strict'; var validation = require('../lib/index') , app = require('./app') , should = require('should') , request = require('supertest'); describe('set default values', function() { describe('when the values are missing', function() { // Expect default values to be set it('should return the request with default values', function(done) { request(app) .post('/defaults') .send({firstname: "Jane", lastname: "Doe"}) .expect(200) .end(function (err, res) { var response = JSON.parse(res.text); response.username.should.equal("jane-doe"); done(); }); }); }); })
'use strict'; var validation = require('../lib/index') , app = require('./app') , should = require('should') , request = require('supertest'); describe.only('set default values', function() { describe('when the values are missing', function() { // Expect default values to be set it('should return the request with default values', function(done) { request(app) .post('/defaults') .send({firstname: "Jane", lastname: "Doe"}) .expect(200) .end(function (err, res) { var response = JSON.parse(res.text); response.username.should.equal("jane-doe"); done(); }); }); }); })
Fix seeding to respect existing records
<?php use GeneaLabs\LaravelGovernor\Action; use GeneaLabs\LaravelGovernor\Entity; use GeneaLabs\LaravelGovernor\Ownership; use GeneaLabs\LaravelGovernor\Permission; use GeneaLabs\LaravelGovernor\Role; use Illuminate\Database\Seeder; class LaravelGovernorPermissionsTableSeeder extends Seeder { public function run() { $superadmin = (new Role)->whereName('SuperAdmin')->get()->first(); $actions = (new Action)->all(); $ownership = (new Ownership)->whereName('any')->get()->first(); $entities = (new Entity)->all(); foreach ($entities as $entity) { foreach ($actions as $action) { (new Permission)->firstOrCreate([ "role_key" => $superadmin->name, "action_key" => $action->name, "ownership_key" => $ownership->name, "entity_key" => $entity->name, ]); } } } }
<?php use GeneaLabs\LaravelGovernor\Action; use GeneaLabs\LaravelGovernor\Entity; use GeneaLabs\LaravelGovernor\Ownership; use GeneaLabs\LaravelGovernor\Permission; use GeneaLabs\LaravelGovernor\Role; use Illuminate\Database\Seeder; class LaravelGovernorPermissionsTableSeeder extends Seeder { public function run() { $superadmin = (new Role)->whereName('SuperAdmin')->get()->first(); $actions = (new Action)->all(); $ownership = (new Ownership)->whereName('any')->get()->first(); $entities = (new Entity)->all(); foreach ($entities as $entity) { foreach ($actions as $action) { $permission = new Permission(); $permission->role()->associate($superadmin); $permission->action()->associate($action); $permission->ownership()->associate($ownership); $permission->entity()->associate($entity); $permission->save(); } } } }
net: Add todo to implement kerberos
// Copyright 2015-2016, Cyrill @ Schumacher.fm and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package net provides additional network helper functions and in subpackages // middleware. // // Which http router should I use? CoreStore doesn't care because it uses the // standard library http API. You can choose nearly any router you like. // // TODO(CyS) consider the next items: // - context Package: https://twitter.com/peterbourgon/status/752022730812317696 // - Sessions: https://github.com/alexedwards/scs // - Form decoding https://github.com/monoculum/formam // - Kerberos github.com/jcmturner/gokrb5 package net
// Copyright 2015-2016, Cyrill @ Schumacher.fm and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package net provides additional network helper functions and in subpackages // middleware. // // Which http router should I use? CoreStore doesn't care because it uses the // standard library http API. You can choose nearly any router you like. // // TODO(CyS) consider the next items: // - context Package: https://twitter.com/peterbourgon/status/752022730812317696 // - Sessions: https://github.com/alexedwards/scs // - Form decoding https://github.com/monoculum/formam package net
Use exact case for ModestMaps dependency
from setuptools import setup, find_packages import sys, os version = '0.0' setup(name='tilequeue', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='', author_email='', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ 'boto', 'ModestMaps', 'TileStache', ], test_suite='tests', entry_points=dict( console_scripts = [ 'queue-write = tilequeue.command:queue_write', 'queue-read = tilequeue.command:queue_read' ] ) )
from setuptools import setup, find_packages import sys, os version = '0.0' setup(name='tilequeue', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='', author_email='', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ 'boto', 'modestmaps', 'TileStache', ], test_suite='tests', entry_points=dict( console_scripts = [ 'queue-write = tilequeue.command:queue_write', 'queue-read = tilequeue.command:queue_read' ] ) )
Rename the autoconfigured AmazonS3 bean - to avoid conflict with spring cloud aws messaging Fixes #622
package internal.org.springframework.content.s3.boot.autoconfigure; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import internal.org.springframework.content.s3.config.S3StoreConfiguration; import internal.org.springframework.content.s3.config.S3StoreFactoryBean; import internal.org.springframework.versions.jpa.boot.autoconfigure.JpaVersionsAutoConfiguration; @Configuration @AutoConfigureAfter({ JpaVersionsAutoConfiguration.class }) @ConditionalOnClass(AmazonS3Client.class) public class S3ContentAutoConfiguration { @Configuration @ConditionalOnMissingBean(S3StoreFactoryBean.class) @Import({ S3StoreConfiguration.class, S3ContentAutoConfigureRegistrar.class }) public static class EnableS3StoresConfig {} @Bean @ConditionalOnMissingBean() public AmazonS3 amazonS3() { AmazonS3 s3Client = new AmazonS3Client(); return s3Client; } }
package internal.org.springframework.content.s3.boot.autoconfigure; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import internal.org.springframework.content.s3.config.S3StoreConfiguration; import internal.org.springframework.content.s3.config.S3StoreFactoryBean; import internal.org.springframework.versions.jpa.boot.autoconfigure.JpaVersionsAutoConfiguration; @Configuration @AutoConfigureAfter({ JpaVersionsAutoConfiguration.class }) @ConditionalOnClass(AmazonS3Client.class) public class S3ContentAutoConfiguration { @Configuration @ConditionalOnMissingBean(S3StoreFactoryBean.class) @Import({ S3StoreConfiguration.class, S3ContentAutoConfigureRegistrar.class }) public static class EnableS3StoresConfig {} @Bean @ConditionalOnMissingBean public AmazonS3 s3Client() { AmazonS3 s3Client = new AmazonS3Client(); return s3Client; } }
Use decimal in the logger to get the most accurate time info
import threading import fresenius import readline import time import sys from decimal import Decimal prompt = '> ' port = sys.argv[1] fresbase = fresenius.FreseniusComm(port = port) logfile = open('seringues.log', 'w') def printrx(): while not logfile.closed: origin, msg = fresbase.recvq.get() logfile.write("{};{}\n".format(Decimal(time.time()), msg)) print msg + "\n" + prompt, def queryloop(): Ts = 0.5 # 2 Hz sample rate tbase = time.time() while not logfile.closed: tnew = time.time() if tnew - tbase > Ts: # d = flow rate, g = infused volume fresbase.sendCommand('1LE;dg') tbase = tnew printthread = threading.Thread(target = printrx) printthread.daemon = True printthread.start() querythread = threading.Thread(target = queryloop) querythread.daemon = True if False: # Start querying for the flow fresbase.sendCommand('0DC') fresbase.sendCommand('1DC') fresbase.sendCommand('1DE;dg') querythread.start() while True: cmd = raw_input(prompt) if cmd == 'quit': break fresbase.sendCommand(cmd) logfile.close() fresbase.stop()
import threading import fresenius import readline import time import sys prompt = '> ' port = sys.argv[1] fresbase = fresenius.FreseniusComm(port = port) logfile = open('seringues.log', 'w') def printrx(): while not logfile.closed: origin, msg = fresbase.recvq.get() logfile.write("{};{}\n".format(time.time(), msg)) print msg + "\n" + prompt, def queryloop(): Ts = 0.5 # 2 Hz sample rate tbase = time.time() while not logfile.closed: tnew = time.time() if tnew - tbase > Ts: # d = flow rate, g = infused volume fresbase.sendCommand('1LE;dg') tbase = tnew printthread = threading.Thread(target = printrx) printthread.daemon = True printthread.start() querythread = threading.Thread(target = queryloop) querythread.daemon = True if False: # Start querying for the flow fresbase.sendCommand('0DC') fresbase.sendCommand('1DC') fresbase.sendCommand('1DE;dg') querythread.start() while True: cmd = raw_input(prompt) if cmd == 'quit': break fresbase.sendCommand(cmd) logfile.close() fresbase.stop()
Set release version to 0.15.0rc5
# -*- coding: cp1252 -*- # ################################################################################## # # Copyright 2014-2017 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com) # # OSRFramework is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################## import osrframework.utils.logger # Calling the logger when being imported osrframework.utils.logger.setupLogger(loggerName="osrframework") __version__="0.15.0rc5"
# -*- coding: cp1252 -*- # ################################################################################## # # Copyright 2014-2017 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com) # # OSRFramework is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################## import osrframework.utils.logger # Calling the logger when being imported osrframework.utils.logger.setupLogger(loggerName="osrframework") __version__="0.15.0rc4"
Fix JS code style issues
'use strict'; angular.module('worklogApp') .controller('MainController', ['$scope', function ($scope) { $scope.newTaskText = ''; $scope.tasks = { planned: [ { id: 1, title: 'task 1' }, { id: 2, title: 'task 2' }, { id: 3, title: 'task 3 has a long name' } ], done: [ { id: 100, title: 'I have done this.' }, { id: 101, title: 'I have done that.' }, { id: 102, title: '"I have done another one, with a long name' } ] }; $scope.createNewTask = function () { console.info ('Creating a new task ...'); if (this.newTaskText) { var id = this.tasks.planned[this.tasks.planned.length - 1].id + 1; //var timestamp = ''; var title = this.newTaskText; this.tasks.planned.push({id: id, title: title}); } }; }]);
'use strict'; angular.module('worklogApp') .controller('MainController', ['$scope', function ($scope) { $scope.text = "bingo!"; $scope.newTaskText = ""; $scope.tasks = { planned: [ { id: 1, title: "task 1" }, { id: 2, title: "task 2" }, { id: 3, title: "task 3 has a long name" } ], done: [ { id: 100, title: "I have done this." }, { id: 101, title: "I have done that." }, { id: 102, title: "I have done another one, with a long name" } ] }; $scope.createNewTask = function () { console.info ("Creating a new task ..."); if (this.newTaskText) { var id = this.tasks.planned[this.tasks.planned.length - 1].id + 1; //var timestamp = ''; var title = this.newTaskText; this.tasks.planned.push({id: id, title: title}); } }; }]);
Add tabbed pane to the center of the frame.
package com.github.aureliano.edocs.app.gui; import java.awt.BorderLayout; import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JPanel; import com.github.aureliano.edocs.app.gui.menu.MenuBar; public class AppFrame extends JFrame { private static final long serialVersionUID = 7618501026967569839L; private TabbedPane tabbedPane; public AppFrame() { this.buildGui(); } private void buildGui() { super.setTitle("e-Docs"); super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(new BorderLayout()); panel.setOpaque(true); panel.add(new VerticalToolBar(), BorderLayout.WEST); this.tabbedPane = new TabbedPane(); panel.add(this.tabbedPane, BorderLayout.CENTER); super.setContentPane(panel); super.setJMenuBar(new MenuBar()); } public void showFrame() { super.pack(); super.setVisible(true); super.setSize(new Dimension(500, 500)); } }
package com.github.aureliano.edocs.app.gui; import java.awt.BorderLayout; import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JPanel; import com.github.aureliano.edocs.app.gui.menu.MenuBar; public class AppFrame extends JFrame { private static final long serialVersionUID = 7618501026967569839L; public AppFrame() { this.buildGui(); } private void buildGui() { super.setTitle("e-Docs"); super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(new BorderLayout()); panel.setOpaque(true); panel.add(new VerticalToolBar(), BorderLayout.WEST); super.setContentPane(panel); super.setJMenuBar(new MenuBar()); } public void showFrame() { super.pack(); super.setVisible(true); super.setSize(new Dimension(500, 500)); } }
Sort ast nodes in constants + remove duplicates
"""Constants relevant to ast code.""" import ast NODE_TYPE_TO_TOKENS = { ast.Add: ('+',), ast.And: ('and',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.Div: ('/',), ast.Eq: ('==',), ast.FloorDiv: ('//',), ast.Gt: ('>',), ast.GtE: ('>=',), ast.In: ('in',), ast.Invert: ('~',), ast.Is: ('is',), ast.IsNot: ('is', 'not',), ast.LShift: ('<<',), ast.Lt: ('<',), ast.LtE: ('<=',), ast.Mod: ('%',), ast.Mult: ('*',), ast.Not: ('not',), ast.NotEq: ('!=',), ast.NotIn: ('not', 'in',), ast.Or: ('or',), ast.Pow: ('**',), ast.RShift: ('>>',), ast.Sub: ('-',), ast.UAdd: ('+',), ast.USub: ('-',), } if hasattr(ast, 'MatMult'): NODE_TYPE_TO_TOKENS[ast.MatMult] = ('@',)
"""Constants relevant to ast code.""" import ast NODE_TYPE_TO_TOKENS = { ast.Add: ('+',), ast.Sub: ('-',), ast.Mult: ('*',), ast.Div: ('/',), ast.Mod: ('%',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.FloorDiv: ('//',), ast.Pow: ('**',), ast.LShift: ('<<',), ast.RShift: ('>>',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.FloorDiv: ('//',), ast.Invert: ('~',), ast.Not: ('not',), ast.UAdd: ('+',), ast.USub: ('-',), ast.And: ('and',), ast.Or: ('or',), ast.Eq: ('==',), ast.NotEq: ('!=',), ast.Lt: ('<',), ast.LtE: ('<=',), ast.Gt: ('>',), ast.GtE: ('>=',), ast.Is: ('is',), ast.IsNot: ('is', 'not',), ast.In: ('in',), ast.NotIn: ('not', 'in',), } if hasattr(ast, 'MatMult'): NODE_TYPE_TO_TOKENS[ast.MatMult] = ('@',)
Convert arrays in site data collection to IterableObjects
<?php namespace TightenCo\Jigsaw; class DataLoader { private $basePath; private $collectionDataLoader; public function __construct($basePath, $collectionDataLoader) { $this->basePath = $basePath; $this->collectionDataLoader = $collectionDataLoader; } public function load($source, $env) { return $this->makeIterableObject( array_merge($this->loadConfigData($env), $this->loadCollectionData($source)) ); } private function loadConfigData($env) { if (file_exists($this->basePath . "/config.{$env}.php")) { $environmentConfig = include $this->basePath . "/config.{$env}.php"; } else { $environmentConfig = []; } return array_merge(include $this->basePath . '/config.php', $environmentConfig); private function makeIterableObject($array) { return collect($array)->map(function ($item, $_) { return is_array($item) ? new IterableObject($this->makeIterableObject($item)) : $item; }); } private function loadCollectionData($source) { return $this->collectionDataLoader->load($source); } }
<?php namespace TightenCo\Jigsaw; class DataLoader { private $basePath; private $collectionDataLoader; public function __construct($basePath, $collectionDataLoader) { $this->basePath = $basePath; $this->collectionDataLoader = $collectionDataLoader; } public function load($source, $env) { return [ 'site' => array_merge($this->loadConfigData($env), $this->loadCollectionData($source)), ]; } private function loadConfigData($env) { if (file_exists($this->basePath . "/config.{$env}.php")) { $environmentConfig = include $this->basePath . "/config.{$env}.php"; } else { $environmentConfig = []; } return array_merge(include $this->basePath . '/config.php', $environmentConfig); } private function loadCollectionData($source) { return $this->collectionDataLoader->load($source); } }
Store defines object_iri; a separate object_identity is unnecessary.
<?php if(!defined('IDENTITY_IRI')) define('IDENTITY_IRI', null); class IdentityModule extends Module { public $moduleId = 'com.nexgenta.eregansu.identity'; public $latestVersion = 0; public static function getInstance($args = null) { if(!isset($args['class'])) $args['class'] = 'IdentityModule'; if(!isset($args['db'])) $args['db'] = IDENTITY_IRI; return parent::getInstance($args); } public function __construct($args) { if(!strncmp($args['db'], 'file:', 5) || !strncmp($args['db'], 'ldap:', 5)) { $args['db'] = null; } parent::__construct($args); } public function dependencies() { $this->depend('com.nexgenta.eregansu.store'); } }
<?php if(!defined('IDENTITY_IRI')) define('IDENTITY_IRI', null); class IdentityModule extends Module { public $moduleId = 'com.nexgenta.eregansu.identity'; public $latestVersion = 1; public static function getInstance($args = null) { if(!isset($args['class'])) $args['class'] = 'IdentityModule'; if(!isset($args['db'])) $args['db'] = IDENTITY_IRI; return parent::getInstance($args); } public function __construct($args) { if(!strncmp($args['db'], 'file:', 5) || !strncmp($args['db'], 'ldap:', 5)) { $args['db'] = null; } parent::__construct($args); } public function dependencies() { $this->depend('com.nexgenta.eregansu.store'); } public function updateSchema($targetVersion) { if($targetVersion == 1) { $t = $this->db->schema->tableWithOptions('object_identity', DBTable::CREATE_ALWAYS); $t->columnWithSpec('uuid', DBType::UUID, null, DBCol::NOT_NULL, null, 'Object identifier'); $t->columnWithSpec('iri', DBType::VARCHAR, 128, DBCol::NOT_NULL, null, 'IRI relating to this user'); $t->indexWithSpec('uuid', DBIndex::INDEX, 'uuid'); $t->indexWithSpec('iri', DBIndex::INDEX, 'iri'); return $t->apply(); } } }
Remove duplicate menu item People
'use strict'; // Setting up route angular.module('core').config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { // Redirect to home view when route not found $urlRouterProvider.otherwise('/'); // Home state routing $stateProvider. state('home', { url: '/', templateUrl: 'modules/core/views/home.client.view.html' }). state('about-us', { url: '/about-us', templateUrl: 'modules/core/views/about-us.client.view.html' }). state('people', { url: '/people', templateUrl: 'modules/core/views/people.client.view.html' }). state('news', { url: '/news', templateUrl: 'modules/core/views/people.client.view.html' }); } ]);
'use strict'; // Setting up route angular.module('core').config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { // Redirect to home view when route not found $urlRouterProvider.otherwise('/'); // Home state routing $stateProvider. state('home', { url: '/', templateUrl: 'modules/core/views/home.client.view.html' }). state('about-us', { url: '/about-us', templateUrl: 'modules/core/views/about-us.client.view.html' }). state('news', { url: '/news', templateUrl: 'modules/core/views/people.client.view.html' }); } ]);
Add singleton scope to navigator.
/** * Copyright (C) 2014 android10.org. All rights reserved. * @author Fernando Cejas (the android10 coder) */ package com.fernandocejas.android10.sample.presentation.navigation; import android.content.Context; import android.content.Intent; import com.fernandocejas.android10.sample.presentation.view.activity.UserDetailsActivity; import com.fernandocejas.android10.sample.presentation.view.activity.UserListActivity; import javax.inject.Singleton; /** * Class used to navigate through the application. */ @Singleton public class Navigator { public void Navigator() { //empty } /** * Goes to the user list screen. * * @param context A Context needed to open the destiny activity. */ public void navigateToUserList(Context context) { if (context != null) { Intent intentToLaunch = UserListActivity.getCallingIntent(context); context.startActivity(intentToLaunch); } } /** * Goes to the user details screen. * * @param context A Context needed to open the destiny activity. */ public void navigateToUserDetails(Context context, int userId) { if (context != null) { Intent intentToLaunch = UserDetailsActivity.getCallingIntent(context, userId); context.startActivity(intentToLaunch); } } }
/** * Copyright (C) 2014 android10.org. All rights reserved. * @author Fernando Cejas (the android10 coder) */ package com.fernandocejas.android10.sample.presentation.navigation; import android.content.Context; import android.content.Intent; import com.fernandocejas.android10.sample.presentation.view.activity.UserDetailsActivity; import com.fernandocejas.android10.sample.presentation.view.activity.UserListActivity; import javax.inject.Inject; /** * Class used to navigate through the application. */ public class Navigator { @Inject public void Navigator() { //empty } /** * Goes to the user list screen. * * @param context A Context needed to open the destiny activity. */ public void navigateToUserList(Context context) { if (context != null) { Intent intentToLaunch = UserListActivity.getCallingIntent(context); context.startActivity(intentToLaunch); } } /** * Goes to the user details screen. * * @param context A Context needed to open the destiny activity. */ public void navigateToUserDetails(Context context, int userId) { if (context != null) { Intent intentToLaunch = UserDetailsActivity.getCallingIntent(context, userId); context.startActivity(intentToLaunch); } } }
Add file basic graph basm test.
package me.wener.bbvm.vm; import me.wener.bbvm.asm.ParseException; import org.junit.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; /** * @author wener * @since 15/12/18 */ public class BasmSpecTest { @Test public void in() throws IOException, ParseException { doTest("../bbvm-test/case/in"); } @Test public void out() throws IOException, ParseException { doTest("../bbvm-test/case/out"); } @Test public void file() throws IOException, ParseException { doTest("../bbvm-test/case/file"); } @Test public void graph() throws IOException, ParseException { doTest("../bbvm-test/case/graph"); } @Test public void basic() throws IOException, ParseException { doTest("../bbvm-test/case/basic"); } private void doTest(String first) throws IOException { BasmTester test = new BasmTester(); Files.walk(Paths.get(first)) .filter(p -> !p.toFile().isDirectory()) .filter(p -> p.toFile().getName().endsWith(".basm")) .forEach(p -> test.init(p.toFile()).run()); } }
package me.wener.bbvm.vm; import me.wener.bbvm.asm.ParseException; import org.junit.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; /** * @author wener * @since 15/12/18 */ public class BasmSpecTest { @Test public void in() throws IOException, ParseException { BasmTester test = new BasmTester(); Files.walk(Paths.get("../bbvm-test/case/in")) .filter(p -> !p.toFile().isDirectory()) .filter(p -> p.toFile().getName().endsWith(".basm")) .forEach(p -> test.init(p.toFile()).run()); } }
Implement `isError` Method in CommentsStatus
<?php /** * Status */ class CommentsStatus { private $code; static private $domain_size = 100; static private $domains = array( 'no_error' => 0, 'system_error' => 100, 'dev_error' => 200, 'user_error' => 300 ); private $exception; function __construct($code, $exception = null) { $this->code = $code; $this->exception = $exception; } public function getCode() { return $this->code; } public function getMessage() { if ($this->exception != null) { return $this->getException()->getMessage(); } return "Status with code {$this->code}."; } public function getException() { return $this->exception; } public function isUserError() { $code = $this->code; $user_domain = CommentsStatus::$domains['user_error']; $size = CommentsStatus::$domain_size; return ($code >= $user_domain) && ($code < ($user_domain + $size)); } public function isError() { return $this->code >= CommentsStatus::$domain_size; } }
<?php /** * Status */ class CommentsStatus { private $code; static private $domain_size = 100; static private $domains = array( 'no_error' => 0, 'system_error' => 100, 'dev_error' => 200, 'user_error' => 300 ); private $exception; function __construct($code, $exception = null) { $this->code = $code; $this->exception = $exception; } public function getCode() { return $this->code; } public function getMessage() { if ($this->exception != null) { return $this->getException()->getMessage(); } return "Status with code {$this->code}."; } public function getException() { return $this->exception; } public function isUserError() { $code = $this->code; $user_domain = CommentsStatus::$domains['user_error']; $size = CommentsStatus::$domain_size; return ($code >= $user_domain) && ($code < ($user_domain + $size)); } }
Fix version printing of tags and releases
import github import github_token import repositories import tagsparser import flock def main(): g = github.Github(github_token.GITHUB_TOKEN) for repo in repositories.REPOSITORIES: tags, releases = g.get_tags_and_releases(repo["owner"], repo["name"], repositories.COUNT) print "Got", [t.version for t in tags], [r.version for r in releases] unreleased_tags = tagsparser.find_unreleased_tags(tags, releases) flockML = flock.create_flockML_for_tags(repo["owner"], repo["name"], unreleased_tags) if flockML: flock.notify_group_about_missing_release_notes(flockML) else: print "No message sending required for {0}".format(repo) if __name__ == '__main__': main()
import github import github_token import repositories import tagsparser import flock def main(): g = github.Github(github_token.GITHUB_TOKEN) for repo in repositories.REPOSITORIES: tags, releases = g.get_tags_and_releases(repo["owner"], repo["name"], repositories.COUNT) print "Got", tags, releases unreleased_tags = tagsparser.find_unreleased_tags(tags, releases) flockML = flock.create_flockML_for_tags(repo["owner"], repo["name"], unreleased_tags) if flockML: flock.notify_group_about_missing_release_notes(flockML) else: print "No message sending required for {0}".format(repo) if __name__ == '__main__': main()
Use member instead of constant.
package main import "html/template" import "log" import "net/http" import "time" import "github.com/stianeikeland/go-rpio" const GPIOPin = 18 const DelaySeconds = 5 type gpioHandler struct { pin rpio.Pin } func GpioHandler(pin rpio.Pin) http.Handler { return &gpioHandler{pin} } func (f *gpioHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFiles("templates/hodoor.html") if err != nil { log.Fatal(err) } type TemplateOutput struct { Pin rpio.Pin Delay int } output := &TemplateOutput{f.pin, DelaySeconds} t.Execute(w, output) timer := time.NewTimer(time.Second * DelaySeconds) go func() { f.pin.Output() f.pin.High() <-timer.C f.pin.Low() }() } func main() { err := rpio.Open() defer rpio.Close() if err != nil { log.Fatal(err) } http.Handle("/hodoor", GpioHandler(rpio.Pin(18))) http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) log.Fatal(http.ListenAndServe(":8080", nil)) }
package main import "html/template" import "log" import "net/http" import "time" import "github.com/stianeikeland/go-rpio" const GPIOPin = 18 const DelaySeconds = 5 type gpioHandler struct { pin rpio.Pin } func GpioHandler(pin rpio.Pin) http.Handler { return &gpioHandler{pin} } func (f *gpioHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFiles("templates/hodoor.html") if err != nil { log.Fatal(err) } type TemplateOutput struct { Pin int Delay int } output := &TemplateOutput{GPIOPin, DelaySeconds} t.Execute(w, output) timer := time.NewTimer(time.Second * DelaySeconds) go func() { f.pin.Output() f.pin.High() <-timer.C f.pin.Low() }() } func main() { err := rpio.Open() defer rpio.Close() if err != nil { log.Fatal(err) } http.Handle("/hodoor", GpioHandler(rpio.Pin(18))) http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) log.Fatal(http.ListenAndServe(":8080", nil)) }
Make it a functional interface Signed-off-by: Jens Reimann <d1bf62d29e711fdf0a5795916341a7b53d204e2a@redhat.com>
/******************************************************************************* * Copyright (c) 2016, 2017 Red Hat Inc and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat Inc - initial API and implementation *******************************************************************************/ package org.eclipse.kura.camel.runner; import org.apache.camel.CamelContext; @FunctionalInterface public interface RoutesProvider { /** * Apply the desired state of camel routes to the context * <p> * <strong>Note: </strong> This method may need to stop and remove * routes which are no longer used * </p> * * @param camelContext * the context the routes should by applied to * @throws Exception * if anything goes wrong */ public void applyRoutes(CamelContext camelContext) throws Exception; }
/******************************************************************************* * Copyright (c) 2016 Red Hat Inc and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat Inc - initial API and implementation *******************************************************************************/ package org.eclipse.kura.camel.runner; import org.apache.camel.CamelContext; public interface RoutesProvider { /** * Apply the desired state of camel routes to the context * <p> * <strong>Note: </strong> This method may need to stop and remove * routes which are no longer used * </p> * * @param camelContext * the context the routes should by applied to * @throws Exception * if anything goes wrong */ public void applyRoutes(CamelContext camelContext) throws Exception; }
Use JSX to initialize AppContainer
/** * Main application file of Fittable * - Requires React.js to be loaded before loading this */ import React from 'react' import ReactDOM from 'react-dom' import Counterpart from 'counterpart' import 'moment/locale/cs' import LocaleCS from './locales/cs.json' import LocaleEN from './locales/en.json' import AppContainer from './containers/AppContainer' const rootElement = document.getElementById('fittable') // Register translations Counterpart.registerTranslations('en', LocaleEN) Counterpart.registerTranslations('cs', Object.assign(LocaleCS, { counterpart: { pluralize: (entry, count) => { entry[ (count === 0 && 'zero' in entry) ? 'zero' : (count === 1) ? 'one' : 'other' ] }, }, })) // Counterpart.setLocale(options.locale) // Moment.locale(options.locale) ReactDOM.render(<AppContainer />, rootElement)
/** * Main application file of Fittable * - Requires React.js to be loaded before loading this */ import React from 'react' import ReactDOM from 'react-dom' import Counterpart from 'counterpart' import 'moment/locale/cs' import LocaleCS from './locales/cs.json' import LocaleEN from './locales/en.json' import AppContainer from './containers/AppContainer' const rootElement = document.getElementById('fittable') // Register translations Counterpart.registerTranslations('en', LocaleEN) Counterpart.registerTranslations('cs', Object.assign(LocaleCS, { counterpart: { pluralize: (entry, count) => { entry[ (count === 0 && 'zero' in entry) ? 'zero' : (count === 1) ? 'one' : 'other' ] }, }, })) // Counterpart.setLocale(options.locale) // Moment.locale(options.locale) ReactDOM.render(React.createElement(AppContainer), rootElement)
chore(reddit): Use Reddit name as username Using Reddit's screen name as username instead of first name will allow the sign to skip one more field.
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class RedditAccount(ProviderAccount): def to_str(self): dflt = super(RedditAccount, self).to_str() name = self.account.extra_data.get("name", dflt) return name class RedditProvider(OAuth2Provider): id = "reddit" name = "Reddit" account_class = RedditAccount def extract_uid(self, data): return data["name"] def extract_common_fields(self, data): return dict(username=data.get("name")) def get_default_scope(self): scope = ["identity"] return scope provider_classes = [RedditProvider]
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class RedditAccount(ProviderAccount): def to_str(self): dflt = super(RedditAccount, self).to_str() name = self.account.extra_data.get("name", dflt) return name class RedditProvider(OAuth2Provider): id = "reddit" name = "Reddit" account_class = RedditAccount def extract_uid(self, data): return data["name"] def extract_common_fields(self, data): return dict(name=data.get("name")) def get_default_scope(self): scope = ["identity"] return scope provider_classes = [RedditProvider]
Add more complex template string
var str1 = `abcde`; var str2 = `abcde${str1}abcde`; var str3 = `abcde${(function () { return 'abc'; }())}abcde`; var str4 = `abcde${({prop1: 1, prop2: 'p'})['prop1']}abcde`; var str5 = `abcde${({prop1: 1, prop2: `edcba${1}ebcda`})['prop1']}abcde`; var str6 = `abcde${({ prop1: 1, prop2: `edcba${1}ebcda` })['prop1']}abcde`; var str7 = `abcde${(function () { return `edcba${str1 + `zz${1}zz`}edcba`; }())}abcde`; var str8 = tag1`abcd ${a}` var str9 = `s${`<tag attr=${exp}>${exp}</tag>`}` var str10 = `<tag attr=${exp}>${exp}</tag>` `${`<tag attr=${exp}>${exp}</tag>`}`
var str1 = `abcde`; var str2 = `abcde${str1}abcde`; var str3 = `abcde${(function () { return 'abc'; }())}abcde`; var str4 = `abcde${({prop1: 1, prop2: 'p'})['prop1']}abcde`; var str5 = `abcde${({prop1: 1, prop2: `edcba${1}ebcda`})['prop1']}abcde`; var str6 = `abcde${({ prop1: 1, prop2: `edcba${1}ebcda` })['prop1']}abcde`; var str7 = `abcde${(function () { return `edcba${str1 + `zz${1}zz`}edcba`; }())}abcde`; var str8 = tag1`abcd ${a}` var str9 = `s${`<tag attr=${exp}>${exp}</tag>`}`
Fix zero-length field error when building docs in Python 2.6
import os import ramrod project = u'stix-ramrod' copyright = u'2015, The MITRE Corporation' version = ramrod.__version__ release = version extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinxcontrib.napoleon', ] intersphinx_mapping = {'http://docs.python.org/': None} templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' rst_prolog = """ **Version**: {0} """.format(release) exclude_patterns = [ '_build', '_includes', 'updates/cybox/cybox*.rst', 'updates/stix/stix*.rst' ] pygments_style = 'sphinx' on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: # only import and set the theme if we're building docs locally import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] else: html_theme = 'default' latex_elements = {} latex_documents = [ ('index', 'stix-ramrod.tex', u'stix-ramrod Documentation', u'The MITRE Corporation', 'manual'), ]
import os import ramrod project = u'stix-ramrod' copyright = u'2015, The MITRE Corporation' version = ramrod.__version__ release = version extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinxcontrib.napoleon', ] intersphinx_mapping = {'http://docs.python.org/': None} templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' rst_prolog = """ **Version**: {} """.format(release) exclude_patterns = [ '_build', '_includes', 'updates/cybox/cybox*.rst', 'updates/stix/stix*.rst' ] pygments_style = 'sphinx' on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: # only import and set the theme if we're building docs locally import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] else: html_theme = 'default' latex_elements = {} latex_documents = [ ('index', 'stix-ramrod.tex', u'stix-ramrod Documentation', u'The MITRE Corporation', 'manual'), ]
Change default naming strating to use fixture name with underscore
<?php /* * This file is part of the FixtureDumper library. * * (c) Martin Parsiegla <martin.parsiegla@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sp\FixtureDumper\Generator; use Doctrine\Common\Persistence\Mapping\ClassMetadata; use Sp\FixtureDumper\Util\ClassUtils; /** * @author Martin Parsiegla <martin.parsiegla@gmail.com> */ class DefaultNamingStrategy implements NamingStrategyInterface { /** * {@inheritdoc} */ public function fixtureName(ClassMetadata $metadata) { return ClassUtils::getClassName($metadata->getName()); } /** * {@inheritdoc} */ public function modelName($model, ClassMetadata $metadata) { $identifiers = $metadata->getIdentifierValues($model); $className = strtolower(preg_replace('/([A-Z])/', '_$1', lcfirst(ClassUtils::getClassName($metadata->getName())))); return $className . ($identifiers ? '_' : '') . implode('_', $identifiers); } }
<?php /* * This file is part of the FixtureDumper library. * * (c) Martin Parsiegla <martin.parsiegla@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sp\FixtureDumper\Generator; use Doctrine\Common\Persistence\Mapping\ClassMetadata; use Sp\FixtureDumper\Util\ClassUtils; /** * @author Martin Parsiegla <martin.parsiegla@gmail.com> */ class DefaultNamingStrategy implements NamingStrategyInterface { /** * {@inheritdoc} */ public function fixtureName(ClassMetadata $metadata) { return ClassUtils::getClassName($metadata->getName()); } /** * {@inheritdoc} */ public function modelName($model, ClassMetadata $metadata) { $identifiers = $metadata->getIdentifierValues($model); $className = lcfirst(ClassUtils::getClassName($metadata->getName())); return $className . implode('_', $identifiers); } }
Revert "increase retries on sqlite connection"
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ /* jslint node: true */ const fs = require('fs') const path = require('path') const sequelizeNoUpdateAttributes = require('sequelize-noupdate-attributes') const Sequelize = require('sequelize') const sequelize = new Sequelize('database', 'username', 'password', { dialect: 'sqlite', storage: 'data/juiceshop.sqlite', logging: false }) sequelizeNoUpdateAttributes(sequelize) const db = {} fs.readdirSync(__dirname) .filter(file => (file.indexOf('.') !== 0) && (file !== 'index.js')) .forEach(file => { const model = sequelize.import(path.join(__dirname, file)) db[model.name] = model }) Object.keys(db).forEach(modelName => { if ('associate' in db[modelName]) { db[modelName].associate(db) } }) db.sequelize = sequelize db.Sequelize = Sequelize module.exports = db
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ /* jslint node: true */ const fs = require('fs') const path = require('path') const sequelizeNoUpdateAttributes = require('sequelize-noupdate-attributes') const Sequelize = require('sequelize') const sequelize = new Sequelize('database', 'username', 'password', { dialect: 'sqlite', retry: { match: [ /SQLITE_BUSY/ ], name: 'query', max: 5 }, storage: 'data/juiceshop.sqlite', logging: false }) sequelizeNoUpdateAttributes(sequelize) const db = {} fs.readdirSync(__dirname) .filter(file => (file.indexOf('.') !== 0) && (file !== 'index.js')) .forEach(file => { const model = sequelize.import(path.join(__dirname, file)) db[model.name] = model }) Object.keys(db).forEach(modelName => { if ('associate' in db[modelName]) { db[modelName].associate(db) } }) db.sequelize = sequelize db.Sequelize = Sequelize module.exports = db
Rename productclass made during migration
from __future__ import unicode_literals from django.db import migrations, models def move_data(apps, schema_editor): Product = apps.get_model('product', 'Product') ProductClass = apps.get_model('product', 'ProductClass') for product in Product.objects.all(): attributes = product.attributes.all() product_class = ProductClass.objects.all() for attribute in attributes: product_class = product_class.filter( variant_attributes__in=[attribute]) product_class = product_class.first() if product_class is None: product_class = ProductClass.objects.create( name='Unnamed product type', has_variants=True) product_class.variant_attributes = attributes product_class.save() product.product_class = product_class product.save() class Migration(migrations.Migration): dependencies = [ ('product', '0019_auto_20161212_0230'), ] operations = [ migrations.RunPython(move_data), ]
from __future__ import unicode_literals from django.db import migrations, models def move_data(apps, schema_editor): Product = apps.get_model('product', 'Product') ProductClass = apps.get_model('product', 'ProductClass') for product in Product.objects.all(): attributes = product.attributes.all() product_class = ProductClass.objects.all() for attribute in attributes: product_class = product_class.filter( variant_attributes__in=[attribute]) product_class = product_class.first() if product_class is None: product_class = ProductClass.objects.create( name='Migrated Product Class', has_variants=True) product_class.variant_attributes = attributes product_class.save() product.product_class = product_class product.save() class Migration(migrations.Migration): dependencies = [ ('product', '0019_auto_20161212_0230'), ] operations = [ migrations.RunPython(move_data), ]
Add ability to define more complex breakpoints.
import _ from 'lodash' import postcss from 'postcss' function buildMediaQuery(breakpoints) { if (_.isString(breakpoints)) { breakpoints = {min: breakpoints} } if (!_.isArray(breakpoints)) { breakpoints = [breakpoints] } return _(breakpoints).map((breakpoint) => { return _(breakpoint).map((value, feature) => { feature = _.get( { min: 'min-width', max: 'max-width', }, feature, feature ) return `(${feature}: ${value})` }).join(' and ') }).join(', ') } export default function(options) { let breakpoints = options.breakpoints return function(css) { Object.keys(breakpoints).forEach(breakpoint => { const variableName = `--breakpoint-${breakpoint}` const mediaQuery = buildMediaQuery(breakpoints[breakpoint]) const rule = postcss.atRule({ name: 'custom-media', params: `${variableName} ${mediaQuery}`, }) css.prepend(rule) }) } }
import _ from 'lodash' import postcss from 'postcss' function buildMediaQuery(breakpoint) { if (_.isString(breakpoint)) { breakpoint = {min: breakpoint} } return _(breakpoint).map((value, feature) => { feature = _.get( { min: 'min-width', max: 'max-width', }, feature, feature ) return `(${feature}: ${value})` }).join(' and ') } export default function(options) { let breakpoints = options.breakpoints return function(css) { Object.keys(breakpoints).forEach(breakpoint => { const variableName = `--breakpoint-${breakpoint}` const mediaQuery = buildMediaQuery(breakpoints[breakpoint]) const rule = postcss.atRule({ name: 'custom-media', params: `${variableName} ${mediaQuery}`, }) css.prepend(rule) }) } }
Update QRCode when text attribute is changed
import Ember from 'ember'; import QRCode from 'qrcode'; export default Ember.Component.extend({ text: null, light: '#ffffff', colorDark: '#000000', width: 128, height: 128, // L/M/Q/H correctLevel: 'Q', didInsertElement: function() { const text = this.get('text'); const elementId = this.get('elementId'); const correctLevel = this.get('correctLevel'); const colorLight = this.get('colorLight'); const colorDark = this.get('colorDark'); const width = this.get('width'); const height = this.get('height'); let qrcode = new QRCode(elementId, { text, width, height, colorDark, colorLight, correctLevel: QRCode.CorrectLevel[correctLevel], }); this.set('qrcode', qrcode); }, willDestroyElement: function() { this.get('qrcode').clear(); }, _recreateCode: Ember.observer('text', function() { this.get('qrcode').makeCode(this.get('text')); }) });
import Ember from 'ember'; import QRCode from 'qrcode'; export default Ember.Component.extend({ text: null, light: '#ffffff', colorDark: '#000000', width: 128, height: 128, // L/M/Q/H correctLevel: 'Q', didInsertElement: function() { const text = this.get('text'); const elementId = this.get('elementId'); const correctLevel = this.get('correctLevel'); const colorLight = this.get('colorLight'); const colorDark = this.get('colorDark'); const width = this.get('width'); const height = this.get('height'); let qrcode = new QRCode(elementId, { text, width, height, colorDark, colorLight, correctLevel: QRCode.CorrectLevel[correctLevel], }); this.set('qrcode', qrcode); }, willDestroyElement: function() { this.get('qrcode').clear(); }, });
[JBKB-996] Delete findMetainfoRelatedTerms method from Genestack Core findMetainfoRelatedTerms is deleted
# -*- coding: utf-8 -*- import sys if not ((2, 7, 5) <= sys.version_info < (3, 0)): sys.stderr.write( 'Python version "%s" is not supported. Required version 2.7.5+, Python 3 is not supported\n' % sys.version ) exit(1) from version import __version__ from genestack_exceptions import (GenestackAuthenticationException, GenestackBaseException, GenestackConnectionFailure, GenestackException, GenestackResponseError, GenestackServerException, GenestackVersionException) from genestack_connection import Connection, Application from file_types import FileTypes from file_permissions import Permissions from metainfo_scalar_values import * from bio_meta_keys import BioMetaKeys from genestack_metainfo import Metainfo from bio_metainfo import BioMetainfo from data_importer import DataImporter from file_initializer import FileInitializer from genome_query import GenomeQuery from utils import get_connection, get_user, make_connection_parser, validate_constant from file_filters import * from share_util import ShareUtil from files_util import FilesUtil, SortOrder, SpecialFolders from datasets_util import DatasetsUtil from groups_util import GroupsUtil from organization_util import OrganizationUtil from task_log_viewer import TaskLogViewer from cla import * from expression_navigator import *
# -*- coding: utf-8 -*- import sys if not ((2, 7, 5) <= sys.version_info < (3, 0)): sys.stderr.write( 'Python version "%s" is not supported. Required version 2.7.5+, Python 3 is not supported\n' % sys.version ) exit(1) from version import __version__ from genestack_exceptions import (GenestackAuthenticationException, GenestackBaseException, GenestackConnectionFailure, GenestackException, GenestackResponseError, GenestackServerException, GenestackVersionException) from genestack_connection import Connection, Application from file_types import FileTypes from file_permissions import Permissions from metainfo_scalar_values import * from bio_meta_keys import BioMetaKeys from genestack_metainfo import Metainfo from bio_metainfo import BioMetainfo from data_importer import DataImporter from file_initializer import FileInitializer from genome_query import GenomeQuery from utils import get_connection, get_user, make_connection_parser, validate_constant from file_filters import * from share_util import ShareUtil from files_util import FilesUtil, MatchType, SortOrder, SpecialFolders from datasets_util import DatasetsUtil from groups_util import GroupsUtil from organization_util import OrganizationUtil from task_log_viewer import TaskLogViewer from cla import * from expression_navigator import *
:arrow_up: Add methods into the storage interface as they are now supported
package request import ( "context" "github.com/ory/fosite" "github.com/ory/fosite/handler/oauth2" "github.com/ory/fosite/handler/openid" ) // Manager provides a generic interface to clients in order to build a DataStore type Manager interface { Storer } // Storer conforms to fosite.Requester and provides methods type Storer interface { fosite.Requester // OAuth2 Required Storage interfaces. oauth2.AuthorizeCodeGrantStorage oauth2.ClientCredentialsGrantStorage oauth2.RefreshTokenGrantStorage // Authenticate is required to implement the oauth2.ResourceOwnerPasswordCredentialsGrantStorage interface Authenticate(ctx context.Context, name string, secret string) error // ouath2.ResourceOwnerPasswordCredentialsGrantStorage is indirectly implemented by the interfaces presented // above. // OpenID Required Storage Interfaces openid.OpenIDConnectRequestStorage // Enable revoking of tokens // see: https://github.com/ory/hydra/blob/master/pkg/fosite_storer.go RevokeRefreshToken(ctx context.Context, requestID string) error RevokeAccessToken(ctx context.Context, requestID string) error }
package request import ( "context" "github.com/ory/fosite" "github.com/ory/fosite/handler/oauth2" "github.com/ory/fosite/handler/openid" ) // Manager provides a generic interface to clients in order to build a DataStore type Manager interface { Storer } // Storer conforms to fosite.Requester and provides methods type Storer interface { fosite.Requester // OAuth2 Required Storage interfaces. oauth2.AuthorizeCodeGrantStorage oauth2.ClientCredentialsGrantStorage oauth2.RefreshTokenGrantStorage // Authenticate is required to implement the oauth2.ResourceOwnerPasswordCredentialsGrantStorage interface Authenticate(ctx context.Context, name string, secret string) error // ouath2.ResourceOwnerPasswordCredentialsGrantStorage is indirectly implemented by the interfaces presented // above. // OpenID Required Storage Interfaces openid.OpenIDConnectRequestStorage // Enable revoking of tokens // see: https://github.com/ory/hydra/blob/master/pkg/fosite_storer.go //RevokeRefreshToken(ctx context.Context, requestID string) error //RevokeAccessToken(ctx context.Context, requestID string) error }
Add columns to polls table
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAnswersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('answers', function (Blueprint $table) { $table->increments('id'); $table->integer('poll_id')->unsigned(); $table->string('answer'); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('answers'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAnswersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('answers', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('answers'); } }
Add more fields to UserEntity
// @flow import { createSelector } from 'reselect'; import { User } from '../actions/ActionTypes'; import createEntityReducer from 'app/utils/createEntityReducer'; export type UserEntity = { id: number, username: string, fullName: string, firstName: string, lastName: string, gender: string, profilePicture: string }; export default createEntityReducer({ key: 'users', types: { fetch: User.FETCH }, mutate(state, action) { switch (action.type) { case User.CONFIRM_STUDENT_USER.SUCCESS: { return { ...state, byId: { ...state.byId, [action.payload.username]: action.payload } }; } default: return state; } } }); export const selectUserById = createSelector( state => state.users.byId, (state, props) => props.userId, (usersById, userId) => { const user = usersById[userId]; if (user) { return user; } return {}; } );
// @flow import { createSelector } from 'reselect'; import { User } from '../actions/ActionTypes'; import createEntityReducer from 'app/utils/createEntityReducer'; export type UserEntity = { username: string }; export default createEntityReducer({ key: 'users', types: { fetch: User.FETCH }, mutate(state, action) { switch (action.type) { case User.CONFIRM_STUDENT_USER.SUCCESS: { return { ...state, byId: { ...state.byId, [action.payload.username]: action.payload } }; } default: return state; } } }); export const selectUserById = createSelector( state => state.users.byId, (state, props) => props.userId, (usersById, userId) => { const user = usersById[userId]; if (user) { return user; } return {}; } );
Increase the code black max height
/* * Copyright 2016 OpenMarket Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.view; import android.content.Context; import android.support.v4.widget.NestedScrollView; import android.util.AttributeSet; public class CodeBlockNestedScrollView extends NestedScrollView { public CodeBlockNestedScrollView(Context context) { super(context); } public CodeBlockNestedScrollView(Context context, AttributeSet attrs) { super(context, attrs); } public CodeBlockNestedScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { heightMeasureSpec = MeasureSpec.makeMeasureSpec(500, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }
/* * Copyright 2016 OpenMarket Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.view; import android.content.Context; import android.support.v4.widget.NestedScrollView; import android.util.AttributeSet; public class CodeBlockNestedScrollView extends NestedScrollView { public CodeBlockNestedScrollView(Context context) { super(context); } public CodeBlockNestedScrollView(Context context, AttributeSet attrs) { super(context, attrs); } public CodeBlockNestedScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { heightMeasureSpec = MeasureSpec.makeMeasureSpec(250, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }
Increase task check time to 1h
from __future__ import absolute_import from datetime import datetime, timedelta from changes.config import queue from changes.constants import Status from changes.models import Task from changes.queue.task import TrackedTask, tracked_task CHECK_TIME = timedelta(minutes=60) @tracked_task def cleanup_tasks(): """ Find any tasks which haven't checked in within a reasonable time period and requeue them if nescessary. """ now = datetime.utcnow() cutoff = now - CHECK_TIME pending_tasks = Task.query.filter( Task.status != Status.finished, Task.date_modified < cutoff, ) for task in pending_tasks: task_func = TrackedTask(queue.get_task(task.task_name)) task_func.delay( task_id=task.task_id.hex, parent_task_id=task.parent_id.hex if task.parent_id else None, **task.data['kwargs'] )
from __future__ import absolute_import from datetime import datetime, timedelta from changes.config import queue from changes.constants import Status from changes.models import Task from changes.queue.task import TrackedTask, tracked_task CHECK_TIME = timedelta(minutes=5) @tracked_task def cleanup_tasks(): """ Find any tasks which haven't checked in within a reasonable time period and requeue them if nescessary. """ now = datetime.utcnow() cutoff = now - CHECK_TIME pending_tasks = Task.query.filter( Task.status != Status.finished, Task.date_modified < cutoff, ) for task in pending_tasks: task_func = TrackedTask(queue.get_task(task.task_name)) task_func.delay( task_id=task.task_id.hex, parent_task_id=task.parent_id.hex if task.parent_id else None, **task.data['kwargs'] )
Make the tweet slightly less robot-y
#!/usr/bin/env python # CoffeeOutsideBot # Copyright 2016, David Crosby # BSD 2-clause license # # TODO - add rest of the locations, etc # TODO - automate weather forecast lookup # TODO - automate Cyclepalooza event creation # TODO - clean this ugly thing up import json import random from twitter import * from ConfigParser import SafeConfigParser parser = SafeConfigParser() parser.read('./cb_config.ini') tcreds = {} # yuck for section in ['twitter']: if parser.has_section(section): if section == 'twitter': for option in parser.options('twitter'): tcreds[option] = parser.get('twitter', option) print(tcreds) locations = [] try: with open('./winter_locations', 'r') as file_handle: for l in file_handle: if len(l.strip()) > 0: locations.append(l.strip()) except IOError, err: print(err) location = random.choice(locations) new_status = "This week's #CoffeeOutside is at " + location + ", see you there!" print(new_status) # The Twitter Bits t = Twitter( auth=OAuth(tcreds['token'], tcreds['token_secret'], tcreds['consumer_key'], tcreds['consumer_secret'])) t.statuses.update(status=new_status)
#!/usr/bin/env python # CoffeeOutsideBot # Copyright 2016, David Crosby # BSD 2-clause license # # TODO - add rest of the locations, etc # TODO - automate weather forecast lookup # TODO - automate Cyclepalooza event creation # TODO - clean this ugly thing up import json import random from twitter import * from ConfigParser import SafeConfigParser parser = SafeConfigParser() parser.read('./cb_config.ini') tcreds = {} # yuck for section in ['twitter']: if parser.has_section(section): if section == 'twitter': for option in parser.options('twitter'): tcreds[option] = parser.get('twitter', option) print(tcreds) locations = [] try: with open('./winter_locations', 'r') as file_handle: for l in file_handle: if len(l.strip()) > 0: locations.append(l.strip()) except IOError, err: print(err) print(locations) location = random.choice(locations) new_status = "The next #CoffeeOutside is at " + location print(new_status) # The Twitter Bits t = Twitter( auth=OAuth(tcreds['token'], tcreds['token_secret'], tcreds['consumer_key'], tcreds['consumer_secret'])) t.statuses.update(status=new_status)
Add TODO for creation of selection group
/* @flow */ type GiftCategory = 'Electronics' | 'Games' | 'Home Decoration'; type GiftWish = string | Array<GiftCategory>; type User = { firstName: string, lastName?: string, giftWish?: GiftWish, }; export type Selection = { giver: User, receiver: User, }; // TODO: Add function to create a selection group (in the SDK?) // // function createSelectionGroup({ // title = '', // description = '', // suggestions = { // currency: 'Euro', // minLimit: 10, // maxLimit: 50 // }}) { } // // ? Question: What is its relation to `selectSecretSanta`? // How does it get called, etc. const selectSecretSanta = ( users: Array<User>, // TODO: Think of adding restrictions as a parameter, such as: // - User X cannot give to User Y // - User A must give to User B // - User N only receives, doesn't give ): Array<Selection> => { const givers = [...users]; return users.map((receiver) => { // Possible givers only for this receiver (receiver cannot be his own giver) const receiverGivers = givers.filter(g => g !== receiver); const giver = receiverGivers[ Math.floor(Math.random() * receiverGivers.length) ]; // Take the selected giver out of the givers array givers.splice(givers.findIndex(g => g === giver), 1); return { giver, receiver, }; }); }; export default selectSecretSanta;
/* @flow */ type GiftCategory = 'Electronics' | 'Games' | 'Home Decoration'; type GiftWish = string | Array<GiftCategory>; type User = { firstName: string, lastName?: string, giftWish?: GiftWish, }; export type Selection = { giver: User, receiver: User, }; const selectSecretSanta = ( users: Array<User>, // TODO: Think of adding restrictions as a parameter, such as: // - User X cannot give to User Y // - User A must give to User B // - User N only receives, doesn't give ): Array<Selection> => { const givers = [...users]; return users.map((receiver) => { // Possible givers only for this receiver (receiver cannot be his own giver) const receiverGivers = givers.filter(g => g !== receiver); const giver = receiverGivers[ Math.floor(Math.random() * receiverGivers.length) ]; // Take the selected giver out of the givers array givers.splice(givers.findIndex(g => g === giver), 1); return { giver, receiver, }; }); }; export default selectSecretSanta;
Add test for one subdirectory
''' GotoNewest tests ''' import unittest import sys sys.path.append('../src/') import gn TEST_DIR = '/tmp/test' class TestGotoNewest(unittest.TestCase): ''' Test class for GotoNewest ''' def test_empty_base_dir(self): ''' If the base directory is empty, raise an AttributeError ''' self.assertRaises(AttributeError, gn.transfer, None) def test_base_dir_with_no_subdirs(self): ''' If the base directory has no subdirectories, raise an AttributeError ''' self.assertRaises(AttributeError, gn.transfer, TEST_DIR) def test_one_subdirectory(self): ''' If there is only one subdirectory in the base directory, return the directory ''' self.assertRaises('temp', gn.transfer, TEST_DIR) if __name__ == '__main__': unittest.main()
''' GotoNewest tests ''' import unittest import sys sys.path.append('../src/') import gn TEST_DIR = '/tmp/test' class TestGotoNewest(unittest.TestCase): ''' Test class for GotoNewest ''' def test_empty_base_dir(self): ''' If the base directory is empty, raise an AttributeError ''' self.assertRaises(AttributeError, gn.transfer, None) def test_base_dir_with_no_subdirs(self): ''' If the base directory has no subdirectories, raise an AttributeError ''' self.assertRaises(AttributeError, gn.transfer, TEST_DIR) if __name__ == '__main__': unittest.main()
Replace _ with () on callbacks that don't use any argument
'use strict'; const http = require('http'); const path = require('path'); const url = require('url'); const auth = require('http-auth'); const HttpStatusCodes = require('http-status-codes'); const stream_file_to_bd = require('./lib/stream_file_to_bd'); const basic_auth = auth.basic({ realm: 'Vidya', file: path.join(__dirname, 'test', 'test_files', 'htpasswd') }); const app = (request, response) => { const target_url = new url.URL(request.url, 'http://localhost'); if (target_url.pathname !== '/') { return reject_connection(response, HttpStatusCodes.NOT_FOUND); } if (request.method !== 'PUT') { return reject_connection(response, HttpStatusCodes.METHOD_NOT_ALLOWED); } stream_file_to_bd(request) .then(() => { response.writeHead(HttpStatusCodes.OK, { 'Content-Type': 'text/plain' }); response.end(); }) .catch(() => { reject_connection(response, HttpStatusCodes.INTERNAL_SERVER_ERROR); }); }; function reject_connection (response, status) { response.writeHead(status, { 'Content-Type': 'text/plain' }); return response.end(); } module.exports = http.createServer(basic_auth.check(app));
'use strict'; const http = require('http'); const path = require('path'); const url = require('url'); const auth = require('http-auth'); const HttpStatusCodes = require('http-status-codes'); const stream_file_to_bd = require('./lib/stream_file_to_bd'); const basic_auth = auth.basic({ realm: 'Vidya', file: path.join(__dirname, 'test', 'test_files', 'htpasswd') }); const app = (request, response) => { const target_url = new url.URL(request.url, 'http://localhost'); if (target_url.pathname !== '/') { return reject_connection(response, HttpStatusCodes.NOT_FOUND); } if (request.method !== 'PUT') { return reject_connection(response, HttpStatusCodes.METHOD_NOT_ALLOWED); } stream_file_to_bd(request) .then(_ => { response.writeHead(HttpStatusCodes.OK, { 'Content-Type': 'text/plain' }); response.end(); }) .catch(_ => { reject_connection(response, HttpStatusCodes.INTERNAL_SERVER_ERROR); }); }; function reject_connection (response, status) { response.writeHead(status, { 'Content-Type': 'text/plain' }); return response.end(); } module.exports = http.createServer(basic_auth.check(app));
Update package to have the tag/release match
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup setup( name = 'cityhall', packages = ['cityhall'], # this must be the same as the name above version = '0.0.10', description = 'A library for accessing City Hall Setting Server', license = 'AGPL', author = 'Alex Popa', author_email = 'alex.popa@digitalborderlands.com', url = 'https://github.com/f00f-nyc/cityhall-python', download_url = 'https://codeload.github.com/f00f-nyc/cityhall-python/legacy.tar.gz/v0.0.10', install_requires=['requests==2.7.0','six==1.9.0'], keywords = ['cityhall', 'enterprise settings', 'settings', 'settings server', 'cityhall', 'City Hall'], test_suite='test', tests_require=['requests==2.7.0','six==1.9.0','mock==1.0.1'], classifiers = [], )
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup setup( name = 'cityhall', packages = ['cityhall'], # this must be the same as the name above version = '0.0.10', description = 'A library for accessing City Hall Setting Server', license = 'AGPL', author = 'Alex Popa', author_email = 'alex.popa@digitalborderlands.com', url = 'https://github.com/f00f-nyc/cityhall-python', download_url = 'https://codeload.github.com/f00f-nyc/cityhall-python/legacy.tar.gz/v0.0.6', install_requires=['requests==2.7.0','six==1.9.0'], keywords = ['cityhall', 'enterprise settings', 'settings', 'settings server', 'cityhall', 'City Hall'], test_suite='test', tests_require=['requests==2.7.0','six==1.9.0','mock==1.0.1'], classifiers = [], )
Fix bug, appering only in Firefox (Date.parse("xx-xx-xxxx xx:xx"))
(function () { 'use strict'; var factoriesModul; try { factoriesModul = angular.module('dcc.factories'); } catch (e) { factoriesModul = angular.module('dcc.factories', []); } factoriesModul.factory('durationValidationFactory', [function () { var factory = {}; factory.isValidTime = function (time) { var timeRegex = /^\d\d:\d\d$/; return !!timeRegex.test(time); }; factory.isValidDay = function (day) { var dayRegex = /^\d\d-\d\d-\d\d\d\d$/; return !!dayRegex.test(day); }; factory.isToAfterFrom = function (day, to, from) { day = day.replace("-", "/").replace("-", "/"); return Date.parse(day + ' ' + to) > Date.parse(day + ' ' + from); }; return factory; }]); }());
(function () { 'use strict'; var factoriesModul; try { factoriesModul = angular.module('dcc.factories'); } catch (e) { factoriesModul = angular.module('dcc.factories', []); } factoriesModul.factory('durationValidationFactory', [function () { var factory = {}; factory.isValidTime = function (time) { var timeRegex = /^\d\d:\d\d$/; return !!timeRegex.test(time); }; factory.isValidDay = function (day) { var dayRegex = /^\d\d-\d\d-\d\d\d\d$/; return !!dayRegex.test(day); }; factory.isToAfterFrom = function (day, to, from) { return Date.parse(day + ' ' + to) > Date.parse(day + ' ' + from); }; return factory; }]); }());
Use Python PEP 8 naming for derived class.
# Input: ${SGE_TASK_ID} # Output: generated models in *.B* files, calculated energies in *.E* files # from modeller import * from modeller.automodel import * import sys # to get different starting models for each task taskid = int(sys.argv[1]) env = environ(rand_seed=-1000-taskid) class MyLoop(loopmodel): def select_loop_atoms(self): res = ( RESIDUE_RANGE ) s = selection(res) if len(s.only_no_topology()) > 0: raise ModellerError, "some selected residues have no topology" return s m = MyLoop(env, inimodel='USER_PDB', sequence='USER_NAME') m.loop.md_level = refine.slow m.loop.starting_model = m.loop.ending_model = taskid m.make()
# Input: ${SGE_TASK_ID} # Output: generated models in *.B* files, calculated energies in *.E* files # from modeller import * from modeller.automodel import * import sys # to get different starting models for each task taskid = int(sys.argv[1]) env = environ(rand_seed=-1000-taskid) class myloop(loopmodel): def select_loop_atoms(self): res = ( RESIDUE_RANGE ) s = selection(res) if len(s.only_no_topology()) > 0: raise ModellerError, "some selected residues have no topology" return s m = myloop(env, inimodel='USER_PDB', sequence='USER_NAME') m.loop.md_level = refine.slow m.loop.starting_model = m.loop.ending_model = taskid m.make()
Fix latexs output encoding to latin1.
import os from .errors import parse_log class LatexError(Exception): pass class LatexBuildError(LatexError): """LaTeX call exception.""" def __init__(self, logfn=None): if os.path.exists(logfn): # the binary log is probably latin1 or utf8? # utf8 throws errors occasionally, so we try with latin1 # and ignore invalid chars binlog = open(logfn, 'rb').read() self.log = binlog.decode('latin1', 'ignore') else: self.log = None def __str__(self): return str(self.log) def get_errors(self, *args, **kwargs): """Parse the log for errors. Any arguments are passed on to :func:`.parse_log`. :return: The return of :func:`.parse_log`, applied to the log associated with this build error. """ return parse_log(self.log)
import os from .errors import parse_log class LatexError(Exception): pass class LatexBuildError(LatexError): """LaTeX call exception.""" def __init__(self, logfn=None): if os.path.exists(logfn): self.log = open(logfn).read() else: self.log = None def __str__(self): return str(self.log) def get_errors(self, *args, **kwargs): """Parse the log for errors. Any arguments are passed on to :func:`.parse_log`. :return: The return of :func:`.parse_log`, applied to the log associated with this build error. """ return parse_log(self.log)
Join using regular separators on the client, not OS-specific ones
package hdfs import ( "os" "path/filepath" "sort" ) // Walk walks the file tree rooted at root, calling walkFn for each file or // directory in the tree, including root. All errors that arise visiting files // and directories are filtered by walkFn. The files are walked in lexical // order, which makes the output deterministic but means that for very large // directories Walk can be inefficient. Walk does not follow symbolic links. func (c *Client) Walk(root string, walkFn filepath.WalkFunc) error { return c.walk(root, walkFn) } func (c *Client) walk(path string, walkFn filepath.WalkFunc) error { file, err := c.Open(path) var info os.FileInfo if file != nil { info = file.Stat() } err = walkFn(path, info, err) if err != nil { if info.IsDir() && err == filepath.SkipDir { return nil } return err } if info == nil || !info.IsDir() { return nil } names, err := file.Readdirnames(0) if err != nil { return walkFn(path, info, err) } sort.Strings(names) for _, name := range names { err = c.walk(filepath.ToSlash(filepath.Join(path, name)), walkFn) if err != nil { return err } } return nil }
package hdfs import ( "os" "path/filepath" "sort" ) // Walk walks the file tree rooted at root, calling walkFn for each file or // directory in the tree, including root. All errors that arise visiting files // and directories are filtered by walkFn. The files are walked in lexical // order, which makes the output deterministic but means that for very large // directories Walk can be inefficient. Walk does not follow symbolic links. func (c *Client) Walk(root string, walkFn filepath.WalkFunc) error { return c.walk(root, walkFn) } func (c *Client) walk(path string, walkFn filepath.WalkFunc) error { file, err := c.Open(path) var info os.FileInfo if file != nil { info = file.Stat() } err = walkFn(path, info, err) if err != nil { if info.IsDir() && err == filepath.SkipDir { return nil } return err } if info == nil || !info.IsDir() { return nil } names, err := file.Readdirnames(0) if err != nil { return walkFn(path, info, err) } sort.Strings(names) for _, name := range names { err = c.walk(filepath.Join(path, name), walkFn) if err != nil { return err } } return nil }
Update java docs for sign()
/** * Copyright (c) 2015 Spotify AB. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.spotify.sshagentproxy; import java.io.Closeable; import java.io.IOException; import java.util.List; public interface AgentProxy extends Closeable { /** * Get a list of public keys from the ssh-agent. * @return A list of {@link Identity} */ List<Identity> list() throws IOException; /** * Ask the ssh-agent to hash and sign some data in the form of an array of bytes. * * According to the ssh-agent specs: * "Upon receiving this request, the agent will look up the private key that * corresponds to the public key contained in key_blob. It will use this * private key to sign the "data" and produce a signature blob using the * key type-specific method described in RFC 4253 section 6.6 "Public Key * Algorithms". * @param identity An array of bytes for data to be signed. * @param data An array of bytes for data to be signed. * @return An array of bytes of signed data. */ byte[] sign(final Identity identity, final byte[] data) throws IOException; }
/** * Copyright (c) 2015 Spotify AB. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.spotify.sshagentproxy; import java.io.Closeable; import java.io.IOException; import java.util.List; public interface AgentProxy extends Closeable { /** * Get a list of public keys from the ssh-agent. * @return A list of {@link Identity} */ List<Identity> list() throws IOException; /** * Ask the ssh-agent to sign some data in the form of an array of bytes. * @param identity An array of bytes for data to be signed. * @param data An array of bytes for data to be signed. * @return An array of bytes of signed data. */ byte[] sign(final Identity identity, final byte[] data) throws IOException; }
SB-748: Fix the issues reported from Sonar.
package org.carlspring.strongbox.cron.context; import org.carlspring.strongbox.config.WebConfig; import org.carlspring.strongbox.cron.config.CronTasksConfig; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.security.test.context.support.WithUserDetails; import org.springframework.test.annotation.IfProfileValue; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.web.WebAppConfiguration; /** * Marks test to be executed only under special spring active profile. * * @author Alex Oreshkevich */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @ContextConfiguration(classes = { CronTasksConfig.class, WebConfig.class }) @WebAppConfiguration @WithUserDetails(value = "admin") @IfProfileValue(name = "spring.profiles.active", values = { "quartz-integration-tests" }) public @interface CronTaskTest { }
package org.carlspring.strongbox.cron.context; import org.carlspring.strongbox.config.WebConfig; import org.carlspring.strongbox.cron.config.CronTasksConfig; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.security.test.context.support.WithUserDetails; import org.springframework.test.annotation.IfProfileValue; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.web.WebAppConfiguration; /** * Marks test to be executed only under special spring active profile. * * @author Alex Oreshkevich */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @ContextConfiguration(classes = { CronTasksConfig.class, WebConfig.class }) @WebAppConfiguration @WithUserDetails(value = "admin") @IfProfileValue(name = "spring.profiles.active", values = { "quartz-integration-test" }) public @interface CronTaskTest { }
Fix crash on invalid int
''' Provides commands to the xkcd system ''' from stickord.helpers.xkcd_api import get_random, get_by_id, print_comic, get_recent from stickord.registry import Command @Command('xkcd', category='xkcd') async def get_comic(cont, _mesg): ''' Search for a comic by id, if no id is provided it will post a random comic. ''' if cont: try: comic_id = int(cont[0]) comic = await get_by_id(comic_id) return await print_comic(comic) except ValueError: pass comic = await get_random() return await print_comic(comic) @Command('newxkcd', category='xkcd') async def get_latest_comic(_cont, _mesg): ''' Posts the latest xkcd comic. ''' comic = await get_recent() return await print_comic(comic)
''' Provides commands to the xkcd system ''' from stickord.helpers.xkcd_api import get_random, get_by_id, print_comic, get_recent from stickord.registry import Command @Command('xkcd', category='xkcd') async def get_comic(cont, _mesg): ''' Search for a comic by id, if no id is provided it will post a random comic. ''' if cont: comic_id = int(cont[0]) comic = await get_by_id(comic_id) return await print_comic(comic) comic = await get_random() return await print_comic(comic) @Command('newxkcd', category='xkcd') async def get_latest_comic(_cont, _mesg): ''' Posts the latest xkcd comic. ''' comic = await get_recent() return await print_comic(comic)
Allow inventory size assertion to be skipped
package org.cyclops.cyclopscore.inventory.container; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.container.ContainerType; import javax.annotation.Nullable; /** * A container for an inventory. * @author rubensworks */ public abstract class InventoryContainer extends ContainerExtended { protected final IInventory inventory; public InventoryContainer(@Nullable ContainerType<?> type, int id, PlayerInventory playerInventory, IInventory inventory) { super(type, id, playerInventory); this.inventory = inventory; if (isAssertInventorySize()) { assertInventorySize(inventory, getSizeInventory()); } this.inventory.openInventory(playerInventory.player); } protected boolean isAssertInventorySize() { return true; } public IInventory getContainerInventory() { return inventory; } @Override protected int getSizeInventory() { return inventory.getSizeInventory(); } @Override public boolean canInteractWith(PlayerEntity player) { return this.inventory.isUsableByPlayer(player); } @Override public void onContainerClosed(PlayerEntity player) { super.onContainerClosed(player); this.inventory.closeInventory(player); } }
package org.cyclops.cyclopscore.inventory.container; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.container.ContainerType; import javax.annotation.Nullable; /** * A container for an inventory. * @author rubensworks */ public abstract class InventoryContainer extends ContainerExtended { protected final IInventory inventory; public InventoryContainer(@Nullable ContainerType<?> type, int id, PlayerInventory playerInventory, IInventory inventory) { super(type, id, playerInventory); this.inventory = inventory; assertInventorySize(inventory, getSizeInventory()); this.inventory.openInventory(playerInventory.player); } public IInventory getContainerInventory() { return inventory; } @Override protected int getSizeInventory() { return inventory.getSizeInventory(); } @Override public boolean canInteractWith(PlayerEntity player) { return this.inventory.isUsableByPlayer(player); } @Override public void onContainerClosed(PlayerEntity player) { super.onContainerClosed(player); this.inventory.closeInventory(player); } }
Fix duplicate Require Dose/Freq for systemic meds setting
<?php class m170831_100900_add_system_setting_disable_correspondence_notes_copy extends CDbMigration { public function up() { $this->insert('setting_metadata', array( 'display_order' => 0, 'field_type_id' => 3, 'key' => 'disable_correspondence_notes_copy', 'name' => 'Disable copy for notes in correspondence', 'data' => serialize(array('on'=>'On', 'off'=>'Off')), 'default_value' => 'on' )); $this->insert('setting_installation', array( 'key' => 'disable_correspondence_notes_copy', 'value' => 'on' )); } public function down() { $this->delete('setting_installation', '`key`="disable_correspondence_notes_copy"'); $this->delete('setting_metadata', '`key`="disable_correspondence_notes_copy"'); } }
<?php class m170831_100900_add_system_setting_disable_correspondence_notes_copy extends CDbMigration { public function up() { $this->insert('setting_metadata', array( 'display_order' => 0, 'field_type_id' => 3, 'key' => 'disable_correspondence_notes_copy', 'name' => 'Require Dose/Freq for systemic meds', 'data' => serialize(array('on'=>'On', 'off'=>'Off')), 'default_value' => 'on' )); $this->insert('setting_installation', array( 'key' => 'disable_correspondence_notes_copy', 'value' => 'on' )); } public function down() { $this->delete('setting_installation', '`key`="disable_correspondence_notes_copy"'); $this->delete('setting_metadata', '`key`="disable_correspondence_notes_copy"'); } }
Add helpful text to template error
from django import template from django.template.defaultfilters import stringfilter from django.template.base import TemplateSyntaxError import hashlib from django_hash_filter.templatetags import get_available_hashes register = template.Library() @register.filter @stringfilter def hash(value, arg): """ Returns a hex-digest of the passed in value for the hash algorithm given. """ arg = str(arg).lower() if not arg in get_available_hashes(): raise TemplateSyntaxError("The %s hash algorithm does not exist. Supported algorithms are: %" % (arg, get_available_hashes())) try: f = getattr(hashlib, arg) hashed = f(value).hexdigest() except Exception: raise ValueError("The %s hash algorithm cannot produce a hex digest. Ensure that OpenSSL is properly installed." % arg) return hashed
from django import template from django.template.defaultfilters import stringfilter from django.template.base import TemplateSyntaxError import hashlib from django_hash_filter.templatetags import get_available_hashes register = template.Library() @register.filter @stringfilter def hash(value, arg): """ Returns a hex-digest of the passed in value for the hash algorithm given. """ arg = str(arg).lower() if not arg in get_available_hashes(): raise TemplateSyntaxError("The %s hash algorithm does not exist." % arg) try: f = getattr(hashlib, arg) hashed = f(value).hexdigest() except Exception: raise ValueError("The %s hash algorithm cannot produce a hex digest. Ensure that OpenSSL is properly installed." % arg) return hashed
Add link to wiki in navbar in app layout
<header class="main-header"> <!-- Logo --> <a href="{{ url('') }}" class="logo"> <span class="logo-mini">O<b>D</b></span> <span class="logo-lg">Open<b>Dominion</b></span> </a> <!-- Header Navbar --> <nav class="navbar navbar-static-top" role="navigation"> <!-- Sidebar toggle button --> <a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button"> <span class="sr-only">Toggle navigation</span> </a> <!-- Navbar Right Menu --> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> @include('partials.notification-nav') @include('partials.wiki-nav') @include('partials.staff-nav') @include('partials.auth-user-nav') </ul> </div> </nav> </header>
<header class="main-header"> <!-- Logo --> <a href="{{ url('') }}" class="logo"> <span class="logo-mini">O<b>D</b></span> <span class="logo-lg">Open<b>Dominion</b></span> </a> <!-- Header Navbar --> <nav class="navbar navbar-static-top" role="navigation"> <!-- Sidebar toggle button --> <a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button"> <span class="sr-only">Toggle navigation</span> </a> <!-- Navbar Right Menu --> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> @include('partials.notification-nav') @include('partials.staff-nav') @include('partials.auth-user-nav') </ul> </div> </nav> </header>
Change exception thrown for calling unsupported helper method
<?php namespace Mdd\QueryBuilder\Conditions; use Mdd\QueryBuilder\Condition; abstract class AbstractCondition implements Condition { public function _and(Condition $condition) { return new Binaries\AndCondition($this, $condition); } public function _or(Condition $condition) { return new Binaries\OrCondition($this, $condition); } public function __call($methodName, $arguments) { $method = '_' . $methodName; if(method_exists($this, $method)) { if(array_key_exists(0, $arguments)) { return $this->$method($arguments[0]); } } throw new \LogicException(sprintf("Unkown method %s", $method)); } }
<?php namespace Mdd\QueryBuilder\Conditions; use Mdd\QueryBuilder\Condition; abstract class AbstractCondition implements Condition { public function _and(Condition $condition) { return new Binaries\AndCondition($this, $condition); } public function _or(Condition $condition) { return new Binaries\OrCondition($this, $condition); } public function __call($methodName, $arguments) { $method = '_' . $methodName; if(method_exists($this, $method)) { if(array_key_exists(0, $arguments)) { return $this->$method($arguments[0]); } } throw new \RuntimeException(sprintf("Unkown method %s", $method)); } }
Update for rename of worker
/* Copyright 2017 Vector Creations Ltd 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. */ // The prescribed way of doing this import would be: //import {IndexedDbStoreWorker} from 'matrix-js-sdk'; // However, this still pulls in all of the js-sdk and we only use a tiny fraction // of it. It also causes an Olm error to appear because we don't have an Olm in scope. // Instead, we do this: import IndexedDBStoreWorker from 'matrix-js-sdk/lib/store/indexeddb-store-worker'; const remoteWorker = new IndexedDBStoreWorker(postMessage); onmessage = remoteWorker.onMessage;
/* Copyright 2017 Vector Creations Ltd 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. */ // The prescribed way of doing this import would be: //import {IndexedDbStoreWorker} from 'matrix-js-sdk'; // However, this still pulls in all of the js-sdk and we only use a tiny fraction // of it. It also causes an Olm error to appear because we don't have an Olm in scope. // Instead, we do this: import IndexedDbStoreWorker from 'matrix-js-sdk/lib/store/indexeddb-remote-worker'; const remoteWorker = new IndexedDbStoreWorker(postMessage); onmessage = remoteWorker.onMessage;
Implement Wires helper method get_nth_wire_position
from enum import Enum from .AbstractModule import AbstractModule, ModuleState class WireColors(Enum): MISSING = 'missing' BLACK = 'black' RED = 'red' WHITE = 'white' BLUE = 'blue' YELLOW = 'yellow' def get_correct_wire(sequence, boolpar): wires_count = get_wires_count(sequence) def get_wires_count(sequence): return len([1 for x in sequence if x != WireColors.MISSING.value]) def get_nth_wire_position(sequence, n): counter = 0 for idx, value in enumerate(sequence): if value != WireColors.MISSING.value: counter += 1 if counter == n: return idx return None class WiresModule(AbstractModule): def export_to_string(self): raise NotImplementedError def import_from_string(self, string): raise NotImplementedError def translate_to_commands(self): raise NotImplementedError def __init__(self): super().__init__() self.name = "WiresModule" self.type_number = 10 self.state = ModuleState.Armed
from enum import Enum from .AbstractModule import AbstractModule, ModuleState class WireColors(Enum): MISSING = 'missing' BLACK = 'black' RED = 'red' WHITE = 'white' BLUE = 'blue' YELLOW = 'yellow' def get_correct_wire(sequence, boolpar): wires_count = get_wires_count(sequence) def get_wires_count(sequence): return len([1 for x in sequence if x != WireColors.MISSING.value]) def get_nth_wire_position(sequence, n): NotImplementedError class WiresModule(AbstractModule): def export_to_string(self): raise NotImplementedError def import_from_string(self, string): raise NotImplementedError def translate_to_commands(self): raise NotImplementedError def __init__(self): super().__init__() self.name = "WiresModule" self.type_number = 10 self.state = ModuleState.Armed
Make search by name default
const api = require('./src/api'); function isRoute(route) { return slot => { return slot.l === route; } } // http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric function isNumeric(n) { return !isNaN(parseFloat(n) && isFinite(n)); } function isId(query) { return isNumeric(query[0]); } function get(query) { if (isId(query)) { return api.byStopId(query).then(stop => { return stop .filter(isRoute("60")) .map((route) => route.ts) .join('\n'); }); } return api.byStopName(query).then(stops => { return stops .map(stop => { return `${stop.name}\t\t${stop.locationId}`; }).join('\n'); }); } if (process.argv.length > 2) { const query = process.argv.slice(2).join(" "); get(query).then(console.log); }
const api = require('./src/api'); function isRoute(route) { return slot => { return slot.l === route; } } // http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric function isNumeric(n) { return !isNaN(parseFloat(n) && isFinite(n)); } function isId(query) { return isNumeric(query[0]); } function get(query) { if (isId(query)) { return api.byStopId(query).then(stop => { return stop .filter(isRoute("60")) .map((route) => route.ts) .join('\n'); }); } else { return api.byStopName(query).then(stops => { return stops .map(stop => { return `${stop.name}\t\t${stop.locationId}`; }).join('\n'); }); } } if (process.argv.length > 2) { const query = process.argv.slice(2).join(" "); get(query).then(console.log); }
Call "routeToState" on page's ready()
/** * @class CM_Page_Abstract * @extends CM_Component_Abstract */ var CM_Page_Abstract = CM_Component_Abstract.extend({ /** @type String */ _class: 'CM_Page_Abstract', /** @type String[] */ _stateParams: [], /** @type String|Null */ _fragment: null, _ready: function() { var location = window.location; var params = queryString.parse(location.search); var state = _.pick(params, _.intersection(_.keys(params), this.getStateParams())); this.routeToState(state, location.pathname + location.search); CM_Component_Abstract.prototype._ready.call(this); }, /** * @returns {String|Null} */ getFragment: function() { return this._fragment; }, /** * @returns {String[]} */ getStateParams: function() { return this._stateParams; }, /** * @param {Object} state * @param {String} fragment */ routeToState: function(state, fragment) { this._fragment = fragment; this._changeState(state); }, /** * @param {Object} state */ _changeState: function(state) { } });
/** * @class CM_Page_Abstract * @extends CM_Component_Abstract */ var CM_Page_Abstract = CM_Component_Abstract.extend({ /** @type String */ _class: 'CM_Page_Abstract', /** @type String[] */ _stateParams: [], /** @type String|Null */ _fragment: null, _ready: function() { this._fragment = window.location.pathname + window.location.search; // @todo routeToState CM_Component_Abstract.prototype._ready.call(this); }, /** * @returns {String|Null} */ getFragment: function() { return this._fragment; }, /** * @returns {String[]} */ getStateParams: function() { return this._stateParams; }, /** * @param {Object} state * @param {String} fragment */ routeToState: function(state, fragment) { this._fragment = fragment; this._changeState(state); }, /** * @param {Object} state */ _changeState: function(state) { } });
Add TODO note on reusability
'use strict'; var request = require('request'); var opts = { uri: 'https://api.github.com' + '/users/' + process.argv[2] + '/events', json: true, method: 'GET', headers: { 'User-Agent': 'nodejs script' } } if (! process.argv[2]) { console.log('Usage: nodejs gevents.js <user-name>'); process.exit(0); } request(opts, function (err, res, body) { if (err) throw new Error(err); var format = '[%s]: %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); } });
'use strict'; var request = require('request'); var opts = { uri: 'https://api.github.com' + '/users/' + process.argv[2] + '/events', json: true, method: 'GET', headers: { 'User-Agent': 'nodejs script' } } if (! process.argv[2]) { console.log('Usage: nodejs gevents.js <user-name>'); process.exit(0); } request(opts, function (err, res, body) { if (err) throw new Error(err); var format = '[%s]: %s %s %s %s'; for (var i = 0; i < body.length; i++) { console.log(format , body[i].created_at , body[i].type , body[i].actor.login , body[i].repo.name); } });
Kill dad code for old compiler
import fetchparser def print_parsed(): for line in fetchparser.parse_input(open("sample.fetch").read()): print line def print_lexed(): import fetchlexer l=fetchlexer.get_lexer() # Give the lexer some input l.input(open("sample.fetch").read()) # Tokenize while True: tok = l.token() if not tok: break # No more input print tok def interpret(): import fetchinterpreter compiled = fetchparser.parse_input(open("sample.fetch").read()) for line in compiled: fetchinterpreter.handle_line(line) print "Output", fetchinterpreter.get_output() if __name__ == "__main__": print "\n--Lexed--" print_lexed() print "\n--Parsed--" try: print_parsed() except SyntaxError: print "Terminating" import sys sys.exit(1) print "\n--Interpreting--" interpret()
import fetchparser def print_parsed(): for line in fetchparser.parse_input(open("sample.fetch").read()): print line def print_lexed(): import fetchlexer l=fetchlexer.get_lexer() # Give the lexer some input l.input(open("sample.fetch").read()) # Tokenize while True: tok = l.token() if not tok: break # No more input print tok def interpret(): import fetchinterpreter compiled = fetchparser.parse_input(open("sample.fetch").read()) for line in compiled: fetchinterpreter.handle_line(line) print "Output", fetchinterpreter.get_output() def execute_compiled(): execfile("fetchout.py") if __name__ == "__main__": print "\n--Lexed--" print_lexed() print "\n--Parsed--" try: print_parsed() except SyntaxError: print "Terminating" import sys sys.exit(1) print "\n--Interpreting--" interpret()
Add goleak to main package
package main import ( "os" "testing" "github.com/rollbar/rollbar-go" "github.com/stretchr/testify/assert" "go.uber.org/goleak" ) func TestMain(m *testing.M) { rollbar.Close() goleak.VerifyTestMain(m) } func TestSetupEnv(t *testing.T) { setupEnv() port := os.Getenv("PORT") assert.NotEqual(t, port, "") } func TestSetupRollbar(t *testing.T) { setupRollbar() assert.Equal(t, rollbar.Token(), os.Getenv("ROLLBAR_SERVER_TOKEN")) assert.Equal(t, rollbar.Environment(), os.Getenv("ENVIRONMENT")) } func TestGetLogger(t *testing.T) { origEnv := os.Getenv("ENVIRONMENT") defer func() { os.Setenv("ENVIRONMENt", origEnv) }() os.Setenv("ENVIRONMENT", "development") logger := getLogger() assert.NotNil(t, logger) os.Setenv("ENVIRONMENT", "production") logger = getLogger() assert.NotNil(t, logger) }
package main import ( "os" "testing" "github.com/rollbar/rollbar-go" "github.com/stretchr/testify/assert" ) func TestSetupEnv(t *testing.T) { setupEnv() port := os.Getenv("PORT") assert.NotEqual(t, port, "") } func TestSetupRollbar(t *testing.T) { setupRollbar() assert.Equal(t, rollbar.Token(), os.Getenv("ROLLBAR_SERVER_TOKEN")) assert.Equal(t, rollbar.Environment(), os.Getenv("ENVIRONMENT")) } func TestGetLogger(t *testing.T) { origEnv := os.Getenv("ENVIRONMENT") defer func() { os.Setenv("ENVIRONMENt", origEnv) }() os.Setenv("ENVIRONMENT", "development") logger := getLogger() assert.NotNil(t, logger) os.Setenv("ENVIRONMENT", "production") logger = getLogger() assert.NotNil(t, logger) }
Fix home books to be the most recent
import _ from 'underscore'; import db from 'dbContext'; import templatesHelper from '../views/helpers/templatesHelper.js'; import pagesHelper from '../views/helpers/pagesHelper.js'; import bookModel from '../models/bookModel.js'; class homeController { load(sammy) { pagesHelper.append('home'); bookModel.getBooks() .descending("createdAt") .limit(3) .find() .then(function(books){ return templatesHelper.append('libraryBook', books, '#library-content'); }) .then(function() { var libraryBookContent = $('#library-content'); libraryBookContent.on('click', 'div img', function() { var id = $(this).attr('data-id'); sammy.redirect('#/library/detailed/' + id); }); }); } } export default new homeController();
import _ from 'underscore'; import db from 'dbContext'; import templatesHelper from '../views/helpers/templatesHelper.js'; import pagesHelper from '../views/helpers/pagesHelper.js'; import bookModel from '../models/bookModel.js'; class homeController { load(sammy) { pagesHelper.append('home'); bookModel.getBooks().limit(3).find() .then(function(books){ return templatesHelper.append('libraryBook', books, '#library-content'); }) .then(function() { var libraryBookContent = $('#library-content'); libraryBookContent.on('click', 'div img', function() { var id = $(this).attr('data-id'); sammy.redirect('#/library/detailed/' + id); }); }); } } export default new homeController();
Change in coordinates in the NeuroHDF create
#!/usr/bin/python # Create a project and stack associated HDF5 file with additional # data such as labels, meshes etc. import os.path as op import h5py from contextlib import closing import numpy as np project_id = 1 stack_id = 2 filepath = '/home/stephan/dev/CATMAID/django/hdf5' with closing(h5py.File(op.join(filepath, '%s_%s.hdf' % (project_id, stack_id)), 'w')) as hfile: mesh=hfile.create_group('meshes') midline=mesh.create_group('midline') midline.create_dataset("vertices", data=np.array( [61200, 15200, 26750,63920, 26400, 76800, 66800,57600,76800, 69200,53120,26750] , dtype = np.float32 ) ) # faces are coded according to the three.js JSONLoader standard. # See https://github.com/mrdoob/three.js/blob/master/src/extras/loaders/JSONLoader.js midline.create_dataset("faces", data=np.array( [0, 0, 1, 2, 0,2,3,0] , dtype = np.uint32 ) )
#!/usr/bin/python # Create a project and stack associated HDF5 file with additional # data such as labels, meshes etc. import os.path as op import h5py from contextlib import closing import numpy as np project_id = 1 stack_id = 1 filepath = '/home/stephan/dev/CATMAID/django/hdf5' with closing(h5py.File(op.join(filepath, '%s_%s.hdf' % (project_id, stack_id)), 'w')) as hfile: mesh=hfile.create_group('meshes') midline=mesh.create_group('midline') midline.create_dataset("vertices", data=np.array( [4900, 40, 0, 5230, 70, 4131, 5250,7620,4131, 4820,7630,0] , dtype = np.float32 ) ) # faces are coded according to the three.js JSONLoader standard. # See https://github.com/mrdoob/three.js/blob/master/src/extras/loaders/JSONLoader.js midline.create_dataset("faces", data=np.array( [0, 0, 1, 2, 0,2,3,0] , dtype = np.uint32 ) )
Add try except to the method that parse idea datetime
# IdeaScaly # Copyright 2015 Jorge Saldivar # See LICENSE for details. import six import dateutil.parser from datetime import datetime def parse_datetime(str_date): try: date_is = dateutil.parser.parse(str_date) return date_is except: print("Invalid date: %s" % str_date) return None def parse_html_value(html): return html[html.find('>')+1:html.rfind('<')] def parse_a_href(atag): start = atag.find('"') + 1 end = atag.find('"', start) return atag[start:end] def convert_to_utf8_str(arg): # written by Michael Norton (http://docondev.blogspot.com/) if isinstance(arg, six.text_type): arg = arg.encode('utf-8') elif not isinstance(arg, bytes): arg = six.text_type(arg).encode('utf-8') return arg def import_simplejson(): try: import simplejson as json except ImportError: try: import json # Python 2.6+ except ImportError: raise ImportError("Can't load a json library") return json
# IdeaScaly # Copyright 2015 Jorge Saldivar # See LICENSE for details. import six import dateutil.parser from datetime import datetime def parse_datetime(str_date): date_is = dateutil.parser.parse(str_date) return date_is def parse_html_value(html): return html[html.find('>')+1:html.rfind('<')] def parse_a_href(atag): start = atag.find('"') + 1 end = atag.find('"', start) return atag[start:end] def convert_to_utf8_str(arg): # written by Michael Norton (http://docondev.blogspot.com/) if isinstance(arg, six.text_type): arg = arg.encode('utf-8') elif not isinstance(arg, bytes): arg = six.text_type(arg).encode('utf-8') return arg def import_simplejson(): try: import simplejson as json except ImportError: try: import json # Python 2.6+ except ImportError: raise ImportError("Can't load a json library") return json
Add default setting for Webpack output.filename
'use strict'; var assign = require('lodash').assign; var utils = require('gulp-util'); var webpack = require('webpack'); var PluginError = utils.PluginError; var defaults = { optimize: false, plugins: { webpack: { entry: './src/main.js', output: { path: './dist', filename: 'main.js' }, plugins: [] } } }; module.exports = function (gulp, options) { var opts = assign(defaults, options); var plugins = opts.plugins; var optimize = opts.optimize; gulp.task('js', function (done) { var settings = plugins.webpack; if (optimize) { settings.plugins.push( new webpack.optimize.UglifyJsPlugin() ); } webpack(settings, function (err, stats) { if (err) throw new PluginError('webpack', err); done(); }); }); };
'use strict'; var assign = require('lodash').assign; var utils = require('gulp-util'); var webpack = require('webpack'); var PluginError = utils.PluginError; var defaults = { optimize: false, plugins: { webpack: { entry: './src/main.js', output: { path: './dist' }, plugins: [] } } }; module.exports = function (gulp, options) { var opts = assign(defaults, options); var plugins = opts.plugins; var optimize = opts.optimize; gulp.task('js', function (done) { var settings = plugins.webpack; if (optimize) { settings.plugins.push( new webpack.optimize.UglifyJsPlugin() ); } webpack(settings, function (err, stats) { if (err) throw new PluginError('webpack', err); done(); }); }); };
Increase timeout so that the large stdout test won't fail on slow machine.
var Process = require("../lib/Process"); var chai = require("chai"); var chaiAsPromised = require("chai-as-promised"); chai.use(chaiAsPromised); var expect = chai.expect; describe("Testing Process class", function () { this.timeout(5000); it("echo hello", function () { var process = new Process({ command: "echo", args: [ "hello" ] }); return expect(process.getCode()).to.eventually.equals(0); }); it("large output", function () { var process = new Process({ command: "head", args: [ "-c", "2048000", "/dev/zero" ] }); return expect(process.getCode().then(function () { return process.getStdout().length; })).to.eventually.equals(1024 * 1024); }); });
var Process = require("../lib/Process"); var chai = require("chai"); var chaiAsPromised = require("chai-as-promised"); chai.use(chaiAsPromised); var expect = chai.expect; describe("Testing Process class", function () { it("echo hello", function () { var process = new Process({ command: "echo", args: [ "hello" ] }); return expect(process.getCode()).to.eventually.equals(0); }); it("large output", function () { var process = new Process({ command: "head", args: [ "-c", "2048000", "/dev/zero" ] }); return expect(process.getCode().then(function () { return process.getStdout().length; })).to.eventually.equals(1024 * 1024); }); });
Add ignored files in gulp-eslint conf
const gulp = require('gulp'); const gutil = require('gulp-util'); const eslint = require('gulp-eslint'); const excludeGitignore = require('gulp-exclude-gitignore'); const mocha = require('gulp-mocha'); const istanbul = require('gulp-istanbul'); gulp.task('linter', eslintCheck); gulp.task('default', gulp.series('linter', gulp.series(istanbulCover, mochaTest))); function eslintCheck() { return gulp.src(['**/*.js', '!**/templates/**']) .pipe(excludeGitignore()) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); } function istanbulCover() { return gulp.src('generators/**/index.js') .pipe(istanbul({includeUntested: true})) .pipe(istanbul.hookRequire()); } function mochaTest() { return gulp.src('test/**/*.js') .pipe(mocha({reporter: 'spec'})) .once('error', err => { gutil.log(gutil.colors.red('[Mocha]'), err.toString()); process.exit(1); }) .pipe(istanbul.writeReports()); }
const gulp = require('gulp'); const gutil = require('gulp-util'); const eslint = require('gulp-eslint'); const excludeGitignore = require('gulp-exclude-gitignore'); const mocha = require('gulp-mocha'); const istanbul = require('gulp-istanbul'); gulp.task('linter', eslintCheck); gulp.task('default', gulp.series('linter', gulp.series(istanbulCover, mochaTest))); function eslintCheck() { return gulp.src('**/*.js') .pipe(excludeGitignore()) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); } function istanbulCover() { return gulp.src('generators/**/index.js') .pipe(istanbul({includeUntested: true})) .pipe(istanbul.hookRequire()); } function mochaTest() { return gulp.src('test/**/*.js') .pipe(mocha({reporter: 'spec'})) .once('error', err => { gutil.log(gutil.colors.red('[Mocha]'), err.toString()); process.exit(1); }) .pipe(istanbul.writeReports()); }
Add --version flag to print atom-shell's version.
var app = require('app'); var dialog = require('dialog'); var path = require('path'); // Quit when all windows are closed and no other one is listening to this. app.on('window-all-closed', function() { if (app.listeners('window-all-closed').length == 1) app.quit(); }); process.argv.splice(1, 0, 'dummyScript'); var argv = require('optimist').argv; // Start the specified app if there is one specified in command line, otherwise // start the default app. if (argv._.length > 0) { try { require(path.resolve(argv._[0])); } catch(e) { if (e.code == 'MODULE_NOT_FOUND') { console.error(e.stack); console.error('Specified app is invalid'); process.exit(1); } else { throw e; } } } else if (argv.version) { console.log(process.versions['atom-shell']); process.exit(0); } else { require('./default_app.js'); }
var app = require('app'); var argv = require('optimist').argv; var dialog = require('dialog'); var path = require('path'); // Quit when all windows are closed and no other one is listening to this. app.on('window-all-closed', function() { if (app.listeners('window-all-closed').length == 1) app.quit(); }); // Start the specified app if there is one specified in command line, otherwise // start the default app. if (argv._.length > 0) { try { require(path.resolve(argv._[0])); } catch(e) { if (e.code == 'MODULE_NOT_FOUND') { console.error(e.stack); console.error('Specified app is invalid'); process.exit(1); } else { throw e; } } } else { require('./default_app.js'); }
Remove $_mockData from TestCase trait It cannot share a property with subclasses because subclasses will always change the value, and this is invalid in PHP.
<?php /** * @package Garp * @author Harmen Janssen <harmen@grrr.nl> */ trait Garp_Test_Traits_UsesTestHelper { /** * @var Garp_Test_PHPUnit_Helper */ protected $_helper; public function setUp(): void { $this->_helper = new Garp_Test_PHPUnit_Helper(); $mockData = property_exists($this, '_mockData') ? $this->_mockData : []; $this->_helper->setUp($mockData); parent::setUp(); } public function tearDown(): void { $mockData = property_exists($this, '_mockData') ? $this->_mockData : []; if ($this->_helper) { $this->_helper->tearDown($mockData); } parent::tearDown(); } }
<?php /** * @package Garp * @author Harmen Janssen <harmen@grrr.nl> */ trait Garp_Test_Traits_UsesTestHelper { /** * @var Garp_Test_PHPUnit_Helper */ protected $_helper; /** * Fixtures * * @var array */ protected $_mockData = array(); public function setUp(): void { $this->_helper = new Garp_Test_PHPUnit_Helper(); $this->_helper->setUp($this->_mockData); parent::setUp(); } public function tearDown(): void { if ($this->_helper) { $this->_helper->tearDown($this->_mockData); } parent::tearDown(); } }
Add a note about root and nmap binary dependency.
import nmap from st2actions.runners.pythonrunner import Action """ Note: This action requires nmap binary to be available and needs to run as root. """ class PortScanner(Action): def run(self, host): result = [] port_details = {} ps = nmap.PortScanner() scan_res = ps.scan(host, arguments='--min-parallelism 100 -sT -sU -sZ') for target_host in ps.all_hosts(): if target_host in ps.all_hosts(): for comm in ps[target_host].all_protocols(): if comm in ['tcp','udp','ip','sctp']: ports = ps[target_host][comm].keys() ports.sort() for port in ports: port_details = {port:{'state':ps[host][comm][port]['state'], 'service':ps[host][comm][port]['name'], 'protocol':comm}} result.append(port_details) return result if __name__ == "__main__": ps = PortScanner() ps.run()
import nmap from st2actions.runners.pythonrunner import Action class PortScanner(Action): def run(self, host): result = [] port_details = {} ps = nmap.PortScanner() scan_res = ps.scan(host, arguments='--min-parallelism 100 -sT -sU -sZ') for target_host in ps.all_hosts(): if target_host in ps.all_hosts(): for comm in ps[target_host].all_protocols(): if comm in ['tcp','udp','ip','sctp']: ports = ps[target_host][comm].keys() ports.sort() for port in ports: port_details = {port:{'state':ps[host][comm][port]['state'], 'service':ps[host][comm][port]['name'], 'protocol':comm}} result.append(port_details) return result if __name__ == "__main__": ps = PortScanner() ps.run()
Remove unwanted whitespace in tests
# Tests for SecretStorage # Author: Dmitry Shachnev, 2013 # License: BSD # Various exception tests import unittest import secretstorage from secretstorage.exceptions import ItemNotFoundException class ExceptionsTest(unittest.TestCase): """A test case that ensures that all SecretStorage exceptions are raised correctly.""" @classmethod def setUpClass(cls): cls.bus = secretstorage.dbus_init(main_loop=False) cls.collection = secretstorage.Collection(cls.bus) def test_double_deleting(self): item = self.collection.create_item('MyItem', {'application': 'secretstorage-test'}, b'pa$$word') item.delete() self.assertRaises(ItemNotFoundException, item.delete) def test_non_existing_item(self): self.assertRaises(ItemNotFoundException, secretstorage.Item, self.bus, '/not/existing/path') def test_non_existing_collection(self): self.assertRaises(ItemNotFoundException, secretstorage.get_collection_by_alias, self.bus, 'non-existing-alias') if __name__ == '__main__': unittest.main()
# Tests for SecretStorage # Author: Dmitry Shachnev, 2013 # License: BSD # Various exception tests import unittest import secretstorage from secretstorage.exceptions import ItemNotFoundException class ExceptionsTest(unittest.TestCase): """A test case that ensures that all SecretStorage exceptions are raised correctly.""" @classmethod def setUpClass(cls): cls.bus = secretstorage.dbus_init(main_loop=False) cls.collection = secretstorage.Collection(cls.bus) def test_double_deleting(self): item = self.collection.create_item('MyItem', {'application': 'secretstorage-test'}, b'pa$$word') item.delete() self.assertRaises(ItemNotFoundException, item.delete) def test_non_existing_item(self): self.assertRaises(ItemNotFoundException, secretstorage.Item, self.bus, '/not/existing/path') def test_non_existing_collection(self): self.assertRaises(ItemNotFoundException, secretstorage.get_collection_by_alias, self.bus, 'non-existing-alias') if __name__ == '__main__': unittest.main()
Remove select2 again, because that sucked
$(function () { 'use strict'; var $coordinator_select = $('#coordinator_id'); var $group_select = $('#group_id'); function set_group_users() { var group_id = $group_select.val(); $.get('/api/group/users/' + group_id, {}, function (data) { $coordinator_select.empty(); _(data.users).forEach(function (user) { var $option = $('<option></option>'); $option.val(user.val); $option.text(user.label); $coordinator_select.append($option); }); }); } $group_select.change(function () { set_group_users(); }); });
$(function () { 'use strict'; var $coordinator_select = $('#coordinator_id'); var $group_select = $('#group_id'); $coordinator_select.select2(); $group_select.select2(); function set_group_users() { var group_id = $group_select.val(); $.get('/api/group/users/' + group_id, {}, function (data) { $coordinator_select.empty(); _(data.users).forEach(function (user) { var $option = $('<option></option>'); $option.val(user.val); $option.text(user.label); $coordinator_select.append($option); }); }); } $group_select.change(function () { set_group_users(); }); });
Fix transformer collection contract class name in service provider
<?php namespace EGALL\Transformer; use Illuminate\Support\ServiceProvider; use EGALL\Transformer\Contracts\Transformer as TransformerContract; use EGALL\Transformer\Contracts\TransformableCollection as TransformableCollectionContract; /** * Transformer service provider. * * @package EGALL\Transformer * @author Erik Galloway <erik@mybarnapp.com> */ class TransformerServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app->bind(TransformerContract::class, Transformer::class); $this->app->bind(TransformableCollectionContract::class, TransformableCollection::class); } }
<?php namespace EGALL\Transformer; use Illuminate\Support\ServiceProvider; use EGALL\Transformer\Contracts\Transformer as TransformerContract; use EGALL\Transformer\Contracts\TransformableCollection as TransformableCollectionContract; /** * Transformer service provider. * * @package EGALL\Transformer * @author Erik Galloway <erik@mybarnapp.com> */ class TransformerServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app->bind(TransformerContract::class, Transformer::class); $this->app->bind(TransformerCollectionContract::class, TransformableCollection::class); } }
Add also ctor without setSize back
package info.u_team.u_team_core.screen; import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.container.Container; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.ITextComponent; public class UBasicContainerScreen<T extends Container> extends UContainerScreen<T> { public UBasicContainerScreen(T container, PlayerInventory playerInventory, ITextComponent title, ResourceLocation background) { super(container, playerInventory, title, background); } public UBasicContainerScreen(T container, PlayerInventory playerInventory, ITextComponent title, ResourceLocation background, int xSize, int ySize) { super(container, playerInventory, title, background); setSize(xSize, ySize); } @Override public void func_230430_a_(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) { func_230446_a_(matrixStack); super.func_230430_a_(matrixStack, mouseX, mouseY, partialTicks); field_230710_m_.forEach(widget -> widget.func_230443_a_(matrixStack, mouseX, mouseY)); func_230459_a_(matrixStack, mouseX, mouseY); } }
package info.u_team.u_team_core.screen; import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.container.Container; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.ITextComponent; public class UBasicContainerScreen<T extends Container> extends UContainerScreen<T> { public UBasicContainerScreen(T container, PlayerInventory playerInventory, ITextComponent title, ResourceLocation background, int xSize, int ySize) { super(container, playerInventory, title, background); setSize(xSize, ySize); } @Override public void func_230430_a_(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) { func_230446_a_(matrixStack); super.func_230430_a_(matrixStack, mouseX, mouseY, partialTicks); field_230710_m_.forEach(widget -> widget.func_230443_a_(matrixStack, mouseX, mouseY)); func_230459_a_(matrixStack, mouseX, mouseY); } }
Hide spurious numpy warnings about divide by zeros and nans. git-svn-id: 4c7b13231a96299fde701bb5dec4bd2aaf383fc6@429 979d6bd5-6d4d-0410-bece-f567c23bd345
""" For examples of dadi's usage, see the examples directory in the source distribution. Documentation of all methods can be found in doc/api/index.html of the source distribution. """ import logging logging.basicConfig() import Demographics1D import Demographics2D import Inference import Integration import Misc import Numerics import PhiManip # Protect import of Plotting in case matplotlib not installed. try: import Plotting except ImportError: pass # We do it this way so it's easier to reload. import Spectrum_mod Spectrum = Spectrum_mod.Spectrum try: # This is to try and ensure we have a nice __SVNVERSION__ attribute, so # when we get bug reports, we know what version they were using. The # svnversion file is created by setup.py. import os _directory = os.path.dirname(Integration.__file__) _svn_file = os.path.join(_directory, 'svnversion') __SVNVERSION__ = file(_svn_file).read().strip() except: __SVNVERSION__ = 'Unknown' # When doing arithmetic with Spectrum objects (which are masked arrays), we # often have masked values which generate annoying arithmetic warnings. Here # we tell numpy to ignore such warnings. This puts greater onus on the user to # check results, but for our use case I think it's the better default. import numpy numpy.seterr(all='ignore')
""" For examples of dadi's usage, see the examples directory in the source distribution. Documentation of all methods can be found in doc/api/index.html of the source distribution. """ import logging logging.basicConfig() import Demographics1D import Demographics2D import Inference import Integration import Misc import Numerics import PhiManip # Protect import of Plotting in case matplotlib not installed. try: import Plotting except ImportError: pass # We do it this way so it's easier to reload. import Spectrum_mod Spectrum = Spectrum_mod.Spectrum try: # This is to try and ensure we have a nice __SVNVERSION__ attribute, so # when we get bug reports, we know what version they were using. The # svnversion file is created by setup.py. import os _directory = os.path.dirname(Integration.__file__) _svn_file = os.path.join(_directory, 'svnversion') __SVNVERSION__ = file(_svn_file).read().strip() except: __SVNVERSION__ = 'Unknown'
Add app.all CORS header code
"use strict"; const express = require("express"); const app = express(); // install request const request = require('request'); const PORT = process.env.PORT || 3000; const rovi = process.env.ROVI_APIKEY || ''; // CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); // API page with CORS header app.get('/api/:artist/:sig', (req, res) => { const artist = req.params.artist; const sig = req.params.sig; console.log(artist); console.log(sig); console.log(rovi); console.log(PORT); console.log(process.env); const url = "http://api.rovicorp.com/search/v2.1/music/search?apikey=" + rovi + "&sig=" + sig + "&query=" + artist + "&entitytype=artist&size=1&include=images,musicbio,discography,videos&formatid=62&type=main"; console.log(url); request.get(url, (err, response, body) => { if (err) throw err; // res.header('Access-Control-Allow-Origin', '*'); res.send(JSON.parse(body)); }); }); app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
"use strict"; const express = require("express"); const app = express(); // install request const request = require('request'); const PORT = process.env.PORT || 3000; const rovi = process.env.ROVI_APIKEY || ''; // API page with CORS header app.get('/api/:artist/:sig', (req, res) => { const artist = req.params.artist; const sig = req.params.sig; console.log(artist); console.log(sig); console.log(rovi); console.log(PORT); console.log(process.env); const url = "http://api.rovicorp.com/search/v2.1/music/search?apikey=" + rovi + "&sig=" + sig + "&query=" + artist + "&entitytype=artist&size=1&include=images,musicbio,discography,videos&formatid=62&type=main"; console.log(url); request.get(url, (err, response, body) => { if (err) throw err; res.header('Access-Control-Allow-Origin', '*'); res.send(JSON.parse(body)); }); }); app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
Fix parsing of dates for Visir. Some dates are being wrongly parsed, so we need to specify some information about the order of things.
import dateutil.parser import scrapy from jobs.items import JobsItem class VisirSpider(scrapy.Spider): name = "visir" start_urls = ['https://job.visir.is/search-results-jobs/'] def parse(self, response): for job in response.css('.thebox'): info = job.css('a')[1] item = JobsItem() item['spider'] = self.name item['url'] = url = info.css('a::attr(href)').extract_first() item['posted'] = dateutil.parser.parse(job.css('td::text').re(r'[\d.]+')[0], dayfirst=False).isoformat() request = scrapy.Request(url, callback=self.parse_specific_job) request.meta['item'] = item yield request next_page = response.urljoin(response.css('.nextBtn a::attr(href)').extract_first()) if next_page != response.url: yield scrapy.Request(next_page, callback=self.parse) def parse_specific_job(self, response): item = response.meta['item'] item['company'] = response.css('.company-name::text').extract_first() item['title'] = response.css('h2::text').extract_first() yield item
import dateutil.parser import scrapy from jobs.items import JobsItem class VisirSpider(scrapy.Spider): name = "visir" start_urls = ['https://job.visir.is/search-results-jobs/'] def parse(self, response): for job in response.css('.thebox'): info = job.css('a')[1] item = JobsItem() item['spider'] = self.name item['url'] = url = info.css('a::attr(href)').extract_first() item['posted'] = dateutil.parser.parse(job.css('td::text').re(r'[\d.]+')[0]).isoformat() request = scrapy.Request(url, callback=self.parse_specific_job) request.meta['item'] = item yield request next_page = response.urljoin(response.css('.nextBtn a::attr(href)').extract_first()) if next_page != response.url: yield scrapy.Request(next_page, callback=self.parse) def parse_specific_job(self, response): item = response.meta['item'] item['company'] = response.css('.company-name::text').extract_first() item['title'] = response.css('h2::text').extract_first() yield item
Use more accurate comment to suppress warning
package uk.gov.register.presentation; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonPropertyOrder({"proof-identifier", "root-hash"}) public class RegisterProof { private static final String proofIdentifier = "merkle:sha-256"; private final String rootHash; public RegisterProof(String rootHash) { this.rootHash = rootHash; } @SuppressWarnings("unused, used as jsonproperty") @JsonProperty("proof-identifier") public String getProofIdentifier() { return proofIdentifier; } @SuppressWarnings("unused, used as jsonproperty") @JsonProperty("root-hash") public String getRootHash() { return rootHash; } }
package uk.gov.register.presentation; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonPropertyOrder({"proof-identifier", "root-hash"}) public class RegisterProof { private static final String proofIdentifier = "merkle:sha-256"; private final String rootHash; public RegisterProof(String rootHash) { this.rootHash = rootHash; } @SuppressWarnings("unused, used from template") @JsonProperty("proof-identifier") public String getProofIdentifier() { return proofIdentifier; } @SuppressWarnings("unused, used from template") @JsonProperty("root-hash") public String getRootHash() { return rootHash; } }
Add content for team table
package de.akquinet.engineering.vaadinator.example.address.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import de.akquinet.engineering.vaadinator.annotations.DisplayBean; import de.akquinet.engineering.vaadinator.annotations.DisplayProperty; import de.akquinet.engineering.vaadinator.annotations.DisplayPropertySetting; import de.akquinet.engineering.vaadinator.annotations.FieldType; @DisplayBean @Entity public class Team { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @DisplayProperty(profileSettings = { @DisplayPropertySetting(showInTable = true) }) private String name; @DisplayProperty(profileSettings = { @DisplayPropertySetting(fieldType = FieldType.CUSTOM, customClassName = "AddressSelectField") }) private Address leader; @DisplayProperty(profileSettings = { @DisplayPropertySetting(showInTable = true, showInDetail = false) }) public String getLeaderName() { return leader != null ? leader.getName() : ""; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getLeader() { return leader; } public void setLeader(Address leader) { this.leader = leader; } }
package de.akquinet.engineering.vaadinator.example.address.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import de.akquinet.engineering.vaadinator.annotations.DisplayBean; import de.akquinet.engineering.vaadinator.annotations.DisplayProperty; import de.akquinet.engineering.vaadinator.annotations.DisplayPropertySetting; import de.akquinet.engineering.vaadinator.annotations.FieldType; @DisplayBean @Entity public class Team { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @DisplayProperty private String name; @DisplayProperty(profileSettings = { @DisplayPropertySetting(fieldType = FieldType.CUSTOM, customClassName = "AddressSelectField") }) private Address leader; public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getLeader() { return leader; } public void setLeader(Address leader) { this.leader = leader; } }
Fix window test border _again_ (more fixed).
#!/usr/bin/python # $Id:$ from pyglet.gl import * def draw_client_border(window): glClearColor(0, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, window.width, 0, window.height, -1, 1) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def rect(x1, y1, x2, y2): glBegin(GL_LINE_LOOP) glVertex2f(x1, y1) glVertex2f(x2, y1) glVertex2f(x2, y2) glVertex2f(x1, y2) glEnd() glColor3f(1, 0, 0) rect(-1, -1, window.width, window.height) glColor3f(0, 1, 0) rect(0, 0, window.width - 1, window.height - 1)
#!/usr/bin/python # $Id:$ from pyglet.gl import * def draw_client_border(window): glClearColor(0, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, window.width, 0, window.height, -1, 1) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def rect(x1, y1, x2, y2): glBegin(GL_LINE_LOOP) glVertex2f(x1, y1) glVertex2f(x2, y1) glVertex2f(x2, y2) glVertex2f(x1, y2) glEnd() glColor3f(1, 0, 0) rect(-1, -1, window.width + 1, window.height - 1) glColor3f(0, 1, 0) rect(0, 0, window.width - 1, window.height - 1)
Add list to expectation in test
# -*- coding: utf-8 -*- import codecs import pytest from poyo import parse_string @pytest.fixture def string_data(): with codecs.open('tests/foobar.yml', encoding='utf-8') as ymlfile: return ymlfile.read() def test_parse_string(string_data): expected = { u'default_context': { u'greeting': u'こんにちは', u'email': u'raphael@hackebrot.de', u'docs': True, u'gui': False, 123: 456.789, u'someint': 1000000, u'foo': u'hallo #welt', u'trueish': u'Falseeeeeee', u'doc_tools': [u'mkdocs', u'sphinx', None], }, u'zZz': True, u'NullValue': None, u'Hello World': { None: u'This is madness', u'gh': u'https://github.com/{0}.git', }, u'Yay #python': u'Cool!' } assert parse_string(string_data) == expected
# -*- coding: utf-8 -*- import codecs import pytest from poyo import parse_string @pytest.fixture def string_data(): with codecs.open('tests/foobar.yml', encoding='utf-8') as ymlfile: return ymlfile.read() def test_parse_string(string_data): expected = { u'default_context': { u'greeting': u'こんにちは', u'email': u'raphael@hackebrot.de', u'docs': True, u'gui': False, 123: 456.789, u'someint': 1000000, u'foo': u'hallo #welt', u'trueish': u'Falseeeeeee', }, u'zZz': True, u'NullValue': None, u'Hello World': { None: u'This is madness', u'gh': u'https://github.com/{0}.git', }, u'Yay #python': u'Cool!' } assert parse_string(string_data) == expected
Replace ngrok url with stub
package com.twilio.notify.quickstart.notifyapi; import com.twilio.notify.quickstart.notifyapi.model.Binding; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.converter.jackson.JacksonConverterFactory; import retrofit2.http.Body; import retrofit2.http.POST; public class TwilioSDKStarterAPI { private static String BASE_SERVER_URL = "YOUR_SDK_STARTER_SERVER_URL"; /** * A resource defined to register Notify bindings using the sdk-starter projects available in * C#, Java, Node, PHP, Python, or Ruby. * * https://github.com/TwilioDevEd?q=sdk-starter */ interface SDKStarterService { @POST("/register") Call<Void> register(@Body Binding binding); } private static SDKStarterService sdkStarterService = new Retrofit.Builder() .baseUrl(BASE_SERVER_URL) .addConverterFactory(JacksonConverterFactory.create()) .build() .create(SDKStarterService.class); public static Call<Void> registerBinding(final Binding binding) { return sdkStarterService.register(binding); } }
package com.twilio.notify.quickstart.notifyapi; import com.twilio.notify.quickstart.notifyapi.model.Binding; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.converter.jackson.JacksonConverterFactory; import retrofit2.http.Body; import retrofit2.http.POST; public class TwilioSDKStarterAPI { private static String BASE_SERVER_URL = "https://f5ab0b54.ngrok.io"; /** * A resource defined to register Notify bindings using the sdk-starter projects available in * C#, Java, Node, PHP, Python, or Ruby. * * https://github.com/TwilioDevEd?q=sdk-starter */ interface SDKStarterService { @POST("/register") Call<Void> register(@Body Binding binding); } private static SDKStarterService sdkStarterService = new Retrofit.Builder() .baseUrl(BASE_SERVER_URL) .addConverterFactory(JacksonConverterFactory.create()) .build() .create(SDKStarterService.class); public static Call<Void> registerBinding(final Binding binding) { return sdkStarterService.register(binding); } }
Add schedules collection to backend Signed-off-by: Juan Martin Runge <2e19f93fe0d263e6ab743b7b04f5a1b612584839@gmail.com>
var mbc = require('mbc-common'), collections = mbc.config.Common.Collections, backboneio = require('backbone.io'), middleware = new mbc.iobackends().get_middleware() ; module.exports = function (db) { var backends = { app: { use: [backboneio.middleware.configStore()] }, sketch: { use: [middleware.uuid], mongo: { db: db, collection: collections.Sketchs, } }, live: { use: [backboneio.middleware.memoryStore()] }, sketchschedule: { use: [middleware.uuid], mongo: { db: db, collection: collections.SketchSchedules, } }, } return backends; };
var mbc = require('mbc-common'), collections = mbc.config.Common.Collections, backboneio = require('backbone.io'), middleware = new mbc.iobackends().get_middleware() ; module.exports = function (db) { var backends = { app: { use: [backboneio.middleware.configStore()] }, sketch: { use: [middleware.uuid], mongo: { db: db, collection: collections.Sketchs, } }, live: { use: [backboneio.middleware.memoryStore()] } } return backends; };
Make it so the assert can stay unchanged.
// template strings - String.raw // To do: make all tests pass, leave the asserts unchanged! describe('on tagged template strings you can use String.raw', function() { it('the `raw` property accesses the string as it was entered', function() { function firstChar(strings) { return strings; } assert.equal(firstChar`\n`, '\\n'); }); it('`raw` can access the backslash of a line-break', function() { function firstCharEntered(strings) { var lineBreak = strings.raw[0]; return lineBreak; } assert.equal(firstCharEntered`\n`, '\\'); }); describe('`String.raw` as a static function', function(){ it('concats the raw strings', function() { var expected = '\n'; assert.equal(String.raw`\n`, expected); }); it('two raw-templates-string-backslashes equal two escaped backslashes', function() { const TWO_BACKSLASHES = '\\'; assert.equal(String.raw`\\`, TWO_BACKSLASHES); }); it('works on unicodes too', function() { var smilie = '\u{1F600}'; var actual = String.raw`\u{1F600}`; assert.equal(actual, smilie); }); }); });
// template strings - String.raw // To do: make all tests pass, leave the asserts unchanged! describe('on tagged template strings you can use String.raw', function() { it('the `raw` property accesses the string as it was entered', function() { function firstChar(strings) { return strings; } assert.equal(firstChar`\n`, '\\n'); }); it('`raw` can access the backslash of a line-break', function() { function firstCharEntered(strings) { var lineBreak = strings.raw[0]; return lineBreak; } assert.equal(firstCharEntered`\n`, '\\'); }); describe('`String.raw` as a static function', function(){ it('concats the raw strings', function() { var expected = '\n'; assert.equal(String.raw`\n`, expected); }); it('two raw-templates-string-backslashes equal two escaped backslashes', function() { const A_BACKSLASH = '\\'; assert.equal(String.raw`\\`, A_BACKSLASH); }); it('works on unicodes too', function() { var smilie = '\u{1F600}'; var actual = String.raw`\u{1F600}`; assert.equal(actual, smilie); }); }); });
Remove install requires and added download_url
#!/usr/bin/env python from __future__ import unicode_literals from csv_generator import __version__ from setuptools import setup, find_packages setup( name='csv_generator', version=__version__, description='Configurable CSV Generator for Django', author='Dan Stringer', author_email='dan.stringer1983@googlemail.com', url='https://github.com/fatboystring/csv_generator/', download_url='https://github.com/fatboystring/csv_generator/tarball/0.5.0', packages=find_packages(exclude=['app']), license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], include_package_data=True, keywords=['csv generator', 'queryset', 'django'], install_requires=[] )
#!/usr/bin/env python from __future__ import unicode_literals from csv_generator import __version__ from setuptools import setup, find_packages setup( name='csv_generator', version=__version__, description='Configurable CSV Generator for Django', author='Dan Stringer', author_email='dan.stringer1983@googlemail.com', url='https://github.com/fatboystring/csv_generator/', packages=find_packages(exclude=['app']), license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], include_package_data=True, keywords=['csv generator', 'queryset', 'django'], install_requires=[], )
Change property to be access
import req from 'superagent'; import {dispatch} from '../dispatcher'; import {Action} from '../actions'; import meta from '../meta'; const DIR_CONFIG='/resource/config/app/moe/somesim', DIR_DOC='/resource/markdown/app/moe/somesim'; export default ()=>{ req .get(DIR_CONFIG+'/somesim.json?='+meta.version) .end((err,res)=>{ dispatch(Action.RecieveEquipList(JSON.parse(res.text))); }); req .get(DIR_CONFIG+'/flower.json?='+meta.version) .end((err,res)=>{ dispatch(Action.RecieveFlowerList(JSON.parse(res.text))); }); req .get(DIR_CONFIG+'/pallet.json?='+meta.version) .end((err,res)=>{ dispatch(Action.RecieveStainList(JSON.parse(res.text))); }); req .get(DIR_DOC+'/readme.md?='+meta.version) .end((err,res)=>{ dispatch(Action.RecieveReadme(res.text)); }); req .get(DIR_DOC+'/update.md?='+meta.version) .end((err,res)=>{ dispatch(Action.RecieveUpdateLog(res.text)); }); }
import req from 'superagent'; import {dispatch} from '../dispatcher'; import {Action} from '../actions'; import meta from '../meta'; const DIR_CONFIG='/resource/config/app/moe/somesim', DIR_DOC='/resource/markdown/app/moe/somesim'; export default ()=>{ req .get(DIR_CONFIG+'/somesim.json?='+meta.version) .end((err,res)=>{ dispatch(Action.RecieveEquipList(res.body)); }); req .get(DIR_CONFIG+'/flower.json?='+meta.version) .end((err,res)=>{ dispatch(Action.RecieveFlowerList(res.body)); }); req .get(DIR_CONFIG+'/pallet.json?='+meta.version) .end((err,res)=>{ dispatch(Action.RecieveStainList(res.body)); }); req .get(DIR_DOC+'/readme.md?='+meta.version) .end((err,res)=>{ dispatch(Action.RecieveReadme(res.text)); }); req .get(DIR_DOC+'/update.md?='+meta.version) .end((err,res)=>{ dispatch(Action.RecieveUpdateLog(res.text)); }); }
Fix a bug on python-2.6 and use a frozenset() Signed-off-by: Ralph Bean <bcd66b84ebceb8404db9191d837c83f1b20bab8e@redhat.com>
__schema = dict( AGENT = 'agent', # Generic use. "Who is responsible for this event?" FIELDS = 'fields', # A list of fields that may be of interest. For instance, # fas uses this to specify which fields were updated in # a user.update event. USER = 'user', # FAS GROUP = 'group', # FAS TAG = 'tag', # For fedora-tagger LOG = 'log', # For fedmsg-logger UPDATE = 'update', # For bodhi # Used only for testing and developing. TEST = 'test', ) # Add these to the toplevel for backwards compat for __i in __schema: vars()[__i] = __schema[__i] # Build a set for use in validation ### TODO: Consider renaming this as it's not really the "keys" here keys = frozenset(__schema.values())
AGENT = 'agent' # Generic use. "Who is responsible for this event?" FIELDS = 'fields' # A list of fields that may be of interest. For instance, # fas uses this to specify which fields were updated in # a user.update event. USER = 'user' # FAS GROUP = 'group' # FAS TAG = 'tag' # For fedora-tagger LOG = 'log' # For fedmsg-logger UPDATE = 'update' # For bodhi # Used only for testing and developing. TEST = 'test' # Build a list for use in validation __k, __v = None, None keys = [__v for __k, __v in globals().items() if not __k.startswith('__')]
test: Use local variables instead of globals
var expect = require('chai').expect; var fs = require('fs'); var PNG = require('png-js'); var QrCode = require('../dist/index.js'); it('should work with basic image', function(done) { var c = fs.readFileSync(__dirname + '/image.png'); var p = new PNG(c); p.decode(function(data) { var qr = new QrCode(); qr.callback = function(result) { expect(result).to.equal('Test'); done(); } qr.decode(p, data); }); }); it('should work with imageData format', function(done) { var c = fs.readFileSync(__dirname + '/image.png'); var p = new PNG(c); p.decode(function(data) { var qr = new QrCode(); qr.callback = function(result) { expect(result).to.equal('Test'); done(); } qr.decode({ height: p.height, width: p.width, data: data }); }); });
expect =require('chai').expect; fs = require('fs'); PNG = require('png-js'); QrCode = require('../dist/index.js'); it('should work with basic image', function(done) { c = fs.readFileSync(__dirname + '/image.png'); p = new PNG(c); p.decode(function(data) { qr = new QrCode(); qr.callback = function(result) { expect(result).to.equal('Test'); done(); } qr.decode(p, data); }); }); it('should work with imageData format', function(done) { c = fs.readFileSync(__dirname + '/image.png'); p = new PNG(c); p.decode(function(data) { qr = new QrCode(); qr.callback = function(result) { expect(result).to.equal('Test'); done(); } qr.decode({ height: p.height, width: p.width, data: data }); }); });
Disable widget test. (does not run on travis)
import os import unittest from Orange.widgets.tests import test_setting_provider, \ test_settings_handler, test_context_handler, \ test_class_values_context_handler, test_domain_context_handler from Orange.widgets.data.tests import test_owselectcolumns try: from Orange.widgets.tests import test_widget run_widget_tests = True except ImportError: run_widget_tests = False def suite(): test_dir = os.path.dirname(__file__) all_tests = [ unittest.TestLoader().discover(test_dir), ] load = unittest.TestLoader().loadTestsFromModule all_tests.extend([ load(test_setting_provider), load(test_settings_handler), load(test_context_handler), load(test_class_values_context_handler), load(test_domain_context_handler), load(test_owselectcolumns) ]) if run_widget_tests: all_tests.extend([ #load(test_widget), # does not run on travis ]) return unittest.TestSuite(all_tests) test_suite = suite() if __name__ == '__main__': unittest.main(defaultTest='suite')
import os import unittest from Orange.widgets.tests import test_setting_provider, \ test_settings_handler, test_context_handler, \ test_class_values_context_handler, test_domain_context_handler from Orange.widgets.data.tests import test_owselectcolumns try: from Orange.widgets.tests import test_widget run_widget_tests = True except ImportError: run_widget_tests = False def suite(): test_dir = os.path.dirname(__file__) all_tests = [ unittest.TestLoader().discover(test_dir), ] load = unittest.TestLoader().loadTestsFromModule all_tests.extend([ load(test_setting_provider), load(test_settings_handler), load(test_context_handler), load(test_class_values_context_handler), load(test_domain_context_handler), load(test_owselectcolumns) ]) if run_widget_tests: all_tests.extend([ load(test_widget), ]) return unittest.TestSuite(all_tests) test_suite = suite() if __name__ == '__main__': unittest.main(defaultTest='suite')
Add missing extras package declaration
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() CHANGES = open(os.path.join(here, 'CHANGES.rst')).read() requires = [ 'caliopen.api.base', ] extras_require = { 'dev': [], 'test': [], } setup(name='caliopen.api.user', namespace_packages=['caliopen', 'caliopen.api'], version='0.0.1', description='Caliopen REST API for user and contact management.', long_description=README + '\n\n' + CHANGES, classifiers=["Programming Language :: Python", ], author='Caliopen contributors', author_email='contact@caliopen.org', url='https://caliopen.org', license='AGPLv3', packages=find_packages(), include_package_data=True, zip_safe=False, extras_require=extras_require, install_requires=requires, tests_require=requires, )
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() CHANGES = open(os.path.join(here, 'CHANGES.rst')).read() requires = [ 'caliopen.api.base', ] setup(name='caliopen.api.user', namespace_packages=['caliopen', 'caliopen.api'], version='0.0.1', description='Caliopen REST API for user and contact management.', long_description=README + '\n\n' + CHANGES, classifiers=["Programming Language :: Python", ], author='Caliopen contributors', author_email='contact@caliopen.org', url='https://caliopen.org', license='AGPLv3', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=requires, tests_require=requires, )
[r=wallyworld],[bug=1311955] Update tests to support "utopic" Add "utopic" to SupportedSeries const in testing package. https://codereview.appspot.com/94730043/
// Copyright 2012, 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package testing import ( "time" "launchpad.net/juju-core/utils" ) // ShortWait is a reasonable amount of time to block waiting for something that // shouldn't actually happen. (as in, the test suite will *actually* wait this // long before continuing) const ShortWait = 50 * time.Millisecond // LongWait is used when something should have already happened, or happens // quickly, but we want to make sure we just haven't missed it. As in, the test // suite should proceed without sleeping at all, but just in case. It is long // so that we don't have spurious failures without actually slowing down the // test suite const LongWait = 10 * time.Second var LongAttempt = &utils.AttemptStrategy{ Total: LongWait, Delay: ShortWait, } // SupportedSeries lists the series known to Juju. var SupportedSeries = []string{"precise", "quantal", "raring", "saucy", "trusty", "utopic"}
// Copyright 2012, 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package testing import ( "time" "launchpad.net/juju-core/utils" ) // ShortWait is a reasonable amount of time to block waiting for something that // shouldn't actually happen. (as in, the test suite will *actually* wait this // long before continuing) const ShortWait = 50 * time.Millisecond // LongWait is used when something should have already happened, or happens // quickly, but we want to make sure we just haven't missed it. As in, the test // suite should proceed without sleeping at all, but just in case. It is long // so that we don't have spurious failures without actually slowing down the // test suite const LongWait = 10 * time.Second var LongAttempt = &utils.AttemptStrategy{ Total: LongWait, Delay: ShortWait, } // SupportedSeries lists the series known to Juju. var SupportedSeries = []string{"precise", "quantal", "raring", "saucy", "trusty"}
Fix Bug in Wait logic
# -*- coding:utf-8 -*- """ Wait ^^^^ .. moduleauthor:: Martin Poppinga <1popping@informatik.uni-hamburg.de> Just waits for something (i.e. that preconditions will be fullfilled) """ import rospy from bitbots_body_behaviour.body.actions.go_to import Stand from bitbots_stackmachine.abstract_action_module import AbstractActionModule from humanoid_league_msgs.msg import HeadMode class Wait(AbstractActionModule): def __init__(self, connector, args=10): super(Wait, self).__init__(connector) self.time = rospy.get_time() + args def perform(self, connector, reevaluate=False): if connector.world_model.ball_seen(): connector.blackboard.set_head_duty(HeadMode.BALL_MODE) self.push(Stand) if self.time < rospy.get_time(): self.pop()
# -*- coding:utf-8 -*- """ Wait ^^^^ .. moduleauthor:: Martin Poppinga <1popping@informatik.uni-hamburg.de> Just waits for something (i.e. that preconditions will be fullfilled) """ import rospy from bitbots_body_behaviour.body.actions.go_to import Stand from bitbots_stackmachine.abstract_action_module import AbstractActionModule from humanoid_league_msgs.msg import HeadMode class Wait(AbstractActionModule): def __init__(self, connector, args=10): super(Wait, self).__init__(connector) self.time = rospy.get_time() + args def perform(self, connector, reevaluate=False): if connector.world_model.ball_seen(): connector.blackboard.set_head_duty(HeadMode.BALL_MODE) self.push(Stand) if self.time > rospy.get_time(): self.pop()
Format displayed JSON more nicely in text area
'use strict'; var GameDataCreator = require('../gamedata'); var PointView = require('../prefabs/pointview'); function Editor() {} Editor.prototype = { create: function() { this.game.data = new GameDataCreator.GameData(); var background = this.game.add.sprite(0, 0, 'background'); this.sprites = this.game.add.group(); background.inputEnabled = true; background.events.onInputDown.add(this.clickListener, this); }, update: function() { }, clickListener: function(sprite, pointer) { var newPoint = new GameDataCreator.GamePoint(Math.floor(pointer.x), Math.floor(pointer.y), 'unvisited'); console.log(newPoint); this.game.data.points.push(newPoint); var pointSprite = new PointView(this.game, newPoint); this.game.add.existing(pointSprite); this.sprites.add(pointSprite); console.log(Math.floor(pointer.x) + ' ' + Math.floor(pointer.y)); console.log(this.game.data.points); var textArea = window.document.getElementById('outputJSON'); textArea.value = JSON.stringify(this.game.data, null, 2); } }; module.exports = Editor;
'use strict'; var GameDataCreator = require('../gamedata'); var PointView = require('../prefabs/pointview'); function Editor() {} Editor.prototype = { create: function() { this.game.data = new GameDataCreator.GameData(); var background = this.game.add.sprite(0, 0, 'background'); this.sprites = this.game.add.group(); background.inputEnabled = true; background.events.onInputDown.add(this.clickListener, this); }, update: function() { }, clickListener: function(sprite, pointer) { var newPoint = new GameDataCreator.GamePoint(Math.floor(pointer.x), Math.floor(pointer.y), 'unvisited'); console.log(newPoint); this.game.data.points.push(newPoint); var pointSprite = new PointView(this.game, newPoint); this.game.add.existing(pointSprite); this.sprites.add(pointSprite); console.log(Math.floor(pointer.x) + ' ' + Math.floor(pointer.y)); console.log(this.game.data.points); var textArea = document.getElementById('outputJSON'); textArea.value = JSON.stringify(this.game.data); } }; module.exports = Editor;
Rename http-random-user key to category
import Cycle from '@cycle/core'; import {div, button, h1, h4, a, makeDOMDriver} from '@cycle/dom'; import {makeHTTPDriver} from '@cycle/http'; function main(sources) { const getRandomUser$ = sources.DOM.select('.get-random').events('click') .map(() => { const randomNum = Math.round(Math.random() * 9) + 1; return { url: 'http://jsonplaceholder.typicode.com/users/' + String(randomNum), category: 'users', method: 'GET' }; }); const user$ = sources.HTTP .filter(res$ => res$.request.category === 'users') .mergeAll() .map(res => res.body) .startWith(null); const vtree$ = user$.map(user => div('.users', [ button('.get-random', 'Get random user'), user === null ? null : div('.user-details', [ h1('.user-name', user.name), h4('.user-email', user.email), a('.user-website', {href: user.website}, user.website) ]) ]) ); return { DOM: vtree$, HTTP: getRandomUser$ }; } Cycle.run(main, { DOM: makeDOMDriver('#main-container'), HTTP: makeHTTPDriver() });
import Cycle from '@cycle/core'; import {div, button, h1, h4, a, makeDOMDriver} from '@cycle/dom'; import {makeHTTPDriver} from '@cycle/http'; function main(sources) { const getRandomUser$ = sources.DOM.select('.get-random').events('click') .map(() => { const randomNum = Math.round(Math.random() * 9) + 1; return { url: 'http://jsonplaceholder.typicode.com/users/' + String(randomNum), key: 'users', method: 'GET' }; }); const user$ = sources.HTTP .filter(res$ => res$.request.key === 'users') .mergeAll() .map(res => res.body) .startWith(null); const vtree$ = user$.map(user => div('.users', [ button('.get-random', 'Get random user'), user === null ? null : div('.user-details', [ h1('.user-name', user.name), h4('.user-email', user.email), a('.user-website', {href: user.website}, user.website) ]) ]) ); return { DOM: vtree$, HTTP: getRandomUser$ }; } Cycle.run(main, { DOM: makeDOMDriver('#main-container'), HTTP: makeHTTPDriver() });
Fix silly javascript bug - was using global variables
function smoothed_count( iterations, final_modulus_squared){ final_modulus = Math.sqrt(final_modulus_squared); if (final_modulus< 1){ return iterations } else{ return iterations - (Math.log(Math.log(final_modulus)) / Math.log(2)) } } function mandelbrot_smoothed_iteration_count( escape_radius_squared, max_iterations, initial_real, initial_imaginary){ var mod_z = (initial_real * initial_real) + (initial_imaginary * initial_imaginary); var real = initial_real; var imaginary = initial_imaginary; var iterations = 0; while (mod_z < escape_radius_squared && iterations != max_iterations){ var new_real = (real * real) - (imaginary * imaginary) + initial_real; imaginary = (2 * real * imaginary) + initial_imaginary; real = new_real; mod_z = (real * real) + (imaginary * imaginary); iterations++; } return smoothed_count(iterations, mod_z) }
function smoothed_count( iterations, final_modulus_squared){ final_modulus = Math.sqrt(final_modulus_squared); if (final_modulus< 1){ return iterations } else{ return iterations - (Math.log(Math.log(final_modulus)) / Math.log(2)) } } function mandelbrot_smoothed_iteration_count( escape_radius_squared, max_iterations, initial_real, initial_imaginary){ mod_z = (initial_real * initial_real) + (initial_imaginary * initial_imaginary); real = initial_real; imaginary = initial_imaginary; iterations = 0; while (mod_z < escape_radius_squared && iterations != max_iterations){ new_real = (real * real) - (imaginary * imaginary) + initial_real; imaginary = (2 * real * imaginary) + initial_imaginary; real = new_real; mod_z = (real * real) + (imaginary * imaginary); iterations++; } return smoothed_count(iterations, mod_z) }
Set config via module.exports not message
'use strict'; var Dropbox = require('dropbox'); var options; var queue = {}; function addToDropboxQueue (message) { var user = message.user; var fileContent = message.file; var fileName = message.fileName; var saveObject = { file: fileContent, token: user.dropbox_token, // jshint ignore:line timeout: setTimeout(function(){ saveToDropBox(fileContent, fileName, user); }, options.delayTime) }; if (queue[fileName]) { clearTimeout(queue[fileName].timeout); } queue[fileName] = saveObject; } function saveToDropBox (file, name, user) { var client = new Dropbox.Client({ key: options.id, secret: options.secret, token: user.dropbox_token // jshint ignore:line }); client.writeFile(name, file, function (err) { if (err) { process.send({ error: err, user: user }); } }); } function handleMessages(message) { if (message.file) { addToDropboxQueue(message); } } module.exports = function (socket, config) { options = config; options.delayTime *= 1000; socket.on('message', function (msg) { handleMessages(JSON.parse(msg.toString())); }); };
'use strict'; var Dropbox = require('dropbox'); var options; var queue = {}; function addToDropboxQueue (message) { var user = message.user; var fileContent = message.file; var fileName = message.fileName; var saveObject = { file: fileContent, token: user.dropbox_token, // jshint ignore:line timeout: setTimeout(function(){ saveToDropBox(fileContent, fileName, user); }, options.delayTime) }; if (queue[fileName]) { clearTimeout(queue[fileName].timeout); } queue[fileName] = saveObject; } function saveToDropBox (file, name, user) { var client = new Dropbox.Client({ key: options.id, secret: options.secret, token: user.dropbox_token // jshint ignore:line }); client.writeFile(name, file, function (err) { if (err) { process.send({ error: err, user: user }); } }); } function handleMessages(message) { if (message.file) { addToDropboxQueue(message); } else if (message.options) { options = message.options; options.delayTime *= 1000; } } module.exports = function (socket) { socket.on('message', function (msg) { handleMessages(JSON.parse(msg.toString())); }); };
Check if url or not
<?php namespace ProjectBundle\Repository; /** * PlayerRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class PlayerRepository extends \Doctrine\ORM\EntityRepository { public function listAndTestLinkPlayers($entryInput) { if (filter_var($entryInput, FILTER_VALIDATE_URL) === FALSE) { return null; } $listOfPlayers = $this->findAll(); foreach($listOfPlayers as $player){ $playerLinkExample = $player->getlinkExample(); if($this->testBetweenToLinks($playerLinkExample, $entryInput)) return array('type' => $player->getId(), 'name' =>$player->getName()); } return null; } private function testBetweenToLinks($databaseLink, $entryLink){ $entry = parse_url($entryLink); $entry = preg_replace('#^www\.(.+\.)#i', '$1', $entry["host"]); if($databaseLink == $entry){ return true; } return false; } // prefer domain name method // private function testBetweenToLinks($databaseLink, $entryLink){ // // similar_text($databaseLink, $entryLink, $percent); // // if($percent > 30){ // return true; // } // // return false; // // } }
<?php namespace ProjectBundle\Repository; /** * PlayerRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class PlayerRepository extends \Doctrine\ORM\EntityRepository { public function listAndTestLinkPlayers($entryInput) { $listOfPlayers = $this->findAll(); foreach($listOfPlayers as $player){ $playerLinkExample = $player->getlinkExample(); if($this->testBetweenToLinks($playerLinkExample, $entryInput)) return array('type' => $player->getId(), 'name' =>$player->getName()); } return null; } private function testBetweenToLinks($databaseLink, $entryLink){ $entry = parse_url($entryLink); $entry = preg_replace('#^www\.(.+\.)#i', '$1', $entry["host"]); if($databaseLink == $entry){ return true; } return false; } // prefer domain name method // private function testBetweenToLinks($databaseLink, $entryLink){ // // similar_text($databaseLink, $entryLink, $percent); // // if($percent > 30){ // return true; // } // // return false; // // } }
Fix NPE on missing mods - still need to actually handle missing mods properly on client
package cpw.mods.fml.common.network; import java.util.List; import net.minecraft.src.NetHandler; import net.minecraft.src.NetworkManager; public class ModMissingPacket extends FMLPacket { public ModMissingPacket() { super(Type.MOD_MISSING); } @Override public byte[] generatePacket(Object... data) { // TODO List<String> missing = (List<String>) data[0]; List<String> badVersion = (List<String>) data[1]; return new byte[0]; } @Override public FMLPacket consumePacket(byte[] data) { // TODO return this; } @Override public void execute(NetworkManager network, FMLNetworkHandler handler, NetHandler netHandler, String userName) { // TODO } }
package cpw.mods.fml.common.network; import net.minecraft.src.NetHandler; import net.minecraft.src.NetworkManager; public class ModMissingPacket extends FMLPacket { public ModMissingPacket() { super(Type.MOD_MISSING); } @Override public byte[] generatePacket(Object... data) { // TODO Auto-generated method stub return null; } @Override public FMLPacket consumePacket(byte[] data) { // TODO Auto-generated method stub return null; } @Override public void execute(NetworkManager network, FMLNetworkHandler handler, NetHandler netHandler, String userName) { // TODO Auto-generated method stub } }
Make sure we ignore cancelled events.
package com.gmail.nossr50.listeners; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import com.gmail.nossr50.util.Hardcore; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Permissions; public class HardcoreListener implements Listener { /** * Monitor PlayerDeath events. * * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerDeath(PlayerDeathEvent event) { Player player = event.getEntity(); if (Misc.isNPCPlayer(player)) { return; } if (!Permissions.hardcoremodeBypass(player)) { Player killer = player.getKiller(); if (killer != null && Hardcore.vampirismEnabled) { Hardcore.invokeVampirism(killer, player); } Hardcore.invokeStatPenalty(player); } } }
package com.gmail.nossr50.listeners; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import com.gmail.nossr50.util.Hardcore; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Permissions; public class HardcoreListener implements Listener { /** * Monitor PlayerDeath events. * * @param event The event to monitor */ @EventHandler(priority = EventPriority.MONITOR) public void onPlayerDeath(PlayerDeathEvent event) { Player player = event.getEntity(); if (Misc.isNPCPlayer(player)) { return; } if (!Permissions.hardcoremodeBypass(player)) { Player killer = player.getKiller(); if (killer != null && Hardcore.vampirismEnabled) { Hardcore.invokeVampirism(killer, player); } Hardcore.invokeStatPenalty(player); } } }