text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add byte rule as application example.
package com.novoda.downloadmanager.demo; import android.app.Application; import android.os.Handler; import android.os.Looper; import com.facebook.stetho.Stetho; import com.novoda.downloadmanager.ByteBasedStorageRequirementRule; import com.novoda.downloadmanager.DownloadManagerBuilder; import com.novoda.downloadmanager.LiteDownloadManagerCommands; public class DemoApplication extends Application { private static final int TWO_HUNDRED_MB_IN_BYTES = 200000000; private volatile LiteDownloadManagerCommands liteDownloadManagerCommands; @Override public void onCreate() { super.onCreate(); Stetho.initializeWithDefaults(this); createLiteDownloadManager(); } private void createLiteDownloadManager() { Handler handler = new Handler(Looper.getMainLooper()); liteDownloadManagerCommands = DownloadManagerBuilder .newInstance(this, handler, R.mipmap.ic_launcher_round) .withLogHandle(new DemoLogHandle()) .withStorageRequirementRules(ByteBasedStorageRequirementRule.withBytesOfStorageRemaining(TWO_HUNDRED_MB_IN_BYTES)) .build(); } public LiteDownloadManagerCommands getLiteDownloadManagerCommands() { return liteDownloadManagerCommands; } }
package com.novoda.downloadmanager.demo; import android.app.Application; import android.os.Handler; import android.os.Looper; import com.facebook.stetho.Stetho; import com.novoda.downloadmanager.DownloadManagerBuilder; import com.novoda.downloadmanager.LiteDownloadManagerCommands; import com.novoda.downloadmanager.PercentageBasedStorageRequirementRule; public class DemoApplication extends Application { private volatile LiteDownloadManagerCommands liteDownloadManagerCommands; @Override public void onCreate() { super.onCreate(); Stetho.initializeWithDefaults(this); createLiteDownloadManager(); } private void createLiteDownloadManager() { Handler handler = new Handler(Looper.getMainLooper()); liteDownloadManagerCommands = DownloadManagerBuilder .newInstance(this, handler, R.mipmap.ic_launcher_round) .withLogHandle(new DemoLogHandle()) .withStorageRequirementRules(PercentageBasedStorageRequirementRule.withPercentageOfStorageRemaining(0.2f)) .build(); } public LiteDownloadManagerCommands getLiteDownloadManagerCommands() { return liteDownloadManagerCommands; } }
Fix for GH-4, isResourceValid should check for PONG not OK
package redis.clients.jedis; import java.io.IOException; import java.net.UnknownHostException; import redis.clients.util.FixedResourcePool; public class JedisPool extends FixedResourcePool<Jedis> { private String host; private int port; private int timeout; public JedisPool(String host) { this.host = host; this.port = Protocol.DEFAULT_PORT; } public JedisPool(String host, int port) { this.host = host; this.port = port; } public JedisPool(String host, int port, int timeout) { this.host = host; this.port = port; this.timeout = timeout; } @Override protected Jedis createResource() { Jedis jedis = new Jedis(this.host, this.port, this.timeout); try { jedis.connect(); } catch (UnknownHostException e) { throw new JedisException(e); } catch (IOException e) { throw new JedisException(e); } return jedis; } @Override protected void destroyResource(Jedis jedis) { jedis.quit(); try { jedis.disconnect(); } catch (IOException e) { throw new JedisException(e); } } @Override protected boolean isResourceValid(Jedis jedis) { return jedis.ping().equals("PONG"); } }
package redis.clients.jedis; import java.io.IOException; import java.net.UnknownHostException; import redis.clients.util.FixedResourcePool; public class JedisPool extends FixedResourcePool<Jedis> { private String host; private int port; private int timeout; public JedisPool(String host) { this.host = host; this.port = Protocol.DEFAULT_PORT; } public JedisPool(String host, int port) { this.host = host; this.port = port; } public JedisPool(String host, int port, int timeout) { this.host = host; this.port = port; this.timeout = timeout; } @Override protected Jedis createResource() { Jedis jedis = new Jedis(this.host, this.port, this.timeout); try { jedis.connect(); } catch (UnknownHostException e) { throw new JedisException(e); } catch (IOException e) { throw new JedisException(e); } return jedis; } @Override protected void destroyResource(Jedis jedis) { jedis.quit(); try { jedis.disconnect(); } catch (IOException e) { throw new JedisException(e); } } @Override protected boolean isResourceValid(Jedis jedis) { return jedis.ping().equals("OK"); } }
Allow the cache to be turned off
<?php /** * Copyright (C) 2016 Stratadox * * 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. * * @author Stratadox * @package Stratadox\Di */ namespace Stratadox\Di; use Closure; interface ContainerInterface { public function set($name, Closure $factory, $cache = true); public function get($name, $type = ''); public function has($name); public function forget($name); }
<?php /** * Copyright (C) 2016 Stratadox * * 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. * * @author Stratadox * @package Stratadox\Di */ namespace Stratadox\Di; use Closure; interface ContainerInterface { public function set($name, Closure $factory, $cache = false); public function get($name, $type = ''); public function has($name); public function forget($name); }
Revert "check user exists by email" This reverts commit 677654e72d5c40db1f6b4217776bf93bfc76b5f4.
package io.live4.api3; import org.stjs.javascript.annotation.Namespace; @Namespace("live4api") public class Api3UserUrls { public static final String API_3_USER = "/api/3/users"; public static final String BYEMAIL = "/byemail"; public static final String OBJECT = "/object"; public static final String LIST = "/list"; public static final String createUrl() { return API_3_USER + OBJECT; } public static final String updateUrl() { return API_3_USER + OBJECT; } public static final String getUrl(String id) { return API_3_USER + OBJECT + "/" + id; } public static final String listUrl(String orgId) { return API_3_USER + LIST + "/" + orgId; } public static String byEmailUrl(String email) { return API_3_USER + BYEMAIL + "/" + email; } }
package io.live4.api3; import org.stjs.javascript.annotation.Namespace; @Namespace("live4api") public class Api3UserUrls { public static final String API_3_USER = "/api/3/users"; public static final String BYEMAIL = "/byemail"; public static final String OBJECT = "/object"; public static final String LIST = "/list"; public static final String CHECK = "/check"; public static final String createUrl() { return API_3_USER + OBJECT; } public static final String updateUrl() { return API_3_USER + OBJECT; } public static final String getUrl(String id) { return API_3_USER + OBJECT + "/" + id; } public static final String listUrl(String orgId) { return API_3_USER + LIST + "/" + orgId; } public static String byEmailUrl(String email) { return API_3_USER + BYEMAIL + "/" + email; } public static String checkUserByEmail(String email) { return API_3_USER + CHECK + "/" + email; } }
Add empty object as default options
import { NativeModules } from 'react-native'; const CookieManager = NativeModules.RNCookieManager; export default { get(url:String, name?: String): Promise<Object|String> { return CookieManager.getCookie(url).then((cookie: Object): Object => { if (name && cookie) { return cookie[name] || null; } else { return cookie ? cookie : null; } }); }, set(url:String, name: String, value: any, options?: Object = {}): Promise { const opts = Object.assign(options); for (let key in opts) { if (opts.hasOwnProperty(key)) { if (key === 'expires') { opts.expires = +opts.expires; } else { opts[key] = '' + opts[key]; } } } return CookieManager.setCookie(url, name + '', value + '', opts); }, clear(url?: String): Promise { return url ? CookieManager.clearCookieFromURL(url) : CookieManager.clearCookies(); } };
import { NativeModules } from 'react-native'; const CookieManager = NativeModules.RNCookieManager; export default { get(url:String, name?: String): Promise<Object|String> { return CookieManager.getCookie(url).then((cookie: Object): Object => { if (name && cookie) { return cookie[name] || null; } else { return cookie ? cookie : null; } }); }, set(url:String, name: String, value: any, options?: Object): Promise { const opts = Object.assign(options); for (let key in opts) { if (opts.hasOwnProperty(key)) { if (key === 'expires') { opts.expires = +opts.expires; } else { opts[key] = '' + opts[key]; } } } return CookieManager.setCookie(url, name + '', value + '', opts); }, clear(url?: String): Promise { return url ? CookieManager.clearCookieFromURL(url) : CookieManager.clearCookies(); } };
Remove prefix "::ffff:" for ipv4 addresses (fixes #909)
const utils = require('../lib/utils') const insecurity = require('../lib/insecurity') const models = require('../models/index') const cache = require('../data/datacache') const challenges = cache.challenges module.exports = function saveLoginIp () { return (req, res, next) => { var loggedInUser = insecurity.authenticatedUsers.from(req) if (loggedInUser !== undefined) { var lastLoginIp = req.headers['true-client-ip'] if (utils.notSolved(challenges.httpHeaderXssChallenge) && lastLoginIp === '<iframe src="javascript:alert(`xss`)>') { utils.solve(challenges.httpHeaderXssChallenge) } if (lastLoginIp === undefined) { lastLoginIp = req.connection.remoteAddress } if (lastLoginIp.substr(0, 7) === '::ffff:') { // Simplify ipv4 addresses lastLoginIp = lastLoginIp.substr(7) } models.User.findByPk(loggedInUser.data.id).then(user => { user.update({ lastLoginIp: lastLoginIp }).then(user => { res.json(user) }).catch(error => { next(error) }) }).catch(error => { next(error) }) } else { res.sendStatus(401) } } }
const utils = require('../lib/utils') const insecurity = require('../lib/insecurity') const models = require('../models/index') const cache = require('../data/datacache') const challenges = cache.challenges module.exports = function saveLoginIp () { return (req, res, next) => { var loggedInUser = insecurity.authenticatedUsers.from(req) if (loggedInUser !== undefined) { var lastLoginIp = req.headers['true-client-ip'] if (utils.notSolved(challenges.httpHeaderXssChallenge) && lastLoginIp === '<iframe src="javascript:alert(`xss`)>') { utils.solve(challenges.httpHeaderXssChallenge) } if (lastLoginIp === undefined) { lastLoginIp = req.connection.remoteAddress } models.User.findByPk(loggedInUser.data.id).then(user => { user.update({ lastLoginIp: lastLoginIp }).then(user => { res.json(user) }).catch(error => { next(error) }) }).catch(error => { next(error) }) } else { res.sendStatus(401) } } }
Clear checksums in liquibase changelog before running scripts. This is necessary, since the changelog files were reindented with the editorconfig values.
package no.priv.bang.ukelonn.bundle.db.liquibase; import java.sql.SQLException; import javax.sql.PooledConnection; import liquibase.Liquibase; import liquibase.database.DatabaseConnection; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.LiquibaseException; import liquibase.resource.ClassLoaderResourceAccessor; public class UkelonnLiquibase { public void createInitialSchema(PooledConnection connect) throws SQLException, LiquibaseException { DatabaseConnection databaseConnection = new JdbcConnection(connect.getConnection()); ClassLoaderResourceAccessor classLoaderResourceAccessor = new ClassLoaderResourceAccessor(getClass().getClassLoader()); Liquibase liquibase = new Liquibase("db-changelog/db-changelog-1.0.0.xml", classLoaderResourceAccessor, databaseConnection); liquibase.clearCheckSums(); liquibase.update(""); } public void updateSchema(PooledConnection connect) throws SQLException, LiquibaseException { DatabaseConnection databaseConnection = new JdbcConnection(connect.getConnection()); ClassLoaderResourceAccessor classLoaderResourceAccessor = new ClassLoaderResourceAccessor(getClass().getClassLoader()); Liquibase liquibase = new Liquibase("db-changelog/db-changelog.xml", classLoaderResourceAccessor, databaseConnection); liquibase.update(""); } }
package no.priv.bang.ukelonn.bundle.db.liquibase; import java.sql.SQLException; import javax.sql.PooledConnection; import liquibase.Liquibase; import liquibase.database.DatabaseConnection; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.LiquibaseException; import liquibase.resource.ClassLoaderResourceAccessor; public class UkelonnLiquibase { public void createInitialSchema(PooledConnection connect) throws SQLException, LiquibaseException { DatabaseConnection databaseConnection = new JdbcConnection(connect.getConnection()); ClassLoaderResourceAccessor classLoaderResourceAccessor = new ClassLoaderResourceAccessor(getClass().getClassLoader()); Liquibase liquibase = new Liquibase("db-changelog/db-changelog-1.0.0.xml", classLoaderResourceAccessor, databaseConnection); liquibase.update(""); } public void updateSchema(PooledConnection connect) throws SQLException, LiquibaseException { DatabaseConnection databaseConnection = new JdbcConnection(connect.getConnection()); ClassLoaderResourceAccessor classLoaderResourceAccessor = new ClassLoaderResourceAccessor(getClass().getClassLoader()); Liquibase liquibase = new Liquibase("db-changelog/db-changelog.xml", classLoaderResourceAccessor, databaseConnection); liquibase.update(""); } }
Return serializable string from base64encode.
from __future__ import print_function import sys import hashlib import base64 def print_error(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def to_unicode(content): # TODO: considering using the 'six' library for this, for now just do something simple. if sys.version_info >= (3,0): return str(content) elif sys.version_info < (3,0): return unicode(content) def sha256hash(content): if _is_unicode(content): content = content.encode('utf-8') return hashlib.sha256(content).hexdigest() def base64encode(content): if _is_unicode(content): content = content.encode('utf-8') return to_unicode(base64.b64encode(content)) def _is_unicode(content): if (sys.version_info >= (3,0) and isinstance(content, str) or sys.version_info < (3,0) and isinstance(content, unicode)): return True return False
from __future__ import print_function import sys import hashlib import base64 def print_error(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def to_unicode(content): # TODO: considering using the 'six' library for this, for now just do something simple. if sys.version_info >= (3,0): return str(content) elif sys.version_info < (3,0): return unicode(content) def sha256hash(content): if _is_unicode(content): content = content.encode('utf-8') return hashlib.sha256(content).hexdigest() def base64encode(content): if _is_unicode(content): content = content.encode('utf-8') return base64.b64encode(content) def _is_unicode(content): if (sys.version_info >= (3,0) and isinstance(content, str) or sys.version_info < (3,0) and isinstance(content, unicode)): return True return False
Fix lodash function import after lodash upgrade
import Mustache from 'mustache' let capitalize = require('lodash/capitalize') let template = `Dear {{name}}, Your request to download course materials for course {{{coursename}}} has been received and currently being processed. You will receive another email when your request has been processed. Unique Request ID: {{id}} Course Name: {{{coursename}}} Delivery Method: {{getDeliveryMethod}} Media Types: {{getMediaTypes}} Name: {{name}} Email: {{email}} Phone: {{phone}} {{#mailingAddress}} Mailing Address: {{{mailingAddress}}} {{city}} {{#state}}{{state}}{{/state}} {{country}} {{postalCode}} {{/mailingAddress}} Please check the above details, and send us an email if there are errors or ommisions. Regards MOOC Fetcher Support ` let renderers = { getDeliveryMethod() { let mapping = { dropbox: 'Dropbox', 'usb-drive': 'USB Drive', gdrive: 'Google Drive' } return mapping[this.deliverymethod] }, getMediaTypes() { return (this.mediatype.map((m) => capitalize(m))).join(', ') } } exports.format = function(inputs) { let templateInputs = Object.assign({}, inputs, renderers), subject = `Your download request for ${inputs.coursename} has been received` let emailText = Mustache.render(template, templateInputs) return {subject, emailText} }
import Mustache from 'mustache' let capitalize = require('lodash/string/capitalize') let template = `Dear {{name}}, Your request to download course materials for course {{{coursename}}} has been received and currently being processed. You will receive another email when your request has been processed. Unique Request ID: {{id}} Course Name: {{{coursename}}} Delivery Method: {{getDeliveryMethod}} Media Types: {{getMediaTypes}} Name: {{name}} Email: {{email}} Phone: {{phone}} {{#mailingAddress}} Mailing Address: {{{mailingAddress}}} {{city}} {{#state}}{{state}}{{/state}} {{country}} {{postalCode}} {{/mailingAddress}} Please check the above details, and send us an email if there are errors or ommisions. Regards MOOC Fetcher Support ` let renderers = { getDeliveryMethod() { let mapping = { dropbox: 'Dropbox', 'usb-drive': 'USB Drive', gdrive: 'Google Drive' } return mapping[this.deliverymethod] }, getMediaTypes() { return (this.mediatype.map((m) => capitalize(m))).join(', ') } } exports.format = function(inputs) { let templateInputs = Object.assign({}, inputs, renderers), subject = `Your download request for ${inputs.coursename} has been received` let emailText = Mustache.render(template, templateInputs) return {subject, emailText} }
Allow choosing which address to listen on from command-line Closes #12
#!/usr/bin/python # coding: utf-8 # This file is part of Supysonic. # # Supysonic is a Python implementation of the Subsonic server API. # Copyright (C) 2013 Alban 'spl0k' Féron # # 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/>. import config import os.path, sys if __name__ == '__main__': if not config.check(): sys.exit(1) if not os.path.exists(config.get('base', 'cache_dir')): os.makedirs(config.get('base', 'cache_dir')) import db from web import app db.init_db() app.run(host = sys.argv[1] if len(sys.argv) > 1 else None, debug = True)
#!/usr/bin/python # coding: utf-8 # This file is part of Supysonic. # # Supysonic is a Python implementation of the Subsonic server API. # Copyright (C) 2013 Alban 'spl0k' Féron # # 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/>. import config import os.path, sys if __name__ == '__main__': if not config.check(): sys.exit(1) if not os.path.exists(config.get('base', 'cache_dir')): os.makedirs(config.get('base', 'cache_dir')) import db from web import app db.init_db() app.run(host = '0.0.0.0', debug = True)
Add new configuration setting for log_directory
# General Settings timerestriction = False debug_mode = True log_directory = './logs' # Email Settings # emailtype = "Gmail" emailtype = "Console" # SMS Settings # outboundsmstype = "WebService" outboundsmstype = "Console" # Twilio Auth Keys account_sid = "twilio sid here" auth_token = "auth token here" # SMS Services Auth basic_auth = 'basic auth header here' spsms_host = 'host here' spsms_url = 'url here' # Postgres Connection Details pg_host = 'localhost' pg_dbname = 'blockbuster' pg_user = 'blockbuster' pg_passwd = 'blockbuster' # Proxy Details proxy_user = '' proxy_pass = '' proxy_host = '' proxy_port = 8080 # Testing test_to_number = '' test_from_number = '' # Pushover Keys pushover_app_token = "pushover_token" # Email Configuration smtp_server = 'smtp.gmail.com:587' mail_username = '' mail_fromaddr = mail_username mail_password = '' mail_monitoring_addr = '' # API Variables api_username = "username here" api_passphrase = "passphrase here" # New Number return_number = "+440000111222"
# General Settings timerestriction = False debug_mode = True # Email Settings # emailtype = "Gmail" emailtype = "Console" # SMS Settings # outboundsmstype = "WebService" outboundsmstype = "Console" # Twilio Auth Keys account_sid = "twilio sid here" auth_token = "auth token here" # SMS Services Auth basic_auth = 'basic auth header here' spsms_host = 'host here' spsms_url = 'url here' # Postgres Connection Details pg_host = 'localhost' pg_dbname = 'blockbuster' pg_user = 'blockbuster' pg_passwd = 'blockbuster' # Proxy Details proxy_user = '' proxy_pass = '' proxy_host = '' proxy_port = 8080 # Testing test_to_number = '' test_from_number = '' # Pushover Keys pushover_app_token = "pushover_token" # Email Configuration smtp_server = 'smtp.gmail.com:587' mail_username = '' mail_fromaddr = mail_username mail_password = '' # API Variables api_username = "username here" api_passphrase = "passphrase here" # New Number return_number = "+440000111222"
Use ops only instead of ops + boolean.
// Copyright 2015 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package audit import ( "gopkg.in/juju/charm.v6-unstable" "time" ) // Operation represents the type of an entry. type Operation string const ( // OpSetPerm represents the setting of ACLs on an entity. // Required fields: Entity, ACL OpSetPerm Operation = "set-perm" // OpSetPromulgate, OpSetUnPromulgate represent the promulgation on an entity. // Required fields: Entity OpSetPromulgate Operation = "set-promulgate" OpSetUnPromulgate Operation = "set-unpromulgate" ) // ACL represents an access control list. type ACL struct { Read []string `json:"read,omitempty"` Write []string `json:"write,omitempty"` } // Entry represents an audit log entry. type Entry struct { Time time.Time `json:"time"` User string `json:"user"` Op Operation `json:"op"` Entity *charm.Reference `json:"entity,omitempty"` ACL *ACL `json:"acl,omitempty"` }
// Copyright 2015 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package audit import ( "gopkg.in/juju/charm.v6-unstable" "time" ) // Operation represents the type of an entry. type Operation string const ( // OpSetPerm represents the setting of ACLs on an entity. // Required fields: Entity, ACL OpSetPerm Operation = "set-perm" // OpSetPromulgated, OpSetPromulgated represent the promulgation on an entity. // Required fields: Entity OpSetPromulgate Operation = "set-promulgate" OpSetUnPromulgate Operation = "set-unpromulgate" ) // ACL represents an access control list. type ACL struct { Read []string `json:"read,omitempty"` Write []string `json:"write,omitempty"` } // Entry represents an audit log entry. type Entry struct { Time time.Time `json:"time"` User string `json:"user"` Op Operation `json:"op"` Entity *charm.Reference `json:"entity,omitempty"` ACL *ACL `json:"acl,omitempty"` }
Include body with GitHub issues.
module.exports = { name: "GitHub", async matches(url) { return url.hostname == "github.com"; }, async parse(url) { let path = url.pathname.split("/"); let bugNumber = path[path.length - 1]; let owner = path[1]; let repo = path[2]; let bugUrl = `https://api.github.com/repos/${owner}/${repo}/issues/${bugNumber}`; let body = await fetch(bugUrl).then(data => data.json()); let prefix = `${repo}: #${bugNumber}`; let type = body.pull_request ? "PR" : "Issue"; let title = `${body.title} (${type})`; return { prefix, title, description: body.body, link: body.html_url }; } };
module.exports = { name: "GitHub", async matches(url) { return url.hostname == "github.com"; }, async parse(url) { let path = url.pathname.split("/"); let bugNumber = path[path.length - 1]; let owner = path[1]; let repo = path[2]; let bugUrl = `https://api.github.com/repos/${owner}/${repo}/issues/${bugNumber}`; let body = await fetch(bugUrl).then(data => data.json()); let prefix = `${repo}: #${bugNumber}`; let type = body.pull_request ? "PR" : "Issue"; let title = `${body.title} (${type})`; return { prefix, title, description: "", link: body.html_url }; } };
Remove force slug update due to special-characters bug.
<?php /** * Custom login logo. * * @return void */ add_action('login_head', function() { $path = ADMIN_URL.'/images/admin-login-logo.png'; echo "<style> h1 a { background-image:url($path) !important; background-size: auto auto !important; } </style>"; }); /** * Custom login logo url. * * @return string */ add_filter('login_headerurl', function() { return LOGIN_HEADER_URL; }); /** * Custom footer text. * * @return void */ add_filter('admin_footer_text', function() { return 'Thank you for creating with <a href="'.AUTHOR_URL.'">'.AUTHOR.'</a>.'; }); /** * Force Perfect JPG Images. * * @return integer */ add_filter('jpeg_quality', function() { return 100; }); /** * Filters that allow shortcodes in Text Widgets */ add_filter('widget_text', 'shortcode_unautop'); add_filter('widget_text', 'do_shortcode');
<?php /** * Custom login logo. * * @return void */ add_action('login_head', function() { $path = ADMIN_URL.'/images/admin-login-logo.png'; echo "<style> h1 a { background-image:url($path) !important; background-size: auto auto !important; } </style>"; }); /** * Custom login logo url. * * @return string */ add_filter('login_headerurl', function() { return LOGIN_HEADER_URL; }); /** * Custom footer text. * * @return void */ add_filter('admin_footer_text', function() { return 'Thank you for creating with <a href="'.AUTHOR_URL.'">'.AUTHOR.'</a>.'; }); /** * Force slug to update on save. * * @return $string */ add_filter('wp_insert_post_data', function($data, $postarr) { if (!in_array($data['post_status'], ['draft', 'pending', 'auto-draft'])) { $data['post_name'] = sanitize_title_with_dashes($data['post_title']); } return $data; }, 99, 2 ); /** * Force Perfect JPG Images. * * @return integer */ add_filter('jpeg_quality', function() { return 100; }); /** * Filters that allow shortcodes in Text Widgets */ add_filter('widget_text', 'shortcode_unautop'); add_filter('widget_text', 'do_shortcode');
Fix stupid copy paste error
from setuptools import setup import csvlib def readme(): with open('README.rst') as f: return f.read() setup(name='csvlib', version=csvlib.__version__, description='A tiny library for handling CSV files.', long_description=readme(), classifiers=[ 'Programming Language :: Python :: 2.7', 'Topic :: Utilities', ], author='Taurus Olson', author_email=u'taurusolson@gmail.com', maintainer='Taurus Olson', url='https://github.com/TaurusOlson/csvlib', packages=['csvlib'], keywords='csv tools', license=csvlib.__license__, include_package_data=True, zip_safe=False )
from setuptools import setup import csvlib def readme(): with open('README.rst') as f: return f.read() setup(name='csvlib', version=csvlib.__version__, description='A tiny library for handling CSV files.', long_description=readme(), classifiers=[ 'Programming Language :: Python :: 2.7', 'Topic :: Utilities', ], author='Taurus Olson', author_email=u'taurusolson@gmail.com', maintainer='Taurus Olson', url='https://github.com/TaurusOlson/csvlib', packages=['csvlib'], keywords='csv tools', license=fntools.__license__, include_package_data=True, zip_safe=False )
Correct location of the views
var bogart = require('bogart') , router = bogart.router() , path = require('path') , mysql = require('mysql') , util = require('./lib/util').Util , settings = require('./config/settings').Settings , fs = require('fs'); var dbSettings = require('./config/settings').Settings.db; var connection = mysql.createConnection(dbSettings); var viewEngine = bogart.viewEngine('mustache', path.join(__dirname, 'lib/views')); var app = bogart.app(); app.use(function (nextApp) { return function (req) { req.env = Object.create(req.env); return nextApp(req); } }); require('./lib/controllers')(router, viewEngine, connection); //require('./lib/accessors') uncomment this line if you want to use accessors app.use(bogart.batteries); //Life is better with batteries app.use(router); // Our router var server = app.start({ port:1337 });
var bogart = require('bogart') , router = bogart.router() , path = require('path') , mysql = require('mysql') , util = require('./lib/util').Util , settings = require('./config/settings').Settings , fs = require('fs'); var dbSettings = require('./config/settings').Settings.db; var connection = mysql.createConnection(dbSettings); var viewEngine = bogart.viewEngine('mustache', path.join(__dirname, 'views')); var app = bogart.app(); app.use(function (nextApp) { return function (req) { req.env = Object.create(req.env); return nextApp(req); } }); require('./lib/controllers')(router, viewEngine, connection); //require('./lib/accessors') uncomment this line if you want to use accessors app.use(bogart.batteries); //Life is better with batteries app.use(router); // Our router var server = app.start({ port:1337 });
Check for TTY and TERM when setting up Color enum Amends 0d27649df30419a79ca063ee3e47073f2ba8330e
import enum import os import subprocess import sys from blessings import Terminal from .misc import isatty if not (isatty(sys.stdout) and os.getenv("TERM")): class Terminal: def __getattr__(self, name): return "" TERM = Terminal() class Color(enum.Enum): none = "" reset = TERM.normal black = TERM.black red = TERM.red green = TERM.green yellow = TERM.yellow blue = TERM.blue magenta = TERM.magenta cyan = TERM.cyan white = TERM.white def __str__(self): return self.value class StreamOptions(enum.Enum): """Choices for stream handling.""" capture = "capture" hide = "hide" none = "none" @property def option(self): return { "capture": subprocess.PIPE, "hide": subprocess.DEVNULL, "none": None, }[self.value]
import enum import subprocess from blessings import Terminal TERM = Terminal() class Color(enum.Enum): none = "" reset = TERM.normal black = TERM.black red = TERM.red green = TERM.green yellow = TERM.yellow blue = TERM.blue magenta = TERM.magenta cyan = TERM.cyan white = TERM.white def __str__(self): return self.value class StreamOptions(enum.Enum): """Choices for stream handling.""" capture = "capture" hide = "hide" none = "none" @property def option(self): return { "capture": subprocess.PIPE, "hide": subprocess.DEVNULL, "none": None, }[self.value]
Add location action updates for saving and resetting
import { generateUUID } from 'react-native-database'; import { selectNewLocationId } from '../../selectors/Entities/location'; export const LOCATION_ACTIONS = { CREATE: 'LOCATION/create', UPDATE: 'LOCATION/update', SAVE_NEW: 'LOCATION/saveNew', SAVE_EDITING: 'LOCATION/saveEditing', RESET: 'LOCATION/reset', }; const createDefaultLocation = () => ({ id: generateUUID(), description: '', code: '', }); const create = () => ({ type: LOCATION_ACTIONS.CREATE, payload: { location: createDefaultLocation() }, }); const reset = () => ({ type: LOCATION_ACTIONS.RESET, }); const update = (id, field, value) => ({ type: LOCATION_ACTIONS.UPDATE, payload: { id, field, value }, }); const saveNew = location => ({ type: LOCATION_ACTIONS.SAVE_NEW, payload: { location }, }); const saveEditing = location => ({ type: LOCATION_ACTIONS.SAVE_EDITING, payload: { location }, }); const updateNew = (value, field) => (dispatch, getState) => { const newLocationId = selectNewLocationId(getState()); dispatch(update(newLocationId, field, value)); }; export const LocationActions = { create, update, updateNew, saveNew, saveEditing, reset, };
import { generateUUID } from 'react-native-database'; import { selectNewLocationId } from '../../selectors/Entities/location'; export const LOCATION_ACTIONS = { CREATE: 'LOCATION/create', UPDATE: 'LOCATION/update', SAVE_NEW: 'LOCATION/saveNew', }; const createDefaultLocation = () => ({ id: generateUUID(), description: '', code: '', }); const create = () => ({ type: LOCATION_ACTIONS.CREATE, payload: createDefaultLocation(), }); const update = (id, field, value) => ({ type: LOCATION_ACTIONS.UPDATE, payload: { id, field, value }, }); const saveNew = location => ({ type: LOCATION_ACTIONS.SAVE_NEW, payload: { location }, }); const updateNew = (value, field) => (dispatch, getState) => { const newLocationId = selectNewLocationId(getState()); dispatch(update(newLocationId, field, value)); }; export const LocationActions = { create, update, updateNew, saveNew, };
Set server port in a static prop
import interfaces.*; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; /** * Chat Server for various clients */ public class MultiUserChatServer implements IChatServer { private List<IChatClient> clients = new ArrayList<>(); private ServerSocket ss; private static int PORT = 8200; public void setupServer() { try { ss = new ServerSocket(PORT); } catch (Exception e) { e.printStackTrace(); } } public void waitForClients() { try { while (true) { Socket socketNovoCliente = ss.accept(); ConnectedClient novoCliente = new ConnectedClient(socketNovoCliente, this); clients.add(novoCliente); } } catch (Exception e) { e.printStackTrace(); } } public List<IChatClient> getClients() { return clients; } }
import interfaces.*; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; /** * Chat Server for various clients */ public class MultiUserChatServer implements IChatServer { private List<IChatClient> clients = new ArrayList<>(); private ServerSocket ss; public void setupServer() { try { ss = new ServerSocket(8200); } catch (Exception e) { e.printStackTrace(); } } public void waitForClients() { try { while (true) { Socket socketNovoCliente = ss.accept(); ConnectedClient novoCliente = new ConnectedClient(socketNovoCliente, this); clients.add(novoCliente); } } catch (Exception e) { e.printStackTrace(); } } public List<IChatClient> getClients() { return clients; } }
Change the direction of the scrolling
console.log("Initializing the runway handlers."); var runway = document.querySelector('.widget-runway-tray-wrapper'); var initialMousePosition = null; var initialScrollLeft = null; runway.addEventListener('touchstart', function(e){ console.log('touchstart'); // this should be enabled only in chrome // in chromium I need to support the multiple touch events when using one finger, // so I just take the first one currently // if (e.touches.length > 1) { console.log('No multiple touch allowed'); return; } initialMousePosition = e.touches[0].pageX; initialScrollLeft = runway.scrollLeft; }, true); runway.addEventListener('touchend', function(e){ console.log('touchend'); initialMousePosition = null; }, true); runway.addEventListener('touchmove', function(e){ console.log('touchmove'); if (initialMousePosition === null) return; // this should be enabled only in chrome // in chromium I need to support the multiple touch events when using one finger, // so I just take the first one currently //if (e.touches.length > 1) { console.log('No multiple touch allowed'); return; } // this scrolls like I feel it should... var dx = initialMousePosition - e.touches[0].pageX; runway.scrollLeft = initialScrollLeft + dx; }, true);
console.log("Initializing the runway handlers."); var runway = document.querySelector('.widget-runway-tray-wrapper'); var initialMousePosition = null; var initialScrollLeft = null; runway.addEventListener('touchstart', function(e){ console.log('touchstart'); // this should be enabled only in chrome // in chromium I need to support the multiple touch events when using one finger, // so I just take the first one currently // if (e.touches.length > 1) { console.log('No multiple touch allowed'); return; } initialMousePosition = e.touches[0].pageX; initialScrollLeft = runway.scrollLeft; }, true); runway.addEventListener('touchend', function(e){ console.log('touchend'); initialMousePosition = null; }, true); runway.addEventListener('touchmove', function(e){ console.log('touchmove'); if (initialMousePosition === null) return; // this should be enabled only in chrome // in chromium I need to support the multiple touch events when using one finger, // so I just take the first one currently //if (e.touches.length > 1) { console.log('No multiple touch allowed'); return; } var dx = e.touches[0].pageX - initialMousePosition; runway.scrollLeft = initialScrollLeft + dx; }, true);
Update docs config for 0.12
# -*- coding: utf-8 -*- # # Phinx documentation build configuration file, created by # sphinx-quickstart on Thu Jun 14 17:39:42 2012. # # Import the base theme configuration from cakephpsphinx.config.all import * # The full version, including alpha/beta/rc tags. release = '0.12.x' # The search index version. search_version = 'phinx-0' # The marketing display name for the book. version_name = '' # Project name shown in the black header bar project = 'Phinx' # Other versions that display in the version picker menu. version_list = [ {'name': '0.12', 'number': '/phinx/12', 'title': '0.12', 'current': True} {'name': '0.11', 'number': '/phinx/11', 'title': '0.11'}, ] # Languages available. languages = ['en', 'es', 'fr', 'ja'] # The GitHub branch name for this version of the docs # for edit links to point at. branch = 'master' # Current version being built version = '0.12' show_root_link = True repository = 'cakephp/phinx' source_path = 'docs/' hide_page_contents = ('search', '404', 'contents')
# -*- coding: utf-8 -*- # # Phinx documentation build configuration file, created by # sphinx-quickstart on Thu Jun 14 17:39:42 2012. # # Import the base theme configuration from cakephpsphinx.config.all import * # The full version, including alpha/beta/rc tags. release = '0.12.x' # The search index version. search_version = 'phinx-0' # The marketing display name for the book. version_name = '' # Project name shown in the black header bar project = 'Phinx' # Other versions that display in the version picker menu. version_list = [ {'name': '0.11', 'number': '/phinx/11', 'title': '0.11', 'current': True}, ] # Languages available. languages = ['en', 'es', 'fr', 'ja'] # The GitHub branch name for this version of the docs # for edit links to point at. branch = 'master' # Current version being built version = '0.11' show_root_link = True repository = 'cakephp/phinx' source_path = 'docs/' hide_page_contents = ('search', '404', 'contents')
FIX - Removed unused dependencies
/* global moment:false */ import { config } from './index.config'; import { routerConfig } from './index.route'; import { themeConfig } from './index.theme'; import { runBlock } from './index.run'; import { MainController } from './main/main.controller'; import { DetailsController } from './details/details.controller'; import { RetractableSearchbarDirective } from '../app/components/retractableSearchbar/retractableSearchbar.directive'; angular.module('generic-search-flow', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngMessages', 'ngAria', 'ngResource', 'ngRoute', 'ngMaterial', 'toastr']) .constant('moment', moment) .config(config) .config(routerConfig) .config(themeConfig) .run(runBlock) .controller('MainController', MainController) .controller('DetailsController', DetailsController) .directive('retractableSearchbar', RetractableSearchbarDirective)
/* global malarkey:false, moment:false */ import { config } from './index.config'; import { routerConfig } from './index.route'; import { themeConfig } from './index.theme'; import { runBlock } from './index.run'; import { MainController } from './main/main.controller'; import { DetailsController } from './details/details.controller'; import { RetractableSearchbarDirective } from '../app/components/retractableSearchbar/retractableSearchbar.directive'; angular.module('generic-search-flow', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngMessages', 'ngAria', 'ngResource', 'ngRoute', 'ngMaterial', 'toastr', 'infinite-scroll']) .constant('malarkey', malarkey) .constant('moment', moment) .config(config) .config(routerConfig) .config(themeConfig) .run(runBlock) .controller('MainController', MainController) .controller('DetailsController', DetailsController) .directive('retractableSearchbar', RetractableSearchbarDirective)
Backup and restore the entire require cache
"use strict"; var path = require("path") module.exports = function (toLoad, mocks) { // Copy the existing cache var originalCache = {} Object.keys(require.cache).forEach(function(name) { originalCache[name] = require.cache[name] }) // Inject all of our mocks Object.keys(mocks).forEach(function(name){ var path = require.resolve(name) if (mocks[name] == null) { delete require.cache[path] } else { require.cache[path] = {exports: mocks[name]} } }) if (/^[.][.]?\//.test(toLoad)) { toLoad = path.resolve(path.dirname(module.parent.filename), toLoad) } var toLoadPath = require.resolve(toLoad) // remove any unmocked version previously loaded delete require.cache[toLoadPath] // load our new version using our mocks var mocked = module.parent.require(toLoadPath) // restore the cache, we can't just assign originalCache to require.cache as the require // object is unique to each module, even though require.cache is shared Object.keys(require.cache).forEach(function(name){ delete require.cache[name] }) Object.keys(originalCache).forEach(function(name){ require.cache[name] = originalCache[name] }) return mocked }
"use strict"; var path = require("path") module.exports = function (toLoad, mocks) { // Inject all of our mocks Object.keys(mocks).forEach(function(name){ var path = require.resolve(name) require.cache[path] = {exports: mocks[name]} }) if (/^[.][.]?\//.test(toLoad)) { toLoad = path.resolve(path.dirname(module.parent.filename), toLoad) } var toLoadPath = require.resolve(toLoad) // remove any unmocked version previously loaded delete require.cache[toLoadPath] // load our new version using our mocks var mocked = module.parent.require(toLoadPath) // remove our version from the cache so anyone else gets the real thing delete require.cache[toLoadPath] // Remove our injected mocks Object.keys(mocks).forEach(function(name){ delete require.cache[require.resolve(name)] }) return mocked }
Remove Assert for perm of dir.
package api import ( "launchpad.net/gocheck" "time" "os" ) func (s *S) TestMountDirectoryFromTime(c *gocheck.C){ time := time.Date(2009,time.November,15,21,40,03,0, time.Local) var ret = mountDirectoryPathFromTime(time) c.Assert(ret, gocheck.Equals, "2009/11/15/21/40/") } func (s *S) TestCreateDir(c *gocheck.C){ err := CreateDir("tmp/test") c.Assert(err, gocheck.IsNil) finfo, err := os.Stat("tmp/test") c.Assert(err, gocheck.IsNil) c.Assert(finfo.IsDir(), gocheck.Equals, true) os.RemoveAll("tmp/test") }
package api import ( "launchpad.net/gocheck" "time" "os" ) func (s *S) TestMountDirectoryFromTime(c *gocheck.C){ time := time.Date(2009,time.November,15,21,40,03,0, time.Local) var ret = mountDirectoryPathFromTime(time) c.Assert(ret, gocheck.Equals, "2009/11/15/21/40/") } func (s *S) TestCreateDir(c *gocheck.C){ err := CreateDir("tmp/test") c.Assert(err, gocheck.IsNil) finfo, err := os.Stat("tmp/test") c.Assert(err, gocheck.IsNil) c.Assert(finfo.IsDir(), gocheck.Equals, true) c.Assert(finfo.Mode().String(), gocheck.Equals, "drwxr-xr-x") os.RemoveAll("tmp/test") }
ADD : app_root global variable
var app = require('app'); var BrowserWindow = require('browser-window'); var ipc = require('ipc'); global.app_root = __dirname+'/app'; global.storage = require(app_root+'/lib/storage/storage'); global.i18n = require(app_root+'/lib/i18n'); var environment = storage.get('environment'); require('crash-reporter').start(); var mainWindow = null; var Menu = require("menu"); app.on('window-all-closed', function(){ if (process.platform != 'darwin') { app.quit(); } }); app.on('ready', function(){ mainWindow = new BrowserWindow({width: 800, height: 600}); mainWindow.loadUrl('file://'+ app_root +'/views/index.html'); if (environment == 'development') mainWindow.openDevTools(); var template = require(app_root+'/lib/menus/main_menu')(app, BrowserWindow, mainWindow); Menu.setApplicationMenu(Menu.buildFromTemplate(template)); mainWindow.on('closed', function() { mainWindow = null; }); });
var app = require('app'); var BrowserWindow = require('browser-window'); var ipc = require('ipc'); global.storage = require(__dirname+'/lib/storage/storage'); global.i18n = require(__dirname+'/lib/i18n'); var environment = storage.get('environment'); require('crash-reporter').start(); var mainWindow = null; var Menu = require("menu"); app.on('window-all-closed', function(){ if (process.platform != 'darwin') { app.quit(); } }); app.on('ready', function(){ mainWindow = new BrowserWindow({width: 800, height: 600}); mainWindow.loadUrl('file://'+ __dirname + '/index.html'); if (environment == 'development') mainWindow.openDevTools(); var template = require(__dirname+'/lib/menus/main_menu')(app, BrowserWindow, mainWindow); Menu.setApplicationMenu(Menu.buildFromTemplate(template)); mainWindow.on('closed', function() { mainWindow = null; }); });
Use Utils.loadView to load main page.
requirejs.config({ shim: { 'facebook' : { export: 'FB' }, 'backbone': { deps: ["underscore", "jquery"], exports: "Backbone" }, 'underscore': { exports: "_" } }, "paths": { "jquery": "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min", "facebook": "//connect.facebook.net/en_US/all", "underscore": "libs/underscore.min", "backbone": "libs/backbone.min", "json": "libs/json2", "text": "libs/text", 'models': 'app/models/modelIndex', 'model_want': 'app/models/want', 'model_wants': 'app/models/wants', 'model_search_item': 'app/models/searchItem', 'model_search_results': 'app/models/searchResults', 'views': 'app/views/viewIndex', 'view_main': 'app/views/main', 'view_search': 'app/views/search', 'utils': 'app/utils' } }); requirejs(["jquery", "underscore", "backbone", "views", "utils"], function($, _, Backbone, Views, Utils) { Utils.loadView(Views.Main); new Views.SearchForm({ el: '#search-section', id: 'search' }); });
requirejs.config({ shim: { 'facebook' : { export: 'FB' }, 'backbone': { deps: ["underscore", "jquery"], exports: "Backbone" }, 'underscore': { exports: "_" } }, "paths": { "jquery": "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min", "facebook": "//connect.facebook.net/en_US/all", "underscore": "libs/underscore.min", "backbone": "libs/backbone.min", "json": "libs/json2", "text": "libs/text", 'models': 'app/models/modelIndex', 'model_want': 'app/models/want', 'model_wants': 'app/models/wants', 'model_search_item': 'app/models/searchItem', 'model_search_results': 'app/models/searchResults', 'views': 'app/views/viewIndex', 'view_main': 'app/views/main', 'view_search': 'app/views/search', 'utils': 'app/utils' } }); requirejs(["jquery", "underscore", "backbone", "views"], function($, _, Backbone, Views) { new Views.Main({ el: '#page-content' }); new Views.SearchForm({ el: '#search-section', id: 'search' }); });
API: Include both the numerical instance.pk & its API URL
""" Instance serializers (API representation) """ #pylint: disable=no-init from rest_framework import serializers from .models import OpenStackServer, OpenEdXInstance class OpenStackServerSerializer(serializers.ModelSerializer): pk_url = serializers.HyperlinkedIdentityField(view_name='api:openstackserver-detail') instance = serializers.HyperlinkedRelatedField(view_name='api:openedxinstance-detail', read_only=True) class Meta: model = OpenStackServer fields = ('pk', 'pk_url', 'status', 'instance', 'openstack_id', 'created', 'modified') class OpenEdXInstanceSerializer(serializers.ModelSerializer): pk_url = serializers.HyperlinkedIdentityField(view_name='api:openedxinstance-detail') server_set = OpenStackServerSerializer(many=True, read_only=True) class Meta: model = OpenEdXInstance fields = ('pk', 'pk_url', 'server_set', 'sub_domain', 'base_domain', 'email', 'name', 'protocol', 'domain', 'url', 'branch_name', 'commit_id', 'github_organization_name', 'github_organization_name', 'github_base_url', 'repository_url', 'updates_feed', 'vars_str', 'created', 'modified')
""" Instance serializers (API representation) """ #pylint: disable=no-init from rest_framework import serializers from .models import OpenStackServer, OpenEdXInstance class OpenStackServerSerializer(serializers.ModelSerializer): pk = serializers.HyperlinkedIdentityField(view_name='api:openstackserver-detail') instance = serializers.HyperlinkedRelatedField(view_name='api:openedxinstance-detail', read_only=True) class Meta: model = OpenStackServer fields = ('pk', 'status', 'instance', 'openstack_id', 'created', 'modified') class OpenEdXInstanceSerializer(serializers.ModelSerializer): pk = serializers.HyperlinkedIdentityField(view_name='api:openedxinstance-detail') server_set = OpenStackServerSerializer(many=True, read_only=True) class Meta: model = OpenEdXInstance fields = ('pk', 'server_set', 'sub_domain', 'base_domain', 'email', 'name', 'protocol', 'domain', 'url', 'branch_name', 'commit_id', 'github_organization_name', 'github_organization_name', 'github_base_url', 'repository_url', 'updates_feed', 'vars_str', 'created', 'modified')
Use PHP 5.4 short array syntax.
#!/usr/bin/env php <?php require 'vendor/autoload.php'; $phpcsCLI = new PHP_CodeSniffer_CLI(); $phpcsViolations = $phpcsCLI->process(['standard' => ['PSR1'], 'files' => ['src', 'tests', 'build.php']]); if ($phpcsViolations > 0) { exit(1); } $phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml'); $phpunitArguments = ['coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration]; $testRunner = new PHPUnit_TextUI_TestRunner(); $result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments); if (!$result->wasSuccessful()) { exit(1); } $coverageFactory = new PHP_CodeCoverage_Report_Factory(); $coverageReport = $coverageFactory->create($result->getCodeCoverage()); if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) { file_put_contents('php://stderr', "Code coverage was NOT 100%\n"); exit(1); } file_put_contents('php://stderr', "Code coverage was 100%\n");
#!/usr/bin/env php <?php require 'vendor/autoload.php'; $phpcsCLI = new PHP_CodeSniffer_CLI(); $phpcsViolations = $phpcsCLI->process(array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php'))); if ($phpcsViolations > 0) { exit(1); } $phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml'); $phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration); $testRunner = new PHPUnit_TextUI_TestRunner(); $result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments); if (!$result->wasSuccessful()) { exit(1); } $coverageFactory = new PHP_CodeCoverage_Report_Factory(); $coverageReport = $coverageFactory->create($result->getCodeCoverage()); if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) { file_put_contents('php://stderr', "Code coverage was NOT 100%\n"); exit(1); } file_put_contents('php://stderr', "Code coverage was 100%\n");
Check for authorization header before split
import expressJwt from 'express-jwt'; import db from '../models'; import config from '../config'; import { AuthenticationError } from '../components/errors'; export function isTokenAuthenticated(req, res, next) { const authString = req.get('Authorization'); if (!authString) { // No auth header provided return next(new AuthenticationError()); } const [scheme, token] = req.get('Authorization').split(' '); if (scheme !== 'Token') { // Only token authentication is accepted return next(new AuthenticationError()); } db.APIToken.findOne({ where: { token } }) .then(apiToken => { if (!apiToken) { return next(new AuthenticationError()); } req.apiToken = apiToken; return next(); }) .catch(next); } export const isAuthenticated = expressJwt({ secret: config.jwtSecret });
import expressJwt from 'express-jwt'; import db from '../models'; import config from '../config'; import { AuthenticationError } from '../components/errors'; export function isTokenAuthenticated(req, res, next) { const [scheme, token] = req.get('Authorization').split(' '); if (scheme !== 'Token') { return next(new AuthenticationError()); } db.APIToken.findOne({ where: { token } }) .then(apiToken => { if (!apiToken) { return next(new AuthenticationError()); } req.apiToken = apiToken; return next(); }) .catch(next); } export const isAuthenticated = expressJwt({ secret: config.jwtSecret });
Fix shorthand translation of "seconds" "seconds" means "less than a minute". In Turkish, "sn" is the abbreviation of "saniye", which means "second". So we should use "dk" which is the abbreviation for "dakika" (minute).
(function (factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (typeof module === 'object' && typeof module.exports === 'object') { factory(require('jquery')); } else { factory(jQuery); } }(function (jQuery) { // Turkish shortened jQuery.timeago.settings.strings = { prefixAgo: null, prefixFromNow: null, suffixAgo: "", suffixFromNow: "", seconds: "1dk", minute: "1d", minutes: "%dd", hour: "1s", hours: "%ds", day: "1g", days: "%dg", month: "1ay", months: "%day", year: "1y", years: "%dy", wordSeparator: " ", numbers: [] }; }));
(function (factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (typeof module === 'object' && typeof module.exports === 'object') { factory(require('jquery')); } else { factory(jQuery); } }(function (jQuery) { // Turkish shortened jQuery.timeago.settings.strings = { prefixAgo: null, prefixFromNow: null, suffixAgo: "", suffixFromNow: "", seconds: "1sn", minute: "1d", minutes: "%dd", hour: "1s", hours: "%ds", day: "1g", days: "%dg", month: "1ay", months: "%day", year: "1y", years: "%dy", wordSeparator: " ", numbers: [] }; }));
Use Yarn over NPM if available
<?php /* * This file is part of Rocketeer * * (c) Maxime Fabre <ehtnam6@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ namespace Rocketeer\Binaries\PackageManagers; /** * Represents the "npm" binary. */ class Npm extends AbstractPackageManager { /** * The name of the manifest file to look for. * * @var string */ protected $manifest = 'package.json'; /** * Get an array of default paths to look for. * * @return string[] */ protected function getKnownPaths() { return [ 'yarn', 'npm', ]; } /** * Get where dependencies are installed. * * @return string|null */ public function getDependenciesFolder() { return 'node_modules'; } }
<?php /* * This file is part of Rocketeer * * (c) Maxime Fabre <ehtnam6@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ namespace Rocketeer\Binaries\PackageManagers; /** * Represents the "npm" binary. */ class Npm extends AbstractPackageManager { /** * The name of the manifest file to look for. * * @var string */ protected $manifest = 'package.json'; /** * Get an array of default paths to look for. * * @return string[] */ protected function getKnownPaths() { return [ 'npm', ]; } /** * Get where dependencies are installed. * * @return string|null */ public function getDependenciesFolder() { return 'node_modules'; } }
Add route function to retrieve group messages
import authControllers from '../controllers'; const usersController = authControllers.users; const loginController = authControllers.login; const groupsController = authControllers.group; const messagesController = authControllers.messages; module.exports = (app) => { app.get('/api', (req, res) => res.status(200).send({ message: 'Welcome to the Todos API!', })); app.post('/api/user/signin', loginController.login); app.post('/api/user/signup', usersController.create); // An API route that allow users create broadcast groups: // POST: /api/group app.post('/api/group', groupsController.create); // An API route that allow users add other users to groups: app.post('/api/group/:groupid/user', (req, res) => res.send(`Added new user to ${req.params.groupid}.`)); // An API route that allows a logged in user post messages to created groups: app.post('/api/group/:groupid/message', messagesController.create); // An API route that allows a logged in user retrieve messages that have been // posted to groups he/she belongs to: app.get('/api/group/:groupid/messages', groupsController.list); // Root route app.get('*', (req, res) => res.send('Sorry, the page u requested does not exist')); };
import authControllers from '../controllers'; const usersController = authControllers.users; const loginController = authControllers.login; const groupsController = authControllers.group; const messagesController = authControllers.messages; module.exports = (app) => { app.get('/api', (req, res) => res.status(200).send({ message: 'Welcome to the Todos API!', })); app.post('/api/user/signin', loginController.login); app.post('/api/user/signup', usersController.create); // An API route that allow users create broadcast groups: // POST: /api/group app.post('/api/group', groupsController.create); // An API route that allow users add other users to groups: app.post('/api/group/:groupid/user', (req, res) => res.send(`Added new user to ${req.params.groupid}.`)); // An API route that allows a logged in user post messages to created groups: app.post('/api/group/:groupid/message', messagesController.create); // An API route that allows a logged in user retrieve messages that have been // posted to groups he/she belongs to: app.get('/api/group/:groupid/messages', (req, res) => res.send(`Welcome! here are the messages for ${req.params.groupid}`)); // Root route app.get('*', (req, res) => res.send('Sorry, the page u requested does not exist')); };
Replace the whole expression rather than the whole node Co-Authored-By: David Buchan-Swanson <c3af9b132736d390414a453d097fd3de5af0f970@gmail.com>
/** * @fileoverview Enforce no single element style arrays * @author Michael Gall */ 'use strict'; module.exports = { meta: { docs: { description: 'Disallow single element style arrays. These cause unnecessary re-renders as the identity of the array always changes', category: 'Stylistic Issues', recommended: false, url: '', }, fixable: 'code', }, create(context) { function reportNode(JSXExpressionNode) { context.report({ node: JSXExpressionNode, message: 'Single element style arrays are not necessary and cause unnecessary re-renders', fix(fixer) { const realStyleNode = JSXExpressionNode.value.expression.elements[0]; const styleSource = context.getSourceCode().getText(realStyleNode); return fixer.replaceText(JSXExpressionNode.value.expression, styleSource); }, }); } // -------------------------------------------------------------------------- // Public // -------------------------------------------------------------------------- return { JSXAttribute(node) { if (node.name.name !== 'style') return; if (node.value.expression.type !== 'ArrayExpression') return; if (node.value.expression.elements.length === 1) { reportNode(node); } }, }; }, };
/** * @fileoverview Enforce no single element style arrays * @author Michael Gall */ 'use strict'; module.exports = { meta: { docs: { description: 'Disallow single element style arrays. These cause unnecessary re-renders as the identity of the array always changes', category: 'Stylistic Issues', recommended: false, url: '', }, fixable: 'code', }, create(context) { function reportNode(JSXExpressionNode) { context.report({ node: JSXExpressionNode, message: 'Single element style arrays are not necessary and cause unnecessary re-renders', fix(fixer) { const realStyleNode = JSXExpressionNode.value.expression.elements[0]; const styleSource = context.getSourceCode().getText(realStyleNode); return fixer.replaceText(JSXExpressionNode.value, `{${styleSource}}`); }, }); } // -------------------------------------------------------------------------- // Public // -------------------------------------------------------------------------- return { JSXAttribute(node) { if (node.name.name !== 'style') return; if (node.value.expression.type !== 'ArrayExpression') return; if (node.value.expression.elements.length === 1) { reportNode(node); } }, }; }, };
Fix read of wrong dictionnary
# Copyright 2017 Eficent Business and IT Consulting Services, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import models class ProcurementRule(models.Model): _inherit = 'procurement.rule' def _get_stock_move_values(self, product_id, product_qty, product_uom, location_id, name, origin, values, group_id): vals = super(ProcurementRule, self)._get_stock_move_values( product_id, product_qty, product_uom, location_id, name, origin, values, group_id) if 'orderpoint_id' in values: vals['orderpoint_ids'] = [(4, values['orderpoint_id'].id)] elif 'orderpoint_ids' in values: vals['orderpoint_ids'] = [(4, o.id) for o in values['orderpoint_ids']] return vals
# Copyright 2017 Eficent Business and IT Consulting Services, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import models class ProcurementRule(models.Model): _inherit = 'procurement.rule' def _get_stock_move_values(self, product_id, product_qty, product_uom, location_id, name, origin, values, group_id): vals = super(ProcurementRule, self)._get_stock_move_values( product_id, product_qty, product_uom, location_id, name, origin, values, group_id) if 'orderpoint_id' in values: vals['orderpoint_ids'] = [(4, values['orderpoint_id'].id)] elif 'orderpoint_ids' in values: vals['orderpoint_ids'] = [(4, o.id) for o in vals['orderpoint_ids']] return vals
refactor(exception-mapper): Remove redundant super calls in constructor
/** * Copyright (C) 2016 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.redhat.ipaas.rest.v1.handler.exception; public class RestError { String developerMsg; String userMsg; Integer errorCode; public RestError() { } public RestError(String developerMsg, String userMsg, Integer errorCode) { this.developerMsg = developerMsg; this.userMsg = userMsg; this.errorCode = errorCode; } public String getDeveloperMsg() { return developerMsg; } public void setDeveloperMsg(String developerMsg) { this.developerMsg = developerMsg; } public String getUserMsg() { return userMsg; } public void setUserMsg(String userMsg) { this.userMsg = userMsg; } public Integer getErrorCode() { return errorCode; } public void setErrorCode(Integer errorCode) { this.errorCode = errorCode; } }
/** * Copyright (C) 2016 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.redhat.ipaas.rest.v1.handler.exception; public class RestError { String developerMsg; String userMsg; Integer errorCode; public RestError() { super(); } public RestError(String developerMsg, String userMsg, Integer errorCode) { super(); this.developerMsg = developerMsg; this.userMsg = userMsg; this.errorCode = errorCode; } public String getDeveloperMsg() { return developerMsg; } public void setDeveloperMsg(String developerMsg) { this.developerMsg = developerMsg; } public String getUserMsg() { return userMsg; } public void setUserMsg(String userMsg) { this.userMsg = userMsg; } public Integer getErrorCode() { return errorCode; } public void setErrorCode(Integer errorCode) { this.errorCode = errorCode; } }
Change version from dev to 0.1.0
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages README_FILE = os.path.join(os.path.dirname(__file__), 'README.rst') setup( name='tomako', version='0.1.0', description='Tomako is the easiest way to use Mako as a template engine ' 'for Tornado', long_description=open(README_FILE).read(), keywords=['tomako', 'mako', 'tornado'], author='Rodrigo Machado', author_email='rcmachado@gmail.com', url='https://github.com/rcmachado/tomako', license='MIT', packages=find_packages(), package_dir={'tomako': 'tomako'}, install_requires=[ "tornado>=2.3", "Mako>=0.7.2", ], include_package_data=True )
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages README_FILE = os.path.join(os.path.dirname(__file__), 'README.rst') setup( name='tomako', version='dev', description='Tomako is the easiest way to use Mako as a template engine ' 'for Tornado', long_description=open(README_FILE).read(), keywords=['tomako', 'mako', 'tornado'], author='Rodrigo Machado', author_email='rcmachado@gmail.com', url='https://github.com/rcmachado/tomako', license='MIT', packages=find_packages(), package_dir={'tomako': 'tomako'}, install_requires=[ "tornado>=2.3", "Mako>=0.7.2", ], include_package_data=True )
Fix requests to the GitHub API
var _ = require('underscore'); var async = require('async'); var request = require('request'); var linters = require('./linters'); var repoURL = 'https://api.github.com/repos/nicolasmccurdy/repos'; var githubRequest = request.defaults({ headers: { Accept: 'application/vnd.github.v3', 'User-Agent': 'ghlint' }, json: true, qs: { client_id: process.env.GHLINT_ID, client_secret: process.env.GHLINT_SECRET } }); module.exports = { linters: linters, lintAll: function (callback) { async.parallel([ function (callback) { githubRequest(repoURL, function (error, response, body) { callback(error, body); }); }, function (callback) { githubRequest(repoURL + '/commits', function (error, response, body) { callback(error, body); }); } ], function (err, data) { callback(err, linters.map(function (linter) { return { message: linter.message, result: linter.lint.apply(linter, data) }; })); }); } };
var _ = require('underscore'); var async = require('async'); var request = require('request'); var linters = require('./linters'); var repoURL = 'https://api.github.com/repos/nicolasmccurdy/repos'; var githubRequest = request.defaults({ headers: { Accept: 'application/vnd.github.v3', 'User-Agent': 'ghlint' }, qs: { client_id: process.env.GHLINT_ID, client_secret: process.env.GHLINT_SECRET } }); module.exports = { linters: linters, lintAll: function (callback) { async.parallel([ function (callback) { githubRequest(repoURL, callback); }, function (callback) { githubRequest(repoURL + '/commits', callback); } ], function (err, data) { callback(err, linters.map(function (linter) { return { message: linter.message, result: linter.lint.apply(linter, data) }; })); }); } };
Allow PUT request to /similarities/:id
from django.shortcuts import get_object_or_404 from rest_framework import permissions, viewsets from similarities.utils import get_similar from .models import Artist from similarities.models import UserSimilarity from .serializers import ArtistSerializer, SimilaritySerializer class ArtistViewSet(viewsets.ModelViewSet): """API endpoint that allows artists to be viewed or edited""" queryset = Artist.objects.all() serializer_class = ArtistSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def get_queryset(self): name = self.request.GET.get('name', "") if name: qs = get_similar(name) else: qs = super().get_queryset() return qs[:100] class SimilarViewSet(viewsets.ModelViewSet): queryset = UserSimilarity.objects.all() serializer_class = SimilaritySerializer permission_classes = (permissions.IsAuthenticated,) http_method_names = ['get', 'post', 'put', 'delete'] filter_fields = ['cc_artist'] def get_queryset(self): return super().get_queryset().filter(user=self.request.user) def pre_save(self, obj): obj.user = self.request.user
from django.shortcuts import get_object_or_404 from rest_framework import permissions, viewsets from similarities.utils import get_similar from .models import Artist from similarities.models import UserSimilarity from .serializers import ArtistSerializer, SimilaritySerializer class ArtistViewSet(viewsets.ModelViewSet): """API endpoint that allows artists to be viewed or edited""" queryset = Artist.objects.all() serializer_class = ArtistSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def get_queryset(self): name = self.request.GET.get('name', "") if name: qs = get_similar(name) else: qs = super().get_queryset() return qs[:100] class SimilarViewSet(viewsets.ModelViewSet): queryset = UserSimilarity.objects.all() serializer_class = SimilaritySerializer permission_classes = (permissions.IsAuthenticated,) http_method_names = ['get', 'post', 'delete'] filter_fields = ['cc_artist'] def get_queryset(self): return super().get_queryset().filter(user=self.request.user) def pre_save(self, obj): obj.user = self.request.user
Send entityName to Graphs API with dots replaced by dashes for FQDN compatibility
// TODO: This is not a real model or controller App.Graphs = Ember.Controller.extend({ graph: function(emberId, entityName, entityType) { entityName = entityName.replace(/\./g, '-'); return Ember.$.ajax({ url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/graphs?entityType=' + entityType + '&entityName=' + entityName, type: 'GET', dataType: 'json' }).then(function (data) { if (entityType == 'node') { App.store.getById('node', emberId).set('graphs', App.associativeToNumericArray(data)); } else if (entityType == 'vm') { App.store.getById('vm', emberId).set('graphs', App.associativeToNumericArray(data)); } }); } }); App.graphs = App.Graphs.create();
// TODO: This is not a real model or controller App.Graphs = Ember.Controller.extend({ graph: function(emberId, entityName, entityType) { return Ember.$.ajax({ url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/graphs?entityType=' + entityType + '&entityName=' + entityName, type: 'GET', dataType: 'json' }).then(function (data) { if (entityType == 'node') { App.store.getById('node', emberId).set('graphs', App.associativeToNumericArray(data)); } else if (entityType == 'vm') { App.store.getById('vm', emberId).set('graphs', App.associativeToNumericArray(data)); } }); } }); App.graphs = App.Graphs.create();
Load bullet and enemy assets
(function() { 'use strict'; function Preloader() { this.asset = null; this.ready = false; } Preloader.prototype = { preload: function () { this.asset = this.add.sprite(this.game.width * 0.5 - 110, this.game.height * 0.5 - 10, 'preloader'); this.load.setPreloadSprite(this.asset); // this.load.onLoadComplete.addOnce(this.onLoadComplete, this); this.loadResources(); this.ready = true; }, loadResources: function () { // load your assets here this.load.image('player-ship-1', 'assets/playerShip2_red.png'); this.load.image('enemy-ship-1', 'assets/enemyBlack1.png'); this.load.image('bullet-1', 'assets/laserRed16.png'); }, create: function () { }, update: function () { // if (!!this.ready) { this.game.state.start('menu'); // } }, onLoadComplete: function () { // this.ready = true; } }; window['airconsole-test'] = window['airconsole-test'] || {}; window['airconsole-test'].Preloader = Preloader; }());
(function() { 'use strict'; function Preloader() { this.asset = null; this.ready = false; } Preloader.prototype = { preload: function () { this.asset = this.add.sprite(this.game.width * 0.5 - 110, this.game.height * 0.5 - 10, 'preloader'); this.load.setPreloadSprite(this.asset); // this.load.onLoadComplete.addOnce(this.onLoadComplete, this); this.loadResources(); this.ready = true; }, loadResources: function () { // load your assets here this.load.image('player-ship-1', 'assets/playerShip2_red.png'); }, create: function () { }, update: function () { // if (!!this.ready) { this.game.state.start('menu'); // } }, onLoadComplete: function () { // this.ready = true; } }; window['airconsole-test'] = window['airconsole-test'] || {}; window['airconsole-test'].Preloader = Preloader; }());
Disable symlink test on Windows
var fstream = require('../fstream.js') var notOpen = false // No symlinks on Windows if (process.platform !== 'win32') { fstream .Writer({ path: 'path/to/symlink', linkpath: './file', isSymbolicLink: true, mode: '0755' // octal strings supported }) .on('close', function () { notOpen = true var fs = require('fs') var s = fs.lstatSync('path/to/symlink') var isSym = s.isSymbolicLink() console.log((isSym ? '' : 'not ') + 'ok 1 should be symlink') var t = fs.readlinkSync('path/to/symlink') var isTarget = t === './file' console.log((isTarget ? '' : 'not ') + 'ok 2 should link to ./file') }) .end() process.on('exit', function () { console.log((notOpen ? '' : 'not ') + 'ok 3 should be closed') }) }
var fstream = require('../fstream.js') var notOpen = false fstream .Writer({ path: 'path/to/symlink', linkpath: './file', isSymbolicLink: true, mode: '0755' // octal strings supported }) .on('close', function () { notOpen = true var fs = require('fs') var s = fs.lstatSync('path/to/symlink') var isSym = s.isSymbolicLink() console.log((isSym ? '' : 'not ') + 'ok 1 should be symlink') var t = fs.readlinkSync('path/to/symlink') var isTarget = t === './file' console.log((isTarget ? '' : 'not ') + 'ok 2 should link to ./file') }) .end() process.on('exit', function () { console.log((notOpen ? '' : 'not ') + 'ok 3 should be closed') })
Set license to AGPL-3 in manifest
# -*- coding: utf-8 -*- { 'name': 'Chilean VAT Ledger', 'license': 'AGPL-3', 'description': ''' Chilean VAT Ledger Management ================================= Creates Sale and Purchase VAT report menus in "accounting/period processing/VAT Ledger" ''', 'version': '0.1', 'author': u'Blanco Martín & Asociados', 'website': 'http://blancomartin.cl', 'depends': [ 'report_aeroo', 'l10n_cl_invoice' ], 'category': 'Reporting subsystems', 'data': [ 'account_vat_report_view.xml', 'report/account_vat_ledger_report.xml', 'security/security.xml', 'security/ir.model.access.csv', ], 'installable': True, 'active': False }
# -*- coding: utf-8 -*- { 'name': 'Chilean VAT Ledger', 'description': ''' Chilean VAT Ledger Management ================================= Creates Sale and Purchase VAT report menus in "accounting/period processing/VAT Ledger" ''', 'version': '0.1', 'author': u'Blanco Martín & Asociados', 'website': 'http://blancomartin.cl', 'depends': [ 'report_aeroo', 'l10n_cl_invoice' ], 'category': 'Reporting subsystems', 'data': [ 'account_vat_report_view.xml', 'report/account_vat_ledger_report.xml', 'security/security.xml', 'security/ir.model.access.csv', ], 'installable': True, 'active': False }
Return early if the check threw an error.
from i3pystatus.core.command import run_through_shell from i3pystatus.updates import Backend from re import split, sub class Dnf(Backend): """ Gets updates for RPM-based distributions with `dnf check-update`. The notification body consists of the status line followed by the package name and version for each update. https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command """ @property def updates(self): command = ["dnf", "check-update"] dnf = run_through_shell(command) if dnf.err: return "?", dnf.err raw = dnf.out update_count = 0 if dnf.rc == 100: lines = raw.splitlines()[2:] lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3] update_count = len(lines) notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw) return update_count, notif_body Backend = Dnf if __name__ == "__main__": """ Call this module directly; Print the update count and notification body. """ dnf = Dnf() print("Updates: {}\n\n{}".format(*dnf.updates))
from i3pystatus.core.command import run_through_shell from i3pystatus.updates import Backend from re import split, sub class Dnf(Backend): """ Gets updates for RPM-based distributions with `dnf check-update`. The notification body consists of the status line followed by the package name and version for each update. https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command """ @property def updates(self): command = ["dnf", "check-update"] dnf = run_through_shell(command) raw = dnf.out update_count = 0 if dnf.rc == 100: lines = raw.splitlines()[2:] lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3] update_count = len(lines) notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw) return update_count, notif_body Backend = Dnf if __name__ == "__main__": """ Call this module directly; Print the update count and notification body. """ dnf = Dnf() print("Updates: {}\n\n{}".format(*dnf.updates))
Disable type checking in Windows 😞
import { execFile } from 'child_process' import flow from 'flow-bin' import { logError, logWarning, log } from '../util/log' const errorCodes = { TYPECHECK_ERROR: 2 } export default (saguiOptions) => new Promise((resolve, reject) => { // Currently Facebook does not provide Windows builds. // https://github.com/flowtype/flow-bin#flow-bin- // // Instead of using `flow`, we show a warning and ignore this task // For further discussion, you can go to: // https://github.com/saguijs/sagui/issues/179 if (process.platform === 'win32') { logWarning('Type checking in Windows is not currently supported') log('Official flow builds for Windows are not currently provided.') log('We are exploring options in https://github.com/saguijs/sagui/issues/179') return resolve() } const commandArgs = ['check', '--color=always'] if (saguiOptions.javaScript && saguiOptions.javaScript.typeCheckAll) { commandArgs.push('--all') } execFile(flow, commandArgs, (err, stdout, stderr) => { if (err) { logError('Type check failed:\n') switch (err.code) { case errorCodes.TYPECHECK_ERROR: console.log(stdout) break default: console.log(err) } reject() } else { log('Type check completed without errors') resolve() } }) })
import { execFile } from 'child_process' import flow from 'flow-bin' import { logError, log } from '../util/log' const errorCodes = { TYPECHECK_ERROR: 2 } export default (saguiOptions) => new Promise((resolve, reject) => { const commandArgs = ['check', '--color=always'] if (saguiOptions.javaScript && saguiOptions.javaScript.typeCheckAll) { commandArgs.push('--all') } execFile(flow, commandArgs, (err, stdout, stderr) => { if (err) { logError('Type check failed:\n') switch (err.code) { case errorCodes.TYPECHECK_ERROR: console.log(stdout) break default: console.log(err) } reject() } else { log('Type check completed without errors') resolve() } }) })
Fix improper case from 'KeyBindings' to keybindings causing build failures on linux.
/*=include modules/accessor.js */ /*=include modules/ajax.js */ /*=include modules/calculation_colums.js */ /*=include modules/clipboard.js */ /*=include modules/download.js */ /*=include modules/edit.js */ /*=include modules/filter.js */ /*=include modules/format.js */ /*=include modules/frozen_columns.js */ /*=include modules/frozen_rows.js */ /*=include modules/group_rows.js */ /*=include modules/history.js */ /*=include modules/html_table_import.js */ /*=include modules/keybindings.js */ /*=include modules/moveable_columns.js */ /*=include modules/moveable_rows.js */ /*=include modules/mutator.js */ /*=include modules/page.js */ /*=include modules/persistence.js */ /*=include modules/resize_columns.js */ /*=include modules/resize_rows.js */ /*=include modules/resize_table.js */ /*=include modules/responsive_layout.js */ /*=include modules/select_row.js */ /*=include modules/sort.js */ /*=include modules/validate.js */
/*=include modules/accessor.js */ /*=include modules/ajax.js */ /*=include modules/calculation_colums.js */ /*=include modules/clipboard.js */ /*=include modules/download.js */ /*=include modules/edit.js */ /*=include modules/filter.js */ /*=include modules/format.js */ /*=include modules/frozen_columns.js */ /*=include modules/frozen_rows.js */ /*=include modules/group_rows.js */ /*=include modules/history.js */ /*=include modules/html_table_import.js */ /*=include modules/Keybindings.js */ /*=include modules/moveable_columns.js */ /*=include modules/moveable_rows.js */ /*=include modules/mutator.js */ /*=include modules/page.js */ /*=include modules/persistence.js */ /*=include modules/resize_columns.js */ /*=include modules/resize_rows.js */ /*=include modules/resize_table.js */ /*=include modules/responsive_layout.js */ /*=include modules/select_row.js */ /*=include modules/sort.js */ /*=include modules/validate.js */
Add center and increase suggested value font size
/** * window.c.ProjectSuggestedContributions component * A Project-show page helper to show suggested amounts of contributions * * Example of use: * view: () => { * ... * m.component(c.ProjectSuggestedContributions, {project: project}) * ... * } */ import m from 'mithril'; import _ from 'underscore'; import projectVM from '../vms/project-vm'; const projectSuggestedContributions = { view: function({attrs}) { const project = attrs.project(); const subscriptionSuggestionUrl = amount => `/projects/${project.project_id}/subscriptions/start?value=${amount * 100}`, contributionSuggestionUrl = amount => `/projects/${project.project_id}/contributions/new?value=${amount * 100}`, suggestionUrl = projectVM.isSubscription(project) ? subscriptionSuggestionUrl : contributionSuggestionUrl, suggestedValues = [10, 25, 50, 100]; return m('#suggestions', _.map(suggestedValues, amount => project ? m(`${project.open_for_contributions ? `a[href="${suggestionUrl(amount)}"].card-reward` : ''}.card-big.u-text-center.card-secondary.u-marginbottom-20`, [ m('.fontsize-jumbo', `R$ ${amount}`) ]) : '')); } }; export default projectSuggestedContributions;
/** * window.c.ProjectSuggestedContributions component * A Project-show page helper to show suggested amounts of contributions * * Example of use: * view: () => { * ... * m.component(c.ProjectSuggestedContributions, {project: project}) * ... * } */ import m from 'mithril'; import _ from 'underscore'; import projectVM from '../vms/project-vm'; const projectSuggestedContributions = { view: function({attrs}) { const project = attrs.project(); const subscriptionSuggestionUrl = amount => `/projects/${project.project_id}/subscriptions/start?value=${amount * 100}`, contributionSuggestionUrl = amount => `/projects/${project.project_id}/contributions/new?value=${amount * 100}`, suggestionUrl = projectVM.isSubscription(project) ? subscriptionSuggestionUrl : contributionSuggestionUrl, suggestedValues = [10, 25, 50, 100]; return m('#suggestions', _.map(suggestedValues, amount => project ? m(`${project.open_for_contributions ? `a[href="${suggestionUrl(amount)}"].card-reward` : ''}.card-big.card-secondary.u-marginbottom-20`, [ m('.fontsize-larger', `R$ ${amount}`) ]) : '')); } }; export default projectSuggestedContributions;
ref: Add lock on identify_revision when revision is missing
from zeus.config import redis from zeus.exceptions import UnknownRepositoryBackend from zeus.models import Repository, Revision from zeus.vcs.base import UnknownRevision def identify_revision(repository: Repository, treeish: str): """ Attempt to transform a a commit-like reference into a valid revision. """ # try to find it from the database first if len(treeish) == 40: revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == treeish ).first() if revision: return revision try: vcs = repository.get_vcs() except UnknownRepositoryBackend: return None vcs.ensure(update_if_exists=False) lock_key = "sync_repo:{repo_id}".format(repo_id=repository.id) # lock this update to avoild piling up duplicate fetch/save calls with redis.lock(lock_key): try: commit = next(vcs.log(parent=treeish, limit=1)) except UnknownRevision: vcs.update() commit = next(vcs.log(parent=treeish, limit=1)) revision, _ = commit.save(repository) return revision
from zeus.exceptions import UnknownRepositoryBackend from zeus.models import Repository, Revision from zeus.vcs.base import UnknownRevision def identify_revision(repository: Repository, treeish: str): """ Attempt to transform a a commit-like reference into a valid revision. """ # try to find it from the database first if len(treeish) == 40: revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == treeish ).first() if revision: return revision try: vcs = repository.get_vcs() except UnknownRepositoryBackend: return None vcs.ensure(update_if_exists=False) try: commit = next(vcs.log(parent=treeish, limit=1)) except UnknownRevision: vcs.update() commit = next(vcs.log(parent=treeish, limit=1)) revision, _ = commit.save(repository) return revision
Fix deserialization with annotated getters
package io.leangen.graphql.metadata.strategy.input; import com.google.gson.FieldNamingPolicy; import com.google.gson.FieldNamingStrategy; import io.leangen.graphql.util.ClassUtils; import java.lang.reflect.Field; import java.util.Optional; /** * Created by bojan.tomic on 5/25/16. */ public class GsonFieldNamingStrategy implements FieldNamingStrategy { private FieldNameGenerator fieldNameGenerator; private FieldNamingStrategy fallback; public GsonFieldNamingStrategy() { this(new AnnotationBasedFieldNameGenerator(), FieldNamingPolicy.IDENTITY); } public GsonFieldNamingStrategy(FieldNameGenerator fieldNameGenerator, FieldNamingStrategy fallback) { this.fieldNameGenerator = fieldNameGenerator; this.fallback = fallback; } @Override public String translateName(Field field) { return fieldNameGenerator.generateFieldName(field) .orElse(nameFromGetter(field) .orElse(fallback.translateName(field))); } private Optional<String> nameFromGetter(Field field) { try { return fieldNameGenerator.generateFieldName(ClassUtils.findGetter(field.getType(), field.getName())); } catch (NoSuchMethodException e) { return Optional.empty(); } } }
package io.leangen.graphql.metadata.strategy.input; import com.google.gson.FieldNamingPolicy; import com.google.gson.FieldNamingStrategy; import java.lang.reflect.Field; /** * Created by bojan.tomic on 5/25/16. */ public class GsonFieldNamingStrategy implements FieldNamingStrategy { private FieldNameGenerator fieldNameGenerator; private FieldNamingStrategy fallback; public GsonFieldNamingStrategy() { this(new AnnotationBasedFieldNameGenerator(), FieldNamingPolicy.IDENTITY); } public GsonFieldNamingStrategy(FieldNameGenerator fieldNameGenerator, FieldNamingStrategy fallback) { this.fieldNameGenerator = fieldNameGenerator; this.fallback = fallback; } @Override public String translateName(Field field) { return fieldNameGenerator.generateFieldName(field).orElse(fallback.translateName(field)); } }
Use self.request.user instead of second query
from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse from django.utils.translation import gettext_lazy as _ from django.views.generic import DetailView, RedirectView, UpdateView User = get_user_model() class UserDetailView(LoginRequiredMixin, DetailView): model = User slug_field = "username" slug_url_kwarg = "username" user_detail_view = UserDetailView.as_view() class UserUpdateView(LoginRequiredMixin, UpdateView): model = User fields = ["name"] def get_success_url(self): return reverse("users:detail", kwargs={"username": self.request.user.username}) def get_object(self): return self.request.user def form_valid(self, form): messages.add_message( self.request, messages.INFO, _("Infos successfully updated") ) return super().form_valid(form) user_update_view = UserUpdateView.as_view() class UserRedirectView(LoginRequiredMixin, RedirectView): permanent = False def get_redirect_url(self): return reverse("users:detail", kwargs={"username": self.request.user.username}) user_redirect_view = UserRedirectView.as_view()
from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse from django.utils.translation import gettext_lazy as _ from django.views.generic import DetailView, RedirectView, UpdateView User = get_user_model() class UserDetailView(LoginRequiredMixin, DetailView): model = User slug_field = "username" slug_url_kwarg = "username" user_detail_view = UserDetailView.as_view() class UserUpdateView(LoginRequiredMixin, UpdateView): model = User fields = ["name"] def get_success_url(self): return reverse("users:detail", kwargs={"username": self.request.user.username}) def get_object(self): return User.objects.get(username=self.request.user.username) def form_valid(self, form): messages.add_message( self.request, messages.INFO, _("Infos successfully updated") ) return super().form_valid(form) user_update_view = UserUpdateView.as_view() class UserRedirectView(LoginRequiredMixin, RedirectView): permanent = False def get_redirect_url(self): return reverse("users:detail", kwargs={"username": self.request.user.username}) user_redirect_view = UserRedirectView.as_view()
Include @sanity/core in bootstrapped packages
export default { // Dependencies for a default Sanity installation core: { '@sanity/base': '^0.0.23', '@sanity/components': '^0.0.27', '@sanity/core': '^0.0.1', '@sanity/default-layout': '^0.0.4', '@sanity/default-login': '^0.0.2', '@sanity/desk-tool': '^0.1.9', 'react': '^15.3.0', 'react-dom': '^15.3.0' }, // Only used for Sanity-style plugins (eg, the ones we build at Sanity.io) plugin: { dev: { '@sanity/check': '^0.0.2', 'babel-cli': '^6.9.0', 'babel-eslint': '^6.0.4', 'babel-plugin-syntax-class-properties': '^6.8.0', 'babel-plugin-transform-class-properties': '^6.9.1', 'babel-preset-es2015': '^6.9.0', 'babel-preset-react': '^6.5.0', 'eslint': '^3.4.0', 'eslint-config-sanity': '^1.1.3', 'eslint-plugin-react': '^6.3.0', 'rimraf': '^2.5.2' }, prod: { 'in-publish': '^2.0.0' } } }
export default { // Dependencies for a default Sanity installation core: { '@sanity/base': '^0.0.23', '@sanity/components': '^0.0.27', '@sanity/default-layout': '^0.0.4', '@sanity/default-login': '^0.0.2', '@sanity/desk-tool': '^0.1.9', 'react': '^15.3.0', 'react-dom': '^15.3.0' }, // Only used for Sanity-style plugins (eg, the ones we build at Sanity.io) plugin: { dev: { '@sanity/check': '^0.0.2', 'babel-cli': '^6.9.0', 'babel-eslint': '^6.0.4', 'babel-plugin-syntax-class-properties': '^6.8.0', 'babel-plugin-transform-class-properties': '^6.9.1', 'babel-preset-es2015': '^6.9.0', 'babel-preset-react': '^6.5.0', 'eslint': '^3.4.0', 'eslint-config-sanity': '^1.1.3', 'eslint-plugin-react': '^6.3.0', 'rimraf': '^2.5.2' }, prod: { 'in-publish': '^2.0.0' } } }
Add convinience method for Postgres test instance.
package com.palantir.atlasdb.keyvalue.rdbms; import javax.sql.DataSource; import org.postgresql.jdbc2.optional.PoolingDataSource; import com.palantir.atlasdb.keyvalue.api.KeyValueService; import com.palantir.atlasdb.keyvalue.impl.AbstractAtlasDbKeyValueServiceTest; public class PostgresKeyValueServiceTest extends AbstractAtlasDbKeyValueServiceTest { private KeyValueService kvs; public static DataSource getTestPostgresDataSource() { PoolingDataSource pgDataSource = new PoolingDataSource(); pgDataSource.setDatabaseName("test"); pgDataSource.setUser("test"); pgDataSource.setPassword("password"); return pgDataSource; } public static PostgresKeyValueService newTestInstance() { PostgresKeyValueService ret = new PostgresKeyValueService(getTestPostgresDataSource()); ret.initializeFromFreshInstance(); return ret; } @Override protected KeyValueService getKeyValueService() { if (kvs == null) { KeyValueService ret = new PostgresKeyValueService(getTestPostgresDataSource()); ret.initializeFromFreshInstance(); kvs = ret; } return kvs; } }
package com.palantir.atlasdb.keyvalue.rdbms; import javax.sql.DataSource; import org.postgresql.jdbc2.optional.PoolingDataSource; import com.palantir.atlasdb.keyvalue.api.KeyValueService; import com.palantir.atlasdb.keyvalue.impl.AbstractAtlasDbKeyValueServiceTest; public class PostgresKeyValueServiceTest extends AbstractAtlasDbKeyValueServiceTest { private KeyValueService kvs; public static DataSource getTestPostgresDataSource() { PoolingDataSource pgDataSource = new PoolingDataSource(); pgDataSource.setDatabaseName("test"); pgDataSource.setUser("test"); pgDataSource.setPassword("password"); return pgDataSource; } @Override protected KeyValueService getKeyValueService() { if (kvs == null) { KeyValueService ret = new PostgresKeyValueService(getTestPostgresDataSource()); ret.initializeFromFreshInstance(); kvs = ret; } return kvs; } }
Update number of fonts in Docker image
""" tests.test_fonts ~~~~~~~~~~~~~~~~~~~~~ Test fonts API. :copyright: (c) 2018 Yoan Tournade. :license: AGPL, see LICENSE for more details. """ import requests def test_api_fonts_list(latex_on_http_api_url): """ The API list available fonts. """ r = requests.get("{}/fonts".format(latex_on_http_api_url), allow_redirects=False) assert r.status_code == 200 payload = r.json() assert "fonts" in payload fonts = payload["fonts"] assert isinstance(fonts, list) is True for font in fonts: assert "family" in font assert "name" in font assert "styles" in font assert isinstance(font["styles"], list) is True assert len(fonts) == 2030
""" tests.test_fonts ~~~~~~~~~~~~~~~~~~~~~ Test fonts API. :copyright: (c) 2018 Yoan Tournade. :license: AGPL, see LICENSE for more details. """ import requests def test_api_fonts_list(latex_on_http_api_url): """ The API list available fonts. """ r = requests.get("{}/fonts".format(latex_on_http_api_url), allow_redirects=False) assert r.status_code == 200 payload = r.json() assert "fonts" in payload fonts = payload["fonts"] assert isinstance(fonts, list) is True for font in fonts: assert "family" in font assert "name" in font assert "styles" in font assert isinstance(font["styles"], list) is True assert len(fonts) == 421
Add Rasmus as stubbed admin user
import { setClient } from '../actions'; function checkAuthorization(dispatch) { const storedUser = localStorage.getItem('user'); if (storedUser) { const user = JSON.parse(storedUser); // const created = Math.round(createdDate.getTime() / 1000); // const ttl = 1209600; // const expiry = created + ttl; // if the user has expired return false // if (created > expiry) return false; dispatch(setClient(user)); return true; } return false; } export function checkIndexAuthorization({ dispatch }) { return (nextState, replace, next) => { if (checkAuthorization(dispatch)) { replace('dashboard'); return next(); } replace('login'); return next(); }; } export function checkDashboardAuthorization({ dispatch, getState }) { return (nextState, replace, next) => { const user = getState().user; if (user) return next(); if (checkAuthorization(dispatch)) return next(); replace('login'); return next(); }; } export function checkAdminAuthorization({ dispatch, getState }) { return (nextState, replace, next) => { if (checkAuthorization(dispatch)) { const user = getState().user; if (user.id === 1 || user.email === 'rasmus@designit.com') { return next(); } } replace('forbidden'); return next(); }; }
import { setClient } from '../actions'; function checkAuthorization(dispatch) { const storedUser = localStorage.getItem('user'); if (storedUser) { const user = JSON.parse(storedUser); // const created = Math.round(createdDate.getTime() / 1000); // const ttl = 1209600; // const expiry = created + ttl; // if the user has expired return false // if (created > expiry) return false; dispatch(setClient(user)); return true; } return false; } export function checkIndexAuthorization({ dispatch }) { return (nextState, replace, next) => { if (checkAuthorization(dispatch)) { replace('dashboard'); return next(); } replace('login'); return next(); }; } export function checkDashboardAuthorization({ dispatch, getState }) { return (nextState, replace, next) => { const user = getState().user; if (user) return next(); if (checkAuthorization(dispatch)) return next(); replace('login'); return next(); }; } export function checkAdminAuthorization({ dispatch, getState }) { return (nextState, replace, next) => { if (checkAuthorization(dispatch)) { const user = getState().user; if (user.id === 1 || user.id === 4) { return next(); } } replace('forbidden'); return next(); }; }
Add DB sync toggle via environment variable
import express from 'express' import mongoose from 'mongoose' import winston from 'winston' import courses from './api/courses' import buildings from './api/buildings' import db from './db' let test = process.argv.join().match('/ava/') let enableSync = process.env.COBALT_ENABLE_DB_SYNC || true // Database connection setup mongoose.connect(process.env.COBALT_MONGO_URI || 'mongodb://localhost/cobalt', err => { if (err) throw new Error(`Failed to connect to MongoDB [${process.env.COBALT_MONGO_URI}]: ${err.message}`) if (!test) { winston.info('Connected to MongoDB') } }) // Express setup let app = express() // Database sync keeper if (!test && enableSync) { db.syncCron() } // API routes let apiVersion = '1.0' app.use(`/${apiVersion}/courses`, courses) app.use(`/${apiVersion}/buildings`, buildings) // Error handlers app.use((req, res, next) => { let err = new Error('Not Found') err.status = 404 next(err) }) app.use((err, req, res, next) => { res.status(err.status || 500) let error = { code: err.status, message: err.message } res.json({ error: error }) }) module.exports = { Server: app }
import express from 'express' import mongoose from 'mongoose' import winston from 'winston' import courses from './api/courses' import buildings from './api/buildings' import db from './db' // Database connection setup let test = process.argv.join().match('/ava/') mongoose.connect(process.env.COBALT_MONGO_URI || 'mongodb://localhost/cobalt', err => { if (err) throw new Error(`Failed to connect to MongoDB [${process.env.COBALT_MONGO_URI}]: ${err.message}`) if (!test) { winston.info('Connected to MongoDB') } }) // Express setup let app = express() // Database sync keeper if (!test) { db.syncCron() } // API routes let apiVersion = '1.0' app.use(`/${apiVersion}/courses`, courses) app.use(`/${apiVersion}/buildings`, buildings) // Error handlers app.use((req, res, next) => { let err = new Error('Not Found') err.status = 404 next(err) }) app.use((err, req, res, next) => { res.status(err.status || 500) let error = { code: err.status, message: err.message } res.json({ error: error }) }) module.exports = { Server: app }
Fix path in resources with absolute path
<?php namespace AssetsBundle\View\Strategy; class ViewHelperStrategy extends \AssetsBundle\View\Strategy\AbstractStrategy{ /** * Render asset file * @param string $sPath */ public function renderAsset($sPath,$iLastModified){ $sExtension = strtolower(pathinfo($sPath, PATHINFO_EXTENSION)); // Is an absolute path? if(!preg_match('/^https?:\/\//', $sPath)) $sPath = $this->getBaseUrl().$sPath.(strpos($sPath, '?')?'&':'?').($iLastModified?:time()); switch($sExtension){ case 'js': $this->getRenderer()->plugin('InlineScript')->appendFile($sPath); break; case 'css': $this->getRenderer()->plugin('HeadLink')->appendStylesheet($sPath,'all'); break; } } }
<?php namespace AssetsBundle\View\Strategy; class ViewHelperStrategy extends \AssetsBundle\View\Strategy\AbstractStrategy{ /** * Render asset file * @param string $sPath */ public function renderAsset($sPath,$iLastModified){ $sExtension = strtolower(pathinfo($sPath, PATHINFO_EXTENSION)); $sPath = $this->getBaseUrl().$sPath.(strpos($sPath, '?')?'&':'?').($iLastModified?:time()); switch($sExtension){ case 'js': $this->getRenderer()->plugin('InlineScript')->appendFile($sPath); break; case 'css': $this->getRenderer()->plugin('HeadLink')->appendStylesheet($sPath,'all'); break; } } }
Insert newlines into composer before post mentions
import { extend } from 'flarum/extension-utils'; import ActionButton from 'flarum/components/action-button'; import PostComment from 'flarum/components/post-comment'; export default function() { extend(PostComment.prototype, 'actionItems', function(items) { var post = this.props.post; if (post.isHidden()) return; items.add('reply', ActionButton.component({ icon: 'reply', label: 'Reply', onclick: () => { var component = post.discussion().replyAction(); if (component) { var quote = window.getSelection().toString(); var mention = '@'+post.user().username()+'#'+post.number()+' '; component.editor.insertAtCursor((component.editor.value() ? '\n\n' : '')+(quote ? '> '+mention+quote+'\n\n' : mention)); // If the composer is empty, then assume we're starting a new reply. // In which case we don't want the user to have to confirm if they // close the composer straight away. if (!component.content()) { component.props.originalContent = mention; } } } }) ); }); }
import { extend } from 'flarum/extension-utils'; import ActionButton from 'flarum/components/action-button'; import PostComment from 'flarum/components/post-comment'; export default function() { extend(PostComment.prototype, 'actionItems', function(items) { var post = this.props.post; if (post.isHidden()) return; items.add('reply', ActionButton.component({ icon: 'reply', label: 'Reply', onclick: () => { var component = post.discussion().replyAction(); if (component) { var quote = window.getSelection().toString(); var mention = '@'+post.user().username()+'#'+post.number()+' '; component.editor.insertAtCursor(quote ? '> '+mention+quote+'\n\n' : mention); // If the composer is empty, then assume we're starting a new reply. // In which case we don't want the user to have to confirm if they // close the composer straight away. if (!component.content()) { component.props.originalContent = mention; } } } }) ); }); }
Add reference to csrf tests in tests loader list
""" Package with all tests for dashboard_app """ import unittest from testscenarios.scenarios import generate_scenarios TEST_MODULES = [ 'models.attachment', 'models.bundle', 'models.bundle_stream', 'models.hw_device', 'models.named_attribute', 'models.sw_package', 'models.test', 'models.test_case', 'models.test_result', 'models.test_run', 'other.csrf', 'other.deserialization', 'other.tests', ] def suite(): loader = unittest.TestLoader() test_suite = unittest.TestSuite() for name in TEST_MODULES: tests = loader.loadTestsFromName('dashboard_app.tests.' + name) test_suite.addTests(generate_scenarios(tests)) return test_suite
""" Package with all tests for dashboard_app """ import unittest from testscenarios.scenarios import generate_scenarios TEST_MODULES = [ 'models.attachment', 'models.bundle', 'models.bundle_stream', 'models.hw_device', 'models.named_attribute', 'models.sw_package', 'models.test', 'models.test_case', 'models.test_result', 'models.test_run', 'other.deserialization', 'other.tests', ] def suite(): loader = unittest.TestLoader() test_suite = unittest.TestSuite() for name in TEST_MODULES: tests = loader.loadTestsFromName('dashboard_app.tests.' + name) test_suite.addTests(generate_scenarios(tests)) return test_suite
Check for potential null pointer exception git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@2103 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
import java.io.*; public class TwoStreams { int x; public void twoStreamsWrong() throws IOException { BufferedReader r = null; Writer w = null; try { r = new BufferedReader(new InputStreamReader(new FileInputStream("hello"))); String l = r.readLine(); w = new OutputStreamWriter(new FileOutputStream("blah")); w.write(l); } finally { if (r != null) { r.close(); } if (w != null) { try { w.close(); } catch (IOException e) { } } } } public void nullDereferenceCheck(TwoStreams o) throws IOException { BufferedReader r = new BufferedReader( new InputStreamReader( new FileInputStream("hello"))); int i = o.x; r.close(); } public void twoStreamsRight() throws IOException { BufferedReader r = null; Writer w = null; try { r = new BufferedReader(new InputStreamReader(new FileInputStream("hello"))); String l = r.readLine(); w = new OutputStreamWriter(new FileOutputStream("blah")); w.write(l); } finally { if (w != null) { try { w.close(); } catch (IOException e) { } } if (r != null) { r.close(); } } } }
import java.io.*; public class TwoStreams { public void twoStreamsWrong() throws IOException { BufferedReader r = null; Writer w = null; try { r = new BufferedReader(new InputStreamReader(new FileInputStream("hello"))); String l = r.readLine(); w = new OutputStreamWriter(new FileOutputStream("blah")); w.write(l); } finally { if (r != null) { r.close(); } if (w != null) { try { w.close(); } catch (IOException e) { } } } } public void twoStreamsRight() throws IOException { BufferedReader r = null; Writer w = null; try { r = new BufferedReader(new InputStreamReader(new FileInputStream("hello"))); String l = r.readLine(); w = new OutputStreamWriter(new FileOutputStream("blah")); w.write(l); } finally { if (w != null) { try { w.close(); } catch (IOException e) { } } if (r != null) { r.close(); } } } }
Fix definition of web client builder
package io.pivotal.portfolio.config; import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerExchangeFilterFunction; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction; import org.springframework.web.reactive.function.client.WebClient; @Configuration public class BeanConfiguration { @Bean public WebClient webClient(WebClient.Builder webClientBuilder, LoadBalancerExchangeFilterFunction eff) { return webClientBuilder .filter(eff) .build(); } }
package io.pivotal.portfolio.config; import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerExchangeFilterFunction; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction; import org.springframework.web.reactive.function.client.WebClient; @Configuration public class BeanConfiguration { @Bean public WebClient webClient(LoadBalancerExchangeFilterFunction eff) { return WebClient.builder() .filter(eff) .build(); } }
[DASH-2278] Change "Installed Sockets" to "My Sockets"
import React from 'react'; import Reflux from 'reflux'; import Helmet from 'react-helmet'; import Actions from './CustomSocketsActions'; import Store from './CustomSocketsStore'; import { Container, InnerToolbar } from '../../common/'; import CustomSocketsList from './CustomSocketsList'; const CustomSockets = React.createClass({ mixins: [ Reflux.connect(Store) ], componentDidMount() { Actions.fetch(); }, render() { const { items, hideDialogs, isLoading } = this.state; return ( <div> <Helmet title="My Sockets" /> <InnerToolbar title="My Sockets" /> <Container> <CustomSocketsList isLoading={isLoading} items={items} hideDialogs={hideDialogs} /> </Container> </div> ); } }); export default CustomSockets;
import React from 'react'; import Reflux from 'reflux'; import Helmet from 'react-helmet'; import Actions from './CustomSocketsActions'; import Store from './CustomSocketsStore'; import { Container, InnerToolbar } from '../../common/'; import CustomSocketsList from './CustomSocketsList'; const CustomSockets = React.createClass({ mixins: [ Reflux.connect(Store) ], componentDidMount() { Actions.fetch(); }, render() { const { items, hideDialogs, isLoading } = this.state; return ( <div> <Helmet title="Installed Sockets" /> <InnerToolbar title="Installed Sockets" /> <Container> <CustomSocketsList isLoading={isLoading} items={items} hideDialogs={hideDialogs} /> </Container> </div> ); } }); export default CustomSockets;
Change widget attribute to string In Django 1.8, widget attribute data-date-picker=True will be rendered as 'data-date-picker'. This patch will just look for the presence of the attribute, ignoring the actual value. Change-Id: I0beabddfe13c060ef2222a09636738428135040a Closes-Bug: #1467935 (cherry picked from commit f4581dd48a7ffdcdf1b0061951e837c69caf9420)
horizon.metering = { init_create_usage_report_form: function() { horizon.datepickers.add('input[data-date-picker]'); horizon.metering.add_change_event_to_period_dropdown(); horizon.metering.show_or_hide_date_fields(); }, init_stats_page: function() { if (typeof horizon.d3_line_chart !== 'undefined') { horizon.d3_line_chart.init("div[data-chart-type='line_chart']", {'auto_resize': true}); } horizon.metering.add_change_event_to_period_dropdown(); horizon.metering.show_or_hide_date_fields(); }, show_or_hide_date_fields: function() { $("#date_from .controls input, #date_to .controls input").val(''); if ($("#id_period").find("option:selected").val() === "other"){ $("#id_date_from, #id_date_to").parent().parent().show(); return true; } else { $("#id_date_from, #id_date_to").parent().parent().hide(); return false; } }, add_change_event_to_period_dropdown: function() { $("#id_period").change(function(evt) { if (horizon.metering.show_or_hide_date_fields()) { evt.stopPropagation(); } }); } };
horizon.metering = { init_create_usage_report_form: function() { horizon.datepickers.add('input[data-date-picker="True"]'); horizon.metering.add_change_event_to_period_dropdown(); horizon.metering.show_or_hide_date_fields(); }, init_stats_page: function() { if (typeof horizon.d3_line_chart !== 'undefined') { horizon.d3_line_chart.init("div[data-chart-type='line_chart']", {'auto_resize': true}); } horizon.metering.add_change_event_to_period_dropdown(); horizon.metering.show_or_hide_date_fields(); }, show_or_hide_date_fields: function() { $("#date_from .controls input, #date_to .controls input").val(''); if ($("#id_period").find("option:selected").val() === "other"){ $("#id_date_from, #id_date_to").parent().parent().show(); return true; } else { $("#id_date_from, #id_date_to").parent().parent().hide(); return false; } }, add_change_event_to_period_dropdown: function() { $("#id_period").change(function(evt) { if (horizon.metering.show_or_hide_date_fields()) { evt.stopPropagation(); } }); } };
Disable Typus.setConfirmUnload(true). It now fires in places where it shouldn’t (search, filtering), making the tool annoying.
$(document).ready(function() { // $("#quicksearch").searchField(); // this didn't work as intended. But since I added the .resource class // on the body element, it worked in places where it shouldn't. I'm disabling it // to return to the earlier behaviour ... // $(".resource :input", document.myForm).bind("change", function() { // Typus.setConfirmUnload(true); // }); // This method is used by Typus::Controller::Bulk $(".action-toggle").click(function() { var status = this.checked; $('input.action-select').each(function() { this.checked = status; }); $('.action-toggle').each(function() { this.checked = status; }); }); }); var Typus = {}; Typus.setConfirmUnload = function(on) { window.onbeforeunload = (on) ? Typus.unloadMessage : null; } Typus.reloadParent = function() { if (Typus.parent_location_reload) parent.location.reload(true); } Typus.unloadMessage = function () { return "You have entered new data on this page. If you navigate away from this page without first saving your data, the changes will be lost."; }
$(document).ready(function() { // $("#quicksearch").searchField(); $(".resource :input", document.myForm).bind("change", function() { Typus.setConfirmUnload(true); }); // This method is used by Typus::Controller::Bulk $(".action-toggle").click(function() { var status = this.checked; $('input.action-select').each(function() { this.checked = status; }); $('.action-toggle').each(function() { this.checked = status; }); }); }); var Typus = {}; Typus.setConfirmUnload = function(on) { window.onbeforeunload = (on) ? Typus.unloadMessage : null; } Typus.reloadParent = function() { if (Typus.parent_location_reload) parent.location.reload(true); } Typus.unloadMessage = function () { return "You have entered new data on this page. If you navigate away from this page without first saving your data, the changes will be lost."; }
Fix issue with test discovery and broken CUDA drivers. This patch allows the test discovery mechanism to work even in the case of a broken/misconfigured CUDA driver. Fixes #2841
from __future__ import print_function, absolute_import, division # Re export from .stubs import (threadIdx, blockIdx, blockDim, gridDim, syncthreads, shared, local, const, grid, gridsize, atomic, threadfence_block, threadfence_system, threadfence) from .cudadrv.error import CudaSupportError from .cudadrv import nvvm from . import initialize from .errors import KernelRuntimeError from .decorators import jit, autojit, declare_device from .api import * from .api import _auto_device from .kernels import reduction reduce = Reduce = reduction.Reduce def is_available(): """Returns a boolean to indicate the availability of a CUDA GPU. This will initialize the driver if it hasn't been initialized. """ # whilst `driver.is_available` will init the driver itself, # the driver initialization may raise and as a result break # test discovery/orchestration as `cuda.is_available` is often # used as a guard for whether to run a CUDA test, the try/except # below is to handle this case. driver_is_available = False try: driver_is_available = driver.driver.is_available except CudaSupportError: pass return driver_is_available and nvvm.is_available() def cuda_error(): """Returns None or an exception if the CUDA driver fails to initialize. """ return driver.driver.initialization_error initialize.initialize_all()
from __future__ import print_function, absolute_import, division # Re export from .stubs import (threadIdx, blockIdx, blockDim, gridDim, syncthreads, shared, local, const, grid, gridsize, atomic, threadfence_block, threadfence_system, threadfence) from .cudadrv.error import CudaSupportError from .cudadrv import nvvm from . import initialize from .errors import KernelRuntimeError from .decorators import jit, autojit, declare_device from .api import * from .api import _auto_device from .kernels import reduction reduce = Reduce = reduction.Reduce def is_available(): """Returns a boolean to indicate the availability of a CUDA GPU. This will initialize the driver if it hasn't been initialized. """ return driver.driver.is_available and nvvm.is_available() def cuda_error(): """Returns None or an exception if the CUDA driver fails to initialize. """ return driver.driver.initialization_error initialize.initialize_all()
Revise Queue instance to q
from __future__ import absolute_import from __future__ import print_function from __future__ import division class Queue(object): """Queue class.""" def __init__(self): self.items = [] def is_empty(self): return self.items == [] def peek(self): return self.items[-1] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def show(self): return self.items def main(): q = Queue() print('Is empty: {}'.format(q.is_empty())) print('Enqueue "dog", 4 & 8.4') q.enqueue('dog') q.enqueue(4) q.enqueue(8.4) print(q.peek()) print('Is empty: {}'.format(q.is_empty())) print('Queue size: {}'.format(q.size())) print('Dequeue: {}'.format(q.dequeue())) print('Is empty: {}'.format(q.is_empty())) print('Queue size: {}'.format(q.size())) print('Show: {}'.format(q.show())) if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division class Queue(object): """Queue class.""" def __init__(self): self.items = [] def is_empty(self): return self.items == [] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def show(self): return self.items def main(): queue = Queue() print('Is empty: {}'.format(queue.is_empty())) print('Enqueue "dog", 4 & 8.4') queue.enqueue('dog') queue.enqueue(4) queue.enqueue(8.4) print('Is empty: {}'.format(queue.is_empty())) print('Queue size: {}'.format(queue.size())) print('Dequeue: {}'.format(queue.dequeue())) print('Is empty: {}'.format(queue.is_empty())) print('Queue size: {}'.format(queue.size())) print('Show: {}'.format(queue.show())) if __name__ == '__main__': main()
Fix typo in trove classifiers
from setuptools import setup, find_packages __author__ = "James King" __email__ = "james@agentultra.com" __version__ = "0.1.1" __license__ = "MIT" __description__ = """ A library of grids and other fine amusements. Contains a Grid and Grid-like data structures and optional modules for rendering them with pygame, creating cellular-automata simulations, games, and such things. """ setup( name="Horton", version=__version__, packages=find_packages(), install_requires = [ "sphinx_bootstrap_theme", # for docs ], extras_require = { 'pygame': ["pygame"], }, author=__author__, author_email=__email__, license=__license__, description=__description__, classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Topic :: Artistic Software", "Topic :: Games/Entertainment", "Topic :: Software Development :: Libraries", ] )
from setuptools import setup, find_packages __author__ = "James King" __email__ = "james@agentultra.com" __version__ = "0.1.1" __license__ = "MIT" __description__ = """ A library of grids and other fine amusements. Contains a Grid and Grid-like data structures and optional modules for rendering them with pygame, creating cellular-automata simulations, games, and such things. """ setup( name="Horton", version=__version__, packages=find_packages(), install_requires = [ "sphinx_bootstrap_theme", # for docs ], extras_require = { 'pygame': ["pygame"], }, author=__author__, author_email=__email__, license=__license__, description=__description__, classifiers=[ "Development Status :: 3 - Alpha", "Inteded Audience :: Developers", "License :: OSI Approved :: MIT License", "Topic :: Artistic Software", "Topic :: Games/Entertainment", "Topic :: Software Development :: Libraries", ] )
Add js to gulp watch
var gulp = require("gulp"); var sourcemaps = require("gulp-sourcemaps"); var sass = require("gulp-sass"); var concat = require("gulp-concat"); var uglify = require("gulp-uglify"); // SASS compilation and minification gulp.task("sass", function() { gulp.src("./sass/**/*.sass") .pipe(sourcemaps.init()) .pipe(sass({outputStyle: "compressed"})) .pipe(sourcemaps.write()) .pipe(gulp.dest("./dist")); }); // JS compilation and minification gulp.task("js", function() { // Build all the scripts from a directory into a file. function buildScriptsForPage(dir, path) { gulp.src(dir+"/*.js") .pipe(sourcemaps.init()) .pipe(concat(path)) .pipe(uglify()) .pipe(sourcemaps.write()) .pipe(gulp.dest("./dist")); } // Scripts for the front page buildScriptsForPage("js/home", "home.js"); // Scrips for the "email sent" page buildScriptsForPage("js/emailsent", "emailsent.js"); }); // Watching gulp.task("watch", function() { gulp.watch("./sass/**/*.sass", ["sass"]); gulp.watch("./js/**/*.js", ["js"]); }); gulp.task("default", ["watch"]);
var gulp = require("gulp"); var sourcemaps = require("gulp-sourcemaps"); var sass = require("gulp-sass"); var concat = require("gulp-concat"); var uglify = require("gulp-uglify"); gulp.task("sass", function() { gulp.src("./sass/**/*.sass") .pipe(sourcemaps.init()) .pipe(sass({outputStyle: "compressed"})) .pipe(sourcemaps.write()) .pipe(gulp.dest("./dist")); }); gulp.task("js", function() { // Build all the scripts from a directory into a file. function buildScriptsForPage(dir, path) { gulp.src(dir+"/*.js") .pipe(sourcemaps.init()) .pipe(concat(path)) .pipe(uglify()) .pipe(sourcemaps.write()) .pipe(gulp.dest("./dist")); } // Scripts for the front page buildScriptsForPage("js/home", "home.js"); // Scrips for the "email sent" page buildScriptsForPage("js/emailsent", "emailsent.js"); }); gulp.task("watch", function() { gulp.watch("./sass/**/*.sass", ["sass"]); }); gulp.task("default", ["watch"]);
Use AWS SDK and concurrency
package main import ( "bufio" "fmt" "os" "sync" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/kinesis" ) // Note: download file with test data // curl https://s3.amazonaws.com/kinesis.test/users.txt -o /tmp/users.txt func main() { wg := &sync.WaitGroup{} jobCh := make(chan string) // read sample data file, _ := os.Open("/tmp/users.txt") defer file.Close() scanner := bufio.NewScanner(file) // initialize kinesis client svc := kinesis.New(session.New()) for i := 0; i < 4; i++ { wg.Add(1) go func() { for data := range jobCh { params := &kinesis.PutRecordInput{ Data: []byte(data), PartitionKey: aws.String("partitionKey"), StreamName: aws.String("hw-test-stream"), } _, err := svc.PutRecord(params) if err != nil { fmt.Println(err.Error()) return } else { fmt.Print(".") } } wg.Done() }() } for scanner.Scan() { data := scanner.Text() jobCh <- data } fmt.Println(".") fmt.Println("Finished populating stream") }
package main import ( "bufio" "fmt" "os" "github.com/harlow/kinesis-connectors" "github.com/joho/godotenv" "github.com/sendgridlabs/go-kinesis" ) func main() { godotenv.Load() // Initialize Kinesis client auth := kinesis.NewAuth() ksis := kinesis.New(&auth, kinesis.Region{}) // Create stream connector.CreateStream(ksis, "userStream", 2) // read file // https://s3.amazonaws.com/kinesis.test/users.txt file, _ := os.Open("tmp/users.txt") defer file.Close() scanner := bufio.NewScanner(file) args := kinesis.NewArgs() args.Add("StreamName", "userStream") ctr := 0 for scanner.Scan() { l := scanner.Text() ctr = ctr + 1 key := fmt.Sprintf("partitionKey-%d", ctr) args := kinesis.NewArgs() args.Add("StreamName", "userStream") args.AddRecord([]byte(l), key) ksis.PutRecords(args) fmt.Print(".") } fmt.Println(".") fmt.Println("Finished populating userStream") }
Set Article.author to a Person instance (if it exists for current user)
from django.contrib import admin from aldryn_apphooks_config.admin import BaseAppHookConfig from aldryn_people.models import Person from cms.admin.placeholderadmin import PlaceholderAdmin, FrontendEditableAdmin from parler.admin import TranslatableAdmin from .models import Article, MockCategory, MockTag, NewsBlogConfig class ArticleAdmin(TranslatableAdmin, PlaceholderAdmin, FrontendEditableAdmin): # TODO: make possible to edit placeholder def add_view(self, request, *args, **kwargs): data = request.GET.copy() try: person = Person.objects.get(user=request.user) data['author'] = person.pk request.GET = data except Person.DoesNotExist: pass return super(ArticleAdmin, self).add_view(request, *args, **kwargs) class MockCategoryAdmin(admin.ModelAdmin): pass class MockTagAdmin(admin.ModelAdmin): pass class NewsBlogConfigAdmin(BaseAppHookConfig): def get_config_fields(self): return [] admin.site.register(Article, ArticleAdmin) admin.site.register(MockTag, MockCategoryAdmin) admin.site.register(MockCategory, MockTagAdmin) admin.site.register(NewsBlogConfig, NewsBlogConfigAdmin)
from django.contrib import admin from aldryn_apphooks_config.admin import BaseAppHookConfig from cms.admin.placeholderadmin import PlaceholderAdmin, FrontendEditableAdmin from parler.admin import TranslatableAdmin from .models import Article, MockCategory, MockTag, NewsBlogConfig class ArticleAdmin(TranslatableAdmin, PlaceholderAdmin, FrontendEditableAdmin): # TODO: make possible to edit placeholder def add_view(self, request, *args, **kwargs): data = request.GET.copy() data['author'] = request.user.id # default author is logged-in user request.GET = data return super(ArticleAdmin, self).add_view(request, *args, **kwargs) class MockCategoryAdmin(admin.ModelAdmin): pass class MockTagAdmin(admin.ModelAdmin): pass class NewsBlogConfigAdmin(BaseAppHookConfig): def get_config_fields(self): return [] admin.site.register(Article, ArticleAdmin) admin.site.register(MockTag, MockCategoryAdmin) admin.site.register(MockCategory, MockTagAdmin) admin.site.register(NewsBlogConfig, NewsBlogConfigAdmin)
Add back filter for Hillary2016
# -*- coding: UTF-8 -*- import numpy from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import config #Much of this code comes from http://adilmoujahid.com/posts/2014/07/twitter-analytics/ class StdOutListener(StreamListener): def on_data(self, data_str): data = json.loads(data_str) if len(data['entities']['urls']) != 0: newdata = {'created_at' : data['created_at'], 'text' : data['text'], 'urls' : [url['expanded_url'] for url in data['entities']['urls'] if url['url'] != '' ] } print json.dumps(newdata) return True def on_error(self, status): print status l = StdOutListener() auth = OAuthHandler(config.consumer_key, config.consumer_secret) auth.set_access_token(config.access_token, config.access_token_secret) stream = Stream(auth, l) stream.filter(track=['#Trump2016', '#Hillary2016'])
# -*- coding: UTF-8 -*- import numpy from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import config #Much of this code comes from http://adilmoujahid.com/posts/2014/07/twitter-analytics/ class StdOutListener(StreamListener): def on_data(self, data_str): data = json.loads(data_str) if len(data['entities']['urls']) != 0: newdata = {'created_at' : data['created_at'], 'text' : data['text'], 'urls' : [url['expanded_url'] for url in data['entities']['urls'] if url['url'] != '' ] } print json.dumps(newdata) return True def on_error(self, status): print status l = StdOutListener() auth = OAuthHandler(config.consumer_key, config.consumer_secret) auth.set_access_token(config.access_token, config.access_token_secret) stream = Stream(auth, l) #stream.filter(track=['#Trump2016', '#Hillary2016']) stream.filter(track=['#Trump2016'])
Add tests for the {index} placeholder
var tape = require('tape'); tape.test('transformer - should be a function', function (assert) { assert.equals(typeof require('../lib/transformer'), 'function'); assert.end(); }); tape.test('transformer - should return a templating function', function (assert) { assert.equals(typeof require('../lib/transformer')(), 'function'); assert.end(); }); tape.test('transformer - should return unmodified file without a template', function (assert) { var transformer = require('../lib/transformer')(); assert.equals(transformer('path/to/file.txt'), 'path/to/file.txt'); assert.end(); }); tape.test('transformer - should modify the filename based on the template with variables', function (assert) { var transformer = require('../lib/transformer')('{basename}.{extname}.old'); assert.equals(transformer('path/to/file.txt'), 'path/to/file.txt.old'); assert.end(); }); tape.test('transformer - should modify the filename based on the template', function (assert) { var transformer = require('../lib/transformer')('different.name'); assert.equals(transformer('path/to/file.txt'), 'path/to/different.name'); assert.end(); }); tape.test('transformer - should replace the {index} parameter', function (assert) { var transformer = require('../lib/transformer')('{index}.foo'); assert.equals(transformer('path/to/file.txt', 100), 'path/to/100.foo'); assert.end(); });
var tape = require('tape'); tape.test('transformer - should be a function', function (assert) { assert.equals(typeof require('../lib/transformer'), 'function'); assert.end(); }); tape.test('transformer - should return a templating function', function (assert) { assert.equals(typeof require('../lib/transformer')(), 'function'); assert.end(); }); tape.test('transformer - should return unmodified file without a template', function (assert) { var transformer = require('../lib/transformer')(); assert.equals(transformer('path/to/file.txt'), 'path/to/file.txt'); assert.end(); }); tape.test('transformer - should modify the filename based on the template with variables', function (assert) { var transformer = require('../lib/transformer')('{basename}.{extname}.old'); assert.equals(transformer('path/to/file.txt'), 'path/to/file.txt.old'); assert.end(); }); tape.test('transformer - should modify the filename based on the template', function (assert) { var transformer = require('../lib/transformer')('different.name'); assert.equals(transformer('path/to/file.txt'), 'path/to/different.name'); assert.end(); });
Use the source version as a doc version
# -*- coding: utf-8 -*- import os import sys import sphinx_rtd_theme import pkg_resources sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src')) import sphinxcontrib; reload(sphinxcontrib) extensions = ['sphinxcontrib.ros'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'sphinxcontritb-ros' copyright = u'2015, Tamaki Nishino' version = pkg_resources.require('sphinxcontrib-ros')[0].version release = version exclude_patterns = ['_build'] pygments_style = 'sphinx' html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] def setup(app): app.add_description_unit('confval', 'confval', 'pair: %s; configuration value')
# -*- coding: utf-8 -*- import os import sys import sphinx_rtd_theme sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src')) import sphinxcontrib; reload(sphinxcontrib) extensions = ['sphinxcontrib.ros'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'sphinxcontritb-ros' copyright = u'2015, Tamaki Nishino' version = '0.1.0' release = '0.1.0' exclude_patterns = ['_build'] pygments_style = 'sphinx' html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] def setup(app): app.add_description_unit('confval', 'confval', 'pair: %s; configuration value')
Add logger at unhandled rejection.
/** * Copyright 2013-2020 the original author or authors from the JHipster project. * * This file is part of the JHipster project, see https://www.jhipster.tech/ * for more information. * * 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. */ const { runJHipster } = require('./program'); const { done, logger } = require('./utils'); module.exports = runJHipster().catch(done); process.on('unhandledRejection', up => { logger.error('Unhandled promise rejection at:'); logger.fatal(up); });
/** * Copyright 2013-2020 the original author or authors from the JHipster project. * * This file is part of the JHipster project, see https://www.jhipster.tech/ * for more information. * * 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. */ const { runJHipster } = require('./program'); const { done } = require('./utils'); module.exports = runJHipster().catch(done); process.on('unhandledRejection', up => { throw up; });
Enable other locales that fully translated on Transifex
var downloadLocales = require('webmaker-download-locales'); var glob = require('glob'); var fs = require('fs-extra'); // Which languages should we pull down? // Don't include en-US because that's committed into git already var supportedLanguages = ['id', 'en_CA', 'es_CL', 'fr', 'nl', 'es_MX', 'cs', 'sv', 'bn_BD', 'sw', 'hi_IN', 'es', 'el', 'pt', 'es_AR', 'zh_TW', 'pt_BR', 'zh_CN', 'tr_TR', 'da_DK', 'fi', 'ru', 'sq', 'es_MX']; module.exports = function (callback) { glob('!./locale/!(en_US)/**.json', function (err, files) { files.forEach(function (file) { fs.removeSync(file); }); downloadLocales({ app: 'webmaker-app', dir: 'locale', languages: supportedLanguages }, callback); }); };
var downloadLocales = require('webmaker-download-locales'); var glob = require('glob'); var fs = require('fs-extra'); // Which languages should we pull down? // Don't include en-US because that's committed into git already var supportedLanguages = ['id', 'en_CA', 'es_CL', 'fr', 'nl', 'es_MX', 'cs', 'sv', 'bn_BD', 'sw', 'hi_IN']; module.exports = function (callback) { glob('!./locale/!(en_US)/**.json', function (err, files) { files.forEach(function (file) { fs.removeSync(file); }); downloadLocales({ app: 'webmaker-app', dir: 'locale', languages: supportedLanguages }, callback); }); };
Add to javadoc, make constructor package private.
package uk.ac.ebi.quickgo.rest.cache; import com.google.common.base.Preconditions; import java.time.DayOfWeek; import java.time.LocalTime; import java.util.Objects; import javax.validation.constraints.NotNull; /** * Data structure holds day of week and time. Used to declare events that have a daily occurrence at a set time. * * @author Tony Wardell * Date: 11/04/2017 * Time: 16:15 * Created with IntelliJ IDEA. */ class DayTime { @NotNull DayOfWeek dayOfWeek; @NotNull LocalTime time; /** * Create an instance of DayTime from {@link DayOfWeek} and {@link LocalTime} instance. * @param dayOfWeek this class represents. * @param time this class represents. */ DayTime(DayOfWeek dayOfWeek, LocalTime time) { Preconditions.checkArgument(Objects.nonNull(dayOfWeek), "Invalid Daytime DayOfWeek parameter passed to " + "constructor. Parameter is null, it should be a valid DayOfWeek instance."); Preconditions.checkArgument(Objects.nonNull(time), "Invalid DayTime time parameter passed to constructor. " + "Parameter was null, it should be a valid LocalTime instance."); this.dayOfWeek = dayOfWeek; this.time = time; } }
package uk.ac.ebi.quickgo.rest.cache; import com.google.common.base.Preconditions; import java.time.DayOfWeek; import java.time.LocalTime; import java.util.Objects; import javax.validation.constraints.NotNull; /** * Data structure holds day of week and time. Used to declare events that have a daily occurrence at a set time. * * @author Tony Wardell * Date: 11/04/2017 * Time: 16:15 * Created with IntelliJ IDEA. */ class DayTime { @NotNull DayOfWeek dayOfWeek; @NotNull LocalTime time; /** * Create an instance of DayTime from {@link DayOfWeek} and {@link LocalTime} instance. * @param dayOfWeek * @param time */ public DayTime(DayOfWeek dayOfWeek, LocalTime time) { Preconditions.checkArgument(Objects.nonNull(dayOfWeek), "Invalid Daytime DayOfWeek parameter passed to " + "constructor. Parameter is null, it should be a valid DayOfWeek instance."); Preconditions.checkArgument(Objects.nonNull(time), "Invalid DayTime time parameter passed to constructor. " + "Parameter was null, it should be a valid LocalTime instance."); this.dayOfWeek = dayOfWeek; this.time = time; } }
Increase timeout to see if it fixes invalid packet sequence in Travis
var assert = require('assert'), Lapidus = require('../index.js'), spawnSync = require('child_process').spawnSync, fs = require('fs'); describe('MySQL', function () { var output; before(function(done) { output = spawnSync('node', ['index.js', '-c', './test/config/lapidus.json'], { timeout: 1500 }); done(); }); it('connects to MySQL valid backends', function () { assert.equal(output.status, 0); assert.equal(output.stderr.toString(), ''); }); it('creates a lookup table of primary keys', function() { assert.notEqual(output.stdout.toString().indexOf('caching for fast lookups'), -1); }); });
var assert = require('assert'), Lapidus = require('../index.js'), spawnSync = require('child_process').spawnSync, fs = require('fs'); describe('MySQL', function () { var output; before(function(done) { output = spawnSync('node', ['index.js', '-c', './test/config/lapidus.json'], {timeout: 1000 }); done(); }); it('connects to MySQL valid backends', function () { assert.equal(output.status, 0); assert.equal(output.stderr.toString(), ''); }); it('creates a lookup table of primary keys', function() { assert.notEqual(output.stdout.toString().indexOf('caching for fast lookups'), -1); }); });
Throw exception if invalid login details are used
# # HamperAuthenticator is the class to handle the authentication part of the provisioning portal. # Instantiate with the email and password you want, it'll pass back the cookie jar if successful, # or an error message on failure # from helpers.driver import HamperDriver from helpers.error import HamperError from termcolor import colored class HamperAuthenticator(object): def __init__(self): super(HamperAuthenticator, self).__init__() def sign_in(self, email=None, password=None): # Grab the HamperDriver singleton driver = HamperDriver() print colored("Authenticating user...", "blue") # Open the profile URL. This will forward to the sign in page if session is invalid driver.get("https://developer.apple.com/account/ios/profile/") email_element = driver.find_element_by_name("appleId") email_element.send_keys(email) password_element = driver.find_element_by_name("accountPassword") password_element.send_keys(password) driver.find_element_by_id("submitButton2").click() if len(driver.find_elements_by_class_name("dserror")) > 0: raise Exception(HamperError(HamperError.HECodeLogInError, driver.find_element_by_class_name("dserror").get_attribute("innerHTML")))
# # HamperAuthenticator is the class to handle the authentication part of the provisioning portal. # Instantiate with the email and password you want, it'll pass back the cookie jar if successful, # or an error message on failure # from helpers.driver import HamperDriver class HamperAuthenticator(object): def __init__(self): super(HamperAuthenticator, self).__init__() def sign_in(self, email=None, password=None): # Grab the HamperDriver singleton driver = HamperDriver() # Open the profile URL. This will forward to the sign in page if session is invalid driver.get("https://developer.apple.com/account/ios/profile/") email_element = driver.find_element_by_name("appleId") email_element.send_keys(email) password_element = driver.find_element_by_name("accountPassword") password_element.send_keys(password) driver.find_element_by_id("submitButton2").click()
Make sure file is closed properly.
import os from setuptools import setup # type: ignore VERSION = '4.5' with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f: description = f.read() setup( name='conllu', packages=["conllu"], python_requires=">=3.6", package_data={ "": ["py.typed"] }, version=VERSION, license='MIT License', description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary', long_description=description, long_description_content_type="text/markdown", author=u'Emil Stenström', author_email="emil@emilstenstrom.se", url='https://github.com/EmilStenstrom/conllu/', keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Operating System :: OS Independent", ], )
import os from setuptools import setup # type: ignore VERSION = '4.5' setup( name='conllu', packages=["conllu"], python_requires=">=3.6", package_data={ "": ["py.typed"] }, version=VERSION, license='MIT License', description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), long_description_content_type="text/markdown", author=u'Emil Stenström', author_email="emil@emilstenstrom.se", url='https://github.com/EmilStenstrom/conllu/', keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Operating System :: OS Independent", ], )
Make the default OK page in the flask example obvious to find
import flask import mmstats application = app = flask.Flask(__name__) app.config['DEBUG'] = True class Stats(mmstats.MmStats): ok = mmstats.CounterField(label="mmstats.example.ok") bad = mmstats.CounterField(label="mmstats.example.bad") working = mmstats.BoolField(label="mmstats.example.working") stats = Stats() def set_working(sender): stats.working = True flask.request_started.connect(set_working, app) def unset_working(sender, response): stats.working = False flask.request_finished.connect(unset_working, app) def inc_response(sender, response): if response.status_code == 200: stats.ok.inc() elif response.status_code == 500: stats.bad.inc() flask.request_finished.connect(inc_response, app) @app.route('/') def ok(): return "OK or see /status for a single process's status" @app.route('/500') def bad(): return 'oh noes!', 500 @app.route('/status') def status(): return """\ <html> <body> <pre> ok: %s bad: %s working: %s </pre> </body> </html>""" % (stats.ok, stats.bad, stats.working) if __name__ == '__main__': app.run(host='0.0.0.0', port=5001)
import flask import mmstats application = app = flask.Flask(__name__) app.config['DEBUG'] = True class Stats(mmstats.MmStats): ok = mmstats.CounterField(label="mmstats.example.ok") bad = mmstats.CounterField(label="mmstats.example.bad") working = mmstats.BoolField(label="mmstats.example.working") stats = Stats() def set_working(sender): stats.working = True flask.request_started.connect(set_working, app) def unset_working(sender, response): stats.working = False flask.request_finished.connect(unset_working, app) def inc_response(sender, response): if response.status_code == 200: stats.ok.inc() elif response.status_code == 500: stats.bad.inc() flask.request_finished.connect(inc_response, app) @app.route('/200') def ok(): return 'OK' @app.route('/500') def bad(): return 'oh noes!', 500 @app.route('/status') def status(): return """\ <html> <body> <pre> ok: %s bad: %s working: %s </pre> </body> </html>""" % (stats.ok, stats.bad, stats.working) if __name__ == '__main__': app.run(host='0.0.0.0', port=5001)
Set title when route changed
(function (Shreds) { 'use strict'; var name = 'feeds'; var container = $('.span-fixed-sidebar'); Shreds.components.push(name); Shreds[name] = { init: function () { }, render: function (context, url) { container.attr('data-template', context); Shreds.ajax.get(url).done(function (data) { Shreds.loadModel(context, data); Shreds.syncView(context); document.title = '[shreds] - ' + (data.title || 'Feeds'); }); }, events: { 'shreds:feeds:render:index': function (ev, data) { Shreds.feeds.render('feeds/index', '/i/feeds.json'); }, 'shreds:feed:render:show': function (ev, data) { Shreds.feeds.render('feeds/show', '/i/feeds/' + data.id + '.json'); } } }; })(window.Shreds);
(function (Shreds) { 'use strict'; var name = 'feeds'; var container = $('.span-fixed-sidebar'); Shreds.components.push(name); Shreds[name] = { init: function () { }, render: function (context, url) { container.attr('data-template', context); Shreds.ajax.get(url).done(function (data) { Shreds.loadModel(context, data); Shreds.syncView(context); }); }, events: { 'shreds:feeds:render:index': function (ev, data) { Shreds.feeds.render('feeds/index', '/i/feeds.json'); }, 'shreds:feed:render:show': function (ev, data) { Shreds.feeds.render('feeds/show', '/i/feeds/' + data.id + '.json'); } } }; })(window.Shreds);
Fix portal import from react-dom
import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import { canUseDOM } from './utils'; class Portal extends React.Component { componentWillUnmount() { if (this.defaultNode) { document.body.removeChild(this.defaultNode); } this.defaultNode = null; } render() { if (!canUseDOM) { return null; } if (!this.props.node && !this.defaultNode) { this.defaultNode = document.createElement('div'); document.body.appendChild(this.defaultNode); } return ReactDOM.createPortal( this.props.children, this.props.node || this.defaultNode ); } } Portal.propTypes = { children: PropTypes.node.isRequired, node: PropTypes.any }; export default Portal;
import React from 'react'; import PropTypes from 'prop-types'; import { createPortal } from 'react-dom'; import { canUseDOM } from './utils'; class Portal extends React.Component { componentWillUnmount() { if (this.defaultNode) { document.body.removeChild(this.defaultNode); } this.defaultNode = null; } render() { if (!canUseDOM) { return null; } if (!this.props.node && !this.defaultNode) { this.defaultNode = document.createElement('div'); document.body.appendChild(this.defaultNode); } return createPortal( this.props.children, this.props.node || this.defaultNode ); } } Portal.propTypes = { children: PropTypes.node.isRequired, node: PropTypes.any }; export default Portal;
Add caching to static files if not in dev mode
const express = require('express'); const clientApp = require('../clientapp'); const config = require('./lib/config'); const nunjucks = require('nunjucks'); const path = require('path'); const middleware = require('./middleware'); const DEV_MODE = config('DEV', false); var app = express(); require('express-monkey-patch')(app); var staticDir = path.join(__dirname, '/static'); var staticRoot = '/static'; app.use(function (req, res, next) { res.locals.static = function static (staticPath) { return path.join(app.mountPoint, staticRoot, staticPath); }; next(); }); app.use(express.compress()); app.use(express.bodyParser()); app.use(middleware.session()); app.use(middleware.csrf({ whitelist: [] })); app.use(staticRoot, express.static(staticDir, {maxAge: DEV_MODE ? 0 : 86400000})); var cApp = clientApp(app, { developmentMode: config('DEV', false) }); app.get('*', cApp.html()); if (!module.parent) { const port = config('PORT', 3000); app.listen(port, function(err) { if (err) { throw err; } console.log('Listening on port ' + port + '.'); }); } else { module.exports = http.createServer(app); }
const express = require('express'); const clientApp = require('../clientapp'); const config = require('./lib/config'); const nunjucks = require('nunjucks'); const path = require('path'); const middleware = require('./middleware'); var app = express(); require('express-monkey-patch')(app); var staticDir = path.join(__dirname, '/static'); var staticRoot = '/static'; app.use(function (req, res, next) { res.locals.static = function static (staticPath) { return path.join(app.mountPoint, staticRoot, staticPath); }; next(); }); app.use(express.compress()); app.use(express.bodyParser()); app.use(middleware.session()); app.use(middleware.csrf({ whitelist: [] })); app.use(staticRoot, express.static(staticDir)); var cApp = clientApp(app, { developmentMode: config('DEV', false) }); app.get('*', cApp.html()); if (!module.parent) { const port = config('PORT', 3000); app.listen(port, function(err) { if (err) { throw err; } console.log('Listening on port ' + port + '.'); }); } else { module.exports = http.createServer(app); }
Make justTeleportedEntities a HashSet instead of ArrayList
package net.simpvp.Portals; import java.io.File; import java.util.UUID; import java.util.HashSet; import org.bukkit.entity.Entity; import org.bukkit.plugin.java.JavaPlugin; public class Portals extends JavaPlugin { public static JavaPlugin instance; public static HashSet<UUID> justTeleportedEntities = new HashSet<UUID>(); public void onEnable() { instance = this; /* Check if this plugin's directory exists, if not create it */ File dir = new File("plugins/Portals"); if ( !dir.exists() ) { dir.mkdir(); } getServer().getPluginManager().registerEvents(new BlockBreak(), this); getServer().getPluginManager().registerEvents(new BlockPlace(), this); getServer().getPluginManager().registerEvents(new PlayerDeath(), this); getServer().getPluginManager().registerEvents(new PlayerToggleSneak(), this); /* Remove comment to enable minecart detection through portals */ /* getServer().getPluginManager().registerEvents(new BlockRedstone(), this); */ SQLite.connect(); } public void onDisable() { SQLite.close(); } }
package net.simpvp.Portals; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.bukkit.entity.Entity; import org.bukkit.plugin.java.JavaPlugin; public class Portals extends JavaPlugin { public static JavaPlugin instance; public static List<UUID> justTeleportedEntities = new ArrayList<UUID>(); public void onEnable() { instance = this; /* Check if this plugin's directory exists, if not create it */ File dir = new File("plugins/Portals"); if ( !dir.exists() ) { dir.mkdir(); } getServer().getPluginManager().registerEvents(new BlockBreak(), this); getServer().getPluginManager().registerEvents(new BlockPlace(), this); getServer().getPluginManager().registerEvents(new PlayerDeath(), this); getServer().getPluginManager().registerEvents(new PlayerToggleSneak(), this); /* Remove comment to enable minecart detection through portals */ /* getServer().getPluginManager().registerEvents(new BlockRedstone(), this); */ SQLite.connect(); } public void onDisable() { SQLite.close(); } }
Trim email address before submitting to API.
(function (window, document, $) { var app = window.devsite; app.pages.signup = function () { var $btn = $('.notify-btn'); $btn.on('click', function() { $btn.addClass('disabled'); $.post('/api/developer-plus/coming-soon', { email: $('input[name="email"]').val().trim() }, function(data, status, xhr) { $btn.addClass('btn-success') .removeClass('btn-primary') .text('Success!'); setTimeout(function () { $('input[name="email"]').val(''); $btn.addClass('btn-primary') .removeClass('btn-success disabled') .text('Notify Me!'); }, 2500); }) .fail(function(e) { $btn.addClass('btn-danger') .removeClass('btn-primary') .text('Error'); setTimeout(function() { $btn.addClass('btn-primary') .removeClass('btn-danger disabled') .text('Notify Me!'); }, 2500); }); }); }; }(window, document, jQuery));
(function (window, document, $) { var app = window.devsite; app.pages.signup = function () { var $btn = $('.notify-btn'); $btn.on('click', function() { $btn.addClass('disabled'); $.post('/api/developer-plus/coming-soon', { email: $('input[name="email"]').val() }, function(data, status, xhr) { $btn.addClass('btn-success') .removeClass('btn-primary') .text('Success!'); setTimeout(function () { $('input[name="email"]').val(''); $btn.addClass('btn-primary') .removeClass('btn-success disabled') .text('Notify Me!'); }, 2500); }) .fail(function(e) { $btn.addClass('btn-danger') .removeClass('btn-primary') .text('Error'); setTimeout(function() { $btn.addClass('btn-primary') .removeClass('btn-danger disabled') .text('Notify Me!'); }, 2500); }); }); }; }(window, document, jQuery));
Add plugin to ignore moment.js language packs.
var webpack = require('webpack'); module.exports = { entry: "./src/app.js", output: { path: "./build", filename: "bundle.js", publicPath: 'http://localhost:8090/assets' }, module: { loaders: [ { test: /\.scss$/, loader: "style!css!sass" }, { test: /\.css$/, loader: "style!css" }, { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }, { test: /\.js$/, loader: "jsx-loader?insertPragma=React.DOM&harmony" }, { test: /\.json$/, loader: "json" } ] }, externals: { 'react': 'React' }, resolve: { extensions: ['', '.js', '.jsx'] }, plugins: [ // Ignore extra languages for moment.js new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/) ] };
module.exports = { entry: "./src/app.js", output: { path: "./build", filename: "bundle.js", publicPath: 'http://localhost:8090/assets' }, module: { loaders: [ { test: /\.scss$/, loader: "style!css!sass" }, { test: /\.css$/, loader: "style!css" }, { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }, { test: /\.js$/, loader: "jsx-loader?insertPragma=React.DOM&harmony" }, { test: /\.json$/, loader: "json" } ] }, externals: { 'react': 'React' }, resolve: { extensions: ['', '.js', '.jsx'] } };
Add a prerelease version number.
""" Flask-Selfdoc ------------- Flask selfdoc automatically creates an online documentation for your flask app. """ from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name='Flask-Selfdoc', version='1.0a1', url='http://github.com/jwg4/flask-selfdoc', license='MIT', author='Arnaud Coomans', maintainer='Jack Grahl', maintainer_email='jack.grahl@gmail.com', description='Documentation generator for flask', long_description=readme(), # py_modules=['flask_autodoc'], # if you would be using a package instead use packages instead # of py_modules: packages=['flask_selfdoc'], package_data={'flask_selfdoc': ['templates/autodoc_default.html']}, zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'Flask' ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], test_suite='tests', )
""" Flask-Selfdoc ------------- Flask selfdoc automatically creates an online documentation for your flask app. """ from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name='Flask-Selfdoc', version='0.2', url='http://github.com/jwg4/flask-selfdoc', license='MIT', author='Arnaud Coomans', maintainer='Jack Grahl', maintainer_email='jack.grahl@gmail.com', description='Documentation generator for flask', long_description=readme(), # py_modules=['flask_autodoc'], # if you would be using a package instead use packages instead # of py_modules: packages=['flask_selfdoc'], package_data={'flask_selfdoc': ['templates/autodoc_default.html']}, zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'Flask' ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], test_suite='tests', )
BLD: Remove test resources created during tests
describe( 'csscomb', function () { var expand = require( 'glob-expand' ); var path = require( 'path' ); var exec = require( '../lib/exec' ); var read = function ( file ) { return require( 'fs' ).readFileSync( file, { encoding: 'utf8' } ); }; //var write = require( 'write' ).sync; var fs = require( 'fs-extra' ); fs.removeSync( './tmp' ); fs.copySync( './resources', './tmp' ); var files = expand( 'tmp/fixtures/**/*.less' ); files.forEach( function ( file ) { var basename = path.basename( file ); it( 'should format the file ' + basename + ' and match the expected result', function ( done ) { exec( './bin/cli.js --no-use-cache ' + file, { stdio: 'ignore' } ).then( function () { var expected = read( path.join( 'tmp/expected/', basename ) ); var result = read( file ); //console.log('here >> task complete, result', result, expected); expect( result ).to.equal( expected ); done(); } ).catch( function ( err ) { done( err ); } ); } ); } ); after( function () { //eslint-disable-line fs.removeSync( './tmp' ); } ); } );
describe( 'csscomb', function () { var expand = require( 'glob-expand' ); var path = require( 'path' ); var exec = require( '../lib/exec' ); var read = function ( file ) { return require( 'fs' ).readFileSync( file, { encoding: 'utf8' } ); }; //var write = require( 'write' ).sync; var fs = require( 'fs-extra' ); fs.removeSync( './tmp' ); fs.copySync( './resources', './tmp' ); var files = expand( 'tmp/fixtures/**/*.less' ); files.forEach( function ( file ) { var basename = path.basename( file ); it( 'should format the file ' + basename + ' and match the expected result', function ( done ) { exec( './bin/cli.js --no-use-cache ' + file, { stdio: 'ignore' } ).then( function () { var expected = read( path.join( 'tmp/expected/', basename ) ); var result = read( file ); //console.log('here >> task complete, result', result, expected); expect( result ).to.equal( expected ); done(); } ).catch( function ( err ) { done( err ); } ); } ); } ); after( function () { //eslint-disable-line //fs.removeSync( './tmp' ); } ); } );
Handle multiple connections and connection reset
var net = require("net"); var express = require("express"); var bodyParser = require("body-parser"); var config = require('./config'); var app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // Create a simple server var server = net.createServer(function (conn) { conn.on("error", function(err) { console.log("Connection Closed: " + err); }); // Handle data from client conn.on("data", function(data) { data = JSON.parse(data); conn.write(JSON.stringify({response: "Received Message: " + data.response})) }); // Let's response with a hello message conn.write( JSON.stringify( { response: "Hey there client!" } ) ); app.post('/command', function(req, res) { conn.write(JSON.stringify({response: req.body.command})); res.end("yes"); }); }); // Listen for connections server.listen(config.PORT_NET, config.ALLOWED_IPS, config.HOST, function () { console.log("Server: Listening"); }); app.listen(config.PORT_APP, function() { console.log("Express started"); });
var net = require("net"); var express = require("express"); var bodyParser = require("body-parser"); var config = require('./config'); var app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // Create a simple server var server = net.createServer(function (conn) { // Handle data from client conn.on("data", function(data) { data = JSON.parse(data); conn.write(JSON.stringify({response: "Received Message: " + data.response})) }); // Let's response with a hello message conn.write( JSON.stringify( { response: "Hey there client!" } ) ); app.listen(config.PORT_APP, function() { console.log("Express started"); }); app.post('/command', function(req, res) { conn.write(JSON.stringify({response: req.body.command})); res.end("yes"); }); }); // Listen for connections server.listen(config.PORT_NET, config.ALLOWED_IPS, config.HOST, function () { console.log("Server: Listening"); });
Update the default send to slack message
<?php namespace Michaeljennings\Snapshot\Listeners; use League\Event\EventInterface; use Maknz\Slack\Client; use Michaeljennings\Snapshot\Exceptions\EndPointNotSetException; class SendToSlack extends Listener { /** * Check if slack is enabled, if so send the snapshot to the relevant * channel. * * @param EventInterface $event * @throws EndPointNotSetException */ public function handle(EventInterface $event) { if ($this->config['slack']['enabled']) { if (empty($this->config['slack']['endpoint'])) { throw new EndPointNotSetException("You must set the endpoint for your slack channel."); } $client = new Client($this->config['slack']['endpoint'], $this->config['slack']['settings']); $client->send($this->getMessage($event->getSnapshot())); } } /** * Get the slack message for the snapshot. If you wish to use markdown * then set the allow_markdown config option to true. * * @param mixed $snapshot * @return string */ protected function getMessage($snapshot) { return '#' . $snapshot->getId() . ' A new snapshot has been captured'; } }
<?php namespace Michaeljennings\Snapshot\Listeners; use League\Event\EventInterface; use Maknz\Slack\Client; use Michaeljennings\Snapshot\Exceptions\EndPointNotSetException; class SendToSlack extends Listener { /** * Check if slack is enabled, if so send the snapshot to the relevant * channel. * * @param EventInterface $event * @throws EndPointNotSetException */ public function handle(EventInterface $event) { if ($this->config['slack']['enabled']) { if (empty($this->config['slack']['endpoint'])) { throw new EndPointNotSetException("You must set the endpoint for your slack channel."); } $client = new Client($this->config['slack']['endpoint'], $this->config['slack']['settings']); $client->send($this->getMessage($event->getSnapshot())); } } /** * Get the slack message for the snapshot. If you wish to use markdown * then set the allow_markdown config option to true. * * @param mixed $snapshot * @return string */ protected function getMessage($snapshot) { return 'A new snapshot has been captured. #' . $snapshot->getId(); } }
Add more detailed print in first module
from jtapi import * import os import sys import re import numpy as np from scipy import misc mfilename = re.search('(.*).py', os.path.basename(__file__)).group(1) ######### # input # ######### print('jt - %s:' % mfilename) handles_stream = sys.stdin handles = gethandles(handles_stream) input_args = readinputargs(handles) input_args = checkinputargs(input_args) ############## # processing # ############## myImageFilename = input_args['myImageFilename'] print '>>>>> loading "myImage" from "%s"' % myImageFilename myImage = np.array(misc.imread(myImageFilename), dtype='float64') print('>>>>> "myImage" has type "%s" and dimensions "%s".' % (str(myImage.dtype), str(myImage.shape))) print '>>>>> position [1, 2] (0-based): %d' % myImage[1, 2] data = dict() output_args = dict() output_args['OutputVar'] = myImage ########## # output # ########## writedata(handles, data) writeoutputargs(handles, output_args)
from jtapi import * import os import sys import re import numpy as np from scipy import misc mfilename = re.search('(.*).py', os.path.basename(__file__)).group(1) ######### # input # ######### print('jt - %s:' % mfilename) handles_stream = sys.stdin handles = gethandles(handles_stream) input_args = readinputargs(handles) input_args = checkinputargs(input_args) ############## # processing # ############## myImageFilename = input_args['myImageFilename'] myImage = np.array(misc.imread(myImageFilename), dtype='float64') print('>>>>> "myImage" has type "%s" and dimensions "%s".' % (str(myImage.dtype), str(myImage.shape))) print '>>>>> position [1, 2] (0-based): %d' % myImage[1, 2] data = dict() output_args = dict() output_args['OutputVar'] = myImage ########## # output # ########## writedata(handles, data) writeoutputargs(handles, output_args)
Add pybit and its dependencies to this package's dependency list.
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() requires = [ 'pyramid', 'pyramid_debugtoolbar', 'waitress', # PyBit and dependencies 'pybit', 'psycopg2', 'amqplib', 'jsonpickle', ] setup(name='acmeio', version='0.0', description='acmeio', long_description=README + '\n\n' + CHANGES, classifiers=[ "Programming Language :: Python", "Framework :: Pyramid", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='', author_email='', url='', keywords='web pyramid pylons', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=requires, tests_require=requires, test_suite="acmeio", entry_points="""\ [paste.app_factory] main = acmeio:main """, )
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() requires = [ 'pyramid', 'pyramid_debugtoolbar', 'waitress', ] setup(name='acmeio', version='0.0', description='acmeio', long_description=README + '\n\n' + CHANGES, classifiers=[ "Programming Language :: Python", "Framework :: Pyramid", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='', author_email='', url='', keywords='web pyramid pylons', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=requires, tests_require=requires, test_suite="acmeio", entry_points="""\ [paste.app_factory] main = acmeio:main """, )
Fix: Use custom WeakMap check until es6-weak-map PR is accepted
'use strict'; var assert = require('assert'); var WM = require('es6-weak-map'); var defaultResolution = require('default-resolution'); var nativeRegex = /[native code]/; // workaround until https://github.com/medikoo/es6-weak-map/pull/4 is merged function hasWeakMap(){ return (global.WeakMap && nativeRegex.test(global.WeakMap.toString())); } // workaround until https://github.com/medikoo/es6-weak-map/pull/4 is merged var runtimes = new (hasWeakMap() ? global.WeakMap : WM)(); function isFunction(fn){ return (typeof fn === 'function'); } function isExtensible(fn){ if(hasWeakMap()){ // native weakmap doesn't care about extensible return true; } return Object.isExtensible(fn); } function lastRun(fn, timeResolution){ assert(isFunction(fn), 'Only functions can check lastRun'); assert(isExtensible(fn), 'Only extensible functions can check lastRun'); var time = runtimes.get(fn); if(time == null){ return; } if(timeResolution == null){ timeResolution = defaultResolution(); } if(timeResolution){ return time - (time % timeResolution); } return time; } function capture(fn){ assert(isFunction(fn), 'Only functions can be captured'); assert(isExtensible(fn), 'Only extensible functions can be captured'); runtimes.set(fn, Date.now()); } lastRun.capture = capture; module.exports = lastRun;
'use strict'; var assert = require('assert'); var WM = require('es6-weak-map'); var hasWeakMap = require('es6-weak-map/is-implemented'); var defaultResolution = require('default-resolution'); var runtimes = new WM(); function isFunction(fn){ return (typeof fn === 'function'); } function isExtensible(fn){ if(hasWeakMap()){ // native weakmap doesn't care about extensible return true; } return Object.isExtensible(fn); } function lastRun(fn, timeResolution){ assert(isFunction(fn), 'Only functions can check lastRun'); assert(isExtensible(fn), 'Only extensible functions can check lastRun'); var time = runtimes.get(fn); if(time == null){ return; } if(timeResolution == null){ timeResolution = defaultResolution(); } if(timeResolution){ return time - (time % timeResolution); } return time; } function capture(fn){ assert(isFunction(fn), 'Only functions can be captured'); assert(isExtensible(fn), 'Only extensible functions can be captured'); runtimes.set(fn, Date.now()); } lastRun.capture = capture; module.exports = lastRun;
Add missing global Rollup alias for apollo-link-http-common This fixes #521, making it so that the apollo-link-http bundle resolves apollo-link-http-common to global.apolloLink.utilities instead of global.apolloLinkHttpCommon (which does not exist).
import sourcemaps from 'rollup-plugin-sourcemaps'; export const globals = { // Apollo 'apollo-client': 'apollo.core', 'apollo-link': 'apolloLink.core', 'apollo-link-batch': 'apolloLink.batch', 'apollo-utilities': 'apollo.utilities', 'apollo-link-http-common': 'apolloLink.utilities', 'zen-observable-ts': 'apolloLink.zenObservable', //GraphQL 'graphql/language/printer': 'printer', 'zen-observable': 'Observable', }; export default name => ({ input: 'lib/index.js', output: { file: 'lib/bundle.umd.js', format: 'umd', name: `apolloLink.${name}`, globals, sourcemap: true, exports: 'named', }, external: Object.keys(globals), onwarn, plugins: [sourcemaps()], }); export function onwarn(message) { const suppressed = ['UNRESOLVED_IMPORT', 'THIS_IS_UNDEFINED']; if (!suppressed.find(code => message.code === code)) { return console.warn(message.message); } }
import sourcemaps from 'rollup-plugin-sourcemaps'; export const globals = { // Apollo 'apollo-client': 'apollo.core', 'apollo-link': 'apolloLink.core', 'apollo-link-batch': 'apolloLink.batch', 'apollo-utilities': 'apollo.utilities', 'zen-observable-ts': 'apolloLink.zenObservable', //GraphQL 'graphql/language/printer': 'printer', 'zen-observable': 'Observable', }; export default name => ({ input: 'lib/index.js', output: { file: 'lib/bundle.umd.js', format: 'umd', name: `apolloLink.${name}`, globals, sourcemap: true, exports: 'named', }, external: Object.keys(globals), onwarn, plugins: [sourcemaps()], }); export function onwarn(message) { const suppressed = ['UNRESOLVED_IMPORT', 'THIS_IS_UNDEFINED']; if (!suppressed.find(code => message.code === code)) { return console.warn(message.message); } }
Clean up backen search js
/** * All methods related to the search */ jsBackend.search = { init: function() { var $synonymBox = $('input.synonymBox'); // synonyms box if ($synonymBox.length > 0) { $synonymBox.multipleTextbox({ emptyMessage: jsBackend.locale.msg('NoSynonymsBox'), addLabel: utils.string.ucfirst(jsBackend.locale.lbl('Add')), removeLabel: utils.string.ucfirst(jsBackend.locale.lbl('DeleteSynonym')) }); } // settings enable/disable $('#searchModules').find('input[type=checkbox]').on('change', function() { var $this = $(this); var $weightElement = $('#' + $this.attr('id') + 'Weight'); if ($this.is(':checked')) { $weightElement.removeAttr('disabled').removeClass('disabled'); return; } $weightElement.prop('disabled', true).addClass('disabled'); }); } }; $(jsBackend.search.init);
/** * All methods related to the search */ jsBackend.search = { // init, something like a constructor init: function() { $synonymBox = $('input.synonymBox'); // synonyms box if($synonymBox.length > 0) { $synonymBox.multipleTextbox( { emptyMessage: jsBackend.locale.msg('NoSynonymsBox'), addLabel: utils.string.ucfirst(jsBackend.locale.lbl('Add')), removeLabel: utils.string.ucfirst(jsBackend.locale.lbl('DeleteSynonym')) }); } // settings enable/disable $('#searchModules input[type=checkbox]').on('change', function() { $this = $(this); if($this.is(':checked')) { $('#' + $this.attr('id') + 'Weight').removeAttr('disabled').removeClass('disabled'); } else { $('#' + $this.attr('id') + 'Weight').prop('disabled', true).addClass('disabled'); } }); } }; $(jsBackend.search.init);
Fix throwing when no source maps on calling `forEach` of null We need here to show frames even if all came from node_modules
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import type { StackFrame } from './stack-frame'; import { parse } from './parser'; import { map } from './mapper'; import { unmap } from './unmapper'; function getStackFrames( error: Error, unhandledRejection: boolean = false, contextSize: number = 3 ): Promise<StackFrame[] | null> { const parsedFrames = parse(error); let enhancedFramesPromise; if (error.__unmap_source) { enhancedFramesPromise = unmap( // $FlowFixMe error.__unmap_source, parsedFrames, contextSize ); } else { enhancedFramesPromise = map(parsedFrames, contextSize); } return enhancedFramesPromise.then(enhancedFrames => { /* if ( enhancedFrames .map(f => f._originalFileName) .filter(f => f != null && f.indexOf('node_modules') === -1).length === 0 ) { return null; } */ return enhancedFrames.filter( ({ functionName }) => functionName == null || functionName.indexOf('__stack_frame_overlay_proxy_console__') === -1 ); }); } export default getStackFrames; export { getStackFrames };
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import type { StackFrame } from './stack-frame'; import { parse } from './parser'; import { map } from './mapper'; import { unmap } from './unmapper'; function getStackFrames( error: Error, unhandledRejection: boolean = false, contextSize: number = 3 ): Promise<StackFrame[] | null> { const parsedFrames = parse(error); let enhancedFramesPromise; if (error.__unmap_source) { enhancedFramesPromise = unmap( // $FlowFixMe error.__unmap_source, parsedFrames, contextSize ); } else { enhancedFramesPromise = map(parsedFrames, contextSize); } return enhancedFramesPromise.then(enhancedFrames => { if ( enhancedFrames .map(f => f._originalFileName) .filter(f => f != null && f.indexOf('node_modules') === -1).length === 0 ) { return null; } return enhancedFrames.filter( ({ functionName }) => functionName == null || functionName.indexOf('__stack_frame_overlay_proxy_console__') === -1 ); }); } export default getStackFrames; export { getStackFrames };
Add lastmod to existing profile picture metadata
"""Add column for profile picture type to User Revision ID: f37d509e221c Revises: c997dc927fbc Create Date: 2020-09-04 15:43:18.413156 """ from enum import Enum import sqlalchemy as sa from alembic import op from werkzeug.http import http_date from indico.core.db.sqlalchemy import PyIntEnum from indico.util.date_time import now_utc # revision identifiers, used by Alembic. revision = 'f37d509e221c' down_revision = 'c997dc927fbc' branch_labels = None depends_on = None class _ProfilePictureSource(int, Enum): standard = 0 identicon = 1 gravatar = 2 custom = 3 def upgrade(): op.add_column('users', sa.Column('picture_source', PyIntEnum(_ProfilePictureSource), nullable=False, server_default='0'), schema='users') op.alter_column('users', 'picture_source', server_default=None, schema='users') op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL') op.execute(''' UPDATE users.users SET picture_metadata = picture_metadata || '{"lastmod": "%s"}'::jsonb WHERE picture_source = 3 AND NOT (picture_metadata ? 'lastmod') ''' % http_date(now_utc())) def downgrade(): op.drop_column('users', 'picture_source', schema='users')
"""Add column for profile picture type to User Revision ID: f37d509e221c Revises: c997dc927fbc Create Date: 2020-09-04 15:43:18.413156 """ from enum import Enum import sqlalchemy as sa from alembic import op from indico.core.db.sqlalchemy import PyIntEnum # revision identifiers, used by Alembic. revision = 'f37d509e221c' down_revision = 'c997dc927fbc' branch_labels = None depends_on = None class _ProfilePictureSource(int, Enum): standard = 0 identicon = 1 gravatar = 2 custom = 3 def upgrade(): op.add_column('users', sa.Column('picture_source', PyIntEnum(_ProfilePictureSource), nullable=False, server_default='0'), schema='users') op.alter_column('users', 'picture_source', server_default=None, schema='users') op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL') def downgrade(): op.drop_column('users', 'picture_source', schema='users')
Use index as unique key prop in category column's list items - using body as the key prop caused ideas with a duplicate body to not be rendered
import React from "react" function CategoryColumn(props) { const categoryToEmoticonUnicodeMap = { happy: "😊", sad: "😥", confused: "😕", } const emoticonUnicode = categoryToEmoticonUnicodeMap[props.category] const filteredIdeas = props.ideas.filter(idea => idea.category === props.category) return ( <section className="column"> <div className="ui center aligned basic segment"> <i>{ emoticonUnicode }</i> <p><a>@{ props.category }</a></p> </div> <div className="ui divider"></div> <ul className={ `${props.category} ideas ui divided list` }> { filteredIdeas.map((idea, index) => <li className="item" key={index}>{idea.body}</li>) } </ul> </section> ) } CategoryColumn.propTypes = { ideas: React.PropTypes.array.isRequired, category: React.PropTypes.string.isRequired, } export default CategoryColumn
import React from "react" function CategoryColumn(props) { const categoryToEmoticonUnicodeMap = { happy: "😊", sad: "😥", confused: "😕", } const emoticonUnicode = categoryToEmoticonUnicodeMap[props.category] const filteredIdeas = props.ideas.filter(idea => idea.category === props.category) return ( <section className="column"> <div className="ui center aligned basic segment"> <i>{ emoticonUnicode }</i> <p><a>@{ props.category }</a></p> </div> <div className="ui divider"></div> <ul className={ `${props.category} ideas ui divided list` }> { filteredIdeas.map(idea => <li className="item" key={idea.body}>{idea.body}</li>) } </ul> </section> ) } CategoryColumn.propTypes = { ideas: React.PropTypes.array.isRequired, category: React.PropTypes.string.isRequired, } export default CategoryColumn
Update void test to reflect the new void model structure The first version I coded up only allowed for a single dump in each dataset. The most current version expects an array of dumps so I needed to update the test.
"""test_void.py Test the parsing of VoID dump files. """ try: import RDF except ImportError: import sys sys.path.append('/usr/lib/python2.7/dist-packages/') import RDF from glharvest import util, void def test_returns_none_if_the_registry_file_is_not_found(): m = util.load_file_into_model("nonexistantvoidfile.ttl") assert m is None def test_can_load_a_simple_void_file(): m = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle') p = void.parse_void_model(m) assert p == { 'http://lod.dataone.org/test': { 'dumps': ['http://lod.dataone.org/test.ttl'], 'features': [ 'http://lod.dataone.org/fulldump' ] } }
"""test_void.py Test the parsing of VoID dump files. """ try: import RDF except ImportError: import sys sys.path.append('/usr/lib/python2.7/dist-packages/') import RDF from glharvest import util, void def test_returns_none_if_the_registry_file_is_not_found(): m = util.load_file_into_model("nonexistantvoidfile.ttl") assert m is None def test_can_load_a_simple_void_file(): m = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle') p = void.parse_void_model(m) assert p == { 'http://lod.dataone.org/test': { 'dataDump': 'http://lod.dataone.org/test.ttl', 'features': [ 'http://lod.dataone.org/fulldump' ] } }
Change redirection from change password page to login
/** * 403 Forbidden Network Error Interceptor * * This interceptor redirects to login page when * any 403 session expired error is returned in any of the * network requests */ var LOGIN_ROUTE = '/login'; var SESSION_EXPIRED = 'session_expired'; var subdomainMatch = /https?:\/\/([^.]+)/; module.exports = function (xhr, textStatus, errorThrown) { if (xhr.status !== 403) return; var error = xhr.responseJSON && xhr.responseJSON.error; if (error === SESSION_EXPIRED) { window.location.href = getRedirectURL(); } }; function getRedirectURL () { // We cannot get accountHost and username from configModel // and userModel because of static pages. God save static pages. var username = getUsernameFromURL(location.href); if (!username) { return ''; } var newURL = location.origin.replace(subdomainMatch, function () { return username; }); return location.protocol + '//' + newURL + LOGIN_ROUTE; } function getUsernameFromURL (url) { var usernameMatches = window.location.pathname.split('/'); if (usernameMatches.length > 2) { return usernameMatches[2]; } var subdomainMatches = url.match(subdomainMatch); if (subdomainMatches) { return subdomainMatches[1]; } return ''; }
/** * 403 Forbidden Network Error Interceptor * * This interceptor redirects to login page when * any 403 session expired error is returned in any of the * network requests */ var PASSWORD_CHANGE_ROUTE = '/password_change/'; var SESSION_EXPIRED = 'session_expired'; var subdomainMatch = /https?:\/\/([^.]+)/; module.exports = function (xhr, textStatus, errorThrown) { if (xhr.status !== 403) return; var error = xhr.responseJSON && xhr.responseJSON.error; if (error === SESSION_EXPIRED) { window.location.href = getRedirectURL(); } }; function getRedirectURL () { // We cannot get accountHost and username from configModel // and userModel because of static pages. God save static pages. var username = getUsernameFromURL(location.href); if (!username) { return ''; } var newURL = location.origin.replace(subdomainMatch, function () { return username; }); return location.protocol + '//' + newURL + PASSWORD_CHANGE_ROUTE + username; } function getUsernameFromURL (url) { var usernameMatches = window.location.pathname.split('/'); if (usernameMatches.length > 2) { return usernameMatches[2]; } var subdomainMatches = url.match(subdomainMatch); if (subdomainMatches) { return subdomainMatches[1]; } return ''; }
Set title for SQUASH admin interface
from django.conf.urls import include, url from django.contrib import admin from rest_framework.authtoken.views import obtain_auth_token from rest_framework.routers import DefaultRouter from . import views admin.site.site_header = 'SQUASH Admin' api_router = DefaultRouter() api_router.register(r'jobs', views.JobViewSet) api_router.register(r'metrics', views.MetricViewSet) urlpatterns = [ url(r'^dashboard/admin', include(admin.site.urls)), url(r'^dashboard/api/', include(api_router.urls)), url(r'^dashboard/api/token/', obtain_auth_token, name='api-token'), url(r'^$', views.HomeView.as_view(), name='home'), url(r'^(?P<pk>[a-zA-Z0-9]*$)', views.ListMetricsView.as_view(), name='metrics-list'), ]
from django.conf.urls import include, url from django.contrib import admin from rest_framework.authtoken.views import obtain_auth_token from rest_framework.routers import DefaultRouter from . import views api_router = DefaultRouter() api_router.register(r'jobs', views.JobViewSet) api_router.register(r'metrics', views.MetricViewSet) urlpatterns = [ url(r'^dashboard/admin', include(admin.site.urls)), url(r'^dashboard/api/', include(api_router.urls)), url(r'^dashboard/api/token/', obtain_auth_token, name='api-token'), url(r'^$', views.HomeView.as_view(), name='home'), url(r'^(?P<pk>[a-zA-Z0-9]*$)', views.ListMetricsView.as_view(), name='metrics-list'), ]
Fix reference to DO_STOCKS_LIST environment variable
const stockIndexRegex = /^([^/]+)\/([^/]+)$/; export const STOCK_INDICES = (process.env.STOCK_INDICES || '') .split(',') .map(code => code.match(stockIndexRegex)) .filter(code => code) .reduce((last, [, code, name]) => ({ ...last, [code]: name }), {}); export const DO_STOCKS_LIST = process.env.DO_STOCKS_LIST !== 'false'; export const FAKE_STOCK_PRICES = process.env.FAKE_STOCK_PRICES === 'true'; export const STOCKS_GRAPH_RESOLUTION = 50; export const STOCK_PRICES_DELAY = FAKE_STOCK_PRICES ? 5000 : 10000; // investment rate of return (assumed, per annum) export const FUTURE_INVESTMENT_RATE = 0.1;
const stockIndexRegex = /^([^/]+)\/([^/]+)$/; export const STOCK_INDICES = (process.env.STOCK_INDICES || '') .split(',') .map(code => code.match(stockIndexRegex)) .filter(code => code) .reduce((last, [, code, name]) => ({ ...last, [code]: name }), {}); export const DO_STOCKS_LIST = process.env.SKIP_STOCKS_LIST !== 'true'; export const FAKE_STOCK_PRICES = process.env.FAKE_STOCK_PRICES === 'true'; export const STOCKS_GRAPH_RESOLUTION = 50; export const STOCK_PRICES_DELAY = FAKE_STOCK_PRICES ? 5000 : 10000; // investment rate of return (assumed, per annum) export const FUTURE_INVESTMENT_RATE = 0.1;