text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix Accept of all HTTP requests to specify json
export default { /** * smartStateFold is supposed to be given as the argument a * `scan` operation over a stream of state|updateFn. State is * expected to be an object, and updateFn is a function that * takes old state and produces new state. * Example: * --s0---fn1----fn2----s10------> * scan(smartStateFold) * --s0---s1-----s2-----s10------> * * where s1 = fn1(s0) * where s2 = fn2(s1) */ smartStateFold(prev, curr) { if (typeof curr === 'function') { return curr(prev); } else { return curr; } }, urlToRequestObjectWithHeaders(url) { return { url: url, method: 'GET', accept: 'json', headers: { 'Content-Type': 'application/json', }, }; }, isTruthy(x) { return !!x; }, };
export default { /** * smartStateFold is supposed to be given as the argument a * `scan` operation over a stream of state|updateFn. State is * expected to be an object, and updateFn is a function that * takes old state and produces new state. * Example: * --s0---fn1----fn2----s10------> * scan(smartStateFold) * --s0---s1-----s2-----s10------> * * where s1 = fn1(s0) * where s2 = fn2(s1) */ smartStateFold(prev, curr) { if (typeof curr === 'function') { return curr(prev); } else { return curr; } }, urlToRequestObjectWithHeaders(url) { return { url: url, method: 'GET', headers: { 'Content-Type': 'application/json', }, }; }, isTruthy(x) { return !!x; }, };
Fix KeyError on Terminal integration
import pprint from pysellus.interfaces import AbstractIntegration class TerminalIntegration(AbstractIntegration): def on_next(self, message): print('Assert error: in {0} -> {1}'.format( message['test_name'], message['expect_function'] )) print('Got:') pprint.pprint(message['element']) def on_error(self, error_message): print('Runtime Error: In {0} -> {1}'.format( error_message['test_name'], error_message['expect_function'] )) print('Got:') pprint.pprint(error_message['error']) def on_completed(self): print("All tests done.")
import pprint from pysellus.interfaces import AbstractIntegration class TerminalIntegration(AbstractIntegration): def on_next(self, message): print('Assert error: in {test_name} -> {1}'.format( message['test_name'], message['expect_function'] )) print('Got:') pprint.pprint(message['element']) def on_error(self, error_message): print('Runtime Error: In {0} -> {1}'.format( error_message['test_name'], error_message['expect_function'] )) print('Got:') pprint.pprint(error_message['error']) def on_completed(self): print("All tests done.")
Update custom JSONEncoder to treat TimestampedData as dict
# -*- coding: utf-8 -*- import json as _json from functools import partial from il2fb.commons.events import Event from il2fb.ds.airbridge.structures import TimestampedData __all__ = ('dumps', 'loads', ) class JSONEncoder(_json.JSONEncoder): def default(self, obj): cls = type(obj) if issubclass(cls, TimestampedData): result = { key: getattr(obj, key) for key in cls.__slots__ } elif hasattr(obj, 'to_primitive'): result = obj.to_primitive() result['__type__'] = f"{cls.__module__}.{cls.__name__}" if issubclass(cls, Event): result.pop('name') result.pop('verbose_name') elif hasattr(obj, 'isoformat'): result = obj.isoformat() else: result = super().default(obj) return result def object_decoder(obj): return obj dumps = partial(_json.dumps, cls=JSONEncoder) loads = partial(_json.loads, object_hook=object_decoder)
# -*- coding: utf-8 -*- import json as _json from functools import partial from il2fb.commons.events import Event __all__ = ('dumps', 'loads', ) class JSONEncoder(_json.JSONEncoder): def default(self, obj): if hasattr(obj, 'to_primitive'): cls = obj.__class__ result = obj.to_primitive() result['__type__'] = f"{cls.__module__}.{cls.__name__}" if issubclass(cls, Event): result.pop('name') result.pop('verbose_name') elif hasattr(obj, 'isoformat'): result = obj.isoformat() else: result = super().default(obj) return result def object_decoder(obj): return obj dumps = partial(_json.dumps, cls=JSONEncoder) loads = partial(_json.loads, object_hook=object_decoder)
Add recursive search to import function
import os import imp modules = {} def load_modules(path="./modules/"): try: modules['juliet_module'] = imp.load_source('juliet_module', path + "juliet_module.py") except ImportError as e: print("Error importing module {0} from directory {1}".format(name,os.getcwd())) print(e) for root, dirs, files in os.walk(path): for name in files: if not name.endswith(".py"): continue print("Importing module {0}".format(name)) try: modules[name.split('.')[0]] = imp.load_source(name.split('.')[0], path + name) except ImportError as e: print("Error importing module {0} from directory {1}".format(name,os.getcwd())) print(e) continue print("Success") load_modules()
import os import imp modules = {} def load_modules(path="./modules/"): # Consider adding recursive searching at some point in the future modules['juliet_module'] = imp.load_source('juliet_module', path + "juliet_module.py") names = os.listdir(path) for name in names: if not name.endswith(".py"): continue print("Importing module {0}".format(name)) try: modules[name.split('.')[0]] = imp.load_source(name.split('.')[0], path + name) except ImportError as e: print("Error importing module {0} from directory {1}".format(name,os.getcwd())) print(e) continue print("Success") load_modules()
Add parameter "quiet" to export function
#!/usr/bin/env python """export_all_data.py - script for exporting all available data""" import os from collectionbatchtool import * def export_all_data(output_dir=None, quiet=True): """ Export table data to CSV files. Parameters ---------- output_dir : str Path to the output directory. """ output_dir = output_dir if output_dir else '' for tabledataset_subclass in TableDataset.__subclasses__(): instance = tabledataset_subclass() if instance.database_query.count() > 0: # no files without data instance.from_database(quiet=quiet) filename = instance.model.__name__.lower() + '.csv' filepath = os.path.join(output_dir, filename) instance.to_csv( filepath, update_sourceid=True, quiet=quiet) if __name__ == '__main__': apply_user_settings('settings.cfg') # change to your own config-file! export_all_data(quiet=False) # call the export function
#!/usr/bin/env python """export_all_data.py - script for exporting all available data""" import os from collectionbatchtool import * def export_all_data(output_dir=None): """ Export table data to CSV files. Parameters ---------- output_dir : str Path to the output directory. """ output_dir = output_dir if output_dir else '' for tabledataset_subclass in TableDataset.__subclasses__(): instance = tabledataset_subclass() if instance.database_query.count() > 0: # no files without data instance.from_database(quiet=False) filename = instance.model.__name__.lower() + '.csv' filepath = os.path.join(output_dir, filename) instance.to_csv(filepath, update_sourceid=True, quiet=False) if __name__ == '__main__': apply_user_settings('settings.cfg') # change to your own config-file! export_all_data() # call the export function
Make LDAP check even better
from __future__ import absolute_import from config import config import ldap # DEFAULTS ldap_config = { 'timeout': 5 } # /DEFAULTS # CONFIG if "ldap" in config: ldap_config.update(config["ldap"]) # /CONFIG def check_ldap_lookup(check, data): check.addOutput("ScoreEngine: %s Check\n" % (check.getServiceName())) check.addOutput("EXPECTED: Sucessful and correct query against the AD (LDAP) server") check.addOutput("OUTPUT:\n") check.addOutput("Starting check...") try: # Setup LDAP l = ldap.initialize('ldap://%s' % data["HOST"]) # Bind to the user we're using to lookup domain = data["DOMAIN"] username = data["USER"] password = data["PASS"] actual_username = "%s\%s" % (domain, username) l.protocol_version = ldap.VERSION3 l.set_option(ldap.OPT_NETWORK_TIMEOUT, ldap_config["timeout"]) l.simple_bind_s(actual_username, password) # We're good! check.setPassed() check.addOutput("Check successful!") except Exception as e: check.addOutput("ERROR: %s: %s" % (type(e).__name__, e)) return
from __future__ import absolute_import from config import config import ldap # DEFAULTS ldap_config = { 'timeout': 5 } # /DEFAULTS # CONFIG if "ldap" in config: ldap_config.update(config["ldap"]) # /CONFIG def check_ldap_lookup(check, data): check.addOutput("ScoreEngine: %s Check\n" % (check.getServiceName())) check.addOutput("EXPECTED: Sucessful and correct query against the AD (LDAP) server") check.addOutput("OUTPUT:\n") check.addOutput("Starting check...") try: # Setup LDAP l = ldap.initialize('ldap://%s' % data["HOST"]) # Bind to the user we're using to lookup username = data["USER"] password = data["PASS"] l.protocol_version = ldap.VERSION3 l.set_option(ldap.OPT_NETWORK_TIMEOUT, ldap_config["timeout"]) l.simple_bind_s(username, password) # We're good! check.setPassed() check.addOutput("Check successful!") except Exception as e: check.addOutput("ERROR: %s: %s" % (type(e).__name__, e)) return
Fix forwarding ephemeral cluster exit code. Summary: Also improves logging a little bit. Test Plan: $ python ephemeral-cluster.py run --rm --entrypoint=bash pgshovel -c "exit 10" $ test $? -eq 10 Reviewers: jeff, tail Reviewed By: tail Differential Revision: http://phabricator.local.disqus.net/D19564
#!/usr/bin/env python import subprocess import sys import uuid usage = """\ Run a command using a temporary docker-compose cluster, removing all containers \ and associated volumes after command completion (regardless of success or \ failure.) Generally, this would be used with the ``run`` command to provide a clean room \ testing environment. """ if not sys.argv[1:]: sys.stderr.write(usage) sys.exit(1) project = uuid.uuid1().hex sys.stderr.write('Setting up ephemeral cluster ({0})...\n'.format(project)) try: subprocess.check_call(['docker-compose', '-p', project] + sys.argv[1:]) except subprocess.CalledProcessError as error: raise SystemExit(error.returncode) finally: sys.stderr.write('\nCleaning up ephemeral cluster ({0})...\n'.format(project)) subprocess.check_call(['docker-compose', '-p', project, 'stop']) subprocess.check_call(['docker-compose', '-p', project, 'rm', '-f', '-v'])
#!/usr/bin/env python import subprocess import sys import uuid usage = """\ Run a command using a temporary docker-compose cluster, removing all containers \ and images after command completion (regardless of success or failure.) Generally, this would be used with the ``run`` command to provide a clean room \ testing environment. """ if not sys.argv[1:]: sys.stderr.write(usage) sys.exit(1) project = uuid.uuid1().hex sys.stderr.write('Starting ephemeral cluster: {0}\n'.format(project)) try: sys.exit(subprocess.check_call(['docker-compose', '-p', project] + sys.argv[1:])) finally: subprocess.check_call(['docker-compose', '-p', project, 'stop']) subprocess.check_call(['docker-compose', '-p', project, 'rm', '-f', '-v'])
[feature] Add waiter for response containing string
package cz.xtf.client; import java.io.IOException; import java.util.function.BooleanSupplier; import java.util.stream.Stream; import cz.xtf.core.config.WaitingConfig; import cz.xtf.core.waiting.SimpleWaiter; import cz.xtf.core.waiting.Waiter; public class HttpWaiters { private final Http client; HttpWaiters(Http httpClient) { this.client = httpClient; } public Waiter ok() { return code(200); } public Waiter code(int code) { BooleanSupplier bs = () -> { try { return client.execute().code() == code; } catch (IOException e) { return false; } }; return new SimpleWaiter(bs, "Waiting for " + client.getUrl().toExternalForm() + " to return " + code).timeout(WaitingConfig.timeout()); } public Waiter responseContains(final String... strings) { BooleanSupplier bs = () -> { try { final String response = client.execute().response(); return Stream.of(strings).allMatch(response::contains); } catch (IOException e) { return false; } }; return new SimpleWaiter(bs, "Waiting for " + client.getUrl().toExternalForm() + " to contain (" + String.join(",", strings) + ")").timeout(WaitingConfig.timeout()); } }
package cz.xtf.client; import cz.xtf.core.config.WaitingConfig; import cz.xtf.core.waiting.SimpleWaiter; import cz.xtf.core.waiting.Waiter; import java.io.IOException; import java.util.function.BooleanSupplier; public class HttpWaiters { private final Http client; HttpWaiters(Http httpClient) { this.client = httpClient; } public Waiter ok() { return code(200); } public Waiter code(int code) { BooleanSupplier bs = () -> { try { return client.execute().code() == code; } catch (IOException e) { return false; } }; return new SimpleWaiter(bs, "Waiting for " + client.getUrl().toExternalForm() + " to return " + code).timeout(WaitingConfig.timeout()); } }
Remove null items from carousel slides
import React, { PropTypes, Component } from 'react'; import Inner from './CarouselInner'; export default class Carousel extends Component { static propTypes = { lowestVisibleItemIndex: PropTypes.number, items: PropTypes.array.isRequired, itemsPerColumn: PropTypes.number, }; static defaultProps = { lowestVisibleItemIndex: 0, items: [], itemsPerColumn: 1, }; render() { const { items, itemsPerColumn, lowestVisibleItemIndex } = this.props; const renderItems = items.filter(item => item); const renderPerColumn = itemsPerColumn < renderItems.length ? itemsPerColumn : renderItems.length; const slideWidth = 100 / renderPerColumn; const position = lowestVisibleItemIndex * (-1 * slideWidth); const transform = `translate3d(${position}%, 0, 0)`; return ( <div> <Inner style={ { transform, } } slideWidth={ slideWidth } > { renderItems } </Inner> </div> ); } }
import React, { PropTypes, Component } from 'react'; import Inner from './CarouselInner'; import getValidIndex from '../../utils/getValidIndex/getValidIndex'; export default class Carousel extends Component { static propTypes = { lowestVisibleItemIndex: PropTypes.number, items: PropTypes.array.isRequired, itemsPerColumn: PropTypes.number, }; static defaultProps = { lowestVisibleItemIndex: 0, items: [], itemsPerColumn: 1, }; render() { const { items, itemsPerColumn, lowestVisibleItemIndex } = this.props; const renderPerColumn = itemsPerColumn < items.length ? itemsPerColumn : items.length; const slideWidth = 100 / renderPerColumn; const position = lowestVisibleItemIndex * (-1 * slideWidth); const transform = `translate3d(${position}%, 0, 0)`; return ( <div> <Inner style={ { transform, } } slideWidth={ slideWidth } > { items } </Inner> </div> ); } }
Fix documentation and log message issue
package cfgfile import ( "flag" "fmt" "io/ioutil" "gopkg.in/yaml.v2" ) // Command line flags var configfile *string var testConfig *bool func CmdLineFlags(flags *flag.FlagSet, name string) { configfile = flags.String("c", fmt.Sprintf("/etc/%s/%s.yml", name, name), "Configuration file") testConfig = flags.Bool("test", false, "Test configuration and exit.") } // Reads config from yaml file into the given interface structure. // In case path is not set this method reads from the default configuration file for the beat. func Read(out interface{}, path string) error { if path == "" { path = *configfile } filecontent, err := ioutil.ReadFile(path) if err != nil { return fmt.Errorf("Failed to read %s: %v. Exiting.", path, err) } if err = yaml.Unmarshal(filecontent, out); err != nil { return fmt.Errorf("YAML config parsing failed on %s: %v. Exiting.", path, err) } return nil } func IsTestConfig() bool { return *testConfig }
package cfgfile import ( "flag" "fmt" "io/ioutil" "gopkg.in/yaml.v2" ) // Command line flags var configfile *string var testConfig *bool func CmdLineFlags(flags *flag.FlagSet, name string) { configfile = flags.String("c", fmt.Sprintf("/etc/%s/%s.yml", name, name), "Configuration file") testConfig = flags.Bool("test", false, "Test configuration and exit.") } // Reads config from yaml file into the given interface structure. // In case the second param path is not set func Read(out interface{}, path string) error { if path == "" { path = *configfile } filecontent, err := ioutil.ReadFile(path) if err != nil { return fmt.Errorf("Fail to read %s: %v. Exiting.", path, err) } if err = yaml.Unmarshal(filecontent, out); err != nil { return fmt.Errorf("YAML config parsing failed on %s: %v. Exiting.", path, err) } return nil } func IsTestConfig() bool { return *testConfig }
Check if a Roleable already has the role before assigning it
<?php namespace Digbang\Security\Roles; use Doctrine\Common\Collections\ArrayCollection; trait RoleableTrait { /** * @type ArrayCollection */ protected $roles; /** * {@inheritdoc} */ public function getRoles() { return $this->roles; } /** * {@inheritdoc} */ public function inRole($role) { return $this->roles->exists(function($key, Role $myRole) use ($role){ return $myRole->is($role); }); } /** * {@inheritdoc} */ public function addRole(Role $role) { if (! $this->inRole($role)) { $this->roles->add($role); } } /** * {@inheritdoc} */ public function removeRole(Role $role) { $this->roles->removeElement($role); } }
<?php namespace Digbang\Security\Roles; use Doctrine\Common\Collections\ArrayCollection; trait RoleableTrait { /** * @type ArrayCollection */ protected $roles; /** * {@inheritdoc} */ public function getRoles() { return $this->roles; } /** * {@inheritdoc} */ public function inRole($role) { return $this->roles->exists(function($key, Role $myRole) use ($role){ return $myRole->is($role); }); } /** * {@inheritdoc} */ public function addRole(Role $role) { $this->roles->add($role); } /** * {@inheritdoc} */ public function removeRole(Role $role) { $this->roles->removeElement($role); } }
Remove a deprecated and unneeded React check
module.exports = { "extends": "justinlocsei/configurations/es6", "ecmaFeatures": { "jsx": true }, "env": { "browser": true }, "plugins": [ "react" ], "rules": { "jsx-quotes": [2, "prefer-double"], "react/jsx-boolean-value": [2, "always"], "react/jsx-curly-spacing": [2, "never"], "react/jsx-handler-names": 2, "react/jsx-no-bind": 2, "react/jsx-no-duplicate-props": [2, {"ignoreCase": true}], "react/jsx-no-undef": 2, "react/jsx-pascal-case": 2, "react/jsx-uses-vars": 2, "react/no-did-mount-set-state": 2, "react/no-did-update-set-state": 2, "react/no-direct-mutation-state": 2, "react/no-multi-comp": 2, "react/no-unknown-property": 2, "react/prop-types": 2, "react/self-closing-comp": 2, "react/wrap-multilines": 2 } };
module.exports = { "extends": "justinlocsei/configurations/es6", "ecmaFeatures": { "jsx": true }, "env": { "browser": true }, "plugins": [ "react" ], "rules": { "jsx-quotes": [2, "prefer-double"], "react/jsx-boolean-value": [2, "always"], "react/jsx-curly-spacing": [2, "never"], "react/jsx-handler-names": 2, "react/jsx-no-bind": 2, "react/jsx-no-duplicate-props": [2, {"ignoreCase": true}], "react/jsx-no-undef": 2, "react/jsx-pascal-case": 2, "react/jsx-uses-vars": 2, "react/no-did-mount-set-state": 2, "react/no-did-update-set-state": 2, "react/no-direct-mutation-state": 2, "react/no-multi-comp": 2, "react/no-unknown-property": 2, "react/prop-types": 2, "react/require-extension": 2, "react/self-closing-comp": 2, "react/wrap-multilines": 2 } };
Increase number of partitions for test purposes
from pyspark.sql import SparkSession from sparkxarray.reader import ncread import os spark = SparkSession.builder.appName('hi').getOrCreate() sc = spark.sparkContext print(os.getcwd()) filename = os.path.abspath('sparkxarray/tests/data/air.sig995.2012.nc') print(filename) rdd1 = ncread(sc, filename, mode='single', partition_on=['lat', 'lon'], partitions=300) print(rdd1.count()) print(rdd1.first()) print(rdd1.getNumPartitions()) rdd2 = ncread(sc, filename, mode='single', partition_on=['time'], partitions=80) print(rdd2.count()) print(rdd2.first()) rdd3 = ncread(sc, filename, mode='single', partition_on=['time', 'lat', 'lon'], partitions=50000) print(rdd3.count()) print(rdd3.first())
from pyspark.sql import SparkSession from sparkxarray.reader import ncread import os spark = SparkSession.builder.appName('hi').getOrCreate() sc = spark.sparkContext print(os.getcwd()) filename = os.path.abspath('sparkxarray/tests/data/air.sig995.2012.nc') print(filename) rdd1 = ncread(sc, filename, mode='single', partition_on=['lat', 'lon'], partitions=300) print(rdd1.count()) print(rdd1.first()) print(rdd1.getNumPartitions()) rdd2 = ncread(sc, filename, mode='single', partition_on=['time'], partitions=80) print(rdd2.count()) print(rdd2.first()) rdd3 = ncread(sc, filename, mode='single', partition_on=['time', 'lat', 'lon'], partitions=800) print(rdd3.count()) print(rdd3.first())
Add optional 'contest_time' parameter for entries
<?php if (isset($_REQUEST["contest_time"])) { $ctime = intval($_REQUEST["contest_time"]); } else { $ctime = null; } $date =& $_REQUEST["date"]; $user =& $_REQUEST["user"]; $priority =& $_REQUEST["priority"]; $text =& $_REQUEST["text"]; if (isset($_REQUEST["submission"])) { $sid = intval($_REQUEST["submission"]); } else { $sid = null; } require_once 'icat.php'; $db = init_db(); $_SESSION['entry_username'] = $user; // when picking contest_time: // 1. choose the contest_time parameter if present // 2. choose the maximum of contest_time in submissions if present // 3. otherwise choose 0 $stmt = mysqli_prepare($db, 'INSERT INTO entries (contest_time, user, priority, text, submission_id) VALUES ((SELECT COALESCE(?, MAX(contest_time), 0) AS last_submission FROM submissions), ?, ?, ?, ?)'); mysqli_stmt_bind_param($stmt, 'isisi', $ctime, $user, $priority, $text, $sid); mysqli_stmt_execute($stmt); $error = mysqli_stmt_error($stmt); if ($error === '') { print("okay"); } else { print("error: " . $error); } mysqli_stmt_close($stmt);
<?php $date =& $_REQUEST["date"]; $user =& $_REQUEST["user"]; $priority =& $_REQUEST["priority"]; $text =& $_REQUEST["text"]; if (isset($_REQUEST["submission"])) { $sid = intval($_REQUEST["submission"]); } else { $sid = null; } require_once 'icat.php'; $db = init_db(); $_SESSION['entry_username'] = $user; $stmt = mysqli_prepare($db, 'INSERT INTO entries (contest_time, user, priority, text, submission_id) VALUES ((SELECT MAX(contest_time) AS last_submission FROM submissions), ?, ?, ?, ?)'); mysqli_stmt_bind_param($stmt, 'sisi', $user, $priority, $text, $sid); mysqli_stmt_execute($stmt); $error = mysqli_stmt_error($stmt); if ($error === '') { print("okay"); } else { print("error: " . $error); } mysqli_stmt_close($stmt);
Make post filtering and mapping more pythonic
# -*- coding: utf-8 -*- from __future__ import unicode_literals class Posts(list): """ Represents a list of posts in a thread. """ def __init__(self, *args): """ Initialise a new posts list. :param args: The list of posts. """ super(Posts, self).__init__(*args) def filter(self, predicate): """ Take a subset of this list of posts. :param predicate: The predicate to use to choose which posts make the cut. :return: The filtered posts. """ return Posts([post for post in self if predicate(post)]) def map(self, transform): """ Applies a transformation function to each post, returning a list of this function's returned values. :param transform: The transformation function. :return: The transformed list of posts. """ return [transform(post) for post in self] def foreach(self, function): """ Call a function for each post. :param function: A function taking a post argument. Return values are ignored. """ for post in self: function(post)
# -*- coding: utf-8 -*- from __future__ import unicode_literals class Posts(list): """ Represents a list of posts in a thread. """ def __init__(self, *args): """ Initialise a new posts list. :param args: The list of posts. """ super(Posts, self).__init__(*args) def filter(self, predicate): """ Take a subset of this list of posts. :param predicate: The predicate to use to choose which posts make the cut. :return: The filtered posts. """ return Posts(filter(predicate, self)) def map(self, transformation): """ Applies a transformation function to each post, returning a list of this function's returned values. :param transformation: The transformation function. :return: The transformed list of posts. """ return map(transformation, self) def foreach(self, function): """ Call a function for each post. :param function: A function taking a post argument. Return values are ignored. """ for post in self: function(post)
Remove getDatabaseDirectory() function from rmgpy.data This function is not being used anywhere, and also has been replaced by the settings in rmgpy, which searches for and saves a database directory
#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # # RMG - Reaction Mechanism Generator # # Copyright (c) 2002-2010 Prof. William H. Green (whgreen@mit.edu) and the # RMG Team (rmg_dev@mit.edu) # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the 'Software'), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # ################################################################################
#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # # RMG - Reaction Mechanism Generator # # Copyright (c) 2002-2010 Prof. William H. Green (whgreen@mit.edu) and the # RMG Team (rmg_dev@mit.edu) # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the 'Software'), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # ################################################################################ import os.path def getDatabaseDirectory(): return os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'database'))
[native] Add optional user info parameter to message list nav params Test Plan: flow Reviewers: ashoat Reviewed By: ashoat Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D341
// @flow import { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types'; import type { MarkdownRules } from '../markdown/rules.react'; import { type UserInfo, userInfoPropType } from 'lib/types/user-types'; import PropTypes from 'prop-types'; import * as React from 'react'; export type MessageListParams = {| threadInfo: ThreadInfo, pendingPersonalThreadUserInfo?: UserInfo, |}; export const messageListRoutePropType = PropTypes.shape({ key: PropTypes.string.isRequired, params: PropTypes.shape({ threadInfo: threadInfoPropType.isRequired, pendingPersonalThreadUserInfo: userInfoPropType, }).isRequired, }); export const messageListNavPropType = PropTypes.shape({ navigate: PropTypes.func.isRequired, setParams: PropTypes.func.isRequired, setOptions: PropTypes.func.isRequired, dangerouslyGetParent: PropTypes.func.isRequired, isFocused: PropTypes.func.isRequired, popToTop: PropTypes.func.isRequired, }); export type MessageListContextType = {| +getTextMessageMarkdownRules: (useDarkStyle: boolean) => MarkdownRules, |}; export const MessageListContext = React.createContext<?MessageListContextType>();
// @flow import { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types'; import type { MarkdownRules } from '../markdown/rules.react'; import PropTypes from 'prop-types'; import * as React from 'react'; export type MessageListParams = {| threadInfo: ThreadInfo, |}; export const messageListRoutePropType = PropTypes.shape({ key: PropTypes.string.isRequired, params: PropTypes.shape({ threadInfo: threadInfoPropType.isRequired, }).isRequired, }); export const messageListNavPropType = PropTypes.shape({ navigate: PropTypes.func.isRequired, setParams: PropTypes.func.isRequired, setOptions: PropTypes.func.isRequired, dangerouslyGetParent: PropTypes.func.isRequired, isFocused: PropTypes.func.isRequired, popToTop: PropTypes.func.isRequired, }); export type MessageListContextType = {| +getTextMessageMarkdownRules: (useDarkStyle: boolean) => MarkdownRules, |}; export const MessageListContext = React.createContext<?MessageListContextType>();
Add code comment for multiply-by-2 algo
'use strict'; // VARIABLES // var MAX_ITER = 1075; // 1023+52 (subnormals) var MAX_BITS = 54; // only 53 bits for fraction // MULT2 // /** * FUNCTION: mult2( x ) * Converts a fraction to a literal bit representation using the multiply-by-2 algorithm. * * @param {Number} x - number less than 1 * @returns {String} bit representation */ function mult2( x ) { var str; var y; var i; var j; str = ''; if ( x === 0 ) { return str; } j = MAX_ITER; // Each time we multiply by 2 and find a ones digit, add a '1'; otherwise, add a '0'.. for ( i = 0; i < MAX_ITER; i++ ) { y = x * 2; if ( y >= 1 ) { x = y - 1; str += '1'; if ( j === MAX_ITER ) { j = i; // first '1' } } else { x = y; str += '0'; } if ( y === 1 || i-j > MAX_BITS ) { break; } } return str; } // end FUNCTION mult2() // EXPORTS // module.exports = mult2;
'use strict'; // VARIABLES // var MAX_ITER = 1075; // 1023+52 (subnormals) var MAX_BITS = 54; // only 53 bits for fraction // MULT2 // /** * FUNCTION: mult2( x ) * Converts a fraction to a literal bit representation using the multiply-by-2 algorithm. * * @param {Number} x - number less than 1 * @returns {String} bit representation */ function mult2( x ) { var str; var y; var i; var j; str = ''; if ( x === 0 ) { return str; } j = MAX_ITER; for ( i = 0; i < MAX_ITER; i++ ) { y = x * 2; if ( y >= 1 ) { x = y - 1; str += '1'; if ( j === MAX_ITER ) { j = i; // first '1' } } else { x = y; str += '0'; } if ( y === 1 || i-j > MAX_BITS ) { break; } } return str; } // end FUNCTION mult2() // EXPORTS // module.exports = mult2;
Update visible restaurants after updating restaurants
import axios from 'axios'; export function getRestaurants ({ commit }) { return new Promise((resolve, reject) => { axios .get('/api/restaurant') .then((response) => { commit('updateRestaurants', response.data.restaurants); commit('updateVisRes', response.data.restaurants); resolve(response); }) .catch((err) => { reject(err); }); }); } export function getRestaurant ({ commit }, identifier) { return new Promise((resolve, reject) => { axios .get('/api/restaurant/' + identifier) .then((response) => { resolve(response); }) .catch((err) => { reject(err); }); }); } export function setRegion ({ commit }, value) { commit('updateRegion', value); } export function setShowMapList ({ commit }, value) { commit('updateShowMapList', value); } // expects payload to be {'restaurant': name, 'favourite': state} export function setFavourite ({ commit }, payload) { commit('updateFavourite', payload); } export function updateVisRes ({ commit }) { commit('updateVisRes'); }
import axios from 'axios'; export function getRestaurants ({ commit }) { return new Promise((resolve, reject) => { axios .get('/api/restaurant') .then((response) => { commit('updateRestaurants', response.data.restaurants); resolve(response); }) .catch((err) => { reject(err); }); }); } export function getRestaurant ({ commit }, identifier) { return new Promise((resolve, reject) => { axios .get('/api/restaurant/' + identifier) .then((response) => { resolve(response); }) .catch((err) => { reject(err); }); }); } export function setRegion ({ commit }, value) { commit('updateRegion', value); } export function setShowMapList ({ commit }, value) { commit('updateShowMapList', value); } // expects payload to be {'restaurant': name, 'favourite': state} export function setFavourite ({ commit }, payload) { commit('updateFavourite', payload); } export function updateVisRes ({ commit }) { commit('updateVisRes'); }
Return empty dictionary instead of None
"""Workflow execution engines.""" from resolwe.flow.engine import BaseEngine class BaseExecutionEngine(BaseEngine): """A workflow execution engine.""" def evaluate(self, data): """Return the code needed to compute a given Data object.""" raise NotImplementedError def get_expression_engine(self, name): """Return an expression engine by its name.""" return self.manager.get_expression_engine(name) def get_output_schema(self, process): """Return any additional output schema for the process.""" return [] def discover_process(self, path): """Perform process discovery in given path. This method will be called during process registration and should return a list of dictionaries with discovered process schemas. """ return [] def prepare_runtime(self, runtime_dir, data): """Prepare runtime directory. This method should return a dictionary of volume maps, where keys are files or directories relative the the runtime directory and values are paths under which these should be made available to the executing program. All volumes will be read-only. """ return {}
"""Workflow execution engines.""" from resolwe.flow.engine import BaseEngine class BaseExecutionEngine(BaseEngine): """A workflow execution engine.""" def evaluate(self, data): """Return the code needed to compute a given Data object.""" raise NotImplementedError def get_expression_engine(self, name): """Return an expression engine by its name.""" return self.manager.get_expression_engine(name) def get_output_schema(self, process): """Return any additional output schema for the process.""" return [] def discover_process(self, path): """Perform process discovery in given path. This method will be called during process registration and should return a list of dictionaries with discovered process schemas. """ return [] def prepare_runtime(self, runtime_dir, data): """Prepare runtime directory. This method should return a dictionary of volume maps, where keys are files or directories relative the the runtime directory and values are paths under which these should be made available to the executing program. All volumes will be read-only. """
Remove stray debug log message
# Python import urllib # Django from django.conf import settings from django.db.models import Q from django.template import Library, Node # Third party from subscription.models import Subscription, UserSubscription # This app from astrobin_apps_premium.utils import premium_get_valid_usersubscription register = Library() @register.inclusion_tag('astrobin_apps_premium/inclusion_tags/premium_badge.html') def premium_badge(user, size = 'large'): return { 'user': user, 'size': size, } @register.filter def is_premium(user): return 'AstroBin Premium' in premium_get_valid_usersubscription(user).subscription.name @register.filter def is_lite(user): return 'AstroBin Lite' in premium_get_valid_usersubscription(user).subscription.name @register.filter def is_free(user): return not (is_lite(user) or is_premium(user))
# Python import urllib # Django from django.conf import settings from django.db.models import Q from django.template import Library, Node # Third party from subscription.models import Subscription, UserSubscription # This app from astrobin_apps_premium.utils import premium_get_valid_usersubscription register = Library() @register.inclusion_tag('astrobin_apps_premium/inclusion_tags/premium_badge.html') def premium_badge(user, size = 'large'): return { 'user': user, 'size': size, } @register.filter def is_premium(user): print "ciao" return 'AstroBin Premium' in premium_get_valid_usersubscription(user).subscription.name @register.filter def is_lite(user): return 'AstroBin Lite' in premium_get_valid_usersubscription(user).subscription.name @register.filter def is_free(user): return not (is_lite(user) or is_premium(user))
Make IsPostOrSuperuserOnly a non-object-level permission.
# Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). from rest_framework import permissions class IsSuperuserOrReadOnly(permissions.BasePermission): '''Allow writes if superuser, read-only otherwise.''' def has_permission(self, request, view): return (request.user.is_superuser or request.method in permissions.SAFE_METHODS) class IsUserOrSuperuser(permissions.BasePermission): '''Accept only the users themselves or superusers.''' def has_object_permission(self, request, view, obj): return request.user.is_superuser or request.user == obj class IsAdvisorOrSuperuser(permissions.BasePermission): '''Accept only the school's advisor or superusers.''' def has_object_permission(self, request, view, obj): return request.user.is_superuser or request.user == obj.advisor class IsPostOrSuperuserOnly(permissions.BasePermission): '''Accept POST (create) requests, superusers-only otherwise.''' def has_permission(self, request, view): return request.method == 'POST' or request.user.is_superuser
# Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). from rest_framework import permissions class IsSuperuserOrReadOnly(permissions.BasePermission): '''Allow writes if superuser, read-only otherwise.''' def has_permission(self, request, view): return (request.user.is_superuser or request.method in permissions.SAFE_METHODS) class IsUserOrSuperuser(permissions.BasePermission): '''Accept only the users themselves or superusers.''' def has_object_permission(self, request, view, obj): return request.user.is_superuser or request.user == obj class IsAdvisorOrSuperuser(permissions.BasePermission): '''Accept only the school's advisor or superusers.''' def has_object_permission(self, request, view, obj): return request.user.is_superuser or request.user == obj.advisor class IsPostOrSuperuserOnly(permissions.BasePermission): '''Accept POST (create) requests, superusers-only otherwise.''' def has_object_permissions(self, request, view, obj): return request.method == 'POST' or request.user.is_superuser
Kill the process group (children of children)
package rerun import ( "fmt" "os" "os/exec" "syscall" ) type Cmd struct { cmd *exec.Cmd args []string } func Command(args ...string) (*Cmd, error) { c := &Cmd{ args: args, } if err := c.Start(); err != nil { return nil, err } return c, nil } func (c *Cmd) Start() error { cmd := exec.Command(c.args[0], c.args[1:]...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Stdin = os.Stdin cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} if err := cmd.Start(); err != nil { return err } c.cmd = cmd return nil } func (c *Cmd) Kill() error { // Kill the children process group, which we created via Setpgid: true. // This should kill children and all its children. if pgid, err := syscall.Getpgid(c.cmd.Process.Pid); err == nil { syscall.Kill(-pgid, 9) } // Make sure our own children gets killed. if err := c.cmd.Process.Kill(); err != nil { fmt.Println(err) } if err := c.cmd.Wait(); err != nil { fmt.Println(err) } return nil }
package rerun import ( "os" "os/exec" ) type Cmd struct { cmd *exec.Cmd args []string } func Run(args ...string) (*Cmd, error) { cmd := &Cmd{ args: args, } if err := cmd.run(); err != nil { return nil, err } return cmd, nil } func (c *Cmd) run() error { c.cmd = nil cmd := exec.Command(c.args[0], c.args[1:]...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Stdin = os.Stdin if err := cmd.Start(); err != nil { return err } c.cmd = cmd return nil } func (c *Cmd) Restart() error { if c.cmd != nil { if err := c.cmd.Process.Kill(); err != nil { return err } } return c.run() }
Fix logging out. :sheepish grin:
<?php namespace AppBundle\Controller; use Symfony\Component\Routing\RouterInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface; class RedirectAfterLogout implements LogoutSuccessHandlerInterface { private $router; public function __construct(RouterInterface $router) { $this->router = $router; } /** * Send the user to a specified URL if redirect_to is specified in the URL instead of the homepage. * * @param Request $request * @return RedirectResponse */ public function onLogoutSuccess(Request $request) { return new RedirectResponse($request->query->get('redirect_to') ? $request->query->get('redirect_to') : $this->router->generate('netrunnerdb_index') ); } }
<?php namespace AppBundle\Controller; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\RouterInterface; use Symfony\Component\Security\Core\SecurityContextInterface; use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface; class RedirectAfterLogout implements LogoutSuccessHandlerInterface { /** * Send the user to a specified URL if redirect_to is specified in the URL instead of the homepage. * * @param Request $request * @return RedirectResponse */ public function onLogoutSuccess(Request $request) { if ($request->query->get('redirect_to')) { $response = new RedirectResponse($request->query->get('redirect_to')); } else { $response = new RedirectResponse($this->generateUrl('netrunnerdb_index')); } return $response; } }
TEST: Add test for parameter_space ordering.
""" Tests for our testing utilities. """ from itertools import product from unittest import TestCase from zipline.utils.test_utils import parameter_space class TestParameterSpace(TestCase): x_args = [1, 2] y_args = [3, 4] @classmethod def setUpClass(cls): cls.xy_invocations = [] cls.yx_invocations = [] @classmethod def tearDownClass(cls): # This is the only actual test here. assert cls.xy_invocations == list(product(cls.x_args, cls.y_args)) assert cls.yx_invocations == list(product(cls.y_args, cls.x_args)) @parameter_space(x=x_args, y=y_args) def test_xy(self, x, y): self.xy_invocations.append((x, y)) @parameter_space(x=x_args, y=y_args) def test_yx(self, y, x): # Ensure that product is called with args in the order that they appear # in the function's parameter list. self.yx_invocations.append((y, x)) def test_nothing(self): # Ensure that there's at least one "real" test in the class, or else # our {setUp,tearDown}Class won't be called if, for example, # `parameter_space` returns None. pass
""" Tests for our testing utilities. """ from itertools import product from unittest import TestCase from zipline.utils.test_utils import parameter_space class TestParameterSpace(TestCase): x_args = [1, 2] y_args = [3, 4] @classmethod def setUpClass(cls): cls.xy_invocations = [] @classmethod def tearDownClass(cls): # This is the only actual test here. assert cls.xy_invocations == list(product(cls.x_args, cls.y_args)) @parameter_space(x=x_args, y=y_args) def test_xy(self, x, y): self.xy_invocations.append((x, y)) def test_nothing(self): # Ensure that there's at least one "real" test in the class, or else # our {setUp,tearDown}Class won't be called if, for example, # `parameter_space` returns None. pass
Replace switch on bool with if-else
package hdf5 // #include "hdf5.h" // // herr_t _go_hdf5_unsilence_errors(void) { // return H5Eset_auto2(H5E_DEFAULT, (H5E_auto2_t)(H5Eprint), stderr); // } // // herr_t _go_hdf5_silence_errors(void) { // return H5Eset_auto2(H5E_DEFAULT, NULL, NULL); // } import "C" import ( "fmt" ) // DisplayErrors enables/disables HDF5's automatic error printing func DisplayErrors(on bool) error { var err error if on { err = h5err(C._go_hdf5_unsilence_errors()) } else { err = h5err(C._go_hdf5_silence_errors()) } if err != nil { return fmt.Errorf("hdf5: could not call H5E_set_auto(): %v", err) } return nil } func init() { if err := DisplayErrors(false); err != nil { panic(err) } } // EOF
package hdf5 // #include "hdf5.h" // // herr_t _go_hdf5_unsilence_errors(void) { // return H5Eset_auto2(H5E_DEFAULT, (H5E_auto2_t)(H5Eprint), stderr); // } // // herr_t _go_hdf5_silence_errors(void) { // return H5Eset_auto2(H5E_DEFAULT, NULL, NULL); // } import "C" import ( "fmt" ) // DisplayErrors enables/disables HDF5's automatic error printing func DisplayErrors(b bool) error { switch b { case true: if err := h5err(C._go_hdf5_unsilence_errors()); err != nil { return fmt.Errorf("hdf5: could not call H5E_set_auto(): %v", err) } default: if err := h5err(C._go_hdf5_silence_errors()); err != nil { return fmt.Errorf("hdf5: could not call H5E_set_auto(): %v", err) } } return nil } func init() { err := DisplayErrors(false) if err != nil { panic(err.Error()) } } // EOF
Add a grunt task to translipe stylus
'use strict'; module.exports = function(grunt) { // Load all tasks require('load-grunt-tasks')(grunt); grunt.initConfig({ pck: grunt.file.readJSON('package.json'), clean: { all: ['typebase.css'] }, watch: { less: { files: ['src/{,*/}*.less'], tasks: ['less:dev'] } }, less: { dev: { files: { "typebase.css": "src/typebase.less" } } }, sass: { dev: { files: { "typebase-sass.css": "src/typebase.sass" } } }, stylus: { dev: { files: { "typebase-stylus.css":"src/typebase.stylus" } } } }); grunt.registerTask('dev', [ 'watch' ]); grunt.registerTask('default', [ 'clean', 'less', ]); };
'use strict'; module.exports = function(grunt) { // Load all tasks require('load-grunt-tasks')(grunt); grunt.initConfig({ pck: grunt.file.readJSON('package.json'), clean: { all: ['typebase.css'] }, watch: { less: { files: ['src/{,*/}*.less'], tasks: ['less:dev'] } }, less: { dev: { files: { "typebase.css": "src/typebase.less" } } }, sass: { dev: { files: { "typebase-sass.css": "src/typebase.sass" } } } }); grunt.registerTask('dev', [ 'watch' ]); grunt.registerTask('default', [ 'clean', 'less', ]); };
Add query to json output in json generation test
import unittest import json import raco.fakedb from raco import RACompiler from raco.language import MyriaAlgebra from myrialang import compile_to_json class DatalogTestCase(unittest.TestCase): def setUp(self): self.db = raco.fakedb.FakeDatabase() def execute_query(self, query): '''Run a test query against the fake database''' #print query dlog = RACompiler() dlog.fromDatalog(query) #print dlog.logicalplan dlog.optimize(target=MyriaAlgebra, eliminate_common_subexpressions=False) #print dlog.physicalplan # test whether we can generate json without errors json_string = json.dumps(compile_to_json( query, dlog.logicalplan, dlog.physicalplan)) assert json_string op = dlog.physicalplan[0][1] output_op = raco.algebra.StoreTemp('__OUTPUT__', op) self.db.evaluate(output_op) return self.db.get_temp_table('__OUTPUT__') def run_test(self, query, expected): '''Execute a test query with an expected output''' actual = self.execute_query(query) self.assertEquals(actual, expected)
import unittest import json import raco.fakedb from raco import RACompiler from raco.language import MyriaAlgebra from myrialang import compile_to_json class DatalogTestCase(unittest.TestCase): def setUp(self): self.db = raco.fakedb.FakeDatabase() def execute_query(self, query): '''Run a test query against the fake database''' #print query dlog = RACompiler() dlog.fromDatalog(query) #print dlog.logicalplan dlog.optimize(target=MyriaAlgebra, eliminate_common_subexpressions=False) #print dlog.physicalplan # test whether we can generate json without errors json_string = json.dumps(compile_to_json( "", dlog.logicalplan, dlog.physicalplan)) assert json_string op = dlog.physicalplan[0][1] output_op = raco.algebra.StoreTemp('__OUTPUT__', op) self.db.evaluate(output_op) return self.db.get_temp_table('__OUTPUT__') def run_test(self, query, expected): '''Execute a test query with an expected output''' actual = self.execute_query(query) self.assertEquals(actual, expected)
Add primitive int value to enum.
/* * Copyright (C) 2014,2015 The Cat Hive Developers. * * 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.cathive.sass; /** * @author Benjamin P. Jung */ public enum SassTag { SASS_BOOLEAN(0), SASS_NUMBER(1), SASS_COLOR(2), SASS_STRING(3), SASS_LIST(4), SASS_MAP(5), SASS_NULL(6), SASS_ERROR(7), SASS_WARNING(8); /** Sass tag primitive int value. */ private final int intValue; private SassTag(final int intValue) { this.intValue = intValue; } public int getIntValue() { return this.intValue; } }
/* * Copyright (C) 2014,2015 The Cat Hive Developers. * * 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.cathive.sass; /** * @author Benjamin P. Jung */ public enum SassTag { SASS_BOOLEAN, SASS_NUMBER, SASS_COLOR, SASS_STRING, SASS_LIST, SASS_MAP, SASS_NULL, SASS_ERROR, SASS_WARNING }
Add classifiers for Python 3.2 and 3.3
#!/usr/bin/env python import os from setuptools import setup, find_packages import versions def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='versions', version=versions.__version__, description='Package version handling library', long_description=read('README.rst'), author='Philippe Muller', url='http://github.com/pmuller/versions', license='MIT', packages=find_packages(), classifiers=( 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development', 'Topic :: System :: Installation/Setup', 'Topic :: System :: Software Distribution', ), )
#!/usr/bin/env python import os from setuptools import setup, find_packages import versions def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='versions', version=versions.__version__, description='Package version handling library', long_description=read('README.rst'), author='Philippe Muller', url='http://github.com/pmuller/versions', license='MIT', packages=find_packages(), classifiers=( 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development', 'Topic :: System :: Installation/Setup', 'Topic :: System :: Software Distribution', ), )
Fix for dependencies using pip
#!/usr/bin/env python from setuptools import setup setup(name='igtdetect', version='1.1.1', description='Line-level classifier for IGT instances, part of RiPLEs pipeline.', author='Ryan Georgi', author_email='rgeorgi@uw.edu', url='https://github.com/xigt/igtdetect', scripts=['detect-igt'], packages=['igtdetect'], install_requires = [ 'wheel', 'setuptools>=53', 'scikit-learn>=0.18.1', 'numpy', 'freki@https://github.com/xigt/freki/archive/v0.3.0.tar.gz', 'riples-classifier@https://github.com/xigt/riples-classifier/archive/0.1.0.tar.gz', ] )
#!/usr/bin/env python from setuptools import setup setup(name='igtdetect', version='1.1.0', description='Line-level classifier for IGT instances, part of RiPLEs pipeline.', author='Ryan Georgi', author_email='rgeorgi@uw.edu', url='https://github.com/xigt/igtdetect', scripts=['detect-igt'], packages=['igtdetect'], install_requires = [ 'scikit-learn == 0.18.1', 'numpy', 'freki', 'riples-classifier', ], dependency_links = [ 'https://github.com/xigt/freki/tarball/master#egg=freki-0.1.0', 'https://github.com/xigt/riples-classifier/tarball/master#egg=riples-classifier-0.1.0', ], )
Fix object serialization and deserialization in Redis Manager module.
import redis import pickle from .idatabasemanager import IDatabaseManager class RedisManager(IDatabaseManager): KEY_MESSAGE_QUEUE = 'message_queue' def __init__(self, redis_url): self.connection = redis.Redis.from_url(redis_url) def queue_message(self, message): serialized_message = pickle.dumps(message) self.connection.rpush(self.KEY_MESSAGE_QUEUE, serialized_message) def get_queued_message(self): serialized_message = self.connection.lpop(self.KEY_MESSAGE_QUEUE) print(serialized_message) if serialized_message != None: return pickle.loads(serialized_message) return None
import redis import pickle from .idatabasemanager import IDatabaseManager class RedisManager(IDatabaseManager): KEY_MESSAGE_QUEUE = 'message_queue' def __init__(self, redis_url): self.connection = redis.Redis.from_url(redis_url) def queue_message(self, message): serialized_message = pickle.dumps(message) self.connection.rpush(self.KEY_MESSAGE_QUEUE, message) # self.connection.save() def get_queued_message(self): serialized_message = self.connection.lpop(self.KEY_MESSAGE_QUEUE) print(serialized_message) # self.connection.save() if serialized_message != None: return pickle.loads(serialized_message) return None
Add a TODO comment for splitting the "remoteUserFailedLogin" error
/* * Copyright (c) 2020. Center for Open Science * * 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 io.cos.cas.authentication.exceptions; import javax.security.auth.login.AccountException; /** * Describes an error condition where authentication has failed during institutional authentication delegation. * * TODO: Divide this exception into two or more detailed ones. For example, one for failure in parsing required * attributes from authenticated Shibboleth session (InstitutionLoginFailedException), one for failure in * communicating with OSF API (OsfApiFailedException), etc. * * @author Michael Haselton * @author Longze Chen * @since 20.1.0 */ public class RemoteUserFailedLoginException extends AccountException { private static final long serialVersionUID = 3472948140572518658L; /** Instantiates a new exception (default). */ public RemoteUserFailedLoginException() { super(); } /** * Instantiates a new exception with a given message. * * @param message the message */ public RemoteUserFailedLoginException(final String message) { super(message); } }
/* * Copyright (c) 2020. Center for Open Science * * 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 io.cos.cas.authentication.exceptions; import javax.security.auth.login.AccountException; /** * Describes an error condition where authentication has failed during authentication delegation. * * @author Michael Haselton * @author Longze Chen * @since 20.1.0 */ public class RemoteUserFailedLoginException extends AccountException { private static final long serialVersionUID = 3472948140572518658L; /** Instantiates a new exception (default). */ public RemoteUserFailedLoginException() { super(); } /** * Instantiates a new exception with a given message. * * @param message the message */ public RemoteUserFailedLoginException(final String message) { super(message); } }
Prepare for release for 8.3dev-601.
/*------------------------------------------------------------------------- * * Copyright (c) 2004-2005, PostgreSQL Global Development Group * * IDENTIFICATION * $PostgreSQL: pgjdbc/org/postgresql/util/PSQLDriverVersion.java,v 1.21 2006/12/01 12:06:21 jurka Exp $ * *------------------------------------------------------------------------- */ package org.postgresql.util; import org.postgresql.Driver; /** * This class holds the current build number and a utility program to print * it and the file it came from. The primary purpose of this is to keep * from filling the cvs history of Driver.java.in with commits simply * changing the build number. The utility program can also be helpful for * people to determine what version they really have and resolve problems * with old and unknown versions located somewhere in the classpath. */ public class PSQLDriverVersion { public final static int buildNumber = 601; public static void main(String args[]) { java.net.URL url = Driver.class.getResource("/org/postgresql/Driver.class"); System.out.println(Driver.getVersion()); System.out.println("Found in: " + url); } }
/*------------------------------------------------------------------------- * * Copyright (c) 2004-2005, PostgreSQL Global Development Group * * IDENTIFICATION * $PostgreSQL: pgjdbc/org/postgresql/util/PSQLDriverVersion.java,v 1.20 2006/12/01 12:02:39 jurka Exp $ * *------------------------------------------------------------------------- */ package org.postgresql.util; import org.postgresql.Driver; /** * This class holds the current build number and a utility program to print * it and the file it came from. The primary purpose of this is to keep * from filling the cvs history of Driver.java.in with commits simply * changing the build number. The utility program can also be helpful for * people to determine what version they really have and resolve problems * with old and unknown versions located somewhere in the classpath. */ public class PSQLDriverVersion { public static int buildNumber = 600; public static void main(String args[]) { java.net.URL url = Driver.class.getResource("/org/postgresql/Driver.class"); System.out.println(Driver.getVersion()); System.out.println("Found in: " + url); } }
Fix casing of require StringUtilities
var assert = require('chai').assert; var StringUtilities = require('../build/stringUtilities').StringUtilities; describe('StringUtilities', function () { describe('format', function () { it('should format a string with no replacements', function () { assert.equal(StringUtilities.format("Test"), "Test"); }); it('should format a string with one replacement', function () { assert.equal(StringUtilities.format("Test %s", "one"), "Test one"); }); it('should format a string with multiple replacements', function () { assert.equal(StringUtilities.format("Test %s %s %s", "one", "two", "three"), "Test one two three"); }); }); describe('toProperCase', function () { it('should properly case a sentence', function () { assert.equal(StringUtilities.toProperCase("this is a test, only a test. the case should be proper."), "This Is A Test, Only A Test. The Case Should Be Proper."); }); }); });
var assert = require('chai').assert; var StringUtilities = require('../build/StringUtilities').StringUtilities; describe('StringUtilities', function () { describe('format', function () { it('should format a string with no replacements', function () { assert.equal(StringUtilities.format("Test"), "Test"); }); it('should format a string with one replacement', function () { assert.equal(StringUtilities.format("Test %s", "one"), "Test one"); }); it('should format a string with multiple replacements', function () { assert.equal(StringUtilities.format("Test %s %s %s", "one", "two", "three"), "Test one two three"); }); }); describe('toProperCase', function () { it('should properly case a sentence', function () { assert.equal(StringUtilities.toProperCase("this is a test, only a test. the case should be proper."), "This Is A Test, Only A Test. The Case Should Be Proper."); }); }); });
Set ddb connection to readonly to get rid of the warning message
package org.imos.ddb; import java.io.File; import java.io.IOException; import net.ucanaccess.jdbc.JackcessOpenerInterface; //imports from Jackcess Encrypt import com.healthmarketscience.jackcess.CryptCodecProvider; import com.healthmarketscience.jackcess.Database; import com.healthmarketscience.jackcess.DatabaseBuilder; public class CryptCodecOpener implements JackcessOpenerInterface { public Database open(File fl,String pwd) throws IOException { DatabaseBuilder dbd =new DatabaseBuilder(fl); dbd.setAutoSync(true); dbd.setCodecProvider(new CryptCodecProvider(pwd)); dbd.setReadOnly(true); return dbd.open(); } //Notice that the parameter setting autosync =true is recommended with UCanAccess for performance reasons. //UCanAccess flushes the updates to disk at transaction end. //For more details about autosync parameter (and related tradeoff), see the Jackcess documentation. }
package org.imos.ddb; import java.io.File; import java.io.IOException; import net.ucanaccess.jdbc.JackcessOpenerInterface; //imports from Jackcess Encrypt import com.healthmarketscience.jackcess.CryptCodecProvider; import com.healthmarketscience.jackcess.Database; import com.healthmarketscience.jackcess.DatabaseBuilder; public class CryptCodecOpener implements JackcessOpenerInterface { public Database open(File fl,String pwd) throws IOException { DatabaseBuilder dbd =new DatabaseBuilder(fl); dbd.setAutoSync(true); dbd.setCodecProvider(new CryptCodecProvider(pwd)); dbd.setReadOnly(false); return dbd.open(); } //Notice that the parameter setting autosync =true is recommended with UCanAccess for performance reasons. //UCanAccess flushes the updates to disk at transaction end. //For more details about autosync parameter (and related tradeoff), see the Jackcess documentation. }
Check null behaviour of emailID in mailchimp sync
<?php class CRM_Mailchimp_BAO_MCSync extends CRM_Mailchimp_DAO_MCSync { public static function create($params) { $instance = new self(); if ($params['email_id'] && $params['mc_list_id']) { $instance->copyValues($params); $instance->save(); } else { // log civicrm error CRM_Core_Error::debug_log_message( 'CRM_Mailchimp_BAO_MCSync $params= '. print_r($params, true), $out = false ); } } public static function getSyncStats() { $stats = array('Added' => 0, 'Updated' => 0,'Removed' => 0, 'Error' => 0); $query = "SELECT sync_status as status, count(*) as count FROM civicrm_mc_sync WHERE is_latest = 1 GROUP BY sync_status"; $dao = CRM_Core_DAO::executeQuery($query); while ($dao->fetch()) { $stats[$dao->status] = $dao->count; } $total = CRM_Mailchimp_Utils::getMemberCountForGroupsToSync(); $blocked = $total - array_sum($stats); $stats['Total'] = $total; $stats['Blocked'] = $blocked; return $stats; } static function resetTable() { $query = "UPDATE civicrm_mc_sync SET is_latest = '0'"; $dao= CRM_Core_DAO::executeQuery($query); return $dao; } }
<?php class CRM_Mailchimp_BAO_MCSync extends CRM_Mailchimp_DAO_MCSync { public static function create($params) { $instance = new self(); $instance->copyValues($params); $instance->save(); } public static function getSyncStats() { $stats = array('Added' => 0, 'Updated' => 0,'Removed' => 0, 'Error' => 0); $query = "SELECT sync_status as status, count(*) as count FROM civicrm_mc_sync GROUP BY sync_status"; $dao = CRM_Core_DAO::executeQuery($query); while ($dao->fetch()) { $stats[$dao->status] = $dao->count; } $total = CRM_Mailchimp_Utils::getMemberCountForGroupsToSync(); $blocked = $total - array_sum($stats); $stats['Total'] = $total; $stats['Blocked'] = $blocked; return $stats; } static function resetTable() { $query = "UPDATE civicrm_mc_sync SET is_latest = '0'"; $dao= CRM_Core_DAO::executeQuery($query); return $dao; } }
Remove DefinePlugin (webpack -p) does this
var path = require("path"); var webpack = require("webpack"); module.exports = { // https://webpack.js.org/configuration/dev-server/ devServer: { contentBase: "./public", compress: true, overlay: true, port: 3000 }, devtool: "cheap-module-source-map", entry: { widgets: ["babel-polyfill", "./src/widgets"] }, module: { rules: [ { include: path.resolve("./src"), test: /\.js$/, use: { loader: "babel-loader", options: { cacheDirectory: true } } } ] }, output: { chunkFilename: "[id].[hash:5]-[chunkhash:7].js", devtoolModuleFilenameTemplate: "[absolute-resource-path]", filename: "[name].js", path: path.resolve("./build") } };
var path = require("path"); var webpack = require("webpack"); module.exports = { // https://webpack.js.org/configuration/dev-server/ devServer: { contentBase: "./public", compress: true, overlay: true, port: 3000 }, devtool: "cheap-module-source-map", entry: { widgets: ["babel-polyfill", "./src/widgets"] }, module: { rules: [ { include: path.resolve("./src"), test: /\.js$/, use: { loader: "babel-loader", options: { cacheDirectory: true } } } ] }, output: { chunkFilename: "[id].[hash:5]-[chunkhash:7].js", devtoolModuleFilenameTemplate: "[absolute-resource-path]", filename: "[name].js", path: path.resolve("./build") }, plugins: [ new webpack.NamedModulesPlugin(), new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify(process.env.NODE_ENV || "development") } }) ] };
Update package names in ijx. This used to be revision r2172.
package ijx.plugin; import imagej.plugin.api.PluginEntry; import imagej.plugin.spi.PluginFinder; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.openide.util.Lookup; public class PluginDiscovery { /** * Tests the plugin discovery mechanism, * printing a list of all discovered plugins. */ public static void main(String[] args) { System.out.println("Scanning for plugin finders..."); Collection<? extends PluginFinder> finders = Lookup.getDefault().lookupAll(PluginFinder.class); List<PluginEntry> plugins = new ArrayList<PluginEntry>(); for (PluginFinder finder : finders) { System.out.println("Querying " + finder + "..."); finder.findPlugins(plugins); } System.out.println("Discovered plugins:"); for (PluginEntry plugin : plugins) { System.out.println("\t" + plugin); } } }
package ijx.plugin; import imagej.plugin.PluginEntry; import imagej.plugin.PluginFinder; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.openide.util.Lookup; public class PluginDiscovery { /** * Tests the plugin discovery mechanism, * printing a list of all discovered plugins. */ public static void main(String[] args) { System.out.println("Scanning for plugin finders..."); Collection<? extends PluginFinder> finders = Lookup.getDefault().lookupAll(PluginFinder.class); List<PluginEntry> plugins = new ArrayList<PluginEntry>(); for (PluginFinder finder : finders) { System.out.println("Querying " + finder + "..."); finder.findPlugins(plugins); } System.out.println("Discovered plugins:"); for (PluginEntry plugin : plugins) { System.out.println("\t" + plugin); } } }
Rename Build to Builder and use /tools/builder as the routing url
import Vue from 'vue'; import Router from 'vue-router'; import Home from '../components/Home'; import About from '../components/About'; import Help from '../components/Help'; import Machine from '../components/settings/Machine'; import Kit from '../components/settings/Kit'; import Container from '../components/settings/Container'; import Builder from '../components/tools/Builder'; Vue.use(Router); const router = new Router({ mode: 'history', // scrollBehavior: () => ({ y: 0 }), routes: [ { path: '/', component: Home }, { path: '/about', component: About }, { path: '/help', component: Help }, { path: '/settings/machine', component: Machine }, { path: '/settings/kits', component: Kit }, { path: '/settings/containers/:type', component: Container }, { path: '/tools/builder', component: Builder }, { path: '*', redirect: '/' }, ], }); export default router;
import Vue from 'vue'; import Router from 'vue-router'; import Home from '../components/Home'; import About from '../components/About'; import Help from '../components/Help'; import Machine from '../components/settings/Machine'; import Kit from '../components/settings/Kit'; import Container from '../components/settings/Container'; import Build from '../components/tools/Build'; import Reset from '../components/tools/Reset'; Vue.use(Router); const router = new Router({ mode: 'history', // scrollBehavior: () => ({ y: 0 }), routes: [ { path: '/', component: Home }, { path: '/about', component: About }, { path: '/help', component: Help }, { path: '/settings/machine', component: Machine }, { path: '/settings/kits', component: Kit }, { path: '/settings/containers/:type', component: Container }, { path: '/tools/build', component: Build }, { path: '/tools/reset', component: Reset }, { path: '*', redirect: '/' }, ], }); export default router;
Fix down button to dp the same tag search
import { remote } from 'electron'; import { call, select, put, takeLatest } from 'redux-saga/effects'; import GIF from './constants'; import { result, error, clear } from './actions'; import request from '../../utils/request'; export function* requestGif(action) { // If there is no query given, grab the latest one from state const tag = action.payload ? action.payload : yield select(state => state.gif.currentQuery); const requestURL = `http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=${tag}`; try { const gif = yield call(request, requestURL); const state = yield select(); // Only continue displaying this result if the window is visible to the user // and they haven't blanked out the search box if (remote.getCurrentWindow().isVisible() && state.gif.currentQuery.length) { yield put(result(gif)); } else { yield put(clear()); } } catch (err) { yield put(error(err)); } } export function* watchRequestGif() { yield takeLatest([GIF.REQUEST, GIF.NEXT], requestGif); }
import { remote } from 'electron'; import { call, select, put, takeLatest } from 'redux-saga/effects'; import GIF from './constants'; import { result, error, clear } from './actions'; import request from '../../utils/request'; export function* requestGif(action) { const requestURL = `http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=${action.payload}`; try { const gif = yield call(request, requestURL); const state = yield select(); // Only continue displaying this result if the window is visible to the user // and they haven't blanked out the search box if (remote.getCurrentWindow().isVisible() && state.gif.currentQuery.length) { yield put(result(gif)); } else { yield put(clear()); } } catch (err) { yield put(error(err)); } } export function* watchRequestGif() { yield takeLatest([GIF.REQUEST, GIF.NEXT], requestGif); }
Fix bug in previous commit
package io_throttler import ( "fmt" "io" "io/ioutil" "github.com/efarrer/iothrottler" ) //CopyThrottled does a normal io.Copy but with throttling func CopyThrottled(bandwidth iothrottler.Bandwidth, dest io.Writer, src io.Reader) (written int64, returnErr error) { pool := iothrottler.NewIOThrottlerPool(bandwidth) defer pool.ReleasePool() var readCloser io.ReadCloser if rc, ok := src.(io.ReadCloser); ok { readCloser = rc } else { readCloser = ioutil.NopCloser(src) } throttledFile, err := pool.AddReader(readCloser) if err != nil { return 0, fmt.Errorf("Cannot add reader to copy throttler, error: %s", err.Error()) } return io.Copy(dest, throttledFile) }
package io_throttler import ( "fmt" "io" "io/ioutil" "github.com/efarrer/iothrottler" ) //CopyThrottled does a normal io.Copy but with throttling func CopyThrottled(bandwidth iothrottler.Bandwidth, dest io.Writer, src io.Reader) (written int64, returnErr error) { pool := iothrottler.NewIOThrottlerPool(bandwidth) defer pool.ReleasePool() var readCloser io.ReadCloser if rc, ok := src.(io.ReadCloser); ok { readCloser = rc } else { readCloser = ioutil.NopCloser(readCloser) } throttledFile, err := pool.AddReader(readCloser) if err != nil { return 0, fmt.Errorf("Cannot add reader to copy throttler, error: %s", err.Error()) } return io.Copy(dest, throttledFile) }
Fix unit test for seo faces url
from django.test import TestCase from functional_tests.factory import FaceFactory class Facetest(TestCase): def setUp(self): self.face = FaceFactory(title='Lokesh') def test_title_to_share_returns_meet_Lokesh__farmer_from_sivaganga_tamil_nadu(self): self.assertEqual(self.face.title_to_share,'Meet Lokesh, farmer from Sivaganga, Tamil Nadu') def test_featured_image_returnes_the_image(self): self.assertEqual(self.face.featured_image,self.face.image) def test_to_str_returns_lokesh_sivaganga(self): self.assertEqual(str(self.face),'Lokesh Sivaganga') def test_get_absolute_url_return_path_with_faces_s_face_page(self): self.assertRegexpMatches(self.face.get_absolute_url(),'/categories/faces/s/lokesh/?')
from django.test import TestCase from functional_tests.factory import FaceFactory class Facetest(TestCase): def setUp(self): self.face = FaceFactory(title='Lokesh') def test_title_to_share_returns_meet_Lokesh__farmer_from_sivaganga_tamil_nadu(self): self.assertEqual(self.face.title_to_share,'Meet Lokesh, farmer from Sivaganga, Tamil Nadu') def test_featured_image_returnes_the_image(self): self.assertEqual(self.face.featured_image,self.face.image) def test_to_str_returns_lokesh_sivaganga(self): self.assertEqual(str(self.face),'Lokesh Sivaganga') def test_get_absolute_url_return_path_with_faces_s_face_page(self): self.assertEqual(self.face.get_absolute_url(),'/categories/faces/s/lokesh/')
Add args to ctor with size
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); } }
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); } @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); } }
[18009] Remove HTTPS support, fix swagger test
package info.elexis.server.core.rest.test.swagger; import static info.elexis.server.core.rest.test.AllTests.REST_URL; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.HttpURLConnection; import org.junit.Test; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import info.elexis.server.core.rest.test.AllTests; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class SwaggerTest { private OkHttpClient client = AllTests.getDefaultOkHttpClient(); private Response response; Gson gson = new Gson(); @Test public void testGetSwaggerConfiguration() throws IOException { Request request = new Request.Builder().url(REST_URL + "/swagger.json").get().build(); response = client.newCall(request).execute(); assertEquals(HttpURLConnection.HTTP_OK, response.code()); String swaggerJson = response.body().string(); JsonElement jelem = gson.fromJson(swaggerJson, JsonElement.class); // JsonObject swagger = jelem.getAsJsonObject(); // JsonObject securityDefinitions = swagger.getAsJsonObject("securityDefinitions"); // JsonObject esoAuth = securityDefinitions.get("esoauth").getAsJsonObject(); // assertEquals("oauth2", esoAuth.get("type").getAsString()); } }
package info.elexis.server.core.rest.test.swagger; import static info.elexis.server.core.rest.test.AllTests.REST_URL; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.HttpURLConnection; import org.junit.Test; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import info.elexis.server.core.rest.test.AllTests; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class SwaggerTest { private OkHttpClient client = AllTests.getDefaultOkHttpClient(); private Response response; Gson gson = new Gson(); @Test public void testGetSwaggerConfiguration() throws IOException { Request request = new Request.Builder().url(REST_URL + "/swagger.json").get().build(); response = client.newCall(request).execute(); assertEquals(HttpURLConnection.HTTP_OK, response.code()); String swaggerJson = response.body().string(); JsonElement jelem = gson.fromJson(swaggerJson, JsonElement.class); JsonObject swagger = jelem.getAsJsonObject(); JsonObject securityDefinitions = swagger.getAsJsonObject("securityDefinitions"); JsonObject esoAuth = securityDefinitions.get("esoauth").getAsJsonObject(); assertEquals("oauth2", esoAuth.get("type").getAsString()); } }
Change public event to event list.
;(function(){ angular.module('flockTogether', ['ngRoute'], function($routeProvider, $httpProvider) { $routeProvider .when('/', { templateUrl: 'partials/event_list.html', controller: 'eventListCtrl' })//END .when '/home' .when('/login', { templateUrl: 'partials/login.html', controller: 'loginCtrl' })//END .when '/login' .when('/create-event', { templateUrl: 'partials/create_event.html', controller: 'createEventCtrl' }) .when('/event-detail/:id', { templateUrl: 'partials/event_detail.html', controller: 'detailCtrl' }) })//END angular.module 'flock' .controller('MainController', function($http, $scope){ $http.get('api/event.json') .then(function(response){ $scope.events = response.data; })//END get event.json })//END MainController })();//END IIFE
;(function(){ angular.module('flockTogether', ['ngRoute'], function($routeProvider, $httpProvider) { $routeProvider .when('/', { templateUrl: 'partials/public_event_list.html', controller: 'publicListCtrl' })//END .when '/home' .when('/login', { templateUrl: 'partials/login.html', controller: 'loginCtrl' })//END .when '/login' .when('/create-event', { templateUrl: 'partials/create_event.html', controller: 'createEventCtrl' }) .when('/event-detail/:id', { templateUrl: 'partials/event_detail.html', controller: 'detailCtrl' }) })//END angular.module 'flock' .controller('MainController', function($http, $scope){ $http.get('api/event.json') .then(function(response){ $scope.events = response.data; })//END get event.json })//END MainController })();//END IIFE
Use response.text for automatic decoding.
from __future__ import unicode_literals import logging import requests from .parsers import WebObsResultsParser logger = logging.getLogger(__name__) WEBOBS_RESULTS_URL = 'http://www.aavso.org/apps/webobs/results/' def download_observations(observer_code): """ Downloads all variable star observations by a given observer. Performs a series of HTTP requests to AAVSO's WebObs search and downloads the results page by page. Each page is then passed to :py:class:`~pyaavso.parsers.webobs.WebObsResultsParser` and parse results are added to the final observation list. """ page_number = 1 observations = [] while True: logger.info('Downloading page %d...', page_number) response = requests.get(WEBOBS_RESULTS_URL, params={ 'obscode': observer_code, 'num_results': 200, 'obs_types': 'all', 'page': page_number, }) parser = WebObsResultsParser(response.text) observations.extend(parser.get_observations()) # kinda silly, but there's no need for lxml machinery here if '>Next</a>' not in response.text: break page_number += 1 return observations
from __future__ import unicode_literals import logging import requests from .parsers import WebObsResultsParser logger = logging.getLogger(__name__) WEBOBS_RESULTS_URL = 'http://www.aavso.org/apps/webobs/results/' def download_observations(observer_code): """ Downloads all variable star observations by a given observer. Performs a series of HTTP requests to AAVSO's WebObs search and downloads the results page by page. Each page is then passed to :py:class:`~pyaavso.parsers.webobs.WebObsResultsParser` and parse results are added to the final observation list. """ page_number = 1 observations = [] while True: logger.info('Downloading page %d...', page_number) response = requests.get(WEBOBS_RESULTS_URL, params={ 'obscode': observer_code, 'num_results': 200, 'obs_types': 'all', 'page': page_number, }) parser = WebObsResultsParser(response.content) observations.extend(parser.get_observations()) # kinda silly, but there's no need for lxml machinery here if '>Next</a>' not in response.content: break page_number += 1 return observations
Fix date picker NAN issue
// @flow import React from 'react'; import { DatePicker } from 'antd'; import { func, string, any } from 'prop-types'; import moment from 'moment'; import CellStyled from './Cell.styles'; import { getDateFormat } from '../../utils'; import { MODES } from '../../constants'; type Props = { children: any, onChange: func, format?: string, mode: string, }; const DateCell = ({ children, onChange, format, mode }: Props) => ( <CellStyled> {mode === MODES.EDIT ? ( <DatePicker showTime defaultValue={children ? moment(children) : null} format={getDateFormat(format)} css={{ width: '100% !important', }} onChange={(momentObject, dateString) => { if (children !== dateString) { // only update value if date string has changed onChange(dateString || null); } }} /> ) : ( children && moment(children).format(getDateFormat(format)) )} </CellStyled> ); DateCell.propTypes = { onChange: func.isRequired, children: any, format: string, mode: string, }; export default DateCell;
// @flow import React from 'react'; import { DatePicker } from 'antd'; import { func, string, any } from 'prop-types'; import moment from 'moment'; import CellStyled from './Cell.styles'; import { getDateFormat } from '../../utils'; import { MODES } from '../../constants'; type Props = { children: any, onChange: func, format?: string, mode: string, }; const DateCell = ({ children, onChange, format, mode }: Props) => ( <CellStyled> {mode === MODES.EDIT ? ( <DatePicker showTime defaultValue={ children ? moment(children, getDateFormat(format)) : null } format={getDateFormat(format)} css={{ width: '100% !important', }} onChange={(momentObject, dateString) => { if (children !== dateString) { // only update value if date string has changed onChange(dateString || null); } }} /> ) : ( children && moment(children).format(getDateFormat(format)) )} </CellStyled> ); DateCell.propTypes = { onChange: func.isRequired, children: any, format: string, mode: string, }; export default DateCell;
Update protocol version to 49
package com.thebuerkle.mcclient.request; import org.apache.mina.core.buffer.IoBuffer; public class HandshakeRequest extends Request { public final String username; public final String host; public final int port; public HandshakeRequest(String username, String host, int port) { super(0x02); this.username = username; this.host = host; this.port = port; } @Override() public int getSize() { return 1 + (2 + this.username.length()*2) + (2+ this.host.length()*2) + 4; } @Override() public void write(IoBuffer out) { mc_byte(out, 49); // 1.4.4 protocol version mc_string(out, username); mc_string(out, host); mc_int(out, port); } }
package com.thebuerkle.mcclient.request; import org.apache.mina.core.buffer.IoBuffer; public class HandshakeRequest extends Request { public final String username; public final String host; public final int port; public HandshakeRequest(String username, String host, int port) { super(0x02); this.username = username; this.host = host; this.port = port; } @Override() public int getSize() { return 1 + (2 + this.username.length()*2) + (2+ this.host.length()*2) + 4; } @Override() public void write(IoBuffer out) { mc_byte(out, 47); // 1.4 protocol version mc_string(out, username); mc_string(out, host); mc_int(out, port); } }
Refactor previous code into a function
function stats(data) { var myId = data["student"]["id"]; var myGrade; var finalGrades; data["evaluations"].forEach(function(grades) { if(grades["name"] === "Pauta Final") { finalGrades = grades; } }); finalGrades["grades"].forEach(function(element) { if(element["id"] === myId) { myGrade = element["grade"] } }); var total = finalGrades["grades"].length; var above = 0; var same = 0; finalGrades["grades"].forEach(function(element) { if(!isNaN(element["grade"]) && element["grade"] > myGrade) { above += 1; } if(element["grade"] === myGrade) { same += 1; } }); console.log("total: ", total); console.log("above: ", above); console.log("same: ", same); console.log("below: ", total-above-same); console.log("you're in the top ", (above+1)/total, "%"); console.log(data["name"], '\t', myGrade, '\t', above, '\t', same, '\t', total-above-same) }
var myId = data["student"]["id"]; var myGrade; var finalGrades; data["evaluations"].forEach(function(grades) { if(grades["name"] === "Pauta Final") { finalGrades = grades; } }); finalGrades["grades"].forEach(function(element) { if(element["id"] === myId) { myGrade = element["grade"] } }); var total = finalGrades["grades"].length; var above = 0; var same = 0; finalGrades["grades"].forEach(function(element) { if(!isNaN(element["grade"]) && element["grade"] > myGrade) { above += 1; } if(element["grade"] === myGrade) { same += 1; } }); console.log("total: ", total); console.log("above: ", above); console.log("same: ", same); console.log("below: ", total-above-same); console.log("you're in the top ", (above+1)/total, "%"); console.log(data["name"], '\t', myGrade, '\t', above, '\t', same, '\t', total-above-same)
Change number of episodes to 60000
''' The Q-learning algorithm is used to learn the state-action values for all Tic-Tac-Toe positions by playing games against itself (self-play). ''' from capstone.game.games import TicTacToe from capstone.game.players import RandPlayer from capstone.rl import Environment, GameMDP from capstone.rl.learners import QLearningSelfPlay from capstone.rl.policies import EGreedy, RandomPolicy from capstone.rl.utils import EpisodicWLDPlotter from capstone.rl.value_functions import TabularQ game = TicTacToe() env = Environment(GameMDP(game)) tabularq = TabularQ(random_state=23) egreedy = EGreedy(env.actions, tabularq, epsilon=0.5, random_state=23) rand_policy = RandomPolicy(env.actions, random_state=23) qlearning = QLearningSelfPlay( env=env, qf=tabularq, policy=rand_policy, learning_rate=0.1, discount_factor=0.99, n_episodes=60000, verbose=0, callbacks=[ EpisodicWLDPlotter( game=game, opp_player=RandPlayer(random_state=23), n_matches=2000, period=1000, filename='tic_ql_tabular_selfplay_all.pdf' ) ] ) qlearning.learn()
''' The Q-learning algorithm is used to learn the state-action values for all Tic-Tac-Toe positions by playing games against itself (self-play). ''' from capstone.game.games import TicTacToe from capstone.game.players import RandPlayer from capstone.rl import Environment, GameMDP from capstone.rl.learners import QLearningSelfPlay from capstone.rl.policies import EGreedy, RandomPolicy from capstone.rl.utils import EpisodicWLDPlotter from capstone.rl.value_functions import TabularQ game = TicTacToe() env = Environment(GameMDP(game)) tabularq = TabularQ(random_state=23) egreedy = EGreedy(env.actions, tabularq, epsilon=0.5, random_state=23) rand_policy = RandomPolicy(env.actions, random_state=23) qlearning = QLearningSelfPlay( env=env, qf=tabularq, policy=rand_policy, learning_rate=0.1, discount_factor=0.99, n_episodes=3000, verbose=0, callbacks=[ EpisodicWLDPlotter( game=game, opp_player=RandPlayer(random_state=23), n_matches=2000, period=1000, filename='tic_ql_tabular_selfplay_all.pdf' ) ] ) qlearning.learn()
Add method to return next name
package main import ( "encoding/json" "flag" "io/ioutil" "log" ) // define CLI flags //TODO: add default path for default file var filepath = flag.String("filepath", "./names.json", "The path to the file with the names") var shouldNameBeRemoved = flag.Bool("remove", true, "if true the name will be removed from list") // Names is an array of names type Names struct { Description string Names []Name } // Name is a name of the tool type Name struct { Name string Removed bool } func main() { flag.Parse() names := loadFile(*filepath) log.Println("Loaded names with description ", names.Description) nextName := nextName(names) log.Println("==================================================") log.Println("The next name is:") log.Println(nextName) log.Println("==================================================") } func loadFile(filepath string) Names { log.Println("Load files from ", filepath) file, err := ioutil.ReadFile(filepath) if err != nil { log.Println("file could not be opened") log.Fatal(err) } var names Names err = json.Unmarshal(file, &names) if err != nil { log.Fatal(err) } return names } func nextName(names Names) string { for _, name := range names.Names { if !name.Removed { if *shouldNameBeRemoved { name.Removed = true } else { log.Println("The name will not be removed!") } return name.Name } } return "test" }
package main import ( "encoding/json" "flag" "io/ioutil" "log" ) // define CLI flags //TODO: add default path for default file var filepath = flag.String("filepath", "./names.json", "The path to the file with the names") var removeName = flag.Bool("remove", true, "if true the name will be removed from list") // Names is an array of names type Names struct { Description string Names []Name } // Name is a name of the tool type Name struct { Name string Removed bool } func main() { flag.Parse() names := loadFile(*filepath) log.Println("Loaded names with description ", names.Description) } func loadFile(filepath string) Names { log.Println("Load files from ", filepath) file, err := ioutil.ReadFile(filepath) if err != nil { log.Println("file could not be opened") log.Fatal(err) } var names Names err = json.Unmarshal(file, &names) if err != nil { log.Fatal(err) } return names }
Add logged user vote field to SubmissionType
import graphene from graphene_django import DjangoObjectType from voting.models import Vote from voting.types import VoteType from .models import Submission from .models import SubmissionType as ModelSubmissionType class SubmissionTypeType(DjangoObjectType): class Meta: model = ModelSubmissionType only_fields = ("id", "name") class SubmissionType(DjangoObjectType): votes = graphene.NonNull(graphene.List(VoteType)) my_vote = graphene.Field(VoteType, user_id=graphene.ID()) def resolve_my_vote(self, info, user_id): try: return self.votes.get(user_id=user_id) except Vote.DoesNotExist: return None def resolve_votes(self, info): return self.votes.all() class Meta: model = Submission only_fields = ( "id", "conference", "title", "elevator_pitch", "notes", "abstract", "owner", "helpers", "topic", "type", "duration", "votes", )
import graphene from graphene_django import DjangoObjectType from voting.types import VoteType from .models import Submission from .models import SubmissionType as ModelSubmissionType class SubmissionTypeType(DjangoObjectType): class Meta: model = ModelSubmissionType only_fields = ("id", "name") class SubmissionType(DjangoObjectType): votes = graphene.NonNull(graphene.List(graphene.NonNull(VoteType))) def resolve_votes(self, info): return self.votes.all() class Meta: model = Submission only_fields = ( "id", "conference", "title", "elevator_pitch", "notes", "abstract", "owner", "helpers", "topic", "type", "duration", "votes", )
Add result page information in feathers format
'use strict'; const request = require('request-promise-native'); const querystring = require('querystring'); const hooks = require('./hooks'); class Service { constructor(options) { this.options = options || {}; } find(params) { const options = {}; if(params.query.$limit) options["page[limit]"] = params.query.$limit; if(params.query.$skip) options["page[offset]"] = params.query.$skip; if(params.query.query) options.query = params.query.query; const contentServerUrl = `https://schul-cloud.org:8090/contents?${querystring.encode(options)}`; return request(contentServerUrl).then(string => { let result = JSON.parse(string); result.total = result.meta.page.total; result.limit = result.meta.page.limit; result.skip = result.meta.page.offset; return result; }); } /*get(id, params) { return Promise.resolve({ id, text: `A new message with ID: ${id}!` }); }*/ } module.exports = function () { const app = this; // Initialize our service with any options it requires app.use('/contents', new Service()); // Get our initialize service to that we can bind hooks const contentService = app.service('/contents'); // Set up our before hooks contentService.before(hooks.before); // Set up our after hooks contentService.after(hooks.after); }; module.exports.Service = Service;
'use strict'; const request = require('request-promise-native'); const querystring = require('querystring'); const hooks = require('./hooks'); class Service { constructor(options) { this.options = options || {}; } find(params) { const options = {}; if(params.query.$limit) options["page[limit]"] = params.query.$limit; if(params.query.$skip) options["page[offset]"] = params.query.$skip; if(params.query.query) options.query = params.query.query; const contentServerUrl = `https://schul-cloud.org:8090/contents?${querystring.encode(options)}`; return request(contentServerUrl).then(string => { return JSON.parse(string); }); } /*get(id, params) { return Promise.resolve({ id, text: `A new message with ID: ${id}!` }); }*/ } module.exports = function () { const app = this; // Initialize our service with any options it requires app.use('/contents', new Service()); // Get our initialize service to that we can bind hooks const contentService = app.service('/contents'); // Set up our before hooks contentService.before(hooks.before); // Set up our after hooks contentService.after(hooks.after); }; module.exports.Service = Service;
Fix handler only checking https protocol
chrome.tabs.onUpdated.addListener( function(tabId, changeInfo, tab) { var url = tab.url; if (url.indexOf('://www.bing.com/maps/default.aspx') > 0 && changeInfo.status == 'loading') { var rtpIndex = url.indexOf("rtp="); if (rtpIndex >= 0) { var rtp = url.substr(rtpIndex + 4); rtp = rtp.substr(0, rtp.indexOf('&')); var address = rtp.substr(rtp.lastIndexOf('_') + 1); chrome.tabs.update(tabId, {url: 'https://www.google.com/maps/preview/place/' + address}); } } } )
chrome.tabs.onUpdated.addListener( function(tabId, changeInfo, tab) { var url = tab.url; if (url.indexOf('https://www.bing.com/maps/default.aspx') == 0 && changeInfo.status == 'loading') { var rtpIndex = url.indexOf("rtp="); if (rtpIndex >= 0) { var rtp = url.substr(rtpIndex + 4); rtp = rtp.substr(0, rtp.indexOf('&')); var address = rtp.substr(rtp.lastIndexOf('_') + 1); chrome.tabs.update(tabId, {url: 'https://www.google.com/maps/preview/place/' + address}); } } } )
Add vendor-name to package.ini as vendor. Looking to find the vendor name based on a root src folder name may proof difficult at times.
<?php namespace Respect\Foundation\InfoProviders; use DirectoryIterator; class VendorName extends AbstractProvider { public function providerPackageIni() { $iniPath = realpath($this->projectFolder.'/package.ini'); if (!file_exists($iniPath)) return ''; $ini = parse_ini_file($iniPath, true); return @$ini['package']['vendor']; } public function providerFolderStructure() { if (file_exists($libraryFolder = new LibraryFolder($this->projectFolder))) foreach (new DirectoryIterator($libraryFolder) as $vendor) if (!$vendor->isDot() && $vendor->isDir() && preg_match('/[A-Z].*/', $vendor->getFileName())) return $vendor->getFileName(); } public function providerDefault() { return ucfirst(preg_replace('/\W+/', '', new UserName($this->projectFolder))); } }
<?php namespace Respect\Foundation\InfoProviders; use DirectoryIterator; class VendorName extends AbstractProvider { public function providerFolderStructure() { if (file_exists($libraryFolder = new LibraryFolder($this->projectFolder))) foreach (new DirectoryIterator($libraryFolder) as $vendor) if (!$vendor->isDot() && $vendor->isDir() && preg_match('/[A-Z].*/', $vendor->getFileName())) return $vendor->getFileName(); } public function providerDefault() { return ucfirst(preg_replace('/\W+/', '', new UserName($this->projectFolder))); } }
Fix prefetched fields in Institutions in API
import django_filters from rest_framework import filters, viewsets from teryt_tree.rest_framework_ext.viewsets import custom_area_filter from .models import Institution, Tag from .serializers import InstitutionSerializer, TagSerializer class InstitutionFilter(filters.FilterSet): jst = django_filters.CharFilter(method=custom_area_filter) def __init__(self, *args, **kwargs): super(InstitutionFilter, self).__init__(*args, **kwargs) self.filters['name'].lookup_expr = 'icontains' class Meta: model = Institution fields = ['name', 'tags', 'jst', 'regon'] class InstitutionViewSet(viewsets.ModelViewSet): queryset = (Institution.objects. select_related('jst'). prefetch_related('tags','parents'). all()) serializer_class = InstitutionSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = InstitutionFilter class TagViewSet(viewsets.ModelViewSet): queryset = Tag.objects.all() serializer_class = TagSerializer
import django_filters from rest_framework import filters, viewsets from teryt_tree.rest_framework_ext.viewsets import custom_area_filter from .models import Institution, Tag from .serializers import InstitutionSerializer, TagSerializer class InstitutionFilter(filters.FilterSet): jst = django_filters.CharFilter(method=custom_area_filter) def __init__(self, *args, **kwargs): super(InstitutionFilter, self).__init__(*args, **kwargs) self.filters['name'].lookup_expr = 'icontains' class Meta: model = Institution fields = ['name', 'tags', 'jst', 'regon'] class InstitutionViewSet(viewsets.ModelViewSet): queryset = (Institution.objects. select_related('jst'). prefetch_related('tags'). all()) serializer_class = InstitutionSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = InstitutionFilter class TagViewSet(viewsets.ModelViewSet): queryset = Tag.objects.all() serializer_class = TagSerializer
Return immediately on error as per old behaviour
var IPHistory = (function() { 'use strict'; function makeRequest() { var request = {login_history: 1, limit: 50}; BinarySocket.send(request); } function responseHandler(msg) { var response = JSON.parse(msg.data); if (!response || response.msg_type !== 'login_history') { return; } if (response.error && response.error.message) { return IPHistoryUI.displayError(response.error.message); } var parsed = response.login_history.map(IPHistoryData.parse); IPHistoryUI.displayTable(parsed); } // localize, title, create tables // register the callback on IPHistoryQueue function init() { IPHistoryUI.init(); makeRequest(); } function clean() { IPHistoryUI.clean(); } return { init: init, clean: clean, responseHandler: responseHandler, }; })();
var IPHistory = (function() { 'use strict'; function makeRequest() { var request = {login_history: 1, limit: 50}; BinarySocket.send(request); } function responseHandler(msg) { var response = JSON.parse(msg.data); if (!response || response.msg_type !== 'login_history') { return; } if (response.error && response.error.message) { IPHistoryUI.displayError(response.error.message); } var parsed = response.login_history.map(IPHistoryData.parse); IPHistoryUI.displayTable(parsed); } // localize, title, create tables // register the callback on IPHistoryQueue function init() { IPHistoryUI.init(); makeRequest(); } function clean() { IPHistoryUI.clean(); } return { init: init, clean: clean, responseHandler: responseHandler, }; })();
Fix null xsd schema on config xml reading
<?php namespace CtiDigital\Configurator\Model\Configurator\Config; use Magento\Framework\Config\SchemaLocatorInterface; use Magento\Framework\Module\Dir; class SchemaLocator implements SchemaLocatorInterface { protected $schema; public function __construct(\Magento\Framework\Module\Dir\Reader $reader) { $this->schema = $reader->getModuleDir(Dir::MODULE_ETC_DIR, 'CtiDigital_Configurator') . '/' . 'configurator.xsd'; } /** * {@inheritdoc} */ public function getSchema() { return $this->schema; } /** * Only one schema will every be required once merged. * * @return null */ public function getPerFileSchema() { return null; } }
<?php namespace CtiDigital\Configurator\Model\Configurator\Config; use Magento\Framework\Config\SchemaLocatorInterface; use Magento\Framework\Module\Dir; class SchemaLocator implements SchemaLocatorInterface { protected $schema; public function __construct(\Magento\Framework\Module\Dir\Reader $reader) { $this->schema = $reader->getModuleDir(Dir::MODULE_ETC_DIR, 'CtiDigital_Configurator') . '/' . 'configurator.xsd'; } /** * {@inheritdoc} */ public function getSchema() { $this->schema; } /** * Only one schema will every be required once merged. * * @return null */ public function getPerFileSchema() { return null; } }
Update to handle an edge case Added an update to handle the case when array size is not a multiple of 3. Without this the program will run into an infinite loop!
import java.util.Arrays; public class ConvertArray { public int getOriginalIndex(int currentIndex, int length) { return (currentIndex % 3) * length + currentIndex/3; } public int[] convert(int[] input) { // When array size is less than 3, returns an error. if (input.length % 3 != 0 ) { System.out.println("Error! Array cannot be divided into three equal parts"); return; } for (int i = 0; i < input.length; ++i) { int originalIndex = getOriginalIndex(i, input.length/3); while (originalIndex < i) { originalIndex = getOriginalIndex(originalIndex, input.length/3); } int temp = input[i]; input[i] = input[originalIndex]; input[originalIndex] = temp; } return input; } public static void main(String[] args) { ConvertArray c = new ConvertArray(); int[] test1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; System.out.println(Arrays.toString(c.convert(test1))); } }
import java.util.Arrays; public class ConvertArray { public int getOriginalIndex(int currentIndex, int length) { return (currentIndex % 3) * length + currentIndex/3; } public int[] convert(int[] input) { for (int i = 0; i < input.length; ++i) { int originalIndex = getOriginalIndex(i, input.length/3); while (originalIndex < i) { originalIndex = getOriginalIndex(originalIndex, input.length/3); } int temp = input[i]; input[i] = input[originalIndex]; input[originalIndex] = temp; } return input; } public static void main(String[] args) { ConvertArray c = new ConvertArray(); int[] test1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; System.out.println(Arrays.toString(c.convert(test1))); } }
Add HTTP status code to logs This adds the status code to the response log message to make it easier to diagnose issues. It also replaces the placeholder "Success" message with the decoded value of the HTTP Status, resulting in messages like: INFO[0041] Response: Temporary Redirect code=307 ...and so on. Both easily consumable by humans and machines.
package server import ( "net/http" "time" "github.com/influxdata/chronograf" ) type logResponseWriter struct { http.ResponseWriter responseCode int } func (l *logResponseWriter) WriteHeader(status int) { l.responseCode = status l.ResponseWriter.WriteHeader(status) } // Logger is middleware that logs the request func Logger(logger chronograf.Logger, next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { now := time.Now() logger. WithField("component", "server"). WithField("remote_addr", r.RemoteAddr). WithField("method", r.Method). WithField("url", r.URL). Info("Request") lrr := &logResponseWriter{w, 0} next.ServeHTTP(lrr, r) later := time.Now() elapsed := later.Sub(now) logger. WithField("component", "server"). WithField("remote_addr", r.RemoteAddr). WithField("response_time", elapsed.String()). WithField("code", lrr.responseCode). Info("Response: ", http.StatusText(lrr.responseCode)) } return http.HandlerFunc(fn) }
package server import ( "net/http" "time" "github.com/influxdata/chronograf" ) // Logger is middleware that logs the request func Logger(logger chronograf.Logger, next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { now := time.Now() logger. WithField("component", "server"). WithField("remote_addr", r.RemoteAddr). WithField("method", r.Method). WithField("url", r.URL). Info("Request") next.ServeHTTP(w, r) later := time.Now() elapsed := later.Sub(now) logger. WithField("component", "server"). WithField("remote_addr", r.RemoteAddr). WithField("response_time", elapsed.String()). Info("Success") } return http.HandlerFunc(fn) }
Add ID support for subscription/ URLs.
# Copyright (C) 2014 Linaro Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Define URLs and handlers to server them.""" from tornado.web import url from handlers import ( DefConfHandler, JobHandler, SubscriptionHandler ) APP_URLS = [ url(r'/api/defconfig(?P<sl>/)?(?P<id>.*)', DefConfHandler, name='defconf'), url(r'/api/job(?P<sl>/)?(?P<id>.*)', JobHandler, name='job'), url( r'/api/subscription(?P<sl>/)?(?P<id>.*)', SubscriptionHandler, name='subscription' ) ]
# Copyright (C) 2014 Linaro Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Define URLs and handlers to server them.""" from tornado.web import url from handlers import ( DefConfHandler, JobHandler, SubscriptionHandler ) APP_URLS = [ url(r'/api/defconfig(?P<sl>/)?(?P<id>.*)', DefConfHandler, name='defconf'), url(r'/api/job(?P<sl>/)?(?P<id>.*)', JobHandler, name='job'), url(r'/api/subscription', SubscriptionHandler, name='subscription') ]
Fix code examples in PHPDoc
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bridge\Twig\TokenParser; use Symfony\Bridge\Twig\Node\DumpNode; use Twig\Token; use Twig\TokenParser\AbstractTokenParser; /** * Token Parser for the 'dump' tag. * * Dump variables with: * * {% dump %} * {% dump foo %} * {% dump foo, bar %} * * @author Julien Galenski <julien.galenski@gmail.com> */ class DumpTokenParser extends AbstractTokenParser { /** * {@inheritdoc} */ public function parse(Token $token) { $values = null; if (!$this->parser->getStream()->test(Token::BLOCK_END_TYPE)) { $values = $this->parser->getExpressionParser()->parseMultitargetExpression(); } $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); return new DumpNode($this->parser->getVarName(), $values, $token->getLine(), $this->getTag()); } /** * {@inheritdoc} */ public function getTag() { return 'dump'; } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bridge\Twig\TokenParser; use Symfony\Bridge\Twig\Node\DumpNode; use Twig\Token; use Twig\TokenParser\AbstractTokenParser; /** * Token Parser for the 'dump' tag. * * Dump variables with: * <pre> * {% dump %} * {% dump foo %} * {% dump foo, bar %} * </pre> * * @author Julien Galenski <julien.galenski@gmail.com> */ class DumpTokenParser extends AbstractTokenParser { /** * {@inheritdoc} */ public function parse(Token $token) { $values = null; if (!$this->parser->getStream()->test(Token::BLOCK_END_TYPE)) { $values = $this->parser->getExpressionParser()->parseMultitargetExpression(); } $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); return new DumpNode($this->parser->getVarName(), $values, $token->getLine(), $this->getTag()); } /** * {@inheritdoc} */ public function getTag() { return 'dump'; } }
Remove pending import record after importing the user
<?php namespace OkulBilisim\OjsImportBundle\Importer\PKP; use Ojs\JournalBundle\Entity\Article; use OkulBilisim\OjsImportBundle\Importer\Importer; class ArticleSubmitterImporter extends Importer { /** * @param UserImporter $userImporter */ public function importArticleSubmitter($userImporter) { $pendingImports = $this->em->getRepository('OkulBilisimOjsImportBundle:PendingSubmitterImport')->findAll(); $this->consoleOutput->writeln("Importing article submitters..."); foreach ($pendingImports as $import) { $user = $userImporter->importUser($import->getOldId()); if ($user) { /** @var Article $article */ $article = $import->getArticle(); $article->setSubmitterUser($user); $this->em->persist($article); } $this->em->remove($import); $this->em->flush(); } } }
<?php namespace OkulBilisim\OjsImportBundle\Importer\PKP; use Ojs\JournalBundle\Entity\Article; use OkulBilisim\OjsImportBundle\Importer\Importer; class ArticleSubmitterImporter extends Importer { /** * @param UserImporter $userImporter */ public function importArticleSubmitter($userImporter) { $pendingImports = $this->em->getRepository('OkulBilisimOjsImportBundle:PendingSubmitterImport')->findAll(); $this->consoleOutput->writeln("Importing article submitters..."); foreach ($pendingImports as $import) { $user = $userImporter->importUser($import->getOldId()); if ($user) { /** @var Article $article */ $article = $import->getArticle(); $article->setSubmitterUser($user); $this->em->persist($article); $this->em->flush($article); } } } }
Add docstrings to JSON migrations functions
import os import sys from glob import glob from importlib import import_module __all__ = ['migrate', 'get_migrations'] HERE = os.path.dirname(__file__) package = sys.modules[__name__].__name__ def get_migrations(): """ Return a generator with all JSON migrations sorted. Each item is a tuple with: - the version number (int) - the label of the migration - the reference to the migrate() function """ for module in sorted(glob(os.path.join(HERE, '[0-9]*.py'))): module_name, _ = os.path.basename(module).rsplit('.', 1) mod = import_module('.' + module_name, package=package) version, label = module_name.split('_', 1) yield int(version), label, mod.migrate def migrate(data, version_src=0): """ Apply all migrations from ``version_src`` to the latest found on ``data``. """ for version, label, func in list(get_migrations()): if version_src < version: data = func(data) version_src = version return data
import os import sys from glob import glob from importlib import import_module __all__ = ['migrate', 'get_migrations'] HERE = os.path.dirname(__file__) package = sys.modules[__name__].__name__ def get_migrations(): for module in sorted(glob(os.path.join(HERE, '[0-9]*.py'))): module_name, _ = os.path.basename(module).rsplit('.', 1) mod = import_module('.' + module_name, package=package) version, label = module_name.split('_', 1) yield int(version), label, mod.migrate def migrate(data, version_src=0): for version, label, func in list(get_migrations()): if version_src < version: data = func(data) version_src = version return data
Remove . and .. dirs from list result
/* * Directory Entry Filler Implementation Class of JSFSFillDir for JSyndicateFS */ package JSyndicateFS; import JSyndicateFSJNI.struct.JSFSFillDir; import JSyndicateFSJNI.struct.JSFSStat; import java.util.ArrayList; /** * * @author iychoi */ public class DirFillerImpl extends JSFSFillDir { private static final String[] SKIP_FILES = {".", ".."}; private ArrayList<String> entries = new ArrayList<String>(); DirFillerImpl() { } @Override public void fill(String name, JSFSStat stbuf, long off) { boolean skip = false; for(String skip_file : SKIP_FILES) { if(name.equals(skip_file)) { skip = true; } } if(!skip) { entries.add(name); } } public String[] getEntryNames() { String[] arr = new String[this.entries.size()]; arr = entries.toArray(arr); return arr; } }
/* * Directory Entry Filler Implementation Class of JSFSFillDir for JSyndicateFS */ package JSyndicateFS; import JSyndicateFSJNI.struct.JSFSFillDir; import JSyndicateFSJNI.struct.JSFSStat; import java.util.ArrayList; /** * * @author iychoi */ public class DirFillerImpl extends JSFSFillDir { private ArrayList<String> entries = new ArrayList<String>(); DirFillerImpl() { } @Override public void fill(String name, JSFSStat stbuf, long off) { entries.add(name); } public String[] getEntryNames() { String[] arr = new String[this.entries.size()]; arr = entries.toArray(arr); return arr; } }
Add sort settings to fixture config.
(function () { 'use strict'; define(function () { return [ { key: 'first', labelText: 'Field One', sort: true }, { key: 'second', labelText: 'Field Two', sort: function (value) { return value ? value.toString().toLowerCase() : undefined; } }, { key: 'third', labelText: 'Field Three' } ]; }); }());
(function () { 'use strict'; define(function () { return [ { key: 'first', labelText: 'Field One' }, { key: 'second', labelText: 'Field Two' }, { key: 'third', labelText: 'Field Three' } ]; }); }());
Add extra method to deal with differing file-name formats
package net.openhft.chronicle.queue.impl.single; import net.openhft.chronicle.core.Jvm; import java.io.File; public enum PrecreatedFiles { ; private static final String PRE_CREATED_FILE_SUFFIX = ".precreated"; public static void renamePreCreatedFileToRequiredFile(final File requiredQueueFile) { final File preCreatedFile = preCreatedFile(requiredQueueFile); if (preCreatedFile.exists()) { if (!preCreatedFile.renameTo(requiredQueueFile)) { Jvm.warn().on(PrecreatedFiles.class, "Failed to rename pre-created queue file"); } } } public static File preCreatedFileForStoreFile(final File requiredStoreFile) { return new File(requiredStoreFile.getParentFile(), requiredStoreFile.getName() + PRE_CREATED_FILE_SUFFIX); } public static File preCreatedFile(final File requiredQueueFile) { final String fileName = requiredQueueFile.getName(); final String name = fileName.substring(0, fileName.length() - 4); return new File(requiredQueueFile.getParentFile(), name + PRE_CREATED_FILE_SUFFIX); } }
package net.openhft.chronicle.queue.impl.single; import net.openhft.chronicle.core.Jvm; import java.io.File; public enum PrecreatedFiles { ; private static final String PRE_CREATED_FILE_SUFFIX = ".precreated"; public static void renamePreCreatedFileToRequiredFile(final File requiredQueueFile) { final File preCreatedFile = preCreatedFile(requiredQueueFile); if (preCreatedFile.exists()) { if (!preCreatedFile.renameTo(requiredQueueFile)) { Jvm.warn().on(PrecreatedFiles.class, "Failed to rename pre-created queue file"); } } } public static File preCreatedFile(final File requiredQueueFile) { return new File(requiredQueueFile.getParentFile(), requiredQueueFile.getName() + PRE_CREATED_FILE_SUFFIX); } }
Add bytebuffer overload to native library.
package nanomsg; import java.nio.ByteBuffer; import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.ptr.PointerByReference; import com.sun.jna.ptr.IntByReference; public class NativeLibrary { public static native int nn_socket (int domain, int protocol); public static native int nn_close (int s); public static native int nn_bind (int s, String addr); public static native int nn_connect (int s, String addr); public static native int nn_send (int s, byte[] buff, int len, int flags); public static native int nn_send (int s, ByteBuffer buff, int len, int flags); public static native int nn_recv (int s, PointerByReference buff, int len, int flags); public static native int nn_setsockopt (int s, int level, int option, Pointer optval, int optvallen); public static native int nn_getsockopt (int s, int level, int option, Pointer optval, Pointer optvallen); public static native int nn_freemsg (Pointer msg); public static native int nn_errno (); public static native int nn_device (int s1, int s2); public static native void nn_term(); public static native String nn_strerror (int errnum); public static native Pointer nn_symbol (int i, IntByReference value); static { Native.register("nanomsg"); } }
package nanomsg; import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.ptr.PointerByReference; import com.sun.jna.ptr.IntByReference; public class NativeLibrary { public static native int nn_socket (int domain, int protocol); public static native int nn_close (int s); public static native int nn_bind (int s, String addr); public static native int nn_connect (int s, String addr); public static native int nn_send (int s, byte[] buff, int len, int flags); public static native int nn_recv (int s, PointerByReference buff, int len, int flags); public static native int nn_setsockopt (int s, int level, int option, Pointer optval, int optvallen); public static native int nn_getsockopt (int s, int level, int option, Pointer optval, Pointer optvallen); public static native int nn_freemsg (Pointer msg); public static native int nn_errno (); public static native int nn_device (int s1, int s2); public static native void nn_term(); public static native String nn_strerror (int errnum); public static native Pointer nn_symbol (int i, IntByReference value); static { Native.register("nanomsg"); } }
Exit the command if it doesn't have the right flags.
package commands import ( "fmt" "github.com/spf13/cobra" "os" ) var outCmd = &cobra.Command{ Use: "out", Short: "Write a file based on key data.", Long: `out is for writing a file based on a Consul key.`, Run: outRun, } func outRun(cmd *cobra.Command, args []string) { checkFlags() } func checkFlags() { if KeyLocation == "" { fmt.Println("Need a key location in -k") os.Exit(1) } if FiletoWrite == "" { fmt.Println("Need a file to write in -f") os.Exit(1) } } var KeyLocation string var FiletoWrite string var MinFileLength int func init() { RootCmd.AddCommand(outCmd) outCmd.Flags().StringVarP(&KeyLocation, "key", "k", "", "key to pull data from") outCmd.Flags().StringVarP(&FiletoWrite, "file", "f", "", "where to write the data") outCmd.Flags().IntVarP(&MinFileLength, "length", "l", 10, "minimum amount of lines in the file") }
package commands import ( "fmt" "github.com/spf13/cobra" ) var outCmd = &cobra.Command{ Use: "out", Short: "Write a file based on key data.", Long: `out is for writing a file based on a Consul key.`, Run: outRun, } func outRun(cmd *cobra.Command, args []string) { checkFlags() } func checkFlags() { if KeyLocation == "" { fmt.Println("Need a key location in -k") } if FiletoWrite == "" { fmt.Println("Need a file to write in -f") } } var KeyLocation string var FiletoWrite string var MinFileLength int func init() { RootCmd.AddCommand(outCmd) outCmd.Flags().StringVarP(&KeyLocation, "key", "k", "", "key to pull data from") outCmd.Flags().StringVarP(&FiletoWrite, "file", "f", "", "where to write the data") outCmd.Flags().IntVarP(&MinFileLength, "length", "l", 10, "minimum amount of lines in the file") }
Fix tests for all timezones
import { module, test } from '../qunit'; import moment from '../../moment'; module('now'); test('now', function (assert) { var startOfTest = new Date().valueOf(), momentNowTime = moment.now(), afterMomentCreationTime = new Date().valueOf(); assert.ok(startOfTest <= momentNowTime, 'moment now() time should be now, not in the past'); assert.ok(momentNowTime <= afterMomentCreationTime, 'moment now() time should be now, not in the future'); }); test('now - custom value', function (assert) { var CUSTOM_DATE = '2015-01-01T01:30:00.000Z'; var oldFn = moment.fn.now; moment.fn.now = function () { return new Date(CUSTOM_DATE).valueOf(); }; try { assert.ok(moment().toISOString() === CUSTOM_DATE, 'moment() constructor should use the function defined by moment.now, but it did not'); assert.ok(moment.utc().toISOString() === CUSTOM_DATE, 'moment() constructor should use the function defined by moment.now, but it did not'); assert.ok(moment.utc([]).toISOString() === '2015-01-01T00:00:00.000Z', 'moment() constructor should fall back to the date defined by moment.now when an empty array is given, but it did not'); } finally { moment.fn.now = oldFn; } });
import { module, test } from '../qunit'; import moment from '../../moment'; module('now'); test('now', function (assert) { var startOfTest = new Date().valueOf(), momentNowTime = moment.now(), afterMomentCreationTime = new Date().valueOf(); assert.ok(startOfTest <= momentNowTime, 'moment now() time should be now, not in the past'); assert.ok(momentNowTime <= afterMomentCreationTime, 'moment now() time should be now, not in the future'); }); test('now - custom value', function (assert) { var CUSTOM_DATE = '2015-01-01T01:30:00.000Z'; var oldFn = moment.fn.now; moment.fn.now = function () { return new Date(CUSTOM_DATE).valueOf(); }; try { assert.ok(moment().toISOString() === CUSTOM_DATE, 'moment() constructor should use the function defined by moment.now, but it did not'); assert.ok(moment([]).toISOString() === '2015-01-01T00:00:00.000Z', 'moment() constructor should fall back to the date defined by moment.now when an empty array is given, but it did not'); assert.ok(moment.utc([]).toISOString() === '2015-01-01T00:00:00.000Z', 'moment() constructor should fall back to the date defined by moment.now when an empty array is given, but it did not'); } finally { moment.fn.now = oldFn; } });
Change working principle of id generating
package org.verapdf.model.tools; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSObject; /** * Created by Evgeniy Muravitskiy on 4/27/15. *<p> * This class specified for creating ID`s for every object from model. */ public final class IDGenerator { private IDGenerator(){} /** * Generate ID for pdf box object. Current method generate a string of the form 'N M' for * {@link org.apache.pdfbox.cos.COSObject}, where 'N' and 'M' are numbers, and <code>null</code> * for other pdf box objects * @param pdfBoxObject object of pdf box library * @return string representation of ID */ public static String generateID(COSBase pdfBoxObject) { if (pdfBoxObject instanceof COSObject) { return ((COSObject) pdfBoxObject).getObjectNumber() + " " + ((COSObject) pdfBoxObject).getGenerationNumber(); } else { return null; } } }
package org.verapdf.model.tools; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSObject; /** * Created by Evgeniy Muravitskiy on 4/27/15. *<p> * This class specified for creating ID`s for every object from model. */ public final class IDGenerator { private IDGenerator(){} /** * Generate ID for pdf box object. Current method generate a string of the form 'N M' for * {@link org.apache.pdfbox.cos.COSObject}, where 'N' and 'M' are numbers, and <code>null</code> * for other pdf box objects * @param pdfBoxObject object of pdf box library * @return string representation of ID */ public static String generateID(COSBase pdfBoxObject) { if (pdfBoxObject instanceof COSObject) { return ((COSObject) pdfBoxObject).getObjectNumber() + " " + ((COSObject) pdfBoxObject).getGenerationNumber(); } return null; } }
Revert msgpack to json content message
# -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import timedelta from celery import Celery from accio.basetask import ManagedTask import django.conf default_app_config = 'accio.apps.Config' REDIS_DB_URL = 'redis://127.0.0.1:6379/0' celery_app = Celery(task_cls=ManagedTask) celery_app.conf.update({ # accio settings 'ACCIO_CELERY_ENABLED': True, 'ACCIO_ATOMIC': True, 'ACCIO_LOGVAULT_URL': REDIS_DB_URL, 'ACCIO_JOBS_MAX_COUNT': 1000, # celery settings 'broker_url': REDIS_DB_URL, 'result_backend': REDIS_DB_URL, 'result_expires': int(timedelta(hours=1).total_seconds()), 'worker_redirect_stdouts_level': 'INFO', 'worker_concurrency': 4, 'task_serializer': 'json', 'result_serializer': 'json', 'accept_content': ['json'] }) celery_app.conf.update(**vars(django.conf.settings._wrapped)) celery_app.autodiscover_tasks()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import timedelta from celery import Celery from accio.basetask import ManagedTask import django.conf default_app_config = 'accio.apps.Config' REDIS_DB_URL = 'redis://127.0.0.1:6379/0' celery_app = Celery(task_cls=ManagedTask) celery_app.conf.update({ # accio settings 'ACCIO_CELERY_ENABLED': True, 'ACCIO_ATOMIC': True, 'ACCIO_LOGVAULT_URL': REDIS_DB_URL, 'ACCIO_JOBS_MAX_COUNT': 1000, # celery settings 'broker_url': REDIS_DB_URL, 'result_backend': REDIS_DB_URL, 'result_expires': int(timedelta(hours=1).total_seconds()), 'worker_redirect_stdouts_level': 'INFO', 'worker_concurrency': 4, 'task_serializer': 'msgpack', 'result_serializer': 'msgpack', 'accept_content': ['msgpack'] }) celery_app.conf.update(**vars(django.conf.settings._wrapped)) celery_app.autodiscover_tasks()
Add alternate callback for Heroku
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { browserHistory, Router } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { configure } from 'redux-auth'; import routes from './routes'; import registerServiceWorker from './registerServiceWorker'; import './stylesheets/main.css'; import configureStore from './redux/configureStore'; const store = configureStore(); const history = syncHistoryWithStore(browserHistory, store); store.dispatch(configure( { apiUrl: process.env.REACT_APP_GOOGLE_CALLBACK_URL || 'http://localhost:3001', authProviderPaths: { facebook: '/auth/facebook', google: '/auth/google_oauth2' } }, { isServer: false, cookies: document.cookie, currentLocation: window.location.href, cleanSession: true, clientOnly: true } )).then(() => { render(( <Provider store={store}> <Router history={history} routes={routes} /> </Provider> ), document.getElementById('root')); registerServiceWorker(); });
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { browserHistory, Router } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { configure } from 'redux-auth'; import routes from './routes'; import registerServiceWorker from './registerServiceWorker'; import './stylesheets/main.css'; import configureStore from './redux/configureStore'; const store = configureStore(); const history = syncHistoryWithStore(browserHistory, store); store.dispatch(configure( { apiUrl: 'http://localhost:3001', authProviderPaths: { facebook: '/auth/facebook', google: '/auth/google_oauth2' } }, { isServer: false, cookies: document.cookie, currentLocation: window.location.href, cleanSession: true, clientOnly: true } )).then(() => { render(( <Provider store={store}> <Router history={history} routes={routes} /> </Provider> ), document.getElementById('root')); registerServiceWorker(); });
Remove bogus panics, spurious comments
package netlink import "os" import "syscall" type Socket struct { fd int } func toErr(eno int)(err os.Error){ if eno != 0 { err = os.NewError(syscall.Errstr(eno))} return } func Dial(nlf NetlinkFamily)(rwc *Socket, err os.Error){ fdno, errno := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_DGRAM, int(nlf)) err = toErr(errno) if err == nil { rwc = &Socket{fd:fdno} } return } func (self *Socket)Close()(err os.Error){ errno := syscall.Close(self.fd) err = toErr(errno) return } func (self *Socket)Write(in []byte)(n int, err os.Error){ n, errno := syscall.Write(self.fd, in) err = toErr(errno) return } func (self *Socket)Read(in []byte)(n int, err os.Error){ n, errno := syscall.Read(self.fd, in) err = toErr(errno) return }
package netlink //import "bytes" //import "encoding/binary" import "os" import "syscall" type Socket struct { fd int } func toErr(eno int)(err os.Error){ if eno != 0 { err = os.NewError(syscall.Errstr(eno))} return } func Dial(nlf NetlinkFamily)(rwc *Socket, err os.Error){ //func Dial(nlfam netlinkFamily)(rwc netlinkSocket, err os.Error){ fdno, errno := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_DGRAM, int(nlf)) err = toErr(errno) if err == nil { rwc = &Socket{fd:fdno} } return } func (self *Socket)Close()(err os.Error){ errno := syscall.Close(self.fd) err = toErr(errno) return } func (self *Socket)Write(in []byte)(n int, err os.Error){ if n < 0 { panic(n) } n, errno := syscall.Write(self.fd, in) err = toErr(errno) return } func (self *Socket)Read(in []byte)(n int, err os.Error){ if n < 0 { panic(n) } n, errno := syscall.Read(self.fd, in) err = toErr(errno) return }
Migrate database for small update
import os from fabric.api import * base_path = os.path.dirname(__file__) project_root = "~/Gather" pip_path = os.path.join(project_root, "bin/pip") python_path = os.path.join(project_root, "bin/python") env.user = "gather" env.hosts = ["gather.whouz.com"] def update_from_github(): with cd(project_root): run("git pull") def update_pip_requirements(): with cd(project_root): run("%s install -r requirements.txt" % pip_path) def migrate_databases(): with cd(project_root): run("%s manage.py db upgrade" % python_path) def reload_nginx(): _current_user = env.user env.user = 'root' run("/etc/init.d/nginx reload") env.user = _current_user def restart_gunicorn(): _current_user = env.user env.user = 'root' run("supervisorctl reload") env.user = _current_user def reload_gunicorn(): run("kill -HUP `cat /tmp/gather.pid`") def update(): update_from_github() migrate_databases() reload_gunicorn() def fullyupdate(): update_from_github() update_pip_requirements() migrate_databases() reload_nginx() reload_gunicorn()
import os from fabric.api import * base_path = os.path.dirname(__file__) project_root = "~/Gather" pip_path = os.path.join(project_root, "bin/pip") python_path = os.path.join(project_root, "bin/python") env.user = "gather" env.hosts = ["gather.whouz.com"] def update_from_github(): with cd(project_root): run("git pull") def update_pip_requirements(): with cd(project_root): run("%s install -r requirements.txt" % pip_path) def migrate_databases(): with cd(project_root): run("%s manage.py db upgrade" % python_path) def reload_nginx(): _current_user = env.user env.user = 'root' run("/etc/init.d/nginx reload") env.user = _current_user def restart_gunicorn(): _current_user = env.user env.user = 'root' run("supervisorctl reload") env.user = _current_user def reload_gunicorn(): run("kill -HUP `cat /tmp/gather.pid`") def update(): update_from_github() reload_gunicorn() def fullyupdate(): update_from_github() update_pip_requirements() migrate_databases() reload_nginx() reload_gunicorn()
Add a hard coded delay to _onProcessExit()
// Karme Edge Launcher // ================= // Dependencies // ------------ var urlparse = require('url').parse var urlformat = require('url').format // Constants // --------- var EDGE_COMMAND = [ 'powershell', 'start', 'shell:AppsFolder\\Microsoft.Windows.Spartan_cw5n1h2txyewy!Microsoft.Spartan.Spartan' ] var TIMEOUT = 1000 // Constructor function EdgeBrowser (baseBrowserDecorator) { baseBrowserDecorator(this) this._getOptions = function (url) { var urlObj = urlparse(url, true) // url.format does not want search attribute delete urlObj.search url = urlformat(urlObj) return EDGE_COMMAND.splice(1).concat(url) } var baseOnProcessExit = this._onProcessExit this._onProcessExit = function (code, errorOutput) { setTimeout(function () { baseOnProcessExit(code, errorOutput) }, TIMEOUT) } } EdgeBrowser.prototype = { name: 'Edge', DEFAULT_CMD: { win32: EDGE_COMMAND[0] }, ENV_CMD: 'EDGE_BIN' } EdgeBrowser.$inject = ['baseBrowserDecorator'] // Publish di module // ----------------- module.exports = { 'launcher:Edge': ['type', EdgeBrowser] }
// Karme Edge Launcher // ================= // Dependencies // ------------ var urlparse = require('url').parse var urlformat = require('url').format // Constants // --------- var EDGE_COMMAND = [ 'powershell', 'start', 'shell:AppsFolder\\Microsoft.Windows.Spartan_cw5n1h2txyewy!Microsoft.Spartan.Spartan' ] // Constructor function EdgeBrowser (baseBrowserDecorator) { baseBrowserDecorator(this) this._getOptions = function (url) { var urlObj = urlparse(url, true) // url.format does not want search attribute delete urlObj.search url = urlformat(urlObj) return EDGE_COMMAND.splice(1).concat(url) } } EdgeBrowser.prototype = { name: 'Edge', DEFAULT_CMD: { win32: EDGE_COMMAND[0] }, ENV_CMD: 'EDGE_BIN' } EdgeBrowser.$inject = ['baseBrowserDecorator'] // Publish di module // ----------------- module.exports = { 'launcher:Edge': ['type', EdgeBrowser] }
Correct remote and public, and last occurence of OC::
<?php /** * ownCloud - bookmarks plugin * * @author Arthur Schiwon * @copyright 2011 Arthur Schiwon blizzz@arthur-schiwon.de * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ //no apps or filesystem $RUNTIME_NOSETUPFS=true; // Check if we are a user OCP\JSON::checkLoggedIn(); OCP\JSON::checkAppEnabled('bookmarks'); require_once(OC_App::getAppPath('bookmarks').'/bookmarksHelper.php'); $id = addBookmark($_GET['url'], $_GET['title'], $_GET['tags']); OCP\JSON::success(array('data' => $id));
<?php /** * ownCloud - bookmarks plugin * * @author Arthur Schiwon * @copyright 2011 Arthur Schiwon blizzz@arthur-schiwon.de * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ //no apps or filesystem $RUNTIME_NOSETUPFS=true; // Check if we are a user OCP\JSON::checkLoggedIn(); OCP\JSON::checkAppEnabled('bookmarks'); require_once(OC::$APPSROOT . '/apps/bookmarks/bookmarksHelper.php'); $id = addBookmark($_GET['url'], $_GET['title'], $_GET['tags']); OCP\JSON::success(array('data' => $id));
[TASK] Fix mail namespace + usage
<?php namespace DreadLabs\VantomasWebsite; use DreadLabs\VantomasWebsite\Mail\ComposerInterface; use DreadLabs\VantomasWebsite\Mail\ConveyableInterface; use DreadLabs\VantomasWebsite\Mail\Exception\FailedRecipientsException; use DreadLabs\VantomasWebsite\Mail\LoggerInterface; class Mail implements MailInterface { /** * @var ComposerInterface */ private $composer; /** * * @var LoggerInterface */ private $logger; /** * * @param ComposerInterface $composer * @param LoggerInterface $logger */ public function __construct( ComposerInterface $composer, LoggerInterface $logger ) { $this->composer = $composer; $this->logger = $logger; } /** * * @param ConveyableInterface $conveyable */ public function convey(ConveyableInterface $conveyable) { try { $message = $this->composer->compose($conveyable); $message->send(); } catch (FailedRecipientsException $e) { $this->logger->alert('The mail could not been sent.', array( 'sender' => $e->getSenderList(), 'receiver' => $e->getReceiverList(), 'failedRecipients' => $e->getFailedRecipients(), ) ); } } }
<?php namespace DreadLabs\Vantomas\Mailer; use DreadLabs\VantomasWebsite\Mail\ComposerInterface; use DreadLabs\VantomasWebsite\Mail\ConveyableInterface; use DreadLabs\VantomasWebsite\Mail\Exception\FailedRecipientsException; use DreadLabs\VantomasWebsite\Mail\LoggerInterface; use DreadLabs\VantomasWebsite\MailInterface; class Mail implements MailInterface { /** * @var ComposerInterface */ private $composer; /** * * @var LoggerInterface */ private $logger; /** * * @param ComposerInterface $composer * @param LoggerInterface $logger */ public function __construct( ComposerInterface $composer, LoggerInterface $logger ) { $this->composer = $composer; $this->logger = $logger; } /** * * @param ConveyableInterface $conveyable */ public function convey(ConveyableInterface $conveyable) { try { $message = $this->composer->compose($conveyable); $message->send(); } catch (FailedRecipientsException $e) { $this->logger->alert('The mail could not been sent.', array( 'sender' => $e->getSenderList(), 'receiver' => $e->getReceiverList(), 'failedRecipients' => $e->getFailedRecipients(), ) ); } } }
Update javascript Tor example to reflect simplified handling of .onion addresses
// Example of how to connect to a Tor hidden service and use it as a peer. // See demo.js to learn how to invoke this program. var bcj = org.bitcoinj; var params = bcj.params.MainNetParams.get(); var context = new bcj.core.Context(params); bcj.utils.BriefLogFormatter.init(); var PeerAddress = Java.type("org.bitcoinj.core.PeerAddress"); var InetSocketAddress = Java.type("java.net.InetSocketAddress"); // The PeerAddress class can now handle InetSocketAddresses with hostnames if they are .onion. var OnionAddress = InetSocketAddress.createUnresolved("hhiv5pnxenvbf4am.onion", params.port); var pg = bcj.core.PeerGroup.newWithTor(context, null, new com.subgraph.orchid.TorClient(), false); pg.addAddress(new PeerAddress(OnionAddress)); pg.start(); pg.waitForPeers(1).get(); print("Connected to: " + pg.connectedPeers); for each (var peer in pg.connectedPeers) { print(peer.peerVersionMessage.subVer); peer.ping().get() } pg.stop();
// Example of how to connect to a Tor hidden service and use it as a peer. // See demo.js to learn how to invoke this program. var bcj = org.bitcoinj; var params = bcj.params.MainNetParams.get(); var context = new bcj.core.Context(params); bcj.utils.BriefLogFormatter.init(); var InetAddress = Java.type("java.net.InetAddress"); var InetSocketAddress = Java.type("java.net.InetSocketAddress"); // Hack around the fact that PeerAddress assumes nodes have IP addresses. Simple enough for now. var OnionAddress = Java.extend(Java.type("org.bitcoinj.core.PeerAddress"), { toSocketAddress: function() { return InetSocketAddress.createUnresolved("hhiv5pnxenvbf4am.onion", params.port); } }); var pg = bcj.core.PeerGroup.newWithTor(context, null, new com.subgraph.orchid.TorClient(), false); // c'tor is bogus here: the passed in InetAddress will be ignored. pg.addAddress(new OnionAddress(InetAddress.localHost, params.port)); pg.start(); pg.waitForPeers(1).get(); print("Connected to: " + pg.connectedPeers); for each (var peer in pg.connectedPeers) { print(peer.peerVersionMessage.subVer); peer.ping().get() } pg.stop();
MSS: Fix pylint: Import outside toplevel (%s) (import-outside-toplevel)
""" This is part of the MSS Python's module. Source: https://github.com/BoboTiG/python-mss """ import platform from typing import TYPE_CHECKING from .exception import ScreenShotError if TYPE_CHECKING: from typing import Any # noqa from .base import MSSMixin # noqa def mss(**kwargs): # type: (Any) -> MSSMixin """ Factory returning a proper MSS class instance. It detects the plateform we are running on and choose the most adapted mss_class to take screenshots. It then proxies its arguments to the class for instantiation. """ # pylint: disable=import-outside-toplevel os_ = platform.system().lower() if os_ == "darwin": from . import darwin return darwin.MSS(**kwargs) if os_ == "linux": from . import linux return linux.MSS(**kwargs) if os_ == "windows": from . import windows return windows.MSS(**kwargs) raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
""" This is part of the MSS Python's module. Source: https://github.com/BoboTiG/python-mss """ import platform from typing import TYPE_CHECKING from .exception import ScreenShotError if TYPE_CHECKING: from typing import Any # noqa from .base import MSSMixin # noqa def mss(**kwargs): # type: (Any) -> MSSMixin """ Factory returning a proper MSS class instance. It detects the plateform we are running on and choose the most adapted mss_class to take screenshots. It then proxies its arguments to the class for instantiation. """ os_ = platform.system().lower() if os_ == "darwin": from . import darwin return darwin.MSS(**kwargs) if os_ == "linux": from . import linux return linux.MSS(**kwargs) if os_ == "windows": from . import windows return windows.MSS(**kwargs) raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
Update rootUrl for dummy app
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, rootURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.rootURL = '/liquid-fire-reveal/'; } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, rootURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/liquid-fire-reveal'; } return ENV; };
Use pypandoc to convert README.md to RST for long_description
from setuptools import setup, find_packages try: import pypandoc def long_description(): return pypandoc.convert_file('README.md', 'rst') except ImportError: def long_description(): return '' setup( name='rq-retry-scheduler', version='0.1.0b1', url='https://github.com/mikemill/rq_retry_scheduler', description='RQ Retry and Scheduler', long_description=long_description(), author='Michael Miller', author_email='mikemill@gmail.com', packages=find_packages(exclude=['*tests*']), license='MIT', install_requires=['rq>=0.6.0'], zip_safe=False, platforms='any', entry_points={ 'console_scripts': [ 'rqscheduler = rq_retry_scheduler.cli:main', ], }, classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.4', ] )
from setuptools import setup, find_packages setup( name='rq-retry-scheduler', version='0.1.0b1', url='https://github.com/mikemill/rq_retry_scheduler', description='RQ Retry and Scheduler', long_description=open('README.rst').read(), author='Michael Miller', author_email='mikemill@gmail.com', packages=find_packages(exclude=['*tests*']), license='MIT', install_requires=['rq>=0.6.0'], zip_safe=False, platforms='any', entry_points={ 'console_scripts': [ 'rqscheduler = rq_retry_scheduler.cli:main', ], }, classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.4', ] )
Remove add private-module signup script to browserify
window.$ = require("jquery"); require("./crumb")(); require("./hiring"); require("./npm-expansions"); require("./email-obfuscate")(); require("./payments")(); require("./pretty-numbers")(); require("./private-npm-beta")(); require('./deep-links')(); require("./tooltips")(); require("./what-npm-is-for")(); require("./billing")(); require("./billing-cancel")(); require("./banner")(); require("./date-formatting")(); require("./keyboard-shortcuts")(); require("./add-active-class-to-links")(); require("./autoselect-inputs")(); require("./package-access")(); require("./buy-enterprise-license")(); require("./twitter-tracking")(); require("./fetch-packages")(); require("./remove-private-module-signup")(); window.github = require("./github")(); window.star = require("./star")();
window.$ = require("jquery"); require("./crumb")(); require("./hiring"); require("./npm-expansions"); require("./email-obfuscate")(); require("./payments")(); require("./pretty-numbers")(); require("./private-npm-beta")(); require('./deep-links')(); require("./tooltips")(); require("./what-npm-is-for")(); require("./billing")(); require("./billing-cancel")(); require("./banner")(); require("./date-formatting")(); require("./keyboard-shortcuts")(); require("./add-active-class-to-links")(); require("./autoselect-inputs")(); require("./package-access")(); require("./buy-enterprise-license")(); require("./twitter-tracking")(); require("./fetch-packages")(); window.github = require("./github")(); window.star = require("./star")();
Fix unresponsive button on collaborations page fixes VICE-2428 flag=none Test Plan: - see repro steps on linked ticket - should not be able to repro - go to /courses/<course_id>/collaborations - click the "add collaboration" button - if button is responsive refreshpage - repeat 15 times - if button is unresponsive leave a QA-1 and a comment Change-Id: Ia834d6dd5371c38d0ee6bd6d9fb422c12f94d763 Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/284877 Tested-by: Service Cloud Jenkins <9144042a601061f88f1e1d7a1753ea3e2972119d@instructure.com> Reviewed-by: Omar Soto-Fortuño <2ca100155bc0669318a7e6f3850629c7667465e1@instructure.com> Product-Review: Omar Soto-Fortuño <2ca100155bc0669318a7e6f3850629c7667465e1@instructure.com> QA-Review: Jeffrey Johnson <7a0f98bfe168bc29d5611ba0275e88567b492abc@instructure.com>
/* * Copyright (C) 2011 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import $ from 'jquery' import ready from '@instructure/ready' import CollaborationsPage from './backbone/views/CollaborationsPage.coffee' import './jquery/index' // eslint-disable-next-line import/extensions import '../../boot/initializers/activateKeyClicks.js' ready(() => { const page = new CollaborationsPage({el: $('body')}) page.initPageState() })
/* * Copyright (C) 2011 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import $ from 'jquery' import CollaborationsPage from './backbone/views/CollaborationsPage.coffee' import './jquery/index' import '../../boot/initializers/activateKeyClicks.js' const page = new CollaborationsPage({el: $('body')}) page.initPageState()
Rename the users.php file to config.php
<?php namespace Modules\Notification\Entities; use Illuminate\Database\Eloquent\Model; /** * @property string type * @property string message * @property string icon_class * @property string title * @property string link * @property bool is_read * @property \Carbon\Carbon created_at * @property \Carbon\Carbon updated_at * @property int user_id */ class Notification extends Model { protected $table = 'notification__notifications'; protected $fillable = ['user_id', 'type', 'message', 'icon_class', 'link', 'is_read', 'title']; protected $appends = ['time_ago']; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { $driver = config('asgard.user.config.driver'); return $this->belongsTo("Modules\\User\\Entities\\{$driver}\\User"); } /** * Return the created time in difference for humans (2 min ago) * @return string */ public function getTimeAgoAttribute() { return $this->created_at->diffForHumans(); } }
<?php namespace Modules\Notification\Entities; use Illuminate\Database\Eloquent\Model; /** * @property string type * @property string message * @property string icon_class * @property string title * @property string link * @property bool is_read * @property \Carbon\Carbon created_at * @property \Carbon\Carbon updated_at * @property int user_id */ class Notification extends Model { protected $table = 'notification__notifications'; protected $fillable = ['user_id', 'type', 'message', 'icon_class', 'link', 'is_read', 'title']; protected $appends = ['time_ago']; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { $driver = config('asgard.user.users.driver'); return $this->belongsTo("Modules\\User\\Entities\\{$driver}\\User"); } /** * Return the created time in difference for humans (2 min ago) * @return string */ public function getTimeAgoAttribute() { return $this->created_at->diffForHumans(); } }
Handle unicode and string creation correctly
"""PyWXSB -- Python W3C XML Schema Bindings. binding - Module used to generate the bindings and at runtime to support the generated bindings utils - Common utilities used in parsing, generating, and running xmlschema - Class that convert XMLSchema from a DOM model to a Python class model based on the XMLSchema components """ class cscRoot (object): """This little bundle of joy exists because in Python 2.6 it became an error to invoke object.__init__ with parameters (unless you also override __new__, in which case it's only a warning. Whatever.). Since I'm bloody not going to check in every class whether super(Myclass,self) refers to object (even if I could figure out how to do that, 'cuz the obvious solutions don't work), we'll just make this thing the root of all cooperative super calling hierarchies.""" def __init__ (self, *args, **kw): # Oh gross. If this class descends from unicode or string, we # get here when object is *not* our direct superclass. In # that case, we have to pass the arguments on up, or the # strings don't get created right. Below is the only way I've # figured out to detect the situation. if self.__class__ != self.__class__.mro()[-1]: super(cscRoot, self).__init__(*args, **kw) from exceptions_ import *
"""PyWXSB -- Python W3C XML Schema Bindings. binding - Module used to generate the bindings and at runtime to support the generated bindings utils - Common utilities used in parsing, generating, and running xmlschema - Class that convert XMLSchema from a DOM model to a Python class model based on the XMLSchema components """ class cscRoot (object): """This little bundle of joy exists because in Python 2.6 it became an error to invoke object.__init__ with parameters (unless you also override __new__, in which case it's only a warning. Whatever.). Since I'm bloody not going to check in every class whether super(Myclass,self) refers to object (even if I could figure out how to do that, 'cuz the obvious solutions don't work), we'll just make this thing the root of all cooperative super calling hierarchies.""" def __init__ (self, *args, **kw): pass #def __new__ (cls, *args, **kw): # return object.__new__(cls) from exceptions_ import *
Fix leak of control on user view
<?php namespace Fabfoto\GalleryBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Component\HttpFoundation\Request; class UserController extends Controller { /** * @Route("/{slug}", name="show_user") */ public function showAboutAction($slug) { $author = $this ->getDoctrine() ->getRepository('FabfotoUserBundle:User') ->findOneBySlug($slug); if (!$author) { throw $this->createNotFoundException('Unable to find user'); } return $this->render('FabfotoGalleryBundle:User:ShowAbout.html.twig', array( 'author' => $author )); } } ?>
<?php namespace Fabfoto\GalleryBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Component\HttpFoundation\Request; class UserController extends Controller { /** * @Route("/{slug}", name="show_user") */ public function showAboutAction($slug) { $author = $this ->getDoctrine() ->getRepository('FabfotoUserBundle:User') ->findOneBySlug($slug); return $this->render('FabfotoGalleryBundle:User:ShowAbout.html.twig', array( 'author' => $author )); } } ?>
Add ECONRESET / socket hang up handling to the proxy
'use strict'; var fs = require('fs'); var http = require('http'); var httpProxy = require('http-proxy'); var hosts = {}; function update() { fs.readFile('../hosts.json', 'utf8', function (err, res) { if (err) { console.error(err.stack || err); return done(); } try { hosts = JSON.parse(res); } catch (ex) { console.error(ex.stack || ex); } return done(); }); function done() { setTimeout(update, 2000); } } update(); var proxy = httpProxy.createProxyServer({}); proxy.on('error', function (err, req, res) { if (err.code !== 'ECONNRESET') throw err; req.destroy(); res.destroy(); }); var server = http.createServer(function (req, res) { var host = hosts[req.headers.host]; if (host && host.port) { proxy.web(req, res, {target: 'http://127.0.0.1:' + host.port}); } else { res.statusCode = 404; res.end('no such host'); } }); server.listen(80);
'use strict'; var fs = require('fs'); var http = require('http'); var httpProxy = require('http-proxy'); var hosts = {}; function update() { fs.readFile('../hosts.json', 'utf8', function (err, res) { if (err) { console.error(err.stack || err); return done(); } try { hosts = JSON.parse(res); } catch (ex) { console.error(ex.stack || ex); } return done(); }); function done() { setTimeout(update, 2000); } } update(); var proxy = httpProxy.createProxyServer({}); var server = http.createServer(function (req, res) { var host = hosts[req.headers.host]; if (host && host.port) { proxy.web(req, res, {target: 'http://127.0.0.1:' + host.port}); } else { res.statusCode = 404; res.end('no such host'); } }); server.listen(80);
Make downloads work in FF.
import ChunkedBlob from './ChunkedBlob' export default class DownloadFile { constructor(name, size, type) { this.name = name this.size = size this.type = type this.chunks = new ChunkedBlob() } addChunk(b) { this.chunks.add(b) } clearChunks() { this.chunks = new ChunkedBlob() } isComplete() { return this.getProgress() === 1 } getProgress() { return this.chunks.size / this.size } download() { let blob = this.chunks.toBlob() let url = URL.createObjectURL(blob) let a = document.createElement('a') document.body.appendChild(a) a.download = this.name a.href = url a.click() setTimeout(() => { URL.revokeObjectURL(url) document.body.removeChild(a) }, 0) } toJSON() { return { name: this.name, size: this.size, type: this.type } } }
import ChunkedBlob from './ChunkedBlob' export default class DownloadFile { constructor(name, size, type) { this.name = name this.size = size this.type = type this.chunks = new ChunkedBlob() } addChunk(b) { this.chunks.add(b) } clearChunks() { this.chunks = new ChunkedBlob() } isComplete() { return this.getProgress() === 1 } getProgress() { return this.chunks.size / this.size } download() { let blob = this.chunks.toBlob() let url = URL.createObjectURL(blob) let a = document.createElement('a') a.download = this.name a.href = url a.click() URL.revokeObjectURL(url) } toJSON() { return { name: this.name, size: this.size, type: this.type } } }
Fix redirection when taking the token from URL.
define(function () { var App = Ember.Application.create() , isDev = /localhost/.test(document.location.href) , tokenRegexp = /authentication_token=([a-zA-Z0-9]+)/; /* Resolve authentication. Removes authentication token from URL to put it in a cookie. */ if (tokenRegexp.test(document.location.href)) { var token = document.location.href.match(tokenRegexp) , cookie; cookie = 'authentication_token=' + token[1]; cookie += '; expires=' + new Date(2100, 0).toUTCString(); document.cookie = cookie; document.location.href = document.location.href.replace(tokenRegexp, ''); return; } else if(tokenRegexp.test(document.cookie)) { App.AUTH_TOKEN = document.cookie.match(tokenRegexp)[1]; } /* Calculate host based on current URL. If the URL includes a `localhost` substring, then we're in a development environment. */ if (isDev) { App.API_HOST = 'http://localhost:5000'; } else { App.API_HOST = 'http://t2api.herokuapp.com'; } App.API_BASE_URL = App.API_HOST + '/api/v1'; App.SIGN_IN_URL = App.API_HOST + '/sign_in'; App.NAVBAR_URL = App.API_HOST + '/navbar'; window.App = App; return App; });
define(function () { var App = Ember.Application.create() , isDev = /localhost/.test(document.location.href) , tokenRegexp = /authentication_token=([a-zA-Z0-9]+)/; /* Resolve authentication. Removes authentication token from URL to put it in a cookie. */ if (tokenRegexp.test(document.location.href)) { var token = document.location.href.match(tokenRegexp) , cookie; cookie = 'authentication_token=' + token[1]; cookie += '; expires=' + new Date(2100, 0).toUTCString(); document.cookie = cookie; document.location.href = document.location.href.replace(tokenRegexp, ''); } else if(tokenRegexp.test(document.cookie)) { App.AUTH_TOKEN = document.cookie.match(tokenRegexp)[1]; } /* Calculate host based on current URL. If the URL includes a `localhost` substring, then we're in a development environment. */ if (isDev) { App.API_HOST = 'http://localhost:5000'; } else { App.API_HOST = 'http://t2api.herokuapp.com'; } App.API_BASE_URL = App.API_HOST + '/api/v1'; App.SIGN_IN_URL = App.API_HOST + '/sign_in'; App.NAVBAR_URL = App.API_HOST + '/navbar'; window.App = App; return App; });
Update name from singleword to Name of App
<?php namespace FeatureBrowser\FeatureBrowser; use FeatureBrowser\FeatureBrowser\Cli\Application; /** * Class ApplicationFactory * * @package FeatureBrowser */ final class ApplicationFactory { const VERSION = '0.0.1'; /** * {@inheritdoc} */ protected function getName() { return 'Feature Browser'; } /** * {@inheritdoc} */ protected function getVersion() { return self::VERSION; } /** * Creates application instance. * * @return Application */ public function createApplication() { return new Application($this->getName(), $this->getVersion()); } }
<?php namespace FeatureBrowser\FeatureBrowser; use FeatureBrowser\FeatureBrowser\Cli\Application; /** * Class ApplicationFactory * * @package FeatureBrowser */ final class ApplicationFactory { const VERSION = '0.0.1'; /** * {@inheritdoc} */ protected function getName() { return 'featurebrowser'; } /** * {@inheritdoc} */ protected function getVersion() { return self::VERSION; } /** * Creates application instance. * * @return Application */ public function createApplication() { return new Application($this->getName(), $this->getVersion()); } }
Update dsub version to 0.4.1. PiperOrigin-RevId: 328637531
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, 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. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.1'
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, 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. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.1.dev0'
Load cached graph in verify cached graphs tool if not already present.
#!/usr/bin/env python import sys from pprint import pprint as pp from cc.payment import flow def verify(): for ignore_balances in (True, False): graph = flow.build_graph(ignore_balances) cached = flow.get_cached_graph(ignore_balances) if not cached: flow.set_cached_graph(graph, ignore_balances) continue diff = compare(cached, graph) if diff: pp(diff) return False return True def compare(g1, g2): e1 = set(normalize(g1.edges(data=True))) e2 = set(normalize(g2.edges(data=True))) return e1.symmetric_difference(e2) def normalize(edge_list): return ((src, dest, data['capacity'], data['weight'], data['creditline_id']) for src, dest, data in edge_list) if __name__ == '__main__': if verify(): print 'OK.' sys.exit(0) else: print 'Mismatch.' sys.exit(1)
#!/usr/bin/env python import sys from pprint import pprint as pp from cc.payment import flow def verify(): for ignore_balances in (True, False): cached = flow.get_cached_graph(ignore_balances) if not cached: continue graph = flow.build_graph(ignore_balances) diff = compare(cached, graph) if diff: pp(diff) return False return True def compare(g1, g2): e1 = set(normalize(g1.edges(data=True))) e2 = set(normalize(g2.edges(data=True))) return e1.symmetric_difference(e2) def normalize(edge_list): return ((src, dest, data['capacity'], data['weight'], data['creditline_id']) for src, dest, data in edge_list) if __name__ == '__main__': if verify(): print 'OK.' sys.exit(0) else: print 'Mismatch.' sys.exit(1)
Add a todo comment in ws onerror
var StrongSocket = require('./StrongSocket'); var session = require('./session'); var i18n = require('./i18n'); var socketInstance; function createGameSocket(url, version, receiveHandler) { socketInstance = new StrongSocket(url, version, { options: { name: "game", debug: true, ignoreUnknownMessages: true, onError: function() { // TODO find a way to get the real error // for now we assume it comes from opening a user game while logged out if (!session.isConnected()) { window.plugins.toast.show(i18n('unauthorizedError'), 'short', 'center'); m.route('/'); } } }, receive: receiveHandler }); return socketInstance; } function createLobbySocket(lobbyVersion, onOpen, handlers) { socketInstance = new StrongSocket( '/lobby/socket/v1', lobbyVersion, { options: { name: 'lobby', pingDelay: 2000, onOpen: onOpen }, events: handlers } ); return socketInstance; } function onPause() { if (socketInstance) socketInstance.destroy(); } function onResume() { if (socketInstance) socketInstance.connect(); } document.addEventListener('pause', onPause, false); document.addEventListener('resume', onResume, false); module.exports = { connectGame: createGameSocket, connectLobby: createLobbySocket };
var StrongSocket = require('./StrongSocket'); var session = require('./session'); var i18n = require('./i18n'); var socketInstance; function createGameSocket(url, version, receiveHandler) { socketInstance = new StrongSocket(url, version, { options: { name: "game", debug: true, ignoreUnknownMessages: true, onError: function() { // probably opening a user game while logged out if (!session.isConnected()) { window.plugins.toast.show(i18n('unauthorizedError'), 'short', 'center'); m.route('/'); } } }, receive: receiveHandler }); return socketInstance; } function createLobbySocket(lobbyVersion, onOpen, handlers) { socketInstance = new StrongSocket( '/lobby/socket/v1', lobbyVersion, { options: { name: 'lobby', pingDelay: 2000, onOpen: onOpen }, events: handlers } ); return socketInstance; } function onPause() { if (socketInstance) socketInstance.destroy(); } function onResume() { if (socketInstance) socketInstance.connect(); } document.addEventListener('pause', onPause, false); document.addEventListener('resume', onResume, false); module.exports = { connectGame: createGameSocket, connectLobby: createLobbySocket };
Fix missing comma after merge
var _ = require('./utils'), Reflux = require('../src'), Keep = require('./Keep'), allowed = {preEmit:1,shouldEmit:1}; /** * Creates an action functor object. It is mixed in with functions * from the `PublisherMethods` mixin. `preEmit` and `shouldEmit` may * be overridden in the definition object. * * @param {Object} definition The action object definition */ module.exports = function(definition) { definition = definition || {}; for(var d in definition){ if (!allowed[d] && Reflux.PublisherMethods[d]) { throw new Error("Cannot override API method " + d + " in action creation. Use another method name or override it on Reflux.PublisherMethods instead." ); } } var context = _.extend({ eventLabel: "action", emitter: new _.EventEmitter(), _isAction: true },Reflux.PublisherMethods,definition); var functor = function() { functor[functor.sync?"trigger":"triggerAsync"].apply(functor, arguments); }; _.extend(functor,context); Keep.createdActions.push(functor); return functor; };
var _ = require('./utils'), Reflux = require('../src'), Keep = require('./Keep'), allowed = {preEmit:1,shouldEmit:1}; /** * Creates an action functor object. It is mixed in with functions * from the `PublisherMethods` mixin. `preEmit` and `shouldEmit` may * be overridden in the definition object. * * @param {Object} definition The action object definition */ module.exports = function(definition) { definition = definition || {}; for(var d in definition){ if (!allowed[d] && Reflux.PublisherMethods[d]) { throw new Error("Cannot override API method " + d + " in action creation. Use another method name or override it on Reflux.PublisherMethods instead." ); } } var context = _.extend({ eventLabel: "action", emitter: new _.EventEmitter() _isAction: true },Reflux.PublisherMethods,definition); var functor = function() { functor[functor.sync?"trigger":"triggerAsync"].apply(functor, arguments); }; _.extend(functor,context); Keep.createdActions.push(functor); return functor; };
Revert to queueing things one-by-one
<?php namespace CodeDay\Clear\Services; use CodeDay\Clear\Models\Batch\Event; use CodeDay\Clear\Models\Batch\Event\Registration; class Notifications { public static function SendNotificationsForAnnouncement($announcement) { $event = $announcement->event; $registrations = $event->registrations; foreach($registrations as $registration) { $devices = $registration->devices; foreach($devices as $device) { switch($device->service) { case "messenger": FacebookMessenger::SendMessage("An announcement from the CodeDay organizers:\n\n" . $announcement->body, $device->token); break; case "sms": Telephony\Sms::send($device->token, "CodeDay Announcement: " . $announcement->body); break; case "app": // TODO companion implementation break; } } } $job->delete(); } }
<?php namespace CodeDay\Clear\Services; use CodeDay\Clear\Models\Batch\Event; use CodeDay\Clear\Models\Batch\Event\Registration; class Notifications { public static function SendNotificationsForAnnouncement($announcement) { \Queue::push(function($job) use ($announcement) { $event = $announcement->event; $registrations = $event->registrations; foreach($registrations as $registration) { $devices = $registration->devices; foreach($devices as $device) { switch($device->service) { case "messenger": FacebookMessenger::SendMessage("An announcement from the CodeDay organizers:\n\n" . $announcement->body, $device->token); break; case "sms": Telephony\Sms::send($device->token, "CodeDay Announcement: " . $announcement->body); break; case "app": // TODO companion implementation break; } } } $job->delete(); }); } }
Add one more test case
'use strict'; const {decode, encode} = require('../app/scripts/obfuscate').default; describe('the encode function', function() { it('outputs nothing if nothing is entered', function () { expect(encode('')).toEqual([]); }); it('converts strings to integers', function () { expect(encode('a')).toEqual([97]); }); it('can hide my mail address', function() { expect(encode('thib@thib')).toEqual([116, 105, 107, 101, 68, 121, 110, 112, 106]); }); }); describe('the decode function', function() { it('outputs nothing if nothing is entered', function () { expect(decode([])).toEqual(''); }); it('converts integers to chars', function () { expect(decode([97])).toEqual('a'); }); it('can hide my mail address', function() { expect(decode([116, 105, 107, 101, 68, 121, 110, 112, 106])).toEqual('thib@thib'); }); }); describe('obfuscation functions can be chained', function() { it('looks fun', function () { expect(decode(encode(decode(encode('Rhinoceros!'))))).toEqual('Rhinoceros!'); }); });
'use strict'; const {decode, encode} = require('../app/scripts/obfuscate').default; describe('the encode function', function() { it('outputs nothing if nothing is entered', function () { expect(encode('')).toEqual([]); }); it('converts strings to integers', function () { expect(encode('a')).toEqual([97]); }); it('can hide my mail address', function() { expect(encode('thib@thib')).toEqual([116, 105, 107, 101, 68, 121, 110, 112, 106]); }); }); describe('the decode function', function() { it('outputs nothing if nothing is entered', function () { expect(decode([])).toEqual(''); }); it('converts integers to chars', function () { expect(decode([97])).toEqual('a'); }); it('can hide my mail address', function() { expect(decode([116, 105, 107, 101, 68, 121, 110, 112, 106])).toEqual('thib@thib'); }); });
Make the broker flag global
package main import ( "flag" "fmt" "os" ) var ( flBroker string flConsumerGroup string flTopic string flPartition int flNewest bool fsConsumerGroup = flag.NewFlagSet("cgo", flag.ContinueOnError) fsGetOffset = flag.NewFlagSet("go", flag.ContinueOnError) ) func init() { flag.Usage = printUsage flag.StringVar(&flBroker, "b", "", "The broker to use") fsConsumerGroup.StringVar(&flConsumerGroup, "c", "", "The consumer group") fsConsumerGroup.StringVar(&flTopic, "t", "", "The topic") fsConsumerGroup.IntVar(&flPartition, "p", -1, "The partition") fsGetOffset.StringVar(&flTopic, "t", "", "The topic") fsGetOffset.IntVar(&flPartition, "p", -1, "The partition") fsGetOffset.BoolVar(&flNewest, "n", true, "Get the newest offset instead of the oldest") } func printUsage() { fmt.Fprintf(os.Stderr, "Usage of %s\n", os.Args[0]) flag.PrintDefaults() fmt.Fprintf(os.Stderr, "\nSubcommands:\n\ncgo (consumer group get offset)\n") fsConsumerGroup.PrintDefaults() fmt.Fprintf(os.Stderr, "\ngo (get offset)\n") fsGetOffset.PrintDefaults() }
package main import ( "flag" "fmt" "os" ) var ( flBroker string flConsumerGroup string flTopic string flPartition int flNewest bool fsConsumerGroup = flag.NewFlagSet("cgo", flag.ContinueOnError) fsGetOffset = flag.NewFlagSet("go", flag.ContinueOnError) ) func init() { flag.Usage = printUsage fsConsumerGroup.StringVar(&flBroker, "b", "", "The broker to use") fsConsumerGroup.StringVar(&flConsumerGroup, "c", "", "The consumer group") fsConsumerGroup.StringVar(&flTopic, "t", "", "The topic") fsConsumerGroup.IntVar(&flPartition, "p", -1, "The partition") fsGetOffset.StringVar(&flBroker, "b", "", "The broker to use") fsGetOffset.StringVar(&flTopic, "t", "", "The topic") fsGetOffset.IntVar(&flPartition, "p", -1, "The partition") fsGetOffset.BoolVar(&flNewest, "n", true, "Get the newest offset instead of the oldest") } func printUsage() { fmt.Fprintf(os.Stderr, "Usage of %s\n", os.Args[0]) flag.PrintDefaults() fmt.Fprintf(os.Stderr, "\nSubcommands:\n\ncgo (consumer group get offset)\n") fsConsumerGroup.PrintDefaults() fmt.Fprintf(os.Stderr, "\ngo (get offset)\n") fsGetOffset.PrintDefaults() }
Fix case where installOn is undefined
var utils = require('shipit-utils'); /** * Symfony tasks */ module.exports = function (gruntOrShipit) { require('./vendors')(gruntOrShipit); require('./cache')(gruntOrShipit); require('./assets')(gruntOrShipit); utils.registerTask(gruntOrShipit, 'symfony:install', [ 'symfony:cache', 'symfony:assets' ]); var shipit = utils.getShipit(gruntOrShipit); // Install vendors locally shipit.on('fetched', function() { shipit.start('symfony:vendors'); }); shipit.on('start', function() { // Prepare new release on server before publish var event = shipit.config.symfony.installOn; event = event !== undefined ? event : 'updated'; // or 'sharedEnd' shipit.on(event, function() { shipit.start('symfony:install'); }); }); };
var utils = require('shipit-utils'); /** * Symfony tasks */ module.exports = function (gruntOrShipit) { require('./vendors')(gruntOrShipit); require('./cache')(gruntOrShipit); require('./assets')(gruntOrShipit); utils.registerTask(gruntOrShipit, 'symfony:install', [ 'symfony:cache', 'symfony:assets' ]); var shipit = utils.getShipit(gruntOrShipit); // Install vendors locally shipit.on('fetched', function() { shipit.start('symfony:vendors'); }); shipit.on('start', function() { // Prepare new release on server before publish var event = shipit.config.symfony.installOn || 'updated'; // or 'sharedEnd' shipit.on(event, function() { shipit.start('symfony:install'); }); }); };