text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add config for phemellc/yii2-settings extension
<?php return [ 'vendorPath' => dirname(dirname(__DIR__)) . '/vendor', 'components' => [ 'cache' => [ 'class' => 'yii\caching\FileCache', ], 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, ], 'survey' => [ 'class' => 'common\components\LimeSurvey', 'username' => 'admin', 'password' => 'Samsung_1', 'url' => 'http://elearning.usarb.md/dmc/limesurvey', 'surveyId' => '429785', ], 'settings' => [ 'class' => 'pheme\settings\components\Settings', ], ], 'modules' => [ 'settings' => [ 'class' => 'pheme\settings\Module', ], ], ];
<?php return [ 'vendorPath' => dirname(dirname(__DIR__)) . '/vendor', 'components' => [ 'cache' => [ 'class' => 'yii\caching\FileCache', ], 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, ], 'survey' => [ 'class' => 'common\components\LimeSurvey', 'username' => 'admin', 'password' => 'Samsung_1', 'url' => 'http://elearning.usarb.md/dmc/limesurvey', 'surveyId' => '429785', ] ], ];
Format the code to black
import torchaudio import librosa # resampling reference https://core.ac.uk/download/pdf/228298313.pdf # resampling input transformation defense for audio T = torchaudio.transforms # Read audio file audio_data = librosa.load(files, sr=16000)[0][-19456:] audio_data = torch.tensor(audio_data).float().to(device) # Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation, thereby prevents an adversarial attack. # resample the audio files to 8kHz from 16kHz sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation") audio_resample_1 = sample(audio_data) # resample the audio back to 16kHz sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation") # Give audio_resample_2 as input to the asr model audio_resample_2 = sample(audio_resample_1)
import torchaudio import librosa # resampling reference https://core.ac.uk/download/pdf/228298313.pdf # resampling input transformation defense for audio T = torchaudio.transforms # Read audio file audio_data = librosa.load(files, sr=16000)[0][-19456:] audio_data = torch.tensor(audio_data).float().to(device) # Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation, # thereby prevents an adversarial attack. # resample the audio files to 8kHz from 16kHz sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation") audio_resample_1 = sample(audio_data) # resample the audio back to 16kHz sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation") # Give audio_resample_2 as input to the asr model audio_resample_2 = sample(audio_resample_1)
Make admin feedback easier understandable
<div class="update" data-productname="<?php p($_['productName']) ?>" data-version="<?php p($_['version']) ?>"> <div class="updateOverview"> <h2 class="title"><?php p($l->t('Update needed')) ?></h2> <div class="infogroup"> <?php if ($_['tooBig']) { p($l->t('Your instance possibly hosts many users and files. To ensure a smooth upgrade process, please use the command line updater (occ upgrade).')); } else { p($l->t('Automatic updating was disabled in config.php. To upgrade your instance, please use the command line updater (occ upgrade).')); } ?><br><br> <?php print_unescaped($l->t('For help, see the <a target="_blank" rel="noreferrer" href="%s">documentation</a>.', [link_to_docs('admin-cli-upgrade')])); ?><br><br> </div> </div> </div>
<div class="update" data-productname="<?php p($_['productName']) ?>" data-version="<?php p($_['version']) ?>"> <div class="updateOverview"> <h2 class="title"><?php p($l->t('Update needed')) ?></h2> <div class="infogroup"> <?php if ($_['tooBig']) { p($l->t('Please use the command line updater because you have a big instance.')); } else { p($l->t('Please use the command line updater because automatic updating is disabled in the config.php.')); } ?><br><br> <?php print_unescaped($l->t('For help, see the <a target="_blank" rel="noreferrer" href="%s">documentation</a>.', [link_to_docs('admin-cli-upgrade')])); ?><br><br> </div> </div> </div>
Replace legacy ipython import with jupyter_client
# Configuration file for Jupyter Hub c = get_config() # spawn with Docker c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner' # The docker instances need access to the Hub, so the default loopback port doesn't work: from jupyter_client.localinterfaces import public_ips c.JupyterHub.hub_ip = public_ips()[0] # OAuth with GitHub c.JupyterHub.authenticator_class = 'oauthenticator.GitHubOAuthenticator' c.Authenticator.whitelist = whitelist = set() c.Authenticator.admin_users = admin = set() import os join = os.path.join here = os.path.dirname(__file__) with open(join(here, 'userlist')) as f: for line in f: if not line: continue parts = line.split() name = parts[0] whitelist.add(name) if len(parts) > 1 and parts[1] == 'admin': admin.add(name) c.GitHubOAuthenticator.oauth_callback_url = os.environ['OAUTH_CALLBACK_URL'] # ssl config ssl = join(here, 'ssl') keyfile = join(ssl, 'ssl.key') certfile = join(ssl, 'ssl.cert') if os.path.exists(keyfile): c.JupyterHub.ssl_key = keyfile if os.path.exists(certfile): c.JupyterHub.ssl_cert = certfile
# Configuration file for Jupyter Hub c = get_config() # spawn with Docker c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner' # The docker instances need access to the Hub, so the default loopback port doesn't work: from IPython.utils.localinterfaces import public_ips c.JupyterHub.hub_ip = public_ips()[0] # OAuth with GitHub c.JupyterHub.authenticator_class = 'oauthenticator.GitHubOAuthenticator' c.Authenticator.whitelist = whitelist = set() c.Authenticator.admin_users = admin = set() import os join = os.path.join here = os.path.dirname(__file__) with open(join(here, 'userlist')) as f: for line in f: if not line: continue parts = line.split() name = parts[0] whitelist.add(name) if len(parts) > 1 and parts[1] == 'admin': admin.add(name) c.GitHubOAuthenticator.oauth_callback_url = os.environ['OAUTH_CALLBACK_URL'] # ssl config ssl = join(here, 'ssl') keyfile = join(ssl, 'ssl.key') certfile = join(ssl, 'ssl.cert') if os.path.exists(keyfile): c.JupyterHub.ssl_key = keyfile if os.path.exists(certfile): c.JupyterHub.ssl_cert = certfile
Add blank space for PEP8
import logging from flask_cors import CORS from flask import Flask, json from flask_hal import HAL, HALResponse from chaosmonkey.api.attacks_blueprint import attacks from chaosmonkey.api.executors_blueprint import executors from chaosmonkey.api.planners_blueprint import planners from chaosmonkey.api.plans_blueprint import plans from chaosmonkey.api.api_errors import APIError log = logging.getLogger(__name__) # Create FlaskApp flask_app = Flask("cm_api") HAL(flask_app, HALResponse) CORS(flask_app) # Register blueprints root = "/api/" prev1 = root + "1" flask_app.register_blueprint(executors, url_prefix=prev1 + "/executors") flask_app.register_blueprint(plans, url_prefix=prev1 + "/plans") flask_app.register_blueprint(attacks, url_prefix=prev1 + "/attacks") flask_app.register_blueprint(planners, url_prefix=prev1 + "/planners") # Register error handler for custom APIError exception @flask_app.errorhandler(APIError) def handle_invalid_usage(error): """ Handler for APIErrors thrown by API endpoints """ log.info('%d %s', error.status_code, error.message) response = json.jsonify(error.to_dict()) response.status_code = error.status_code return response
import logging from flask_cors import CORS from flask import Flask, json from flask_hal import HAL, HALResponse from chaosmonkey.api.attacks_blueprint import attacks from chaosmonkey.api.executors_blueprint import executors from chaosmonkey.api.planners_blueprint import planners from chaosmonkey.api.plans_blueprint import plans from chaosmonkey.api.api_errors import APIError log = logging.getLogger(__name__) # Create FlaskApp flask_app = Flask("cm_api") HAL(flask_app, HALResponse) CORS(flask_app) # Register blueprints root = "/api/" prev1 = root + "1" flask_app.register_blueprint(executors, url_prefix=prev1 + "/executors") flask_app.register_blueprint(plans, url_prefix=prev1 + "/plans") flask_app.register_blueprint(attacks, url_prefix=prev1 + "/attacks") flask_app.register_blueprint(planners, url_prefix=prev1 + "/planners") # Register error handler for custom APIError exception @flask_app.errorhandler(APIError) def handle_invalid_usage(error): """ Handler for APIErrors thrown by API endpoints """ log.info('%d %s', error.status_code, error.message) response = json.jsonify(error.to_dict()) response.status_code = error.status_code return response
Fix a typo in the documentation.
package oplogc import "time" type Operation struct { // ID holds the operation id used to resume the streaming in case of connection failure. ID string // Event is the kind of operation. It can be insert, update or delete. Event string // Data holds the operation metadata. Data *OperationData ack chan<- Operation } // OperationData is the data part of the SSE event for the operation. type OperationData struct { // ID is the object id. ID string `json:"id"` // Type is the object type. Type string `json:"type"` // Ref contains the URL to fetch to object refered by the operation. This field may // not be present if the oplog server is not configured to generate this field. Ref string `json:"ref,omitempty"` // Timestamp is the time when the operation happened. Timestamp time.Time `json:"timestamp"` // Parents is a list of strings describing the objects related to the object // refered by the operation. Parents []string `json:"parents"` } // Done must be called once the operation has been processed by the consumer func (o *Operation) Done() { o.ack <- *o }
package oplogc import "time" type Operation struct { // ID holds the operation id used to resume the streaming in case of connection failure. ID string // Event is the kind of operation. I can be one of insert, update or delete. Event string // Data holds the operation metadata. Data *OperationData ack chan<- Operation } // OperationData is the data part of the SSE event for the operation. type OperationData struct { // ID is the object id. ID string `json:"id"` // Type is the object type. Type string `json:"type"` // Ref contains the URL to fetch to object refered by the operation. This field may // not be present if the oplog server is not configured to generate this field. Ref string `json:"ref,omitempty"` // Timestamp is the time when the operation happened. Timestamp time.Time `json:"timestamp"` // Parents is a list of strings describing the objects related to the object // refered by the operation. Parents []string `json:"parents"` } // Done must be called once the operation has been processed by the consumer func (o *Operation) Done() { o.ack <- *o }
OAK-15: Clean up oak-jcr - formatting git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1301494 13f79535-47bb-0310-9956-ffa450edef68
package org.apache.jackrabbit.oak.jcr.state; import org.apache.jackrabbit.oak.jcr.json.JsonValue; import org.apache.jackrabbit.oak.model.AbstractPropertyState; public class PropertyStateImpl extends AbstractPropertyState { private final String name; private final JsonValue value; public PropertyStateImpl(String name, JsonValue value) { this.name = name; this.value = value; } public JsonValue getValue() { return value; } @Override public String getName() { return name; } @Override public String getEncodedValue() { return value.toJson(); } @Override public String toString() { return name + ':' + getEncodedValue(); } }
package org.apache.jackrabbit.oak.jcr.state; import org.apache.jackrabbit.oak.jcr.json.JsonValue; import org.apache.jackrabbit.oak.model.AbstractPropertyState; public class PropertyStateImpl extends AbstractPropertyState { private final String name; private final JsonValue value; public PropertyStateImpl(String name, JsonValue value) { this.name = name; this.value = value; } public JsonValue getValue() { return value; } @Override public String getName() { return name; } @Override public String getEncodedValue() { return value.toJson(); } @Override public String toString() { return name + ':' + getEncodedValue(); } }
Fix some logic and deferred creation bugs
var Stirrup = function(library) { if(typeof library !== 'object' && typeof library !== 'function') { throw 'You must provide Stirrup with a promise library'; } this.library = library; this.isNative = (typeof Promise === 'function' && Promise.toString().indexOf('[native code]') > -1); var constructor = this.getConstructor(); this.buildDefer(constructor); this.buildStaticFunctions(); return constructor; }; Stirrup.prototype.getConfig = function() { //@@config return config; }; Stirrup.prototype.getConstructor = function() { if(!this.isNative) { return this.getConfig().constructor ? this.library[this.getConfig().constructor] : this.library; } else { return Promise; } }; Stirrup.prototype.buildDefer = function(constructor) { var config = this.getConfig(); if(!this.isNative && config.defer) { constructor.defer = this.library[config.defer]; } else { //TODO: Promise inspection capability //https://github.com/petkaantonov/bluebird/blob/master/API.md#inspect---promiseinspection var defer = function() { var fulfill, reject; var promise = new constructor(function(f, r) { fulfill = f; reject = r; }); return { fulfill: fulfill, reject: reject, promise: promise } }; constructor.defer = defer; } };
var Stirrup = function(library) { if(typeof library !== 'object' && typeof library !== 'function') { throw 'You must provide Stirrup with a promise library'; } this.library = library; this.isNative = (typeof Promise === 'function' && Promise.toString().indexOf('[native code]') > -1); var constructor = this.getConstructor(); this.buildDefer(constructor); this.buildStaticFunctions(); return constructor; }; Stirrup.prototype.getConfig = function() { //@@config return config; }; Stirrup.prototype.getConstructor = function() { if(!this.isNative) { return this.getConfig().constructor ? this.library[this.getConfig().constructor] : this.library; } else { return this.library; } }; Stirrup.prototype.buildDefer = function(constructor) { var config = this.getConfig(); if(!this.isNative && config.defer) { this.defer = this.library[config.defer]; } else { //TODO: Promise inspection capability //https://github.com/petkaantonov/bluebird/blob/master/API.md#inspect---promiseinspection this.defer = function() { var fulfill, reject; var promise = new constuctor(function(f, r) { fulfill = f; reject = r; }); return { fulfill: fulfill, reject: reject, promise: promise } } } };
Fix bug in get_offsets with span == 1 Very specific bug made span of 1 include center (start) point.
from __future__ import division import itertools def get_offsets(span): """ Get matrix offsets for a square of distance `span`. """ if span < 0: raise ValueError('Cannot return neighbours for negative distance') all_offsets = set(itertools.product([x for x in range(-span, span + 1)], repeat=2)) if span >= 1: inner_offsets = set(itertools.product([x for x in range(-(span - 1), span)], repeat=2)) else: inner_offsets = set() return all_offsets - inner_offsets def find_neighbours_2D(array, start, span): """ Return neighbours in a 2D array, given a start point and range. """ x, y = start # Start coords rows = len(array) # How many rows cols = len(array[0]) # Assume square matrix return def new(size, value=None): """ Initialize a new square matrix. """ return [[value] * size for _ in range(size)]
from __future__ import division import itertools def get_offsets(span): """ Get matrix offsets for a square of distance `span`. """ if span < 0: raise ValueError('Cannot return neighbours for negative distance') all_offsets = set(itertools.product([x for x in range(-span, span + 1)], repeat=2)) if span > 1: inner_offsets = set(itertools.product([x for x in range(-(span - 1), span)], repeat=2)) else: inner_offsets = set() return all_offsets - inner_offsets def find_neighbours_2D(array, start, span): """ Return neighbours in a 2D array, given a start point and range. """ x, y = start # Start coords rows = len(array) # How many rows cols = len(array[0]) # Assume square matrix return def new(size, value=None): """ Initialize a new square matrix. """ return [[value] * size for _ in range(size)]
Fix bug of not stopping algorithm in time.
import numpy """ Board represents a four in a row game board. Author: Isaac Arvestad """ class Board: """ Initializes the game with a certain number of rows and columns. """ def __init__(self, rows, columns): self.rows = rows self.columns = columns self.boardMatrix = numpy.zeros((rows, columns)) """ Attempts to add a piece to a certain column. If the column is full the move is illegal and false is returned, otherwise true is returned. """ def addPiece(self, column, value): "Check if column is full." if self.boardMatrix.item(0,column) != 0: return False "Place piece." for y in range(self.rows): if y == self.rows - 1: # Reached bottom self.boardMatrix.itemset((y, column), value) break elif self.boardMatrix.item(y + 1, column) == 0: # Next row is also empty continue else: # Next row is not empty self.boardMatrix.itemset((y, column), value) break return True
import numpy """ Board represents a four in a row game board. Author: Isaac Arvestad """ class Board: """ Initializes the game with a certain number of rows and columns. """ def __init__(self, rows, columns): self.rows = rows self.columns = columns self.boardMatrix = numpy.zeros((rows, columns)) """ Attempts to add a piece to a certain column. If the column is full the move is illegal and false is returned, otherwise true is returned. """ def addPiece(self, column, value): "Check if column is full." if self.boardMatrix.item(0,column) != 0: return False "Place piece." for y in range(self.rows): if y == self.rows - 1: # Reached bottom self.boardMatrix.itemset((y, column), value) elif self.boardMatrix.item(y + 1, column) == 0: # Next row is also empty continue else: # Next row is not empty self.boardMatrix.itemset((y, column), value) return True
Set interval to 5 seconds instead of 10
"use strict"; let https = require('https'); let keys = require("./secretKeys.js"); exports.init = function (mainCallback) { let options = { host: "api.carriots.com", path: "/streams/?max=1&order=-1", port: 443, method: "GET", headers: { "Accept": "application/json", "carriots.apiKey": keys.CARRIOTS_APIKEY, "Connection": "keep-alive", "Content-Type": "application/json", "Host": "api.carriots.com" } }; setInterval(function () { let req = https.request(options, (res) => { res.on('data', (chunk) => { let body = []; body.push(chunk); let msg = JSON.parse(body.toString()); if (undefined !== msg && undefined !== msg.result) { let data = msg.result[0].data; mainCallback(data.sender, data.quantity, "Carriots"); } }); }); req.on('error', (e) => { console.error(e); }); req.end(); }, 5000); };
"use strict"; let https = require('https'); let keys = require("./secretKeys.js"); exports.init = function (mainCallback) { let options = { host: "api.carriots.com", path: "/streams/?max=1&order=-1", port: 443, method: "GET", headers: { "Accept": "application/json", "carriots.apiKey": keys.CARRIOTS_APIKEY, "Connection": "keep-alive", "Content-Type": "application/json", "Host": "api.carriots.com" } }; setInterval(function () { let req = https.request(options, (res) => { res.on('data', (chunk) => { let body = []; body.push(chunk); let msg = JSON.parse(body.toString()); if (undefined !== msg && undefined !== msg.result) { let data = msg.result[0].data; mainCallback(data.sender, data.quantity, "Carriots"); } }); }); req.on('error', (e) => { console.error(e); }); req.end(); }, 10000); };
Update the cytoscape alias to `cytoscape/src/cjs` This updates the cytoscape alias with the recent changes to the cytoscape build system. When you pull this commit into your local copy, make sure to `npm i cytoscape` to make sure your cytoscape dependency is in-sync. Note that when we make merges to master for releases, we should lock down the commit that the cytoscape dependecy points to. This would ensure that prod builds are always the same.
const webpack = require('webpack'); const { env } = require('process'); const isProd = env.NODE_ENV === 'production'; const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); const isNonNil = x => x != null; const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; const isProfile = env.PROFILE == 'true'; let conf = { entry: './src/client/index.js', output: { filename: './build/bundle.js' }, devtool: 'inline-source-map', module: { rules: [ { test: /node_modules\/cytoscape\/.*/, loader: 'babel-loader'}, { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' } ] }, resolve: { alias: { cytoscape: 'cytoscape/src/cjs' } }, plugins: [ isProfile ? new BundleAnalyzerPlugin() : null, new webpack.EnvironmentPlugin(['NODE_ENV']), new webpack.optimize.CommonsChunkPlugin({ name: 'deps', filename: './build/deps.js', minChunks( module ){ let context = module.context || ''; return context.indexOf('node_modules') >= 0; } }), isProd ? new UglifyJSPlugin() : null ].filter( isNonNil ) }; module.exports = conf;
const webpack = require('webpack'); const { env } = require('process'); const isProd = env.NODE_ENV === 'production'; const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); const isNonNil = x => x != null; const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; const isProfile = env.PROFILE == 'true'; let conf = { entry: './src/client/index.js', output: { filename: './build/bundle.js' }, devtool: 'inline-source-map', module: { rules: [ { test: /node_modules\/cytoscape\/.*/, loader: 'babel-loader'}, { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' } ] }, resolve: { alias: { cytoscape: 'cytoscape/src/umd' } }, plugins: [ isProfile ? new BundleAnalyzerPlugin() : null, new webpack.EnvironmentPlugin(['NODE_ENV']), new webpack.optimize.CommonsChunkPlugin({ name: 'deps', filename: './build/deps.js', minChunks( module ){ let context = module.context || ''; return context.indexOf('node_modules') >= 0; } }), isProd ? new UglifyJSPlugin() : null ].filter( isNonNil ) }; module.exports = conf;
Adjust with the latest Configo
package main import ( // standard pkgs "fmt" "html/template" "log" "net/http" // non standard pkgs "github.com/bpdp/configo" ) type Config struct { Title string Port string } func handler(w http.ResponseWriter, req *http.Request) { t, err := template.ParseFiles("templates/default.tpl") if err != nil { log.Fatal(err) } type Person struct { Name string //exported field since it begins with a capital letter } p := Person{Name: "bpdp"} t.Execute(w, p) } func main() { var cnf Config if err := configo.ReadConfig("conf/lapmachine.toml", &cnf); err != nil { fmt.Println("Config Load Error: %g", err) } http.HandleFunc("/display", handler) http.Handle("/", http.FileServer(http.Dir("assets/"))) fmt.Println(cnf.Title + " serving http request at port " + cnf.Port) http.ListenAndServe(cnf.Port, nil) }
package main import ( // standard pkgs "fmt" "html/template" "log" "net/http" // non standard pkgs "github.com/bpdp/configo" ) func handler(w http.ResponseWriter, req *http.Request) { t, err := template.ParseFiles("templates/default.tpl") if err != nil { log.Fatal(err) } type Person struct { Name string //exported field since it begins with a capital letter } p := Person{Name: "bpdp"} t.Execute(w, p) } func main() { var config = configo.ReadConfig("conf/lapmachine.toml") http.HandleFunc("/display", handler) http.Handle("/", http.FileServer(http.Dir("assets/"))) fmt.Println("Serving http request at port " + config.Port) http.ListenAndServe(config.Port, nil) }
Remove unneeded name, add needed @Transaction* annotations. Even on the findCustomer method. EclipseLink is picky (right
package session; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import domain.Customer; import domain.Order; @Stateless @TransactionManagement(TransactionManagementType.CONTAINER) public class XaJpaDemoBean { @PersistenceContext(name="customer") EntityManager customerEntityManager; @PersistenceContext(name="orders") EntityManager orderEntityManager; @TransactionAttribute(TransactionAttributeType.REQUIRED) public Customer findCustomer(int id) { return customerEntityManager.find(Customer.class, id); } @TransactionAttribute(TransactionAttributeType.REQUIRED) public void saveCustomerOrder(Customer c, Order o, Boolean succeeds) { System.out.println("XaJpaDemoBean.saveCustomerOrder()"); try { // Update the customer entity in the database. c.setNumberOfOrders(c.getNumberOfOrders() + 1); System.out.println("XaJpaDemoBean.saveCustomerOrder(): Updated Customer with Id " + c.getId()); // Insert the order entity in the database. orderEntityManager.persist(o); System.out.println("XaJpaDemoBean.saveCustomerOrder(): Created order with Id " + o.getId()); } finally { if (!succeeds) { throw new RuntimeException("XaJpaDemoBean.saveCustomerOrder(): Simulated failure!"); } } } }
package session; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import domain.Customer; import domain.Order; @Stateless(name="XaJpaDemoBean") public class XaJpaDemoBean { @PersistenceContext(name="customer") EntityManager customerEntityManager; @PersistenceContext(name="orders") EntityManager orderEntityManager; public Customer findCustomer(int id) { return customerEntityManager.find(Customer.class, id); } public void saveCustomerOrder(Customer c, Order o, Boolean succeeds) { System.out.println("XaJpaDemoBean.saveCustomerOrder()"); try { // Update the customer entity in the database. c.setNumberOfOrders(c.getNumberOfOrders() + 1); System.out.println("XaJpaDemoBean.saveCustomerOrder(): Updated Customer with Id " + c.getId()); // Insert the order entity in the database. orderEntityManager.persist(o); System.out.println("XaJpaDemoBean.saveCustomerOrder(): Created order with Id " + o.getId()); } finally { if (!succeeds) { throw new RuntimeException("XaJpaDemoBean.saveCustomerOrder(): Simulated failure!"); } } } }
Revert "Don't throw an exception when pygments fails to highlight." This reverts commit 32def91d2c9b5b25418ca59884b4f00ff3849b9d. epriestley's fix is live!
<?php final class PhutilDefaultSyntaxHighlighterEnginePygmentsFuture extends FutureProxy { private $source; private $scrub; public function __construct(Future $proxied, $source, $scrub = false) { parent::__construct($proxied); $this->source = $source; $this->scrub = $scrub; } protected function didReceiveResult($result) { list($status, $body, $headers) = $result; if (!$status->isError() && strlen($body)) { // Strip off fluff Pygments adds. $body = preg_replace( '@^<div class="highlight"><pre>(.*)</pre></div>\s*$@s', '\1', $body); if ($this->scrub) { $body = preg_replace('/^.*\n/', '', $body); } return phutil_safe_html($body); } throw new PhutilSyntaxHighlighterException($body, $status->getStatusCode()); } }
<?php final class PhutilDefaultSyntaxHighlighterEnginePygmentsFuture extends FutureProxy { private $source; private $scrub; public function __construct(Future $proxied, $source, $scrub = false) { parent::__construct($proxied); $this->source = $source; $this->scrub = $scrub; } protected function didReceiveResult($result) { list($status, $body, $headers) = $result; if (!$status->isError() && strlen($body)) { // Strip off fluff Pygments adds. $body = preg_replace( '@^<div class="highlight"><pre>(.*)</pre></div>\s*$@s', '\1', $body); if ($this->scrub) { $body = preg_replace('/^.*\n/', '', $body); } return phutil_safe_html($body); } // TODO(csilvers): remove this `return`, and go back to the throw, // once epriestley has resolved https://admin.phacility.com/PHI1764 return id(new PhutilDefaultSyntaxHighlighter())->getHighlightFuture($this->source)->resolve(); // throw new PhutilSyntaxHighlighterException($body, $status->getStatusCode()); } }
Update intent actions to use assistant SID inline Maintaining consistency with the auto-generated code samples for Understand, which don't allow for our variable-named placeholder values
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) # Provide actions for your assistant: say something and listen for a repsonse. update_action = { 'actions': [ {'say': 'Hi there, I\'m your virtual assistant! How can I help you?'}, {'listen': True} ] } # Update the default intent to use your new actions. # Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/assistant/list client.preview.understand \ .assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .intents('hello-world') \ .intent_actions().update(update_action) print("Intent actions updated")
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) assistant_sid = 'UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Provide actions for your assistant: say something and listen for a repsonse. update_action = { 'actions': [ {'say': 'Hi there, I\'m your virtual assistant! How can I help you?'}, {'listen': True} ] } # Update the default intent to use your new actions. client.preview.understand \ .assistants(assistant_sid) \ .intents('hello-world') \ .intent_actions().update(update_action) print("Intent actions updated")
Set URL submission score cutoff to 4.
#encoding:utf-8 from urllib.parse import urlparse from utils import get_url t_channel = '@ya_metro' subreddit = 'Subways' def send_post(submission, r2t): what, url, ext = get_url(submission) title = submission.title link = submission.shortlink text = '{}\n{}'.format(title, link) if what == 'text': return False elif what == 'album': base_url = submission.url text = '{}\n{}\n\n{}'.format(title, base_url, link) r2t.send_text(text) r2t.send_album(url) return True elif what == 'other': domain = urlparse(url).netloc if domain in ('www.youtube.com', 'youtu.be'): text = '{}\n{}\n\n{}'.format(title, url, link) return r2t.send_text(text) elif submission.score >= 4: text = '{}\n{}\n\n{}'.format(title, url, link) return r2t.send_text(text) else: return False elif what in ('gif', 'img'): return r2t.send_gif_img(what, url, ext, text) else: return False
#encoding:utf-8 from urllib.parse import urlparse from utils import get_url t_channel = '@ya_metro' subreddit = 'Subways' def send_post(submission, r2t): what, url, ext = get_url(submission) title = submission.title link = submission.shortlink text = '{}\n{}'.format(title, link) if what == 'text': return False elif what == 'album': base_url = submission.url text = '{}\n{}\n\n{}'.format(title, base_url, link) r2t.send_text(text) r2t.send_album(url) return True elif what == 'other': domain = urlparse(url).netloc if domain in ('www.youtube.com', 'youtu.be'): text = '{}\n{}\n\n{}'.format(title, url, link) return r2t.send_text(text) elif submission.score > 10: text = '{}\n{}\n\n{}'.format(title, url, link) return r2t.send_text(text) else: return False elif what in ('gif', 'img'): return r2t.send_gif_img(what, url, ext, text) else: return False
Remove commented line we definitely will never need
import sys import json import requests from string import Template import dateutil.parser def posts_at_url(url): current_page = 1 max_page = sys.maxint while current_page <= max_page: resp = requests.get(url, params={'json':1,'page':current_page}) results = json.loads(resp.content) current_page += 1 max_page = results['pages'] for p in results['posts']: yield p def documents(name, url, **kwargs): for post in posts_at_url(url): yield process_post(post) def process_post(post): del post['comments'] post['_id'] = post['slug'] # remove fields we're not interested in post['category'] = [cat['title'] for cat in post['taxonomy_fj_category']] post['tags'] = [tag['title'] for tag in post['taxonomy_fj_tag']] author_template = Template("$first_name $last_name") post['author'] = [author['title'] for author in post['taxonomy_author']] dt = dateutil.parser.parse(post['date']) dt_string = dt.strftime('%Y-%m-%dT%H:%M:%SZ') post['date'] = dt_string return post
import sys import json import requests from string import Template import dateutil.parser def posts_at_url(url): current_page = 1 max_page = sys.maxint while current_page <= max_page: resp = requests.get(url, params={'json':1,'page':current_page}) results = json.loads(resp.content) current_page += 1 max_page = results['pages'] for p in results['posts']: yield p def documents(name, url, **kwargs): for post in posts_at_url(url): yield process_post(post) def process_post(post): del post['comments'] # del post['content'] post['_id'] = post['slug'] # remove fields we're not interested in post['category'] = [cat['title'] for cat in post['taxonomy_fj_category']] post['tags'] = [tag['title'] for tag in post['taxonomy_fj_tag']] author_template = Template("$first_name $last_name") post['author'] = [author['title'] for author in post['taxonomy_author']] dt = dateutil.parser.parse(post['date']) dt_string = dt.strftime('%Y-%m-%dT%H:%M:%SZ') post['date'] = dt_string return post
Fix accessing the user agent string in newer FastBoot versions
import Service from '@ember/service'; import { computed, get, getProperties, set } from '@ember/object'; import { getOwner } from '@ember/application'; import { isBlank } from '@ember/utils'; import isMobile from 'ismobilejs'; export default Service.extend({ fastboot: computed(function() { return getOwner(this).lookup('service:fastboot'); }), init() { this._super(...arguments); let queries = []; if (get(this, 'fastboot.isFastBoot')) { const headers = get(this, 'fastboot.request.headers'); let userAgent = get(headers, 'headers.user-agent')[0]; if (isBlank(userAgent)) { return; } queries = getProperties( isMobile(userAgent), ['any', 'phone', 'tablet', 'apple', 'android', 'amazon', 'windows', 'seven_inch', 'other'] ); } else { queries = isMobile; } for (let media in queries) { set(this, media, queries[media]); } } });
import Service from '@ember/service'; import { computed, get, getProperties, set } from '@ember/object'; import { getOwner } from '@ember/application'; import isMobile from 'ismobilejs'; export default Service.extend({ fastboot: computed(function() { return getOwner(this).lookup('service:fastboot'); }), init() { this._super(...arguments); let queries = []; if (get(this, 'fastboot.isFastBoot')) { const headers = get(this, 'fastboot.request.headers'); const userAgent = get(headers, 'user-agent'); if (userAgent) { queries = getProperties( isMobile(userAgent), ['any', 'phone', 'tablet', 'apple', 'android', 'amazon', 'windows', 'seven_inch', 'other'] ); } } else { queries = isMobile; } for (let media in queries) { set(this, media, queries[media]); } } });
Revert database password policy while problems with keyring investigated
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from random import choice from string import ascii_letters, digits import secretstorage from keyring import set_password, get_password __author__ = 'Shamal Faily' def setDatabasePassword(dbUser): # rp = ''.join(choice(ascii_letters + digits) for i in range(32)) # set_password('cairisdb',dbUser,rp) # return rp return '' def getDatabasePassword(dbUser): # return get_password('cairisdb',dbUser) return ''
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from random import choice from string import ascii_letters, digits import secretstorage from keyring import set_password, get_password __author__ = 'Shamal Faily' def setDatabasePassword(dbUser): rp = ''.join(choice(ascii_letters + digits) for i in range(32)) set_password('cairisdb',dbUser,rp) return rp def getDatabasePassword(dbUser): return get_password('cairisdb',dbUser)
Test OC_User_Database in Test_User_Database instead of OC_User_Dummy.
<?php /** * ownCloud * * @author Robin Appelman * @copyright 2012 Robin Appelman icewind@owncloud.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ class Test_User_Database extends Test_User_Backend { /** * get a new unique user name * test cases can override this in order to clean up created user * @return array */ public function getUser() { $user=uniqid('test_'); $this->users[]=$user; return $user; } public function setUp() { $this->backend=new OC_User_Database(); } public function tearDown() { foreach($this->users as $user) { $this->backend->deleteUser($user); } } }
<?php /** * ownCloud * * @author Robin Appelman * @copyright 2012 Robin Appelman icewind@owncloud.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ class Test_User_Database extends Test_User_Backend { /** * get a new unique user name * test cases can override this in order to clean up created user * @return array */ public function getUser() { $user=uniqid('test_'); $this->users[]=$user; return $user; } public function setUp() { $this->backend=new OC_User_Dummy(); } public function tearDown() { foreach($this->users as $user) { $this->backend->deleteUser($user); } } }
:art: Add selected attribute to message type
'use babel' /* @flow */ export type Atom$Point = [number, number] export type Atom$Range = [Atom$Point, Atom$Point] | {start: {row: number, column: number}, end: {row: number, column: number}} export type Linter$Message = { key: string, type: string, text?: string, html?: string, name?: ?string, range?: Atom$Range, trace?: Array<Linter$Message>, severity: 'error' | 'warning' | 'info', filePath?: string, selected?: ((message: Linter$Message) => void) } export type Linter$State = {} export type Linter$Linter = { name?: string, number: number, deactivated: boolean, scope: 'file' | 'project', } export type Linter$Regular = Linter$Linter & { grammarScopes: Array<string>, lint: Function } export type Linter$Indie = Linter$Linter & { } export type Linter$Difference = { added: Array<Linter$Message>, removed: Array<Linter$Message>, messages: Array<Linter$Message> } export type Linter$UI = { name?: string, activate(): void, didCalculateMessages(difference: Linter$Difference): void, didBeginLinting(linter: Linter$Regular, filePath: ?string): void, didFinishLinting(linter: Linter$Regular, filePath: ?string): void, dispose(): void }
'use babel' /* @flow */ export type Atom$Point = [number, number] export type Atom$Range = [Atom$Point, Atom$Point] | {start: {row: number, column: number}, end: {row: number, column: number}} export type Linter$Message = { key: string, type: string, text?: string, html?: string, name?: ?string, range?: Atom$Range, trace?: Array<Linter$Message>, severity: 'error' | 'warning' | 'info', filePath?: string } export type Linter$State = {} export type Linter$Linter = { name?: string, number: number, deactivated: boolean, scope: 'file' | 'project', } export type Linter$Regular = Linter$Linter & { grammarScopes: Array<string>, lint: Function } export type Linter$Indie = Linter$Linter & { } export type Linter$Difference = { added: Array<Linter$Message>, removed: Array<Linter$Message>, messages: Array<Linter$Message> } export type Linter$UI = { name?: string, activate(): void, didCalculateMessages(difference: Linter$Difference): void, didBeginLinting(linter: Linter$Regular, filePath: ?string): void, didFinishLinting(linter: Linter$Regular, filePath: ?string): void, dispose(): void }
Fix TraceSampler for Console Commands The array key 'route' doesn't always exist which them emits a PHP warning, fixed with a check.
<?php declare(strict_types=1); namespace App\Service; use Sentry\Tracing\SamplingContext; class SentryTraceSampler { private const SKIP_ROUTES = ['app_ics_geticsfeed', 'app_download_downloadmaterials']; /** * Don't sample ICS or LM transactions as they are very noisy * everything else we sample 10% of */ public function getTracesSampler(): callable { return function (SamplingContext $context): float { $tags = $context->getTransactionContext()->getTags(); if (array_key_exists('route', $tags) && in_array($tags['route'], self::SKIP_ROUTES)) { return 0; } return 0.1; }; } }
<?php declare(strict_types=1); namespace App\Service; use Sentry\Tracing\SamplingContext; class SentryTraceSampler { private const SKIP_ROUTES = ['app_ics_geticsfeed', 'app_download_downloadmaterials']; /** * Don't sample ICS or LM transactions as they are very noisy * everything else we sample 10% of */ public function getTracesSampler(): callable { return function (SamplingContext $context): float { $tags = $context->getTransactionContext()->getTags(); if (in_array($tags['route'], self::SKIP_ROUTES)) { return 0; } return 0.1; }; } }
Update extract language package to use inner delete commands to reduce the amount of space used at any given point in time.
import optparse import os import glob optparser = optparse.OptionParser() optparser.add_option("-f", "--filename", dest="filename", help="Language package file") optparser.add_option("-d", "--destination", dest="destination", help="Base destination folder") optparser.add_option("-l", "--language", dest="language", help="Language to un-package") (opts, _) = optparser.parse_args() full_destination_path = opts.destination + "/" + opts.language if not os.path.exists(full_destination_path): os.makedirs(full_destination_path) outer_untar_command = "tar -xvf " + opts.filename + " -C " + full_destination_path print(outer_untar_command) os.system(outer_untar_command) for inner_filename in glob.glob(full_destination_path+"/*.tar.gz"): inner_untar_command = "tar -xvzf " + inner_filename + " -C " + full_destination_path print(inner_untar_command) os.system(inner_untar_command) inner_delete_command = "rm " + inner_filename print(inner_delete_command) os.system(inner_delete_command)
import optparse import os import glob optparser = optparse.OptionParser() optparser.add_option("-f", "--filename", dest="filename", help="Language package file") optparser.add_option("-d", "--destination", dest="destination", help="Base destination folder") optparser.add_option("-l", "--language", dest="language", help="Language to un-package") (opts, _) = optparser.parse_args() full_destination_path = opts.destination + "/" + opts.language if not os.path.exists(full_destination_path): os.makedirs(full_destination_path) outer_untar_command = "tar -xvf " + opts.filename + " -C " + full_destination_path print(outer_untar_command) os.system(outer_untar_command) for inner_filename in glob.glob(full_destination_path+"/*.tar.gz"): inner_untar_command = "tar -xvzf " + inner_filename + " -C " + full_destination_path print(inner_untar_command) os.system(inner_untar_command) delete_intermediate_files_command = "rm " + full_destination_path + "/*.tar.gz" print(delete_intermediate_files_command) os.system(delete_intermediate_files_command)
Add listen to all events
const chokidar = require("chokidar"); const log = require("./services/logger.service"); const FileIndex = require("./util/fileIndex"); const FileRecognizer = require("./util/fileRecognizer"); const options = require("./util/cmdargs").parseArguments(); const Publisher = require("./amqp/publisher"); const Generator = require("./util/messageGenerator"); const fs = require("fs"); const generator = new Generator(options); const publisher = new Publisher(options); const fileindex = new FileIndex(options, new FileRecognizer(options), publisher, generator); log.success('Watching folder: ' + options.folder); chokidar.watch(options.folder, { ignored: (path) => { // Ignore sub-folders return RegExp(options.folder + '.+/').test(path) }, awaitWriteFinish: { stabilityThreshold: 2000, pollInterval: 500 }, usePolling: true, interval: 500, binaryInterval: 500, useFsEvents: true }) .on('add', (path) => { fileindex.add_file(path, fileindex.determine_file_type(path, options), options, publisher, generator); }) .on('all', (event, path) => { console.log('ALL: ', event, ' - ', path); });
const chokidar = require("chokidar"); const log = require("./services/logger.service"); const FileIndex = require("./util/fileIndex"); const FileRecognizer = require("./util/fileRecognizer"); const options = require("./util/cmdargs").parseArguments(); const Publisher = require("./amqp/publisher"); const Generator = require("./util/messageGenerator"); const fs = require("fs"); const generator = new Generator(options); const publisher = new Publisher(options); const fileindex = new FileIndex(options, new FileRecognizer(options), publisher, generator); log.success('Watching folder: ' + options.folder); chokidar.watch(options.folder, { ignored: (path) => { // Ignore sub-folders return RegExp(options.folder + '.+/').test(path) }, awaitWriteFinish: { stabilityThreshold: 2000, pollInterval: 500 }, usePolling: true, interval: 500, binaryInterval: 500, useFsEvents: true }) .on('add', (path) => { log.info('RECEIVED EVENT FOR FILE', path); fileindex.add_file(path, fileindex.determine_file_type(path, options), options, publisher, generator); }) .on('raw', (event, path, details) => { console.log('Raw event info:', event, path, details); });
Remove container/list as per suggestions from @pnelson
package main import ( "bytes" "encoding/json" "log" "os/exec" "strings" "time" ) // Stat represents stats to send to graphite type Stat struct { Key string `json:"key"` Value string `json:"value"` DT int64 `json:"dt"` } func main() { var stats []Stat var out bytes.Buffer cmd := exec.Command("typeperf", "-sc", "1", "processor(_total)\\% processor time") cmd.Stdout = &out err := cmd.Run() if err != nil { log.Fatal(err) } chunks := strings.Split(out.String(), ",") chunks = strings.Split(chunks[2], "\"") stat := Stat{"cpu", chunks[1], time.Now().Unix()} stats = append(stats, stat) b, err := json.Marshal(stat) log.Printf("Output: %s", string(b)) }
package main import ( "bytes" "container/list" "encoding/json" "log" "os/exec" "strings" "time" ) // Stat represents stats to send to graphite type Stat struct { Key string `json:"key"` Value string `json:"value"` DT int64 `json:"dt"` } func main() { stats := list.New() var out bytes.Buffer cmd := exec.Command("typeperf", "-sc", "1", "processor(_total)\\% processor time") cmd.Stdout = &out err := cmd.Run() if err != nil { log.Fatal(err) } chunks := strings.Split(out.String(), ",") chunks = strings.Split(chunks[2], "\"") stat := Stat{"cpu", chunks[1], time.Now().Unix()} stats.PushBack(stat) b, err := json.Marshal(stat) log.Printf("Output: %s", string(b)) }
Remove extra text per pull request comment.
package hudson.plugins.git.extensions.impl; import hudson.Extension; import hudson.Util; import hudson.plugins.git.extensions.FakeGitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionDescriptor; import org.kohsuke.stapler.DataBoundConstructor; /** * The Git plugin checks code out to a detached head. Configure * LocalBranch to force checkout to a specific local branch. * Configure this extension as null or as "**" to signify that * the local branch name should be the same as the remote branch * name sans the remote repository prefix (origin for example). * * @author Kohsuke Kawaguchi */ public class LocalBranch extends FakeGitSCMExtension { private String localBranch; @DataBoundConstructor public LocalBranch(String localBranch) { this.localBranch = Util.fixEmptyAndTrim(localBranch); } public String getLocalBranch() { return localBranch; } @Extension public static class DescriptorImpl extends GitSCMExtensionDescriptor { @Override public String getDisplayName() { return "Check out to specific local branch"; } } }
package hudson.plugins.git.extensions.impl; import hudson.Extension; import hudson.Util; import hudson.plugins.git.extensions.FakeGitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionDescriptor; import org.kohsuke.stapler.DataBoundConstructor; /** * The Git plugin checks code out to a detached head. Configure * LocalBranch to force checkout to a specific local branch. * Configure this extension as null or as "**" to signify that * the local branch name should be the same as the remote branch * name sans the remote repository prefix (origin for example). * * @author Kohsuke Kawaguchi */ public class LocalBranch extends FakeGitSCMExtension { private String localBranch; @DataBoundConstructor public LocalBranch(String localBranch) { this.localBranch = Util.fixEmptyAndTrim(localBranch); } public String getLocalBranch() { return localBranch; } @Extension public static class DescriptorImpl extends GitSCMExtensionDescriptor { @Override public String getDisplayName() { return "Check out to specific local branch, null to use remote branch name."; } } }
Switch rate limiter windowsize to 1. There seem to be occasional errors from the API, so let's be conservative.
package lib import ( "time" ) const windows = 1 type RateLimit struct { Period time.Duration Rate uint toks chan struct{} paused bool } func (r *RateLimit) Start() { r.paused = false if r.toks == nil { r.toks = make(chan struct{}, windows*r.Rate) } go func() { for true { for i := uint(0); i < r.Rate; i++ { r.toks <- struct{}{} } time.Sleep(r.Period) if r.paused { break } } }() } func (r *RateLimit) Stop() { r.paused = true } func (r *RateLimit) TryGet() bool { select { case _ = <-r.toks: return true default: return false } } func (r *RateLimit) Get() { _ = <-r.toks }
package lib import ( "time" ) const windows = 2 type RateLimit struct { Period time.Duration Rate uint toks chan struct{} paused bool } func (r *RateLimit) Start() { r.paused = false if r.toks == nil { r.toks = make(chan struct{}, windows*r.Rate) } go func() { for true { for i := uint(0); i < r.Rate; i++ { r.toks <- struct{}{} } time.Sleep(r.Period) if r.paused { break } } }() } func (r *RateLimit) Stop() { r.paused = true } func (r *RateLimit) TryGet() bool { select { case _ = <-r.toks: return true default: return false } } func (r *RateLimit) Get() { _ = <-r.toks }
Update bunyan integration test: show monkey-patch
'use strict'; var bunyan = require('bunyan'); var logShim = require('thehelp-log-shim'); var logger = logShim('test:scenarios:bunyan'); // this should not show up; the default level is info logger.verbose('this is the default verbose text'); logger.info('this is the info text', { data: { yes: 'no' } }); logger.warn('this is the warn text', function(arg1, arg2, arg3, arg4) { /*jshint unused: false*/ logger.warn('warn callback!'); }); logger.error('this is the error %s', 'interpolation'); // monkey-patching to approximate global configuration var create = bunyan.createLogger; bunyan.createLogger = function(options) { options.level = 'debug'; return create(options); }; // this will show up var second = logShim('test:scenarios:bunyan:custom'); second.verbose('this is the custom verbose text');
'use strict'; var bunyan = require('bunyan'); var logShim = require('thehelp-log-shim'); var logger = logShim('test:scenarios:bunyan'); logger.verbose('this is the default verbose text'); logger.info('this is the info text', { data: { yes: 'no' } }); logger.warn('this is the warn text', function(arg1, arg2, arg3, arg4) { /*jshint unused: false*/ logger.warn('warn callback!'); }); logger.error('this is the error %s', 'interpolation'); logShim.loadLogger = function(moduleName) { var logger = bunyan.createLogger({ name: moduleName, level: 'debug' }); logger.verbose = logger.debug; return logger; }; var second = logShim('test:scenarios:bunyan:custom'); second.verbose('this is the custom verbose text');
Make sure 'keyevent' works if metastate is null.
package io.appium.android.bootstrap.handler; import io.appium.android.bootstrap.AndroidCommand; import io.appium.android.bootstrap.AndroidCommandResult; import io.appium.android.bootstrap.CommandHandler; import java.util.Hashtable; import org.json.JSONException; import org.json.JSONObject; import com.android.uiautomator.core.UiDevice; /** * This handler is used to PressKeyCode. * */ public class PressKeyCode extends CommandHandler { public Integer keyCode; public Integer metaState; /* * @param command The {@link AndroidCommand} used for this handler. * * @return {@link AndroidCommandResult} * * @throws JSONException * * @see io.appium.android.bootstrap.CommandHandler#execute(io.appium.android. * bootstrap.AndroidCommand) */ @Override public AndroidCommandResult execute(final AndroidCommand command) throws JSONException { try { final Hashtable<String, Object> params = command.params(); keyCode = (Integer) params.get("keycode"); if (params.get("metastate") != JSONObject.NULL) { metaState = (Integer) params.get("metastate"); UiDevice.getInstance().pressKeyCode(keyCode, metaState); } else { UiDevice.getInstance().pressKeyCode(keyCode); } return getSuccessResult(true); } catch (final Exception e) { return getErrorResult(e.getMessage()); } } }
package io.appium.android.bootstrap.handler; import io.appium.android.bootstrap.AndroidCommand; import io.appium.android.bootstrap.AndroidCommandResult; import io.appium.android.bootstrap.CommandHandler; import java.util.Hashtable; import org.json.JSONException; import org.json.JSONObject; import com.android.uiautomator.core.UiDevice; /** * This handler is used to PressKeyCode. * */ public class PressKeyCode extends CommandHandler { public Integer keyCode; public Integer metaState; /* * @param command The {@link AndroidCommand} used for this handler. * * @return {@link AndroidCommandResult} * * @throws JSONException * * @see io.appium.android.bootstrap.CommandHandler#execute(io.appium.android. * bootstrap.AndroidCommand) */ @Override public AndroidCommandResult execute(final AndroidCommand command) throws JSONException { try { final Hashtable<String, Object> params = command.params(); keyCode = (Integer) params.get("keycode"); if (params.get("metastate") != JSONObject.NULL) { metaState = (Integer) params.get("metastate"); } UiDevice.getInstance().pressKeyCode(keyCode, metaState); return getSuccessResult(true); } catch (final Exception e) { return getErrorResult(e.getMessage()); } } }
Update URL for supported browsers
module.exports = (ctx) => ({ map: ctx.file.dirname.startsWith('docs') ? false : { inline: false, annotation: true, sourcesContent: true }, plugins: { autoprefixer: { browsers: [ // // Official browser support policy: // https://getbootstrap.com/docs/4.0/getting-started/browsers-devices/#supported-browsers // 'Chrome >= 45', // Exact version number here is kinda arbitrary 'Firefox ESR', // Note: Edge versions in Autoprefixer & Can I Use refer to the EdgeHTML rendering engine version, // NOT the Edge app version shown in Edge's "About" screen. // For example, at the time of writing, Edge 20 on an up-to-date system uses EdgeHTML 12. // See also https://github.com/Fyrd/caniuse/issues/1928 'Edge >= 12', 'Explorer >= 10', // Out of leniency, we prefix these 1 version further back than the official policy. 'iOS >= 9', 'Safari >= 9', // The following remain NOT officially supported, but we're lenient and include their prefixes to avoid severely breaking in them. 'Android >= 4.4', 'Opera >= 30' ] } } })
module.exports = (ctx) => ({ map: ctx.file.dirname.startsWith('docs') ? false : { inline: false, annotation: true, sourcesContent: true }, plugins: { autoprefixer: { browsers: [ // // Official browser support policy: // https://v4-alpha.getbootstrap.com/getting-started/browsers-devices/#supported-browsers // 'Chrome >= 45', // Exact version number here is kinda arbitrary 'Firefox ESR', // Note: Edge versions in Autoprefixer & Can I Use refer to the EdgeHTML rendering engine version, // NOT the Edge app version shown in Edge's "About" screen. // For example, at the time of writing, Edge 20 on an up-to-date system uses EdgeHTML 12. // See also https://github.com/Fyrd/caniuse/issues/1928 'Edge >= 12', 'Explorer >= 10', // Out of leniency, we prefix these 1 version further back than the official policy. 'iOS >= 9', 'Safari >= 9', // The following remain NOT officially supported, but we're lenient and include their prefixes to avoid severely breaking in them. 'Android >= 4.4', 'Opera >= 30' ] } } })
Replace Math.toIntExact() with a simple .intValue() 'cause toIntExact() is not abailable at Java 6
package com.fewlaps.quitnowcache; import java.util.concurrent.TimeUnit; public class QNCacheBuilder { private boolean caseSensitiveKeys = true; private Integer autoReleaseInSeconds = null; private long defaultKeepaliveInMillis = QNCache.KEEPALIVE_FOREVER; public QNCacheBuilder setCaseSensitiveKeys(boolean caseSensitiveKeys) { this.caseSensitiveKeys = caseSensitiveKeys; return this; } public QNCacheBuilder setAutoRelease(int units, TimeUnit timeUnit) { this.autoReleaseInSeconds = Long.valueOf(timeUnit.toSeconds(units)).intValue(); return this; } public QNCacheBuilder setAutoReleaseInSeconds(Integer autoReleaseInSeconds) { this.autoReleaseInSeconds = autoReleaseInSeconds; return this; } public QNCacheBuilder setDefaultKeepalive(int units, TimeUnit timeUnit) { this.defaultKeepaliveInMillis = timeUnit.toMillis(units); return this; } public QNCacheBuilder setDefaultKeepaliveInMillis(long defaultKeepaliveInMillis) { this.defaultKeepaliveInMillis = defaultKeepaliveInMillis; return this; } public <T> QNCache<T> createQNCache() { return new QNCache<T>(caseSensitiveKeys, autoReleaseInSeconds, defaultKeepaliveInMillis); } }
package com.fewlaps.quitnowcache; import java.util.concurrent.TimeUnit; public class QNCacheBuilder { private boolean caseSensitiveKeys = true; private Integer autoReleaseInSeconds = null; private long defaultKeepaliveInMillis = QNCache.KEEPALIVE_FOREVER; public QNCacheBuilder setCaseSensitiveKeys(boolean caseSensitiveKeys) { this.caseSensitiveKeys = caseSensitiveKeys; return this; } public QNCacheBuilder setAutoRelease(int units, TimeUnit timeUnit) { this.autoReleaseInSeconds = Math.toIntExact(timeUnit.toSeconds(units)); return this; } public QNCacheBuilder setAutoReleaseInSeconds(Integer autoReleaseInSeconds) { this.autoReleaseInSeconds = autoReleaseInSeconds; return this; } public QNCacheBuilder setDefaultKeepalive(int units, TimeUnit timeUnit) { this.defaultKeepaliveInMillis = timeUnit.toMillis(units); return this; } public QNCacheBuilder setDefaultKeepaliveInMillis(long defaultKeepaliveInMillis) { this.defaultKeepaliveInMillis = defaultKeepaliveInMillis; return this; } public <T> QNCache<T> createQNCache() { return new QNCache<T>(caseSensitiveKeys, autoReleaseInSeconds, defaultKeepaliveInMillis); } }
Allow simply setting { fingerprint: false } as a shortcut option to disable
var path = require('path'); var fs = require('fs'); var assetRev = require('./lib/asset-rev'); module.exports = { name: 'broccoli-asset-rev', initializeOptions: function() { var defaultOptions = { enabled: this.app.env === 'production', exclude: [], extensions: ['js', 'css', 'png', 'jpg', 'gif'], prepend: '', replaceExtensions: ['html', 'css', 'js'] } // Allow simply setting { fingerprint: false } as a shortcut option to disable if (this.app.options.fingerprint === false) { this.options = this.app.options.fingerprint = { enabled: false }; } else { this.options = this.app.options.fingerprint = this.app.options.fingerprint || {}; } for (var option in defaultOptions) { if (!this.options.hasOwnProperty(option)) { this.options[option] = defaultOptions[option]; } } }, postprocessTree: function (type, tree) { if (type === 'all' && this.options.enabled) { tree = assetRev(tree, this.options); } return tree; }, included: function (app) { this.app = app; this.initializeOptions(); }, treeFor: function() {} }
var path = require('path'); var fs = require('fs'); var assetRev = require('./lib/asset-rev'); module.exports = { name: 'broccoli-asset-rev', initializeOptions: function() { var defaultOptions = { enabled: this.app.env === 'production', exclude: [], extensions: ['js', 'css', 'png', 'jpg', 'gif'], prepend: '', replaceExtensions: ['html', 'css', 'js'] } this.options = this.app.options.fingerprint = this.app.options.fingerprint || {}; for (var option in defaultOptions) { if (!this.options.hasOwnProperty(option)) { this.options[option] = defaultOptions[option]; } } }, postprocessTree: function (type, tree) { if (type === 'all' && this.options.enabled) { tree = assetRev(tree, this.options); } return tree; }, included: function (app) { this.app = app; this.initializeOptions(); }, treeFor: function() {} }
Include polyfills on browser tests
const dotenv = require('dotenv'); const webpack = require('webpack'); const config = require('../../webpack.config'); dotenv.load({ silent: true, path: '../../.env' }); module.exports = { entry: [ require.resolve('babel-polyfill'), require.resolve('whatwg-fetch'), '!mocha-loader!./test.js' ], output: { path: __dirname, filename: 'bundle.js' }, plugins: [ new webpack.DefinePlugin({ __CRAFT_TOKEN__: JSON.stringify(process.env.CRAFT_TOKEN), __CRAFT_OWNER__: JSON.stringify(process.env.CRAFT_OWNER), __CRAFT_URL__: JSON.stringify(process.env.CRAFT_URL), __DEBUG__: JSON.stringify(process.env.DEBUG), __TRAVIS_BUILD_ID__: JSON.stringify(process.env.TRAVIS_BUILD_ID) }) ], module: config.module };
const dotenv = require('dotenv'); const webpack = require('webpack'); dotenv.load({ silent: true, path: '../../.env' }); module.exports = { entry: '!mocha-loader!./test.js', output: { path: __dirname, filename: 'bundle.js' }, plugins: [ new webpack.DefinePlugin({ __CRAFT_TOKEN__: JSON.stringify(process.env.CRAFT_TOKEN), __CRAFT_OWNER__: JSON.stringify(process.env.CRAFT_OWNER), __CRAFT_URL__: JSON.stringify(process.env.CRAFT_URL), __DEBUG__: JSON.stringify(process.env.DEBUG), __TRAVIS_BUILD_ID__: JSON.stringify(process.env.TRAVIS_BUILD_ID) }) ], module: { rules: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/, options: { cacheDirectory: true } } ] } };
Reset postdata in index module
<?php global $post; $items = get_field('index', $module->ID); ?> <div class="grid" data-equal-container> <?php foreach ($items as $item) : $post = $item['page']; setup_postdata($post); ?> <div class="grid-md-6"> <a href="<?php the_permalink(); ?>" class="box box-index" data-equal-item> <?php if ($item['image_display'] == 'featured' && $thumbnail = get_thumbnail_source()) : ?> <img class="box-image" src="<?php echo $thumbnail; ?>"> <?php elseif ($item['image_display'] == 'custom' && !empty($item['custom_image'])) : ?> <img class="box-image" src="<?php echo $item['custom_image']['url']; ?>" alt="<?php echo (!empty($item['custom_image']['alt'])) ? $item['custom_image']['alt'] : $item['custom_image']['description']; ?>"> <?php endif; ?> <div class="box-content"> <h5 class="box-index-title link-item"><?php the_title(); ?></h5> <?php the_excerpt(); ?> </div> </a> </div> <?php endforeach; ?> </div> <?php wp_reset_postdata(); ?>
<?php global $post; $items = get_field('index', $module->ID); ?> <div class="grid" data-equal-container> <?php foreach ($items as $item) : $post = $item['page']; setup_postdata($post); ?> <div class="grid-md-6"> <a href="<?php the_permalink(); ?>" class="box box-index" data-equal-item> <?php if ($item['image_display'] == 'featured' && $thumbnail = get_thumbnail_source()) : ?> <img class="box-image" src="<?php echo $thumbnail; ?>"> <?php elseif ($item['image_display'] == 'custom' && !empty($item['custom_image'])) : ?> <img class="box-image" src="<?php echo $item['custom_image']['url']; ?>" alt="<?php echo (!empty($item['custom_image']['alt'])) ? $item['custom_image']['alt'] : $item['custom_image']['description']; ?>"> <?php endif; ?> <div class="box-content"> <h5 class="box-index-title link-item"><?php the_title(); ?></h5> <?php the_excerpt(); ?> </div> </a> </div> <?php endforeach; ?> </div>
Move code endpoint to test static index
package main import ( "net/http" "log" "github.com/gorilla/mux" ) const BIND_ADDRESS string = ":8000" const STATIC_DIRECTORY string = "static" const STATIC_MOUNT_POINT string = "/" func RootHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Gorilla!\n")) } func main() { log.Printf("Starting server on %s.\n", BIND_ADDRESS) r := mux.NewRouter() // Routes consist of a path and a handler function. r.HandleFunc("/test", RootHandler) r.PathPrefix(STATIC_MOUNT_POINT).Handler( http.StripPrefix(STATIC_MOUNT_POINT, http.FileServer(http.Dir(STATIC_DIRECTORY)))) // Bind to a port and pass our router in log.Fatal(http.ListenAndServe(BIND_ADDRESS, r)) }
package main import ( "net/http" "log" "github.com/gorilla/mux" ) const BIND_ADDRESS string = ":8000" const STATIC_DIRECTORY string = "static" const STATIC_MOUNT_POINT string = "/" func RootHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Gorilla!\n")) } func main() { log.Printf("Starting server on %s.\n", BIND_ADDRESS) r := mux.NewRouter() // Routes consist of a path and a handler function. r.HandleFunc("/", RootHandler) r.PathPrefix(STATIC_MOUNT_POINT).Handler( http.StripPrefix(STATIC_MOUNT_POINT, http.FileServer(http.Dir(STATIC_DIRECTORY)))) // Bind to a port and pass our router in log.Fatal(http.ListenAndServe(BIND_ADDRESS, r)) }
Fix env vars always evaluating as true Env vars come through as strings. Which are true. The default on our values is also true. Meaning it would never change. So we have to do special string checking to get it to actually change. Yay.
#! /usr/bin/env python """ Our github hook receiving server. """ import os from flask import Flask from flask_hookserver import Hooks from github import validate_review_request from slack import notify_reviewer app = Flask(__name__) app.config['GITHUB_WEBHOOKS_KEY'] = os.environ.get('GITHUB_WEBHOOKS_KEY') if os.environ.get('GIT_HOOK_VALIDATE_IP', 'True').lower() in ['false', '0']: app.config['VALIDATE_IP'] = False if os.environ.get('GIT_HOOK_VALIDATE_SIGNATURE', 'True').lower() in ['false', '0']: app.config['VALIDATE_SIGNATURE'] = False hooks = Hooks(app, url='/hooks') @hooks.hook('ping') def ping(data, guid): return 'pong' @hooks.hook('pull_request') def pull_request(data, guid): if validate_review_request(data): notify_reviewer(data) result = 'Reviewer Notified' else: result = 'Action ({}) ignored'.format(data.get('action')) return result app.run(host='0.0.0.0')
#! /usr/bin/env python """ Our github hook receiving server. """ import os from flask import Flask from flask_hookserver import Hooks from github import validate_review_request from slack import notify_reviewer app = Flask(__name__) app.config['GITHUB_WEBHOOKS_KEY'] = os.environ.get('GITHUB_WEBHOOKS_KEY') app.config['VALIDATE_IP'] = os.environ.get('GIT_HOOK_VALIDATE_IP', True) app.config['VALIDATE_SIGNATURE'] = os.environ.get('GIT_HOOK_VALIDATE_SIGNATURE', True) hooks = Hooks(app, url='/hooks') @hooks.hook('ping') def ping(data, guid): return 'pong' @hooks.hook('pull_request') def pull_request(data, guid): if validate_review_request(data): notify_reviewer(data) result = 'Reviewer Notified' else: result = 'Action ({}) ignored'.format(data.get('action')) return result app.run(host='0.0.0.0')
Check if there is any output processor
import snactor.output_processors from snactor.executors.payload import PayloadExecutor, registered_executor from snactor.registry import get_output_processor class BashExecutorDefinition(PayloadExecutor.Definition): def __init__(self, init): super(BashExecutorDefinition, self).__init__(init) self.executable = "/bin/bash" self.output_processor = get_output_processor(init.get('output-processor', None)) @registered_executor('bash') class BashExecutor(PayloadExecutor): Definition = BashExecutorDefinition def handle_stdout(self, stdout, data): self.log.debug("handle_stdout(%s)", stdout) if self.definition.executor.output_processor: self.definition.executor.output_processor.process(stdout, data) def __init__(self, definition): super(BashExecutor, self).__init__(definition)
import snactor.output_processors from snactor.executors.payload import PayloadExecutor, registered_executor from snactor.registry import get_output_processor class BashExecutorDefinition(PayloadExecutor.Definition): def __init__(self, init): super(BashExecutorDefinition, self).__init__(init) self.executable = "/bin/bash" self.output_processor = get_output_processor(init.get('output-processor', None)) @registered_executor('bash') class BashExecutor(PayloadExecutor): Definition = BashExecutorDefinition def handle_stdout(self, stdout, data): self.log.debug("handle_stdout(%s)", stdout) self.definition.executor.output_processor.process(stdout, data) def __init__(self, definition): super(BashExecutor, self).__init__(definition)
Fix error with string rank value
# coding: utf-8 import os import time from twython import Twython import requests APP_KEY = os.environ.get('APP_KEY') APP_SECRET = os.environ.get('APP_SECRET') OAUTH_TOKEN = os.environ.get('OAUTH_TOKEN') OAUTH_TOKEN_SECRET = os.environ.get('OAUTH_TOKEN_SECRET') twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) def post_tweet(currency): template = """ {name} - {symbol} Price: ${price_usd} Change in 1h: {percent_change_1h}% Market cap: ${market_cap_usd} Ranking: {rank} #{name} #{symbol} """ if currency['percent_change_1h'] > 0: currency['percent_change_1h'] = '+{}'.format(currency['percent_change_1h']) twitter.update_status(status=template.format(**currency)) def main(): response = requests.get('https://api.coinmarketcap.com/v1/ticker/') for currency in sorted(response.json(), key=lambda x: int(x['rank']))[:10]: post_tweet(currency) time.sleep(5) if __name__ == '__main__': main()
# coding: utf-8 import os import time from twython import Twython import requests APP_KEY = os.environ.get('APP_KEY') APP_SECRET = os.environ.get('APP_SECRET') OAUTH_TOKEN = os.environ.get('OAUTH_TOKEN') OAUTH_TOKEN_SECRET = os.environ.get('OAUTH_TOKEN_SECRET') twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) def post_tweet(currency): template = """ {name} - {symbol} Price: ${price_usd} Change in 1h: {percent_change_1h}% Market cap: ${market_cap_usd} Ranking: {rank} #{name} #{symbol} """ if currency['percent_change_1h'] > 0: currency['percent_change_1h'] = '+{}'.format(currency['percent_change_1h']) twitter.update_status(status=template.format(**currency)) def main(): response = requests.get('https://api.coinmarketcap.com/v1/ticker/') for currency in sorted(response.json(), key=lambda x: x['rank'])[:10]: post_tweet(currency) time.sleep(5) if __name__ == '__main__': main()
Fix typo in role check
""" Usage: scripts/generate-user-email-list.py <data_api_url> <data_api_token> """ import csv import sys from docopt import docopt from dmutils.apiclient import DataAPIClient def generate_user_email_list(data_api_url, data_api_token): client = DataAPIClient(data_api_url, data_api_token) writer = csv.writer(sys.stdout, delimiter=',', quotechar='"') for user in client.find_users_iter(): if user['active'] and user['role'] == 'supplier': writer.writerow([ user['emailAddress'], user['name'], user['supplier']['supplierId'], user['supplier']['name']]) if __name__ == '__main__': arguments = docopt(__doc__) generate_user_email_list( data_api_url=arguments['<data_api_url>'], data_api_token=arguments['<data_api_token>'])
""" Usage: scripts/generate-user-email-list.py <data_api_url> <data_api_token> """ import csv import sys from docopt import docopt from dmutils.apiclient import DataAPIClient def generate_user_email_list(data_api_url, data_api_token): client = DataAPIClient(data_api_url, data_api_token) writer = csv.writer(sys.stdout, delimiter=',', quotechar='"') for user in client.find_users_iter(): if user['active'] and user['role'] != 'supplier': writer.writerow([ user['emailAddress'], user['name'], user['supplier']['supplierId'], user['supplier']['name']]) if __name__ == '__main__': arguments = docopt(__doc__) generate_user_email_list( data_api_url=arguments['<data_api_url>'], data_api_token=arguments['<data_api_token>'])
Update file based on the php:lint task
<?php /** * Saves in cache using transient function of wordpress a request using callbacks * similar as wordpress does. Works only for WP. * * @package on-cache-please * @since 1.0.0 */ if ( ! function_exists( 'on_cache_please' ) ) { /** * Function to storage the cache on automatic. * * @since 1.0.0 * @param array $args { * An array of arguments. * @type string $key name. The name of the transient of the request. * @type string $key callback. The name of the function or the function * to execute that returns the data. * @type int $key duration. The duration of the cache. * } */ function on_cache_please( array $args = array() ) { $args = is_array( $args ) ? $args : array(); $args = wp_parse_args( $args, array( 'name' => '', 'callback' => false, 'duration' => HOUR_IN_SECONDS, )); $data = get_transient( $args['name'] ); if ( false === $data ) { if ( is_callable( $args['callback'] ) ) { $data = call_user_func( $args['callback'] ); set_transient( $args['name'], $data, $args['duration'] ); } } return $data; } }
<?php if ( ! function_exists( 'on_cache_please' ) ){ /** * Function to storage the cache on automatic. * @since 1.0.0 * @param */ function on_cache_please( array $args = array() ) { $args = is_array( $args ) ? $args : array(); $args = wp_parse_args( $args, array( 'name' => '', 'callback' => false, 'duration' => HOUR_IN_SECONDS, )); $data = get_transient( $args['name'] ); if( $data === false ){ if ( is_callable( $args['callback'] ) ) { $data = call_user_func( $args['callback'] ); set_transient( $args['name'], $data, $args['duration'] ); } } return $data; } }
Reduce redundancy with opts object
var fs = require('fs'); var Jafar = function(opts) { var that = this, // TODO: would need error handling to ensure opts exists at all inputJson = opts.json ? opts.json : null; if (!inputJson || (typeof(inputJson) !== 'object' && typeof(inputJson) !== 'string')) { throw new Error('You must pass a reference to a valid JSON object/file into Jafar constructor!'); } this.json = (typeof(inputJson) === 'object') ? inputJson : this.readJsonFile(inputJson); }; Jafar.prototype.readJsonFile = function(input) { try { return JSON.parse(fs.readFileSync(input)); } catch(err) { throw new Error('Input JSON file could not be read!'); } }; Jafar.prototype.displayJson = function() { console.log(this.json); }; module.exports = Jafar;
var fs = require('fs'); var Jafar = function(opts) { var that = this; if (!opts.json || (typeof(opts.json) !== 'object' && typeof(opts.json) !== 'string')) { throw new Error('You must pass a reference to a valid JSON object/file into Jafar constructor!'); } this.json = (typeof(opts.json) === 'object') ? opts.json : this.parseJsonFile(opts.json); }; Jafar.prototype.parseJsonFile = function(input) { try { return JSON.parse(fs.readFileSync(input)); } catch(err) { throw new Error('Input JSON file could not be read!'); } }; Jafar.prototype.displayJson = function() { console.log(this.json); }; module.exports = Jafar;
Check how Travis handles stderr output
#!/usr/bin/env node var fold = require('./index.js'), ret; console.error('stderr output...'); console.error('stderr output...'); ret = [ fold.start('foo'), 'bar', 'next line', 'next line', fold.start('bar'), 'next line', 'next line', 'next line', fold.end('bar'), 'next line', 'next line', 'next line', fold.end('foo'), 'test', 'test', fold.start('https://github.com/macbre/phantomas/issues/141'), 'Testing <https://github.com/macbre/phantomas/issues/141>', 'foo', 'bar', fold.end('https://github.com/macbre/phantomas/issues/141') ]; console.log(ret.join('\n').trim()); console.log('Hello, ' + process.env.USER + '!'); console.log( fold.wrap('FooBar', "test\n123\ntest\n") );
#!/usr/bin/env node var fold = require('./index.js'), ret; ret = [ fold.start('foo'), 'bar', 'next line', 'next line', fold.start('bar'), 'next line', 'next line', 'next line', fold.end('bar'), 'next line', 'next line', 'next line', fold.end('foo'), 'test', 'test', fold.start('https://github.com/macbre/phantomas/issues/141'), 'Testing <https://github.com/macbre/phantomas/issues/141>', 'foo', 'bar', fold.end('https://github.com/macbre/phantomas/issues/141') ]; console.log(ret.join('\n').trim()); console.log('Hello, ' + process.env.USER + '!'); console.log( fold.wrap('FooBar', "test\n123\ntest\n") );
Add px to rem convertor
/** * Converts breakpoint units in px to rem or em * @param {Object} breakpoints - an object containing breakpoint names as keys and the width as value * @param {number} [16] ratio - size of 1 rem in px. What is your main font-size in px? * @param {'rem' | 'em'} unit */ function pxToEmOrRem(breakpoints, ratio = 16, unit) { const newBreakpoints = {}; for (let key in breakpoints) { const point = breakpoints[key]; if (String(point).includes('px')) { newBreakpoints[key] = +(parseInt(point) / ratio) + unit; continue; } newBreakpoints[key] = point; } return newBreakpoints; } /** * Converts breakpoint units in px to em * @param {Object} breakpoints - an object containing breakpoint names as keys and the width as value * @param {number} [16] ratio - size of 1em in px. What is your main font-size in px? */ export function pxToEm(breakpoints, ratio = 16) { return pxToEmOrRem(breakpoints, ratio, 'em'); } /** * Converts breakpoint units in px to rem * @param {Object} breakpoints - an object containing breakpoint names as keys and the width as value * @param {number} [16] ratio - size of 1rem in px. What is your main font-size in px? */ export function pxToRem(breakpoints, ratio = 16) { return pxToEmOrRem(breakpoints, ratio, 'rem'); }
/** * Converts breakpoint units in px to rem or em * @param {Object} breakpoints - an object containing breakpoint names as keys and the width as value * @param {number} [16] ratio - size of 1 rem in px. What is your main font-size in px? * @param {'rem' | 'em'} unit */ function pxToEmOrRem(breakpoints, ratio = 16, unit) { const newBreakpoints = {}; for (let key in breakpoints) { const point = breakpoints[key]; if (String(point).includes('px')) { newBreakpoints[key] = +(parseInt(point) / ratio) + unit; continue; } newBreakpoints[key] = point; } return newBreakpoints; } /** * Converts breakpoint units in px to em * @param {Object} breakpoints - an object containing breakpoint names as keys and the width as value * @param {number} [16] ratio - size of 1em in px. What is your main font-size in px? */ export function pxToEm(breakpoints, ratio = 16) { return pxToEmOrRem(breakpoints, ratio, 'em'); }
Move react-rte to vendor bundle
const path = require('path'); exports.browsers = [ 'last 2 versions', 'ios_saf >= 8', 'ie >= 10', 'chrome >= 49', 'firefox >= 49', '> 1%', ]; exports.resolve = { alias: { components: path.join(__dirname, '..', 'app', 'components'), containers: path.join(__dirname, '..', 'app', 'containers'), views: path.join(__dirname, '..', 'app', 'views'), actions: path.join(__dirname, '..', 'app', 'actions'), utils: path.join(__dirname, '..', 'app', 'utils'), assets: path.join(__dirname, '..', 'app', 'assets'), }, }; exports.vendor = [ 'react', 'react-dom', 'react-router', 'codemirror', 'react-codemirror', 'socket.io-client', 'socket.io-parser', 'engine.io-client', 'engine.io-parser', 'lodash', 'moment', 'draft-js', 'draft-js-export-html', 'draft-js-utils', 'react-color', 'react-redux', 'redux', 'immutability-helper', 'immutable', 'history', 'axios', 'react-dnd', 'react-dnd-html5-backend', 'core-js', 'react-rte', ];
const path = require('path'); exports.browsers = [ 'last 2 versions', 'ios_saf >= 8', 'ie >= 10', 'chrome >= 49', 'firefox >= 49', '> 1%', ]; exports.resolve = { alias: { components: path.join(__dirname, '..', 'app', 'components'), containers: path.join(__dirname, '..', 'app', 'containers'), views: path.join(__dirname, '..', 'app', 'views'), actions: path.join(__dirname, '..', 'app', 'actions'), utils: path.join(__dirname, '..', 'app', 'utils'), assets: path.join(__dirname, '..', 'app', 'assets'), }, }; exports.vendor = [ 'react', 'react-dom', 'react-router', 'codemirror', 'react-codemirror', 'socket.io-client', 'socket.io-parser', 'engine.io-client', 'engine.io-parser', 'lodash', 'moment', 'draft-js', 'draft-js-export-html', 'draft-js-utils', 'react-color', 'react-redux', 'redux', 'immutability-helper', 'immutable', 'history', 'axios', 'react-dnd', 'react-dnd-html5-backend', 'core-js', ];
Fix exit code of unittest.
# TODO: Test robustness, test speed import unittest, time, sys from common_conf import * from test_server import EchoServer, MessageServer import argparse import threading from test_server import TestMessageServer from test_client import TestClientWithDummyServer from test_commands import TestCommands from test_realistic_rendering import TestRealisticRendering if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--travis', action='store_true') # Only run test availabe to travis CI args = parser.parse_args() suites = [] load = unittest.TestLoader().loadTestsFromTestCase s = load(TestMessageServer); suites.append(s) s = load(TestClientWithDummyServer); suites.append(s) if not args.travis: s = load(TestCommands); suites.append(s) s = load(TestRealisticRendering); suites.append(s) suite_obj = unittest.TestSuite(suites) ret = not unittest.TextTestRunner(verbosity = 2).run(suite_obj).wasSucessful() sys.exit(ret)
# TODO: Test robustness, test speed import unittest, time, sys from common_conf import * from test_server import EchoServer, MessageServer import argparse import threading from test_server import TestMessageServer from test_client import TestClientWithDummyServer from test_commands import TestCommands from test_realistic_rendering import TestRealisticRendering if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--travis', action='store_true') # Only run test availabe to travis CI args = parser.parse_args() suites = [] load = unittest.TestLoader().loadTestsFromTestCase s = load(TestMessageServer); suites.append(s) s = load(TestClientWithDummyServer); suites.append(s) if not args.travis: s = load(TestCommands); suites.append(s) s = load(TestRealisticRendering); suites.append(s) suite_obj = unittest.TestSuite(suites) unittest.TextTestRunner(verbosity = 2).run(suite_obj)
Fix preview route for trashbin
<?php /** @var $this \OCP\Route\IRouter */ $this->create('core_ajax_trashbin_preview', 'ajax/preview.php') ->actionInclude('files_trashbin/ajax/preview.php'); $this->create('files_trashbin_ajax_delete', 'ajax/delete.php') ->actionInclude('files_trashbin/ajax/delete.php'); $this->create('files_trashbin_ajax_isEmpty', 'ajax/isEmpty.php') ->actionInclude('files_trashbin/ajax/isEmpty.php'); $this->create('files_trashbin_ajax_list', 'ajax/list.php') ->actionInclude('files_trashbin/ajax/list.php'); $this->create('files_trashbin_ajax_undelete', 'ajax/undelete.php') ->actionInclude('files_trashbin/ajax/undelete.php'); // Register with the capabilities API \OC_API::register('get', '/cloud/capabilities', array('OCA\Files_Trashbin\Capabilities', 'getCapabilities'), 'files_trashbin', \OC_API::USER_AUTH);
<?php /** @var $this \OCP\Route\IRouter */ $this->create('core_ajax_trashbin_preview', '/preview')->action( function() { require_once __DIR__ . '/../ajax/preview.php'; }); $this->create('files_trashbin_ajax_delete', 'ajax/delete.php') ->actionInclude('files_trashbin/ajax/delete.php'); $this->create('files_trashbin_ajax_isEmpty', 'ajax/isEmpty.php') ->actionInclude('files_trashbin/ajax/isEmpty.php'); $this->create('files_trashbin_ajax_list', 'ajax/list.php') ->actionInclude('files_trashbin/ajax/list.php'); $this->create('files_trashbin_ajax_undelete', 'ajax/undelete.php') ->actionInclude('files_trashbin/ajax/undelete.php'); // Register with the capabilities API \OC_API::register('get', '/cloud/capabilities', array('OCA\Files_Trashbin\Capabilities', 'getCapabilities'), 'files_trashbin', \OC_API::USER_AUTH);
Fix golint errors when generating informer code Kubernetes-commit: acf78cd6133de6faea9221d8c53b02ca6009b0bb
/* Copyright The Kubernetes Authors. 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. */ // Code generated by informer-gen. DO NOT EDIT. package internalinterfaces import ( time "time" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" cache "k8s.io/client-go/tools/cache" versioned "k8s.io/sample-controller/pkg/client/clientset/versioned" ) // NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer. type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer // SharedInformerFactory a small interface to allow for adding an informer without an import cycle type SharedInformerFactory interface { Start(stopCh <-chan struct{}) InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer } // TweakListOptionsFunc is a function that transforms a v1.ListOptions. type TweakListOptionsFunc func(*v1.ListOptions)
/* Copyright The Kubernetes Authors. 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. */ // Code generated by informer-gen. DO NOT EDIT. package internalinterfaces import ( time "time" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" cache "k8s.io/client-go/tools/cache" versioned "k8s.io/sample-controller/pkg/client/clientset/versioned" ) type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer // SharedInformerFactory a small interface to allow for adding an informer without an import cycle type SharedInformerFactory interface { Start(stopCh <-chan struct{}) InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer } type TweakListOptionsFunc func(*v1.ListOptions)
Add migrations path to env.Config
package env import ( "encoding/json" "flag" "os" "path" ) type config struct { Database string `json:"database"` Telegram telegram `json:"telegram"` VK vk `json:"vk"` Migrations string } type telegram struct { Webhook string `json:"webhook"` Token string `json:"token"` } type vk struct { Confirmation string `json:"confirmation"` Token string `json:"token"` } // Config returns current configuration. var Config config func init() { var configPath string root := os.Getenv("RAND_CHAT_ROOT") if flag.Lookup("test.v") == nil { configPath = path.Join(root, "/config.json") } else { configPath = path.Join(root, "/config.test.json") } configFile, err := os.Open(configPath) if err != nil { panic(err) } json.NewDecoder(configFile).Decode(&Config) Config.Migrations = "file://" + path.Join(root, "/migrations") }
package env import ( "encoding/json" "flag" "os" ) type config struct { Database string `json:"database"` Telegram telegram `json:"telegram"` VK vk `json:"vk"` } type telegram struct { Webhook string `json:"webhook"` Token string `json:"token"` } type vk struct { Confirmation string `json:"confirmation"` Token string `json:"token"` } // Config returns current configuration. var Config config func init() { var path = os.Getenv("RAND_CHAT_ROOT") if flag.Lookup("test.v") == nil { path += "/config.json" } else { path += "/config.test.json" } file, err := os.Open(path) if err != nil { panic(err) } json.NewDecoder(file).Decode(&Config) if err != nil { panic(err) } }
Return the image url and create load tag
window.ImgLoader = function(){ throw new Error(); } window.ImgLoader.init = function(){ window.ImgLoader._count = 0; window.ImgLoader.container = document.createElement('load'); window.ImgLoader.container.style.display = 'none'; document.head.appendChild(window.ImgLoader.container); } window.ImgLoader.count = function(inc){ switch (inc) { case '+': window.ImgLoader._count++; break; case '-': window.ImgLoader._count--; break; default: throw new Error(); } } window.ImgLoader.getCount = function(){ return window.ImgLoader._count; } window.ImgLoader.isLoaded = function(){ return window.ImgLoader.getCount() === 0 ? true : false; } window.ImgLoader.load = function(_url){ window.ImgLoader.count('+'); var img = document.createElement('img'); img.src = _url; window.ImgLoader.container.appendChild(img); img.onload = function () { window.ImgLoader.container.removeChild(img); window.ImgLoader.count('-'); } return _url; } window.ImgLoader.init();
window.ImgLoader = function () { throw new Error(); } window.ImgLoader._count = 0; window.ImgLoader.count = function(inc){ switch (inc) { case '+': window.ImgLoader._count++; break; case '-': window.ImgLoader._count--; break; default: throw new Error(); } } window.ImgLoader.getCount = function(){ return window.ImgLoader._count; } window.ImgLoader.isLoaded = function () { return window.ImgLoader.getCount() === 0 ? true : false; } window.ImgLoader.load = function (url){ window.ImgLoader.count('+'); var img = document.createElement('img'); img.src = url; img.style.display = 'none'; document.body.appendChild(img); img.onload = function () { document.body.removeChild(img); window.ImgLoader.count('-'); } }
Mark the package not zipsafe so test discovery finds directories.
from setuptools import setup, find_packages import sys, os here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() version = '0.1' setup(name='nested_formset', version=version, description="", long_description=README, classifiers=[ 'License :: OSI Approved :: BSD License', ], keywords='', url='https://github.com/nyergler/nested-formset', license='BSD', packages=find_packages('src'), package_dir={'': 'src'}, include_package_data=True, zip_safe=False, install_requires=[ 'Django>=1.5', 'django-discover-runner', 'rebar', ], )
from setuptools import setup, find_packages import sys, os here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() version = '0.1' setup(name='nested_formset', version=version, description="", long_description=README, classifiers=[ 'License :: OSI Approved :: BSD License', ], keywords='', url='https://github.com/nyergler/nested-formset', license='BSD', packages=find_packages('src'), package_dir={'': 'src'}, include_package_data=True, zip_safe=True, install_requires=[ 'Django>=1.5', 'django-discover-runner', 'rebar', ], )
Make group property in user visible.
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ /* foam.RELATIONSHIP({ cardinality: '*:*', sourceModel: 'foam.nanos.auth.Group', targetModel: 'foam.nanos.auth.Permission', forwardName: 'permissions', inverseName: 'groups', sourceProperty: { hidden: true }, targetProperty: { hidden: true } }); */ /* foam.RELATIONSHIP({ cardinality: '*:*', sourceModel: 'foam.nanos.auth.User', targetModel: 'foam.nanos.auth.Group', forwardName: 'groups', inverseName: 'users', sourceProperty: { hidden: true }, targetProperty: { hidden: true } }); */ foam.RELATIONSHIP({ cardinality: '1:*', sourceModel: 'foam.nanos.auth.Group', targetModel: 'foam.nanos.auth.User', forwardName: 'users', inverseName: 'group', sourceProperty: { hidden: true }, targetProperty: { hidden: false } });
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ /* foam.RELATIONSHIP({ cardinality: '*:*', sourceModel: 'foam.nanos.auth.Group', targetModel: 'foam.nanos.auth.Permission', forwardName: 'permissions', inverseName: 'groups', sourceProperty: { hidden: true }, targetProperty: { hidden: true } }); */ /* foam.RELATIONSHIP({ cardinality: '*:*', sourceModel: 'foam.nanos.auth.User', targetModel: 'foam.nanos.auth.Group', forwardName: 'groups', inverseName: 'users', sourceProperty: { hidden: true }, targetProperty: { hidden: true } }); */ foam.RELATIONSHIP({ cardinality: '1:*', sourceModel: 'foam.nanos.auth.Group', targetModel: 'foam.nanos.auth.User', forwardName: 'users', inverseName: 'group', sourceProperty: { hidden: true }, targetProperty: { hidden: true } });
Resolve import error introduced in last commit.
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup import re import os from codecs import open version = '' with open('koordinates/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) with open('README.rst', 'r', 'utf-8') as f: readme = f.read() with open('HISTORY.rst', 'r', 'utf-8') as f: history = f.read() setup( name='koordinates', packages=['koordinates',], version=version, description='koordinates is a Python client library for a number of Koordinates web APIs', long_description=readme + '\n\n' + history, author='Richard Shea', author_email='rshea@thecubagroup.com', url='https://github.com/koordinates/python-client', download_url = 'https://github.com/koordinates/python-client/tarball/0.1', keywords='koordinates api', license = 'BSD', classifiers=[], test_suite='tests', )
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup version = '' with open('koordinates/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) with open('README.rst', 'r', 'utf-8') as f: readme = f.read() with open('HISTORY.rst', 'r', 'utf-8') as f: history = f.read() setup( name='koordinates', packages=['koordinates',], version=version description='koordinates is a Python client library for a number of Koordinates web APIs', long_description=readme + '\n\n' + history author='Richard Shea', author_email='rshea@thecubagroup.com', url='https://github.com/koordinates/python-client', download_url = 'https://github.com/koordinates/python-client/tarball/0.1', keywords='koordinates api', license = 'BSD', classifiers=[], test_suite='tests', )
Add unit test for recursive expressions
package com.hubspot.jinjava.interpret; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; public class ContextTest { private static final String RESOLVED_EXPRESSION = "exp" ; private static final String RESOLVED_FUNCTION = "func" ; private static final String RESOLVED_VALUE = "val" ; private Context context; @Before public void setUp() { context = new Context(); } @Test public void itAddsResolvedValuesFromAnotherContextObject() { Context donor = new Context(); donor.addResolvedValue(RESOLVED_VALUE); donor.addResolvedFunction(RESOLVED_FUNCTION); donor.addResolvedExpression(RESOLVED_EXPRESSION); assertThat(context.getResolvedValues()).doesNotContain(RESOLVED_VALUE); assertThat(context.getResolvedFunctions()).doesNotContain(RESOLVED_FUNCTION); assertThat(context.getResolvedExpressions()).doesNotContain(RESOLVED_EXPRESSION); context.addResolvedFrom(donor); assertThat(context.getResolvedValues()).contains(RESOLVED_VALUE); assertThat(context.getResolvedFunctions()).contains(RESOLVED_FUNCTION); assertThat(context.getResolvedExpressions()).contains(RESOLVED_EXPRESSION); } @Test public void itRecursivelyAddsValuesUpTheContextChain() { Context child = new Context(context); child.addResolvedExpression(RESOLVED_EXPRESSION); assertThat(context.getResolvedExpressions().contains(RESOLVED_EXPRESSION)); } }
package com.hubspot.jinjava.interpret; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; public class ContextTest { private static final String RESOLVED_EXPRESSION = "exp" ; private static final String RESOLVED_FUNCTION = "func" ; private static final String RESOLVED_VALUE = "val" ; private Context context; @Before public void setUp() { context = new Context(); } @Test public void itAddsResolvedValuesFromAnotherContextObject() { Context donor = new Context(); donor.addResolvedValue(RESOLVED_VALUE); donor.addResolvedFunction(RESOLVED_FUNCTION); donor.addResolvedExpression(RESOLVED_EXPRESSION); assertThat(context.getResolvedValues()).doesNotContain(RESOLVED_VALUE); assertThat(context.getResolvedFunctions()).doesNotContain(RESOLVED_FUNCTION); assertThat(context.getResolvedExpressions()).doesNotContain(RESOLVED_EXPRESSION); context.addResolvedFrom(donor); assertThat(context.getResolvedValues()).contains(RESOLVED_VALUE); assertThat(context.getResolvedFunctions()).contains(RESOLVED_FUNCTION); assertThat(context.getResolvedExpressions()).contains(RESOLVED_EXPRESSION); } }
BB-3925: Add offer button unavailable on Quote create
define([ 'jquery', './select2-view' ], function($, Select2View) { 'use strict'; var Select2AutocompleteView; Select2AutocompleteView = Select2View.extend({ events: { 'change': function(e) { var selectedData = this.$el.data().selectedData || []; if (e.added) { selectedData = selectedData.push(e.added); $(this).data('selected-data', selectedData); } } } }); return Select2AutocompleteView; });
define([ 'jquery', './select2-view' ], function($, Select2View) { 'use strict'; var Select2AutocompleteView; Select2AutocompleteView = Select2View.extend({ events: { 'change': function(e) { var selectedData = $(this.$el).data().selectedData; if (e.added) { selectedData = selectedData.push(e.added); $(this).data('selected-data', selectedData); } } } }); return Select2AutocompleteView; });
Master: Update migration, add currency column to wallet table
<?php use yii\db\Migration; use yii\db\mysql\Schema; class m160107_221900_add_wallet_table extends Migration { public function up() { $this->createTable('{{%wallet}}', [ 'id' => Schema::TYPE_PK, 'user_id' => Schema::TYPE_INTEGER . ' NOT NULL', 'name' => Schema::TYPE_STRING . ' NOT NULL', 'currency' => 'CHAR(3)', 'created_at' => Schema::TYPE_DATETIME . ' NOT NULL', 'updated_at' => Schema::TYPE_DATETIME ]); $this->addForeignKey('fk_wallet_user', 'wallet', 'user_id', 'user', 'id', 'CASCADE', 'CASCADE'); } public function down() { $this->dropForeignKey('fk_wallet_user', 'wallet'); $this->dropTable('{{%wallet}}'); } }
<?php use yii\db\Migration; use yii\db\mysql\Schema; class m160107_221900_add_wallet_table extends Migration { public function up() { $this->createTable('{{%wallet}}', [ 'id' => Schema::TYPE_PK, 'user_id' => Schema::TYPE_INTEGER . ' NOT NULL', 'name' => Schema::TYPE_STRING . ' NOT NULL', 'created_at' => Schema::TYPE_DATETIME . ' NOT NULL', 'updated_at' => Schema::TYPE_DATETIME ]); $this->addForeignKey('fk_wallet_user', 'wallet', 'user_id', 'user', 'id', 'CASCADE', 'CASCADE'); } public function down() { $this->dropForeignKey('fk_wallet_user', 'wallet'); $this->dropTable('{{%wallet}}'); } }
Fix plotter to use 'Agg'.
import matplotlib matplotlib.use('Agg') import numpy as np from jug import TaskGenerator import ezplot __all__ = ['plot_stack'] @TaskGenerator def plot_stack(stack_results, problems=None, policies=None, name=''): problems = problems if problems is not None else stack_results.key() nfigs = len(problems) fig = ezplot.figure(figsize=(5*nfigs, 4)) for i, expt in enumerate(problems): results = stack_results[expt] policies = policies if policies is not None else results.keys() ax = fig.add_subplot(1, nfigs, i+1) for policy in policies: xbest, ybest = zip(*results[policy]) iters = np.arange(np.shape(ybest)[1]) mu = np.mean(ybest, axis=0) std = np.std(ybest, axis=0) / np.sqrt(len(ybest)) ax.plot_banded(iters, mu, std, label=policy) ax.set_title(expt, fontsize=16) ax.legend(loc=0, fontsize=16) ezplot.plt.savefig(name) return fig
import numpy as np from jug import TaskGenerator import ezplot __all__ = ['plot_stack'] @TaskGenerator def plot_stack(stack_results, problems=None, policies=None, name=''): problems = problems if problems is not None else stack_results.key() nfigs = len(problems) fig = ezplot.figure(figsize=(5*nfigs, 4)) for i, expt in enumerate(problems): results = stack_results[expt] policies = policies if policies is not None else results.keys() ax = fig.add_subplot(1, nfigs, i+1) for policy in policies: xbest, ybest = zip(*results[policy]) iters = np.arange(np.shape(ybest)[1]) mu = np.mean(ybest, axis=0) std = np.std(ybest, axis=0) / np.sqrt(len(ybest)) ax.plot_banded(iters, mu, std, label=policy) ax.set_title(expt, fontsize=16) ax.legend(loc=0, fontsize=16) ezplot.plt.savefig(name) return fig
Revise for loop to find neighbor vertices
def topological_sort_recur(adjacency_dict, start_vertex, visited_set, finish_ls): """Topological Sorting by Recursion.""" visited_set.add(start_vertex) for neighbor_vertex in adjacency_dict[start_vertex] - visited_set: topological_sort_recur( adjacency_dict, neighbor_vertex, visited_set, finish_ls) finish_ls.insert(0, start_vertex) print(finish_ls) def topological_sort(adjacency_dict): """Topological Sorting for Directed Acyclic Graph (DAG).""" visited_set = set() finish_ls = [] for vertex in adjacency_dict: if vertex not in visited_set: topological_sort_recur( adjacency_dict, vertex, visited_set, finish_ls) print(finish_ls) def main(): # DAG. dag_adjacency_dict = { 'A': {'D'}, 'B': {'D'}, 'C': {'D'}, 'D': {'G', 'E'}, 'E': {'J'}, 'F': {'G'}, 'G': {'I'}, 'I': {'J'}, 'J': set() } topological_sort(dag_adjacency_dict) if __name__ == '__main__': main()
def topological_sort_recur(adjacency_dict, start_vertex, visited_set, finish_ls): """Topological Sorting by Recursion.""" visited_set.add(start_vertex) for neighbor_vertex in adjacency_dict[start_vertex]: if neighbor_vertex not in visited_set: topological_sort_recur( adjacency_dict, neighbor_vertex, visited_set, finish_ls) finish_ls.insert(0, start_vertex) print(finish_ls) def topological_sort(adjacency_dict): """Topological Sorting for Directed Acyclic Graph (DAG).""" visited_set = set() finish_ls = [] for vertex in adjacency_dict: if vertex not in visited_set: topological_sort_recur( adjacency_dict, vertex, visited_set, finish_ls) print(finish_ls) def main(): # DAG. dag_adjacency_dict = { 'A': {'D'}, 'B': {'D'}, 'C': {'D'}, 'D': {'G', 'E'}, 'E': {'J'}, 'F': {'G'}, 'G': {'I'}, 'I': {'J'}, 'J': {} } topological_sort(dag_adjacency_dict) if __name__ == '__main__': main()
Disable web animations benchmark. It is crashing. BUG=320042 NOTRY=True TBR=dtu@chromium.org Review URL: https://codereview.chromium.org/70233018 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@235452 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from telemetry import test from telemetry.core import util from measurements import blink_perf class BlinkPerfAll(test.Test): tag = 'all' test = blink_perf.BlinkPerfMeasurement def CreatePageSet(self, options): path = os.path.join(util.GetChromiumSrcDir(), 'third_party', 'WebKit', 'PerformanceTests') return blink_perf.CreatePageSetFromPath(path) class BlinkPerfAnimation(test.Test): tag = 'animation' test = blink_perf.BlinkPerfMeasurement def CreatePageSet(self, options): path = os.path.join(util.GetChromiumSrcDir(), 'third_party', 'WebKit', 'PerformanceTests', 'Animation') return blink_perf.CreatePageSetFromPath(path) class BlinkPerfWebAnimations(test.Test): tag = 'web_animations' test = blink_perf.BlinkPerfMeasurement enabled = False # crbug.com/320042 def CreatePageSet(self, options): path = os.path.join(util.GetChromiumSrcDir(), 'third_party', 'WebKit', 'PerformanceTests', 'Animation') return blink_perf.CreatePageSetFromPath(path) def CustomizeBrowserOptions(self, options): options.AppendExtraBrowserArgs('--enable-web-animations-css')
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from telemetry import test from telemetry.core import util from measurements import blink_perf class BlinkPerfAll(test.Test): tag = 'all' test = blink_perf.BlinkPerfMeasurement def CreatePageSet(self, options): path = os.path.join(util.GetChromiumSrcDir(), 'third_party', 'WebKit', 'PerformanceTests') return blink_perf.CreatePageSetFromPath(path) class BlinkPerfAnimation(test.Test): tag = 'animation' test = blink_perf.BlinkPerfMeasurement def CreatePageSet(self, options): path = os.path.join(util.GetChromiumSrcDir(), 'third_party', 'WebKit', 'PerformanceTests', 'Animation') return blink_perf.CreatePageSetFromPath(path) class BlinkPerfWebAnimations(test.Test): tag = 'web_animations' test = blink_perf.BlinkPerfMeasurement def CreatePageSet(self, options): path = os.path.join(util.GetChromiumSrcDir(), 'third_party', 'WebKit', 'PerformanceTests', 'Animation') return blink_perf.CreatePageSetFromPath(path) def CustomizeBrowserOptions(self, options): options.AppendExtraBrowserArgs('--enable-web-animations-css')
Hide back to top link from screen readers
<?php /** * Template for displaying the footer * * Description for template. * * @Author: Roni Laukkarinen * @Date: 2020-05-11 13:33:49 * @Last Modified by: Roni Laukkarinen * @Last Modified time: 2020-05-11 13:33:49 * * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials * @package air-light */ namespace Air_Light; ?> </div><!-- #content --> <footer id="colophon" class="site-footer"> <?php get_template_part( 'template-parts/footer/demo-content' ); ?> <a aria-hidden="true" href="#page" class="js-trigger top" data-mt-duration="300"><span class="screen-reader-text"><?php echo esc_html_e( 'Back to top', 'air-light' ); ?></span><?php include get_theme_file_path( '/svg/chevron-up.svg' ); ?></a> </footer><!-- #colophon --> </div><!-- #page --> <?php wp_footer(); ?> </body> </html>
<?php /** * Template for displaying the footer * * Description for template. * * @Author: Roni Laukkarinen * @Date: 2020-05-11 13:33:49 * @Last Modified by: Roni Laukkarinen * @Last Modified time: 2020-05-11 13:33:49 * * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials * @package air-light */ namespace Air_Light; ?> </div><!-- #content --> <footer id="colophon" class="site-footer"> <?php get_template_part( 'template-parts/footer/demo-content' ); ?> <a href="#page" class="js-trigger top" data-mt-duration="300"><span class="screen-reader-text"><?php echo esc_html_e( 'Back to top', 'air-light' ); ?></span><?php include get_theme_file_path( '/svg/chevron-up.svg' ); ?></a> </footer><!-- #colophon --> </div><!-- #page --> <?php wp_footer(); ?> </body> </html>
Add helper method for creating needed field mappings
package age; import java.io.IOException; import java.lang.reflect.Type; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Map; public class CSVReader { private static final int CLASS_INDEX = 0; public static void main(String[] args){ } public static void createMappingFromLine(String[] tokens, Map<String, Object> values, Map<String, String> fieldTypes){ for(int i = 1; i < tokens.length; i++){ String[] subtokens = tokens[i].split(":"); String fieldName = subtokens[0]; String value = subtokens[1]; String type = subtokens[2]; values.put(fieldName, SkillObjectCreator.valueOf(type, value)); fieldTypes.put(fieldName, type); } } public static String getClassNameFromEntry(String[] tokens){ if(tokens.length > 0){ return tokens[CLASS_INDEX]; }else{ return null; } } public static List<String> readCSV(Path path){ List<String> content = new ArrayList<>(); try{ Files.lines(path).forEach( (String line) -> { content.add(line); }); } catch (IOException e) { e.printStackTrace(); } return content; } }
package age; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; public class CSVReader { private static final int CLASS_INDEX = 0; public static void main(String[] args){ } public static String getClassNameFromLine(String line){ String[] tokens = line.split(";"); if(tokens.length > 0){ return tokens[CLASS_INDEX]; }else{ return null; } } public static List<String> readCSV(Path path){ List<String> content = new ArrayList<>(); try{ Files.lines(path).forEach( (String line) -> { content.add(line); }); } catch (IOException e) { e.printStackTrace(); } return content; } }
Rename server task to node
/* global require */ var gulp = require('gulp'), spawn = require('child_process').spawn, ember, node; gulp.task('node', function () { if (node) node.kill(); // Kill server if one is running node = spawn('node', ['server.js'], {cwd: 'node', stdio: 'inherit'}); node.on('close', function (code) { if (code === 8) { console.log('Node error detected, waiting for changes...'); } }); }); gulp.task('ember', function () { ember = spawn('./node_modules/.bin/ember', ['server', '--port=4900', '--proxy=http://localhost:3900'], {cwd: 'ember', stdio: 'inherit'}); ember.on('close', function (code) { if (code === 8) { console.log('Ember error detected, waiting for changes...'); } }); }); gulp.task('default', function () { gulp.run('node'); gulp.run('ember'); // Reload node if files changed gulp.watch(['node/**/*.js'], function () { gulp.run('node'); }); }); // kill node server on exit process.on('exit', function() { if (node) node.kill(); if (ember) ember.kill(); });
/* global require */ var gulp = require('gulp'), spawn = require('child_process').spawn, ember, node; gulp.task('server', function () { if (node) node.kill(); // Kill server if one is running node = spawn('node', ['server.js'], {cwd: 'node', stdio: 'inherit'}); node.on('close', function (code) { if (code === 8) { console.log('Node error detected, waiting for changes...'); } }); }); gulp.task('ember', function () { ember = spawn('./node_modules/.bin/ember', ['server', '--port=4900', '--proxy=http://localhost:3900'], {cwd: 'ember', stdio: 'inherit'}); ember.on('close', function (code) { if (code === 8) { console.log('Ember error detected, waiting for changes...'); } }); }); gulp.task('default', function () { gulp.run('server'); gulp.run('ember'); // Reload server if files changed gulp.watch(['node/**/*.js'], function () { gulp.run('server'); }); }); // kill node server on exit process.on('exit', function() { if (node) node.kill(); if (ember) ember.kill(); });
Add test task to grunt.
module.exports = function(grunt) { // Project configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: 'src/<%= pkg.name %>.js' }, uglify: { options: { banner: '/* <%= pkg.name %>.js v<%= pkg.version %>, Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author %>, <%= pkg.license %> License */\n' }, build: { src: 'src/<%= pkg.name %>.js', dest: 'dist/<%= pkg.name %>.min.js' } } }); // Load the plugin that provides the "uglify" task. grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); // Default task. grunt.registerTask('default', ['jshint', 'uglify']); // Test task grunt.registerTask('test', ['jshint']); }
module.exports = function(grunt) { // Project configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: 'src/<%= pkg.name %>.js' }, uglify: { options: { banner: '/* <%= pkg.name %>.js v<%= pkg.version %>, Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author %>, <%= pkg.license %> License */\n' }, build: { src: 'src/<%= pkg.name %>.js', dest: 'dist/<%= pkg.name %>.min.js' } } }); // Load the plugin that provides the "uglify" task. grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); // Default tast(s). grunt.registerTask('default', ['uglify', 'jshint']); }
Add message_type field into message model
from django.db import models class Channel(models.Model): def __str__(self): return self.name name = models.CharField(max_length=20, unique=True) class Message(models.Model): def __str__(self): return self.text def to_dict(self): serializable_fields = ('text', 'datetime_start', 'datetime_sent', 'username') return {key: getattr(self, key) for key in serializable_fields} TEXT = 'text' IMAGE = 'image' MESSAGE_TYPE = ( (TEXT, 'text'), (IMAGE, 'image'), ) text = models.TextField(max_length=2000) datetime_start = models.DateTimeField(default=None) datetime_sent = models.DateTimeField(default=None, null=True) typing = models.BooleanField(default=False) username = models.CharField(max_length=20) channel = models.ForeignKey(Channel) message_type = models.CharField(max_length=10, choices=MESSAGE_TYPE, default=TEXT)
from django.db import models class Channel(models.Model): def __str__(self): return self.name name = models.CharField(max_length=20, unique=True) class Message(models.Model): def __str__(self): return self.text def to_dict(self): serializable_fields = ('text', 'datetime_start', 'datetime_sent', 'username') return {key: getattr(self, key) for key in serializable_fields} text = models.TextField(max_length=2000) datetime_start = models.DateTimeField(default=None) datetime_sent = models.DateTimeField(default=None, null=True) typing = models.BooleanField(default=False) username = models.CharField(max_length=20) channel = models.ForeignKey(Channel)
Revert refactor to keep PR scoped well
import React, { Component } from 'react'; import config from 'config/environment'; import troopImage from 'images/Troop.png'; import styles from './idme.css'; class Idme extends Component { openIDME = () => { window.open(`${config.idmeOAuthUrl}?client_id=${config.idmeClientId}&redirect_uri=${ config.host }/profile/verify&response_type=token&scope=military&display=popup', '', 'scrollbars=yes,menubar=no,status=no,location=no,toolbar=no,width=750,height=780,top=200,left=200`); }; render() { return ( <div className={styles.wrapper}> {/* eslint-disable jsx-a11y/click-events-have-key-events */} <span className={styles.authbtn} role="link" onClick={this.openIDME} tabIndex={0}> <img className={styles.authImage} src={troopImage} alt="Verify your status with Id.Me" /> </span> </div> ); } } export default Idme;
import React, { Component } from 'react'; import config from 'config/environment'; import troopImage from 'images/Troop.png'; import styles from './idme.css'; class Idme extends Component { onKeyUp = (event) => { if (event.key === 'Enter') { this.idMe(); } }; onClick = () => { window.open(`${config.idmeOAuthUrl}?client_id=${config.idmeClientId}&redirect_uri=${ config.host }/profile/verify&response_type=token&scope=military&display=popup', '', 'scrollbars=yes,menubar=no,status=no,location=no,toolbar=no,width=750,height=780,top=200,left=200`); }; render() { return ( <div className={styles.wrapper}> <span className={styles.authbtn} role="link" onClick={this.onClick} onKeyUp={this.onKeyUp} tabIndex={0} > <img className={styles.authImage} src={troopImage} alt="Verify your status with Id.Me" /> </span> </div> ); } } export default Idme;
Reduce test coverage target for statements
const TEST_TYPE = ((argv) => { let match = argv[argv.length - 1].match(/npm\/test-(\w+).js/); return match && match[1] || ''; })(process.argv); function configOverrides(testType) { switch (testType) { case 'unit': return { statements: 55, branches: 40, functions: 40, lines: 60 }; default: return {} } } module.exports = { // @todo cover `all` files by writing unit test for bundled lib/sandbox files // all: true, 'check-coverage': true, 'report-dir': '.coverage', 'temp-dir': '.nyc_output', include: ['lib/**/*.js'], reporter: ['lcov', 'json', 'text', 'text-summary'], ...configOverrides(TEST_TYPE), };
const TEST_TYPE = ((argv) => { let match = argv[argv.length - 1].match(/npm\/test-(\w+).js/); return match && match[1] || ''; })(process.argv); function configOverrides(testType) { switch (testType) { case 'unit': return { statements: 60, branches: 40, functions: 40, lines: 60 }; default: return {} } } module.exports = { // @todo cover `all` files by writing unit test for bundled lib/sandbox files // all: true, 'check-coverage': true, 'report-dir': '.coverage', 'temp-dir': '.nyc_output', include: ['lib/**/*.js'], reporter: ['lcov', 'json', 'text', 'text-summary'], ...configOverrides(TEST_TYPE), };
Apply sanitization to limit, skip & p
module.exports = function( action, options ) { this.reservedParams.push('limit', 'skip', 'p'); if (action === 'index') { this.on('sanitize', function( req ) { req.sanitizeQuery('limit').toInt(); req.sanitizeQuery('skip').toInt(); req.sanitizeQuery('p').toInt(); }); this.on('validate', function( req ) { var maxLimit = options.maxLimit; req.checkQuery('limit').optional().isInt(); req.checkQuery('limit', 'limit must be greater than, or equal to 1').optional().isGTE(1); req.checkQuery('limit', 'limit must be less than, or equal to ' + maxLimit).optional().isLTE(maxLimit); req.checkQuery('skip').optional().isInt(); req.checkQuery('skip', 'skip must be greater than, or equal to 1').optional().isGTE(1); req.checkQuery('p').optional().isInt(); req.checkQuery('p', 'p must be greater than, or equal to 1').optional().isGTE(1); }); this.pre('query', function() { var page = this.req.query.p || 1, limit = this.req.query.limit || options.pageSize, skip = this.req.query.skip || limit * (page - 1); this.query.skip(skip); this.query.limit(limit); }); } };
module.exports = function( action, options ) { this.reservedParams.push('limit', 'skip', 'p'); if (action === 'index') { this.on('validate', function( req ) { var maxLimit = options.maxLimit; req.checkQuery('limit').optional().isInt(); req.checkQuery('limit', 'limit must be greater than, or equal to 1').optional().isGTE(1); req.checkQuery('limit', 'limit must be less than, or equal to ' + maxLimit).optional().isLTE(maxLimit); req.checkQuery('skip').optional().isInt(); req.checkQuery('skip', 'skip must be greater than, or equal to 1').optional().isGTE(1); req.checkQuery('p').optional().isInt(); req.checkQuery('p', 'p must be greater than, or equal to 1').optional().isGTE(1); }); this.pre('query', function() { var page = this.req.query.p || 1, limit = this.req.query.limit || options.pageSize, skip = this.req.query.skip || limit * (page - 1); this.query.skip(skip); this.query.limit(limit); }); } };
Add ∞ for infinite duration
export const formatBytes = (bytes) => { if (bytes === 0) { return '0 Bytes'; } if (!bytes) { return null; } const k = 1000; const dm = 2; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`; } export const formatRPDuration = (duration) => { if (duration === '0' || duration === '0s') { return '∞'; } let adjustedTime = duration; const [_, hours, minutes, seconds] = duration.match(/(\d*)h(\d*)m(\d*)s/); // eslint-disable-line no-unused-vars const hoursInDay = 24; if (hours > hoursInDay) { const remainder = hours % hoursInDay; const days = (hours - remainder) / hoursInDay; adjustedTime = `${days}d`; adjustedTime += +remainder === 0 ? '' : `${remainder}h`; adjustedTime += +minutes === 0 ? '' : `${minutes}m`; adjustedTime += +seconds === 0 ? '' : `${seconds}s`; } else { adjustedTime = `${hours}h`; adjustedTime += +minutes === 0 ? '' : `${minutes}m`; adjustedTime += +seconds === 0 ? '' : `${seconds}s`; } return adjustedTime; }
export const formatBytes = (bytes) => { if (bytes === 0) { return '0 Bytes'; } if (!bytes) { return null; } const k = 1000; const dm = 2; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`; } export const formatRPDuration = (duration) => { if (duration === '0' || duration === '0s') { return 'infinite'; } let adjustedTime = duration; const [_, hours, minutes, seconds] = duration.match(/(\d*)h(\d*)m(\d*)s/); // eslint-disable-line no-unused-vars const hoursInDay = 24; if (hours > hoursInDay) { const remainder = hours % hoursInDay; const days = (hours - remainder) / hoursInDay; adjustedTime = `${days}d`; adjustedTime += +remainder === 0 ? '' : `${remainder}h`; adjustedTime += +minutes === 0 ? '' : `${minutes}m`; adjustedTime += +seconds === 0 ? '' : `${seconds}s`; } else { adjustedTime = `${hours}h`; adjustedTime += +minutes === 0 ? '' : `${minutes}m`; adjustedTime += +seconds === 0 ? '' : `${seconds}s`; } return adjustedTime; }
Make changes to get_hosts() to return a list of dict
#!/usr/bin/env python # -*- coding: utf-8 -*- """ AnsibleInventory: INTRO: USAGE: """ import os import ansible.inventory class AnsibleInventory(object): ''' Ansible Inventory wrapper class. ''' def __init__(self, inventory_filename): ''' Initialize Inventory ''' if not os.path.exists(inventory_filename): print "Provide a valid inventory filename" return self.inventory = ansible.inventory.InventoryParser(inventory_filename) def get_hosts(self, group=None): ''' Get the hosts ''' hostlist = [] for group in self.inventory.groups: groupdict = {} groupdict['group'] = group groupdict['hostlist'] = [] groupobj = self.inventory.groups.get(group) for host in groupobj.get_hosts(): groupdict['hostlist'].append(host.name) hostlist.append(groupdict) return hostlist
#!/usr/bin/env python # -*- coding: utf-8 -*- """ AnsibleInventory: INTRO: USAGE: """ import os import ansible.inventory class AnsibleInventory(object): ''' Ansible Inventory wrapper class. ''' def __init__(self, inventory_filename): ''' Initialize Inventory ''' if not os.path.exists(inventory_filename): print "Provide a valid inventory filename" return self.inventory = ansible.inventory.InventoryParser(inventory_filename) def get_hosts(self, group=None): ''' Get the hosts ''' if not group: return self.inventory.hosts.keys() groupobj = self.inventory.groups.get(group, None) if not groupobj: return None hostobjs = groupobj.get_hosts() hostlist = [] for host in hostobjs: hostlist.append(host.name) return hostlist
Store pretty printed version of cassete
var mkdirp = require('mkdirp'); var fs = require('fs'); var getDirName = require('path').dirname; function serialize(response) { return { status: response.status, statusText: response.statusText, headers: response.headers, data: response.data } } function store(path, payload) { mkdirp.sync(getDirName(path)); var json = JSON.stringify(payload, null, '\t'); return new Promise(function(resolve, reject) { fs.writeFile(path, json, { mode: 0o777 }, function(err) { if (err) reject(err); else resolve(); }); }) } exports.success = function (cassetePath) { return function(response) { var serialized = serialize(response) return store(cassetePath, serialized).then(function() { return response; }) } }; exports.failure = function(error) { return Promise.reject(error); };
var mkdirp = require('mkdirp'); var fs = require('fs'); var getDirName = require('path').dirname; function serialize(response) { return { status: response.status, statusText: response.statusText, headers: response.headers, data: response.data } } function store(path, payload) { mkdirp.sync(getDirName(path)); var json = JSON.stringify(payload); return new Promise(function(resolve, reject) { fs.writeFile(path, json, { mode: 0o777 }, function(err) { if (err) reject(err); else resolve(); }); }) } exports.success = function (cassetePath) { return function(response) { var serialized = serialize(response) return store(cassetePath, serialized).then(function() { return response; }) } }; exports.failure = function(error) { return Promise.reject(error); };
III-1406: Rename audience type enum instantiation spec
<?php namespace CultuurNet\UDB3\Event\ValueObjects; class AudienceTypeTest extends \PHPUnit_Framework_TestCase { /** * @test */ public function it_should_instantiate_audience_type_enums_by_a_name() { $options = AudienceType::getConstants(); $this->assertEquals( [ AudienceType::EVERYONE()->getName() => AudienceType::EVERYONE(), AudienceType::MEMBERS()->getName() => AudienceType::MEMBERS(), AudienceType::EDUCATION()->getName() => AudienceType::EDUCATION(), ], $options ); } }
<?php namespace CultuurNet\UDB3\Event\ValueObjects; class AudienceTypeTest extends \PHPUnit_Framework_TestCase { /** * @test */ public function it_has_specified_options() { $options = AudienceType::getConstants(); $this->assertEquals( [ AudienceType::EVERYONE()->getName() => AudienceType::EVERYONE(), AudienceType::MEMBERS()->getName() => AudienceType::MEMBERS(), AudienceType::EDUCATION()->getName() => AudienceType::EDUCATION(), ], $options ); } }
IssueNotesRefactor: Add existence check to find the note.
import _ from 'underscore'; export const notes = state => state.notes; export const targetNoteHash = state => state.targetNoteHash; export const getNotesData = state => state.notesData; export const getNotesDataByProp = state => prop => state.notesData[prop]; export const getIssueData = state => state.issueData; export const getIssueDataByProp = state => prop => state.issueData[prop]; export const getUserData = state => state.userData || {}; export const getUserDataByProp = state => prop => state.userData && state.userData[prop]; export const notesById = state => state.notes.reduce((acc, note) => { note.notes.every(n => Object.assign(acc, { [n.id]: n })); return acc; }, {}); const reverseNotes = array => array.slice(0).reverse(); const isLastNote = (note, state) => !note.system && state.userData !== undefined && note.author && note.author.id === state.userData.id; export const getCurrentUserLastNote = state => _.flatten( reverseNotes(state.notes) .map(note => reverseNotes(note.notes)), ).find(el => isLastNote(el, state)); export const getDiscussionLastNote = state => discussion => reverseNotes(discussion.notes) .find(el => isLastNote(el, state));
import _ from 'underscore'; export const notes = state => state.notes; export const targetNoteHash = state => state.targetNoteHash; export const getNotesData = state => state.notesData; export const getNotesDataByProp = state => prop => state.notesData[prop]; export const getIssueData = state => state.issueData; export const getIssueDataByProp = state => prop => state.issueData[prop]; export const getUserData = state => state.userData || {}; export const getUserDataByProp = state => prop => state.userData && state.userData[prop]; export const notesById = state => state.notes.reduce((acc, note) => { note.notes.every(n => Object.assign(acc, { [n.id]: n })); return acc; }, {}); const reverseNotes = array => array.slice(0).reverse(); const isLastNote = (note, state) => !note.system && state.userData !== undefined && note.author.id === state.userData.id; export const getCurrentUserLastNote = state => _.flatten( reverseNotes(state.notes) .map(note => reverseNotes(note.notes)), ).find(el => isLastNote(el, state)); export const getDiscussionLastNote = state => discussion => reverseNotes(discussion.notes) .find(el => isLastNote(el, state));
Simplify enyo.load call since it handles arrays natively Enyo-DCO-1.1-Signed-Off-By: Ben Combee (ben.combee@lge.com)
(function() { if(window.cordova || window.PhoneGap) { var v = window.useCordovaTVVersion||"3.0"; var externalModules = [ "/usr/palm/frameworks/cordova-tv/" + v + "/advertisement.js", "/usr/palm/frameworks/cordova-tv/" + v + "/billing.js", "/usr/palm/frameworks/cordova-tv/" + v + "/broadcast.js", "/usr/palm/frameworks/cordova-tv/" + v + "/camera.js", "/usr/palm/frameworks/cordova-tv/" + v + "/deviceinfo.js", "/usr/palm/frameworks/cordova-tv/" + v + "/drmagent.js", "/usr/palm/frameworks/cordova-tv/" + v + "/mrcu.js", "/usr/palm/frameworks/cordova-tv/" + v + "/push.js", "/usr/palm/frameworks/cordova-tv/" + v + "/upnp.js" ]; enyo.load(externalModules); } else { enyo.warn("Cordova not found, ignoring tv modules"); } })();
(function() { if(window.cordova || window.PhoneGap) { var v = window.useCordovaTVVersion||"3.0"; var externalModules = [ "/usr/palm/frameworks/cordova-tv/" + v + "/advertisement.js", "/usr/palm/frameworks/cordova-tv/" + v + "/billing.js", "/usr/palm/frameworks/cordova-tv/" + v + "/broadcast.js", "/usr/palm/frameworks/cordova-tv/" + v + "/camera.js", "/usr/palm/frameworks/cordova-tv/" + v + "/deviceinfo.js", "/usr/palm/frameworks/cordova-tv/" + v + "/drmagent.js", "/usr/palm/frameworks/cordova-tv/" + v + "/mrcu.js", "/usr/palm/frameworks/cordova-tv/" + v + "/push.js", "/usr/palm/frameworks/cordova-tv/" + v + "/upnp.js" ]; enyo.load.apply(enyo, externalModules); } else { enyo.warn("Cordova not found, ignoring tv modules"); } })();
Make edit link show form.
$(document).ready(function() { // Delete $('#content').on('submit', 'form.delete_form', function (event) { event.preventDefault(); var $target = $(event.target); $.ajax({ url: $target.attr('action'), type: 'DELETE' }).done(function(response) { $target.closest('.task').remove(); }); }); // Toggle $('#content').on('submit', 'form.toggle_form', function (event) { event.preventDefault(); var $target = $(event.target); var $complete_btn = $target.children('input[type=submit]'); $complete_btn.attr("disabled", true); $.ajax({ url: $target.attr('action'), type: 'PUT' }).done(function (response) { $target.closest('.task').replaceWith(response); }) }) // Edit link $('#content').on('click', 'a.edit_link', function(event) { event.preventDefault(); var $target = $(event.target); $target.closest('.task').children('.edit_wrapper').show(); }); });
$(document).ready(function() { // This is called after the document has loaded in its entirety // This guarantees that any elements we bind to will exist on the page // when we try to bind to them // See: http://docs.jquery.com/Tutorials:Introducing_$(document).ready() $('#content').on('submit', 'form.delete_form', function (event) { event.preventDefault(); var $target = $(event.target); $.ajax({ url: $target.attr('action'), type: 'DELETE' }).done(function(response) { $target.closest('.task').remove(); }); }); $('#content').on('submit', 'form.toggle_form', function (event) { event.preventDefault(); var $target = $(event.target); var $complete_btn = $target.children('input[type=submit]'); $complete_btn.attr("disabled", true); $.ajax({ //url: '/task/' + task_id + '/toggle_complete' url: $target.attr('action'), type: 'PUT' }).done(function (response) { $target.closest('.task').replaceWith(response); // $target.closest('.task').find('p.description').first().toggleClass('strikethrough'); // // Deal with the button // var text = $complete_btn.val() == "Complete" ? "Uncomplete" : "Complete"; // $complete_btn.val(text); // $complete_btn.attr("disabled", false); }) }) });
Use named parameters on command-line closes #202
process.env.NODE_ENV = 'test' const {MongoClient} = require('mongodb'), N = require('nitroglycerin') var db = null const getDb = (done) => { if (db) return done(db) MongoClient.connect("mongodb://localhost:27017/exosphere-_____serviceRole_____-test", N( (mongoDb) => { db = mongoDb done(db) })) } module.exports = function() { this.setDefaultTimeout(1000) this.Before( function(_scenario, done) { getDb( (db) => { db.collection('_____modelName_____s').drop(function(err) { // ignore errors here, since we are only cleaning up the test database // and it might not even exist done() }) }) }) this.After(function() { this.exocom && this.exocom.close() this.process && this.process.close() }) this.registerHandler('AfterFeatures', (_event, done) => { getDb( (db) => { db.collection('_____modelName_____s').drop() db.close(function(err, result){ if (err) { throw new Error(err) } done() }) }) }) }
process.env.NODE_ENV = 'test' const {MongoClient} = require('mongodb'), N = require('nitroglycerin') var db = null const getDb = (done) => { if (db) return done(db) MongoClient.connect("mongodb://localhost:27017/exosphere-_____serviceRole_____-test", N( (mongoDb) => { db = mongoDb done(db) })) } module.exports = function() { this.setDefaultTimeout(1000) this.Before( function(_scenario, done) { getDb( (db) => { db.collection('_____modelName_____s').drop() done() }) }) this.After(function() { this.exocom && this.exocom.close() this.process && this.process.close() }) this.registerHandler('AfterFeatures', (_event, done) => { getDb( (db) => { db.collection('_____modelName_____s').drop() db.close(function(err, result){ if (err) { throw new Error(err) } done() }) }) }) }
Use the object instead of the class
from django.db import models def register(cls, admin_cls): cls.add_to_class('_prepared_date', models.TextField('Date of Preparation', blank=True, null=True)) def getter(obj): if not obj._prepared_date: try: return obj.get_ancestors(ascending=True).filter(_prepared_date__isnull=False)[0]._prepared_date except IndexError: return None return obj._prepared_date def setter(obj, value): obj._prepared_date = value cls.prepared_date = property(getter, setter) if admin_cls and admin_cls.fieldsets: admin_cls.fieldsets[2][1]['fields'].append('_prepared_date')
from django.db import models def register(cls, admin_cls): cls.add_to_class('_prepared_date', models.TextField('Date of Preparation', blank=True, null=True)) def getter(): if not cls._prepared_date: try: return cls.get_ancestors(ascending=True).filter(_prepared_date__isnull=False)[0]._prepared_date except IndexError: return None return cls._prepared_date def setter(value): cls._prepared_date = value cls.prepared_date = property(getter, setter) if admin_cls and admin_cls.fieldsets: admin_cls.fieldsets[2][1]['fields'].append('_prepared_date')
Set icon, summary for notification
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import subprocess as spr import time def main(): start = datetime.datetime.now() start_str = start.strftime("%H:%M:%S") spr.call(['notify-send', '--app-name', 'POMODORO', '--icon', 'dialog-information', 'New pomodoro', 'From: {}'.format(start_str)]) time.sleep(30 * 60) end = datetime.datetime.now() duration = (end - start).total_seconds() // 60 for i in range(5): time.sleep(3) spr.call( ['notify-send', 'POMO: {0:.0f} minute passed.\tFrom {1}'.format( duration, start_str ) ] ) if __name__ == "__main__": main()
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import subprocess as spr import time def main(): start = datetime.datetime.now() spr.call(['notify-send', 'Started new pomodoro']) time.sleep(30 * 60) end = datetime.datetime.now() duration = (end - start).total_seconds() // 60 for i in range(5): time.sleep(3) spr.call( ['notify-send', 'POMO: {0:.0f} minute passed.\tFrom {1}'.format( duration, start.strftime("%H:%M:%S")) ] ) if __name__ == "__main__": main()
Use weak but dependency-free entropy source in PhutilOpaqueEnvelope Summary: If PHP doesn't have access to /dev/urandom, we currently fatal here before we can get to the setup check for it. To avoid this, use a weaker random source. This doesn't need to be a strong random source, since it's only protecting against accidental disclosure through logs, etc. Test Plan: - Dumped the resulting key and verified it "looked" random. - Dumped a bunch of them to a file and gzipped it, verified it got larger. - Had user in question apply patch and verified he got to the /dev/urandom setup check ("open_basedir configured crazy"). Reviewers: vrana, btrahan, asherkin Reviewed By: asherkin CC: aran Differential Revision: https://secure.phabricator.com/D4561
<?php /** * Holds the key for @{class:PhutilOpaqueEnvelope} in a logically distant * location so it will never appear in stack traces, etc. You should never need * to use this class directly. See @{class:PhutilOpaqueEnvelope} for * information about opaque envelopes. * * @task internal Internals */ final class PhutilOpaqueEnvelopeKey { private static $key; /* -( Internals )---------------------------------------------------------- */ /** * @task internal */ private function __construct() { // <private> } /** * @task internal */ public static function getKey() { if (self::$key === null) { // NOTE: We're using a weak random source because cryptographic levels // of security aren't terribly important here and it allows us to use // envelopes on systems which don't have a strong random source. Notably, // this lets us make it to the readbility check for `/dev/urandom` in // Phabricator on systems where we can't read it. self::$key = ''; for ($ii = 0; $ii < 8; $ii++) { self::$key .= md5(mt_rand(), $raw_output = true); } } return self::$key; } }
<?php /** * Holds the key for @{class:PhutilOpaqueEnvelope} in a logically distant * location so it will never appear in stack traces, etc. You should never need * to use this class directly. See @{class:PhutilOpaqueEnvelope} for * information about opaque envelopes. * * @task internal Internals */ final class PhutilOpaqueEnvelopeKey { private static $key; /* -( Internals )---------------------------------------------------------- */ /** * @task internal */ private function __construct() { // <private> } /** * @task internal */ public static function getKey() { if (self::$key === null) { try { self::$key = Filesystem::readRandomBytes(128); } catch (Exception $ex) { // NOTE: We can't throw here! Otherwise we might get a stack trace // including the string that was passed to PhutilOpaqueEnvelope's // constructor. Just die() instead. die( "Unable to read random bytes in PhutilOpaqueEnvelope. (This ". "causes an immediate process exit to avoid leaking the envelope ". "contents in a stack trace.)"); } } return self::$key; } }
Use the official notation of the Django package Even if pypi is case insensitive, all other packages include django with an uppercase D. This package using lowercase will lead to uninstalls/reinstalls when using pip-compile and other tools. Please accept the change to make it compatible.
import os from setuptools import setup, find_packages version = "1.4.0" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "django-macaddress", version = version, url = 'http://github.com/tubaman/django-macaddress', license = 'BSD', description = "MAC address model and form fields for Django apps.", long_description = read('README.rst'), author = 'Ryan Nowakowski', author_email = 'tubaman@fattuba.com', maintainer = 'Arun K. R.', maintainer_email = 'the1.arun@gmail.com', packages = ['macaddress', 'macaddress.tests'], install_requires = ['netaddr'], tests_require = ['Django'], test_suite="runtests.runtests", classifiers = [ 'Development Status :: 5 - Production/Stable', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', ] )
import os from setuptools import setup, find_packages version = "1.4.0" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "django-macaddress", version = version, url = 'http://github.com/tubaman/django-macaddress', license = 'BSD', description = "MAC address model and form fields for Django apps.", long_description = read('README.rst'), author = 'Ryan Nowakowski', author_email = 'tubaman@fattuba.com', maintainer = 'Arun K. R.', maintainer_email = 'the1.arun@gmail.com', packages = ['macaddress', 'macaddress.tests'], install_requires = ['netaddr'], tests_require = ['django'], test_suite="runtests.runtests", classifiers = [ 'Development Status :: 5 - Production/Stable', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', ] )
Fix wrong change for package.
/* * $Id$ * * Copyright 2009 Hiroki Ata * * 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 org.aexlib.gae; import java.io.File; import com.google.appengine.tools.development.ApiProxyLocalImpl; import com.google.apphosting.api.ApiProxy; import junit.framework.TestCase; public class GAEBaseTestCase extends TestCase { @Override protected void setUp() throws Exception { super.setUp(); ApiProxy.setEnvironmentForCurrentThread(new TestEnvironment()); ApiProxy.setDelegate(new ApiProxyLocalImpl(new File("target")){}); } @Override protected void tearDown() throws Exception { // not strictly necessary to null these out but there's no harm either ApiProxy.setDelegate(null); ApiProxy.setEnvironmentForCurrentThread(null); super.tearDown(); } public void testDummy() { } }
/* * $Id$ * * Copyright 2009 Hiroki Ata * * 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 org.aexlib.gae; import java.io.File; import org.aexlib.gae.tool.TestEnvironment; import com.google.appengine.tools.development.ApiProxyLocalImpl; import com.google.apphosting.api.ApiProxy; import junit.framework.TestCase; public class GAEBaseTestCase extends TestCase { @Override protected void setUp() throws Exception { super.setUp(); ApiProxy.setEnvironmentForCurrentThread(new TestEnvironment()); ApiProxy.setDelegate(new ApiProxyLocalImpl(new File("target")){}); } @Override protected void tearDown() throws Exception { // not strictly necessary to null these out but there's no harm either ApiProxy.setDelegate(null); ApiProxy.setEnvironmentForCurrentThread(null); super.tearDown(); } public void testDummy() { } }
Remove spurious console.log from yepnope path filter
/** * YepNope Path Filter * * Usage: * yepnope.paths = { * 'google': '//ajax.googleapis.com/ajax', * 'my-cdn': '//cdn.myawesomesite.com' * }; * yepnope({ * load: ['google/jquery/1.7.2/jquery.min.js', 'google/jqueryui/1.8.18/jquery-ui.min.js', 'my-cdn/style.css', '/non/path/directory/file.js'] * }); * * Official Yepnope Plugin * * WTFPL License * * by Kenneth Powers | mail@kenpowers.net */ (function () { var addPathFilter = function (yn) { // add each prefix yn.addFilter(function (resource) { // check each url for path for (path in yn.paths) { resource.url = resource.url.replace(new RegExp('^' + path), yn.paths[path]); return resource; } // carry on my wayward, son return resource; }); }; if (yepnope) addPathFilter(yepnope); else if (modernizr.load) addPathFilter(modernizr.load); })();
/** * YepNope Path Filter * * Usage: * yepnope.paths = { * 'google': '//ajax.googleapis.com/ajax', * 'my-cdn': '//cdn.myawesomesite.com' * }; * yepnope({ * load: ['google/jquery/1.7.2/jquery.min.js', 'google/jqueryui/1.8.18/jquery-ui.min.js', 'my-cdn/style.css', '/non/path/directory/file.js'] * }); * * Official Yepnope Plugin * * WTFPL License * * by Kenneth Powers | mail@kenpowers.net */ (function () { var addPathFilter = function (yn) { // add each prefix yn.addFilter(function (resource) { // check each url for path for (path in yn.paths) { resource.url = resource.url.replace(new RegExp('^' + path), yn.paths[path]); return resource; } // carry on my wayward, son return resource; }); }; console.log(yepnope); if (yepnope) addPathFilter(yepnope); else if (modernizr.load) addPathFilter(modernizr.load); })();
Refactor .catch's to use util.handleError
var Roadmap = require('./roadmapModel.js'), handleError = require('../../util.js').handleError; module.exports = { createRoadmap : function (req, res, next) { var newRoadmap = req.body; Roadmap(newRoadmap).save() .then(function(dbResults){ res.status(201).json(dbResults); }) .catch(handleError(next)); }, getRoadmaps : function (req, res, next) { Roadmap.find({}) .then(function(dbResults){ res.status(200).json(dbResults); }) .catch(handleError(next)); }, getRoadmapByID : function (req, res, next) { var _id = req.params.roadmapID; Roadmap.findById(_id) .then(function(dbResults){ res.json(dbResults); }) .catch(handleError(next)); }, updateRoadmap : function (req, res, next) { }, deleteRoadmap : function (req, res, next) { } };
var Roadmap = require('./roadmapModel.js'); module.exports = { createRoadmap : function (req, res, next) { var newRoadmap = req.body; Roadmap(newRoadmap).save() .then(function(dbResults){ res.status(201).json(dbResults); }) .catch(function(err){ next(err); }); }, getRoadmaps : function (req, res, next) { Roadmap.find({}) .then(function(dbResults){ res.status(200).json(dbResults); }) .catch(function(err){ next(err); }); }, getRoadmapByID : function (req, res, next) { }, updateRoadmap : function (req, res, next) { }, deleteRoadmap : function (req, res, next) { } };
[YIL-83] Fix sonar: add functional interface.
/* * This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT) * * Copyright (c) 2017 Grégory Van den Borre * * More infos available: https://www.yildiz-games.be * * 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. */ package be.yildiz.shared.entity; /** * @author Grégory Van den Borre */ @FunctionalInterface public interface EntityCreator<T extends Entity> { T create(EntityToCreate e); }
/* * This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT) * * Copyright (c) 2017 Grégory Van den Borre * * More infos available: https://www.yildiz-games.be * * 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. */ package be.yildiz.shared.entity; /** * @author Grégory Van den Borre */ public interface EntityCreator<T extends Entity> { T create(EntityToCreate e); }
Check if there is a server before shutting it down
import startMirage from 'ember-cli-mirage/start-mirage'; import { settled } from '@ember/test-helpers'; // // Used to set up mirage for a test. Must be called after one of the // `ember-qunit` `setup*Test()` methods. It starts the server and sets // `this.server` to point to it, and shuts the server down when the test // finishes. // // NOTE: the `hooks = self` is for mocha support // export default function setupMirage(hooks = self) { hooks.beforeEach(function() { if (!this.owner) { throw new Error('You must call one of the ember-qunit setupTest(),' + ' setupRenderingTest() or setupApplicationTest() methods before' + ' calling setupMirage()'); } this.server = startMirage(this.owner); }); hooks.afterEach(function() { return settled().then(() => { if (this.server) { this.server.shutdown(); delete this.server; } }); }); }
import startMirage from 'ember-cli-mirage/start-mirage'; import { settled } from '@ember/test-helpers'; // // Used to set up mirage for a test. Must be called after one of the // `ember-qunit` `setup*Test()` methods. It starts the server and sets // `this.server` to point to it, and shuts the server down when the test // finishes. // // NOTE: the `hooks = self` is for mocha support // export default function setupMirage(hooks = self) { hooks.beforeEach(function() { if (!this.owner) { throw new Error('You must call one of the ember-qunit setupTest(),' + ' setupRenderingTest() or setupApplicationTest() methods before' + ' calling setupMirage()'); } this.server = startMirage(this.owner); }); hooks.afterEach(function() { return settled().then(() => { this.server.shutdown(); delete this.server; }); }); }
Make chandl available directly on the command line
# -*- coding: utf-8 -*- import codecs from setuptools import setup, find_packages def _read_file(name, encoding='utf-8'): """ Read the contents of a file. :param name: The name of the file in the current directory. :param encoding: The encoding of the file; defaults to utf-8. :return: The contents of the file. """ with codecs.open(name, encoding=encoding) as f: return f.read() setup( name='chandl', version='0.0.1', description='A lightweight tool for parsing and downloading 4chan threads.', long_description=_read_file('README.md'), license='MIT', url='https://github.com/gebn/chandl', author='George Brighton', author_email='oss@gebn.co.uk', packages=find_packages(), install_requires=[ 'six>=1.9.0' ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Topic :: Utilities' ], entry_points={ 'console_scripts': [ 'chandl = chandl.__main__:main', ] } )
# -*- coding: utf-8 -*- import codecs from setuptools import setup, find_packages def _read_file(name, encoding='utf-8'): """ Read the contents of a file. :param name: The name of the file in the current directory. :param encoding: The encoding of the file; defaults to utf-8. :return: The contents of the file. """ with codecs.open(name, encoding=encoding) as f: return f.read() setup( name='chandl', version='0.0.1', description='A lightweight tool for parsing and downloading 4chan threads.', long_description=_read_file('README.md'), license='MIT', url='https://github.com/gebn/chandl', author='George Brighton', author_email='oss@gebn.co.uk', packages=find_packages(), install_requires=[ 'six>=1.9.0' ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Topic :: Utilities' ] )
Make IUCNredlist connector to work in V2.
<?php namespace php_active_record; define('DOWNLOAD_WAIT_TIME', '300000'); // .3 seconds wait time include_once(dirname(__FILE__) . "/../../config/environment.php"); require_library('connectors/IUCNRedlistAPI'); $GLOBALS['ENV_DEBUG'] = false; // create new _temp file $resource_file = fopen(CONTENT_RESOURCE_LOCAL_PATH . "211_temp.xml", "w+"); // start the resource file with the XML header fwrite($resource_file, \SchemaDocument::xml_header()); // query IUCN and write results to file IUCNRedlistAPI::get_taxon_xml($resource_file); // write the resource footer fwrite($resource_file, \SchemaDocument::xml_footer()); fclose($resource_file); // cache the previous version and make this new version the current version @unlink(CONTENT_RESOURCE_LOCAL_PATH . "211_previous.xml"); @rename(CONTENT_RESOURCE_LOCAL_PATH . "211.xml", CONTENT_RESOURCE_LOCAL_PATH . "211_previous.xml"); rename(CONTENT_RESOURCE_LOCAL_PATH . "211_temp.xml", CONTENT_RESOURCE_LOCAL_PATH . "211.xml"); // set to force harvest if(filesize(CONTENT_RESOURCE_LOCAL_PATH . "211.xml")) { $GLOBALS['db_connection']->update("UPDATE resources SET resource_status_id=" . ResourceStatus::force_harvest()->id . " WHERE id=211"); } ?>
<?php define('DOWNLOAD_WAIT_TIME', '300000'); // .3 seconds wait time include_once(dirname(__FILE__) . "/../../config/environment.php"); require_library('connectors/IUCNRedlistAPI'); $GLOBALS['ENV_DEBUG'] = false; // create new _temp file $resource_file = fopen(CONTENT_RESOURCE_LOCAL_PATH . "211_temp.xml", "w+"); // start the resource file with the XML header fwrite($resource_file, SchemaDocument::xml_header()); // query IUCN and write results to file IUCNRedlistAPI::get_taxon_xml($resource_file); // write the resource footer fwrite($resource_file, SchemaDocument::xml_footer()); fclose($resource_file); // cache the previous version and make this new version the current version @unlink(CONTENT_RESOURCE_LOCAL_PATH . "211_previous.xml"); @rename(CONTENT_RESOURCE_LOCAL_PATH . "211.xml", CONTENT_RESOURCE_LOCAL_PATH . "211_previous.xml"); rename(CONTENT_RESOURCE_LOCAL_PATH . "211_temp.xml", CONTENT_RESOURCE_LOCAL_PATH . "211.xml"); // set to force harvest if(filesize(CONTENT_RESOURCE_LOCAL_PATH . "211.xml")) { $GLOBALS['db_connection']->update("UPDATE resources SET resource_status_id=".ResourceStatus::find_or_create_by_label('Force Harvest')->id." WHERE id=211"); } ?>
Add support for varnish backend secret and pass a domain when it's defined in settings
import varnish import logging from django.conf import settings #STUB config options here VARNISH_HOST = settings.VARNISH_HOST VARNISH_PORT = settings.VARNISH_PORT VARNISH_DEBUG = settings.DEBUG VARNISH_SECRET = settings.VARNISH_SECRET or None VARNISH_SITE_DOMAIN = settings.VARNISH_SITE_DOMAIN or '.*' class VarnishManager(object): def __init__(self): varnish_url = "{host}:{port}".format(host=VARNISH_HOST, port=VARNISH_PORT) self.handler = varnish.VarnishHandler(varnish_url, secret=VARNISH_SECRET) def __send_command(self, command): if VARNISH_DEBUG: logging.info("unrun cache command (debug on): {0}".format(command)) else: self.handler.fetch(command.encode('utf-8')) def close(self): self.handler.close() def purge(self, command): cmd = r'ban req.http.host ~ "{host}" && req.url ~ "{url}"'.format( host = VARNISH_SITE_DOMAIN.encode('ascii'), url = command.encode('ascii'), ) self.__send_command(cmd) def purge_all(self): return self.expire('.*')
import varnish import logging from django.conf import settings #STUB config options here VARNISH_HOST = settings.VARNISH_HOST VARNISH_PORT = settings.VARNISH_PORT VARNISH_DEBUG = settings.DEBUG VARNISH_SITE_DOMAIN = ".*" class VarnishManager(object): def __init__(self): self.handler = varnish.VarnishHandler([VARNISH_HOST, VARNISH_PORT]) def __send_command(self, command): if VARNISH_DEBUG: logging.info("unrun cache command (debug on): {0}".format(command)) else: self.handler.fetch(command.encode('utf-8')) def close(self): self.handler.close() def purge(self, command): cmd = r'ban req.http.host ~ "{host}" && req.url ~ "{url}"'.format( host = VARNISH_SITE_DOMAIN.encode('ascii'), url = command.encode('ascii'), ) self.__send_command(cmd) def purge_all(self): return self.expire('.*')
Change specific driver version in Opera test
/* * (C) Copyright 2015 Boni Garcia (http://bonigarcia.github.io/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.github.bonigarcia.wdm.test.opera; import org.junit.jupiter.api.BeforeEach; import org.openqa.selenium.opera.OperaDriver; import io.github.bonigarcia.wdm.test.base.VersionTestParent; /** * Test asserting operadriver versions. * * @author Boni Garcia * @since 1.2.2 */ class OperaVersionTest extends VersionTestParent { @BeforeEach void setup() { driverClass = OperaDriver.class; specificVersions = new String[] { "2.45", "91.0.4472.77" }; } }
/* * (C) Copyright 2015 Boni Garcia (http://bonigarcia.github.io/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.github.bonigarcia.wdm.test.opera; import org.junit.jupiter.api.BeforeEach; import org.openqa.selenium.opera.OperaDriver; import io.github.bonigarcia.wdm.test.base.VersionTestParent; /** * Test asserting operadriver versions. * * @author Boni Garcia * @since 1.2.2 */ class OperaVersionTest extends VersionTestParent { @BeforeEach void setup() { driverClass = OperaDriver.class; specificVersions = new String[] { "0.2.2", "2.32" }; } }
Stop sorting sessions by ID (column removed).
package io.miti.beetle.cache; import io.miti.beetle.model.Session; import java.util.List; public final class SessionCache { /** The one instance of the cache object. */ private static final SessionCache cache; /** The list of objects in the cache. */ private List<Session> list = null; /** Instantiate the cache. */ static { cache = new SessionCache(); } /** * Private default constructor. */ private SessionCache() { super(); } /** * Get the cache. * * @return the data cache */ public static SessionCache get() { return cache; } /** * Load the cache. */ public void loadCache() { if (list != null) { return; } list = Session.getList(); } public List<Session> getList() { return list; } /** * Print the list of objects in the cache. */ public void printList() { if (list == null) { System.out.println("(List is null)"); return; } System.out.println("Session Objects:"); for (Session obj : list) { System.out.println(" " + obj.toString()); } } }
package io.miti.beetle.cache; import io.miti.beetle.model.Session; import java.util.List; public final class SessionCache { /** The one instance of the cache object. */ private static final SessionCache cache; /** The list of objects in the cache. */ private List<Session> list = null; /** Instantiate the cache. */ static { cache = new SessionCache(); } /** * Private default constructor. */ private SessionCache() { super(); } /** * Get the cache. * * @return the data cache */ public static SessionCache get() { return cache; } /** * Load the cache. */ public void loadCache() { if (list != null) { return; } list = Session.getList("order by ID"); } public List<Session> getList() { return list; } /** * Print the list of objects in the cache. */ public void printList() { if (list == null) { System.out.println("(List is null)"); return; } System.out.println("Session Objects:"); for (Session obj : list) { System.out.println(" " + obj.toString()); } } }
Add link from candidate thumbnail to candidate detail page
import React from 'react'; import { Image } from 'react-bootstrap' import { Route } from 'react-router-dom' import CandidateCounter from './CandidateCounter' import styles from './candidatethumbnail.css' export default class CandidateThumbnail extends React.Component { render() { return ( <Route render={({ history}) => ( <div className="col-lg-4 col-md-4 col-sm-12 col-xs-12"> <div className="card" onClick = {() => { history.push('/election/dkijakarta/candidate/'+this.props.name) }}> <div className="candidate-card-title"> <h3>{this.props.name}</h3> </div> <div className="candidate-card-divider"></div> <div className="candidate-card-image-link" > <Image className="candidate-card-image" src={this.props.img} responsive/> </div> <div className="candidate-card-counter"> <CandidateCounter counter={this.props.counter}/> </div> </div> </div> )} /> ); } }
import React from 'react'; import { Image } from 'react-bootstrap' import CandidateCounter from './CandidateCounter' import styles from './candidatethumbnail.css' export default class CandidateThumbnail extends React.Component { render() { return ( <div className="col-lg-4 col-md-4 col-sm-12 col-xs-12"> <div className="card"> <div className="candidate-card-title"> <h3>{this.props.name}</h3> </div> <div className="candidate-card-divider"></div> <div className="candidate-card-image-link"> <Image className="candidate-card-image" src={this.props.img} responsive/> </div> <div className="candidate-card-counter"> <CandidateCounter counter={this.props.counter}/> </div> </div> </div> ); } }
Update for React Router 4
import React, { Component } from 'react'; import { connect } from 'react-redux'; export default function(ComposedComponent) { function mapStateToProps(state) { return { authenticated: state.auth.authenticated }; } class Authentication extends Component { // static contextTypes = { // router: React.PropTypes.object // } componentWillMount() { if (!this.props.authenticated) { this.props.history.push('/'); } } componentWillUpdate(nextProps) { if (!nextProps.authenticated) { this.props.history.push('/'); } } render() { return <ComposedComponent {...this.props} /> } } return connect(mapStateToProps)(Authentication); }
import React, { Component } from 'react'; import { connect } from 'react-redux'; export default function(ComposedComponent) { function mapStateToProps(state) { return { authenticated: state.auth.authenticated }; } class Authentication extends Component { // static contextTypes = { // router: React.PropTypes.object // } componentWillMount() { if (!this.props.authenticated) { this.props.history.push('/'); } } componentWillUpdate(nextProps) { if (!nextProps.authenticated) { this.context.router.push('/'); } } render() { return <ComposedComponent {...this.props} /> } } return connect(mapStateToProps)(Authentication); }
Fix asset path in checkout page
<?php namespace Concrete\Package\VividStore\Controller\SinglePage\Checkout; use Page; use PageController; use Core; use \Concrete\Core\Localization\Service\CountryList; use View; use Package; use User; use \Concrete\Package\VividStore\Src\VividStore\Orders\Order as VividOrder; use \Concrete\Package\VividStore\Src\VividStore\Customer\Customer as Customer; defined('C5_EXECUTE') or die(_("Access Denied.")); class Complete extends PageController { public function view() { $customer = new Customer(); $order = VividOrder::getByID($customer->getLastOrderID()); if(is_object($order)){ $this->set("order",$order); } else { $this->redirect("/cart"); } $this->addFooterItem(Core::make('helper/html')->javascript('vivid-store.js','vivid_store')); $this->addHeaderItem(Core::make('helper/html')->css('vivid-store.css','vivid_store')); } }
<?php namespace Concrete\Package\VividStore\Controller\SinglePage\Checkout; use Page; use PageController; use Core; use \Concrete\Core\Localization\Service\CountryList; use View; use Package; use User; use \Concrete\Package\VividStore\Src\VividStore\Orders\Order as VividOrder; use \Concrete\Package\VividStore\Src\VividStore\Customer\Customer as Customer; defined('C5_EXECUTE') or die(_("Access Denied.")); class Complete extends PageController { public function view() { $customer = new Customer(); $order = VividOrder::getByID($customer->getLastOrderID()); if(is_object($order)){ $this->set("order",$order); } else { $this->redirect("/cart"); } $pkg = Package::getByHandle('vivid_store'); $packagePath = $pkg->getRelativePath(); $this->addFooterItem(Core::make('helper/html')->javascript($packagePath.'/js/vivid-store.js','vivid-store')); $this->addHeaderItem(Core::make('helper/html')->css($packagePath.'/css/vivid-store.css','vivid-store')); } }
Debug log of app mount path
import express from 'express'; import Debug from 'debug'; import path from 'path'; import Router from './router'; const debug = Debug('league-tooltips:middleware'); export default (apiKey, region, opts = {}) => { debug('Init middleware', region); const rawRoute = opts.url || '/'; const parsedRoute = path.parse(rawRoute).base; const route = `${parsedRoute}/`; debug('Route', route); debug('Initializing base router'); const router = express(); router.use(route, (req, res, next) => { debug('App mount path', req.app.mountpath); // Include the mount path of the application in the middleware route res.locals.tooltipsRoute = path.join(req.app.mountpath, route); next(); }); const routerMiddleware = new Router(apiKey, region, route, opts); router.use(route, routerMiddleware.create()); debug('Initialized base router'); debug(`Serving the tooltips on ${route}`); return router; };
import express from 'express'; import Debug from 'debug'; import path from 'path'; import Router from './router'; const debug = Debug('league-tooltips:middleware'); export default (apiKey, region, opts = {}) => { debug('Init middleware', region); const rawRoute = opts.url || '/'; const parsedRoute = path.parse(rawRoute).base; const route = `${parsedRoute}/`; debug('Route', route); debug('Initializing base router'); const router = express(); router.use(route, (req, res, next) => { // Include the mount path of the application in the middleware route res.locals.tooltipsRoute = path.join(req.app.mountpath, route); next(); }); const routerMiddleware = new Router(apiKey, region, route, opts); router.use(route, routerMiddleware.create()); debug('Initialized base router'); debug(`Serving the tooltips on ${route}`); return router; };
Tidy up the magic glow layer
package com.minelittlepony.client.render; import net.minecraft.client.render.RenderLayer; import net.minecraft.client.render.RenderPhase; import net.minecraft.client.render.VertexFormats; public class MagicGlow extends RenderPhase { private MagicGlow(String name, Runnable beginAction, Runnable endAction) { super(name, beginAction, endAction); } static final RenderLayer MAGIC = RenderLayer.method_24048("mlp_magic_glow", VertexFormats.POSITION_COLOR_TEXTURE_LIGHT_NORMAL, 7, 256, RenderLayer.MultiPhaseData.builder() .texture(NO_TEXTURE) .transparency(TRANSLUCENT_TRANSPARENCY) .lightmap(DISABLE_LIGHTMAP) .cull(DISABLE_CULLING) .build(false)); public static RenderLayer getRenderLayer() { return MAGIC; } }
package com.minelittlepony.client.render; import net.minecraft.client.render.RenderLayer; import net.minecraft.client.render.RenderPhase; import net.minecraft.client.render.VertexFormats; public class MagicGlow extends RenderPhase { public MagicGlow(String name, Runnable beginAction, Runnable endAction) { super(name, beginAction, endAction); } public static RenderLayer getRenderLayer() { return RenderLayer.method_24048("mlp_magic_glow", VertexFormats.POSITION_COLOR_TEXTURE_LIGHT_NORMAL, 7, 256, RenderLayer.MultiPhaseData.builder() .texture(NO_TEXTURE) .transparency(TRANSLUCENT_TRANSPARENCY) .lightmap(DISABLE_LIGHTMAP) .cull(DISABLE_CULLING) .build(false)); } }
Move matrix init to top
var numRows = 4 var numCols = 4 var matrix = [ [false, false, false, false], [false, false, false, false], [false, false, false, false], [false, false, false, false] ] for (var row = 0; row < numRows; row++) { for (var col = 0; col < numCols; col++) { matrix[row][col] = Math.random() < 0.5; setLightColor(row, col); } } function getLightId(row, col) { return "#light-" + row + "-" + col } function setLightColor(row, col) { var lightId = getLightId(row, col) if (matrix[row][col] ) { $(lightId).css("background-color", "pink") } else { $(lightId).css("background-color", "gray") } } function lightClick(row, col) { matrix[row][col] = !matrix[row][col]; setLightColor(row, col); }
var numRows = 4 var numCols = 4 var matrix = [ [false, false, false, false], [false, false, false, false], [false, false, false, false], [false, false, false, false] ] function getLightId(row, col) { return "#light-" + row + "-" + col } function setLightColor(row, col) { var lightId = getLightId(row, col) if (matrix[row][col] ) { $(lightId).css("background-color", "pink") } else { $(lightId).css("background-color", "gray") } } for (var row = 0; row < numRows; row++) { for (var col = 0; col < numCols; col++) { matrix[row][col] = Math.random() < 0.5; setLightColor(row, col); } } function lightClick(row, col) { matrix[row][col] = !matrix[row][col]; setLightColor(row, col); }
Add feature to set start/end messages
import logging class rangelog: logger = None startmsg = "--> Start: {name}" endmsg = "<-- End:" # noqa @classmethod def set_logger(cls, logger=None): if logger is None: cls.logger = logging.getLogger() cls.logger.setLevel(getattr(logging, 'INFO')) cls.logger.addHandler(logging.StreamHandler()) elif isinstance(logger, logging.Logger): cls.logger = logger @classmethod def set_start_msg(cls, msg): cls.startmsg = msg @classmethod def set_end_msg(cls, msg): cls.endmsg = msg def __init__(self, name): if rangelog.logger is None: rangelog.set_logger() self.name = name def __enter__(self): rangelog.logger.info(rangelog.startmsg.format(name=self.name)) return rangelog.logger def __exit__(self, *args): rangelog.logger.info(rangelog.endmsg.format(name=self.name))
import logging class rangelog: logger = None startlog = "--> Start: {name}" endlog = "<-- End:" # noqa @classmethod def set_logger(cls, logger=None): if logger is None: cls.logger = logging.getLogger() cls.logger.setLevel(getattr(logging, 'INFO')) cls.logger.addHandler(logging.StreamHandler()) elif isinstance(logger, logging.Logger): cls.logger = logger def __init__(self, name): if rangelog.logger is None: rangelog.set_logger() self.name = name def __enter__(self): rangelog.logger.info(rangelog.startlog.format(name=self.name)) return rangelog.logger def __exit__(self, *args): rangelog.logger.info(rangelog.endlog.format(name=self.name))
Fix divide by zero error in vectors loading
import numpy SPACY_MODELS = {} VECTORS = {} def get_spacy(lang, **kwargs): global SPACY_MODELS import spacy if lang not in SPACY_MODELS: SPACY_MODELS[lang] = spacy.load(lang, **kwargs) return SPACY_MODELS[lang] def get_vectors(ops, lang): global VECTORS key = (ops.device, lang) if key not in VECTORS: nlp = get_spacy(lang) nV = max(lex.rank for lex in nlp.vocab)+1 nM = nlp.vocab.vectors_length vectors = numpy.zeros((nV, nM), dtype='float32') for lex in nlp.vocab: if lex.has_vector: vectors[lex.rank] = lex.vector / (lex.vector_norm+1e-8) VECTORS[key] = ops.asarray(vectors) return VECTORS[key]
import numpy SPACY_MODELS = {} VECTORS = {} def get_spacy(lang, **kwargs): global SPACY_MODELS import spacy if lang not in SPACY_MODELS: SPACY_MODELS[lang] = spacy.load(lang, **kwargs) return SPACY_MODELS[lang] def get_vectors(ops, lang): global VECTORS key = (ops.device, lang) if key not in VECTORS: nlp = get_spacy(lang) nV = max(lex.rank for lex in nlp.vocab)+1 nM = nlp.vocab.vectors_length vectors = numpy.zeros((nV, nM), dtype='float32') for lex in nlp.vocab: if lex.has_vector: vectors[lex.rank] = lex.vector / lex.vector_norm VECTORS[key] = ops.asarray(vectors) return VECTORS[key]
Fix undefined work_dir and scene_dir variables
"""Host API required Work Files tool""" import os import nuke def file_extensions(): return [".nk"] def has_unsaved_changes(): return nuke.root().modified() def save_file(filepath): path = filepath.replace("\\", "/") nuke.scriptSaveAs(path) nuke.Root()["name"].setValue(path) nuke.Root()["project_directory"].setValue(os.path.dirname(path)) nuke.Root().setModified(False) def open_file(filepath): filepath = filepath.replace("\\", "/") # To remain in the same window, we have to clear the script and read # in the contents of the workfile. nuke.scriptClear() nuke.scriptReadFile(filepath) nuke.Root()["name"].setValue(filepath) nuke.Root()["project_directory"].setValue(os.path.dirname(filepath)) nuke.Root().setModified(False) return True def current_file(): current_file = nuke.root().name() # Unsaved current file if current_file == 'Root': return None return os.path.normpath(current_file).replace("\\", "/") def work_root(session): work_dir = session["AVALON_WORKDIR"] scene_dir = session.get("AVALON_SCENEDIR") if scene_dir: path = os.path.join(work_dir, scene_dir) else: path = work_dir return os.path.normpath(path).replace("\\", "/")
"""Host API required Work Files tool""" import os import nuke def file_extensions(): return [".nk"] def has_unsaved_changes(): return nuke.root().modified() def save_file(filepath): path = filepath.replace("\\", "/") nuke.scriptSaveAs(path) nuke.Root()["name"].setValue(path) nuke.Root()["project_directory"].setValue(os.path.dirname(path)) nuke.Root().setModified(False) def open_file(filepath): filepath = filepath.replace("\\", "/") # To remain in the same window, we have to clear the script and read # in the contents of the workfile. nuke.scriptClear() nuke.scriptReadFile(filepath) nuke.Root()["name"].setValue(filepath) nuke.Root()["project_directory"].setValue(os.path.dirname(filepath)) nuke.Root().setModified(False) return True def current_file(): current_file = nuke.root().name() # Unsaved current file if current_file == 'Root': return None return os.path.normpath(current_file).replace("\\", "/") def work_root(session): if scene_dir: path = os.path.join(work_dir, scene_dir) else: path = work_dir return os.path.normpath(path).replace("\\", "/")
Remove unused code that seems to stem from PointText.
/* * Paper.js * * This file is part of Paper.js, a JavaScript Vector Graphics Library, * based on Scriptographer.org and designed to be largely API compatible. * http://paperjs.org/ * http://scriptographer.org/ * * Distributed under the MIT license. See LICENSE file for details. * * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey * http://lehni.org/ & http://jonathanpuckey.com/ * * All rights reserved. */ var TextItem = this.TextItem = Item.extend({ beans: true, initialize: function() { this.base(); this.content = null; this.setCharacterStyle(this._project.getCurrentStyle()); this.setParagraphStyle(); }, getCharacterStyle: function() { return this._characterStyle; }, setCharacterStyle: function(style) { this._characterStyle = CharacterStyle.create(this, style); }, getParagraphStyle: function() { return this._paragraphStyle; }, setParagraphStyle: function(style) { this._paragraphStyle = ParagraphStyle.create(this, style); } });
/* * Paper.js * * This file is part of Paper.js, a JavaScript Vector Graphics Library, * based on Scriptographer.org and designed to be largely API compatible. * http://paperjs.org/ * http://scriptographer.org/ * * Distributed under the MIT license. See LICENSE file for details. * * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey * http://lehni.org/ & http://jonathanpuckey.com/ * * All rights reserved. */ var TextItem = this.TextItem = Item.extend({ beans: true, initialize: function() { this.base(); point = Point.read(arguments, 0, 1); this.content = null; this.setCharacterStyle(this._project.getCurrentStyle()); this.setParagraphStyle(); }, getCharacterStyle: function() { return this._characterStyle; }, setCharacterStyle: function(style) { this._characterStyle = CharacterStyle.create(this, style); }, getParagraphStyle: function() { return this._paragraphStyle; }, setParagraphStyle: function(style) { this._paragraphStyle = ParagraphStyle.create(this, style); } });
Sort countries before generating combinations.
import sys import itertools import collections import networkx as nx from irco import logging log = logging.get_logger() def get_countries(publication): publication_countries = set() for affiliation in publication.affiliations: country = affiliation.institution.country if country is None: print >>sys.stderr, 'Undefined country for "{}"'.format( affiliation.institution.name) else: publication_countries.add(country) return publication_countries def create(session, publications): g = nx.Graph() papers_count = collections.Counter() collaborations_count = collections.Counter() for publication in publications: publication_countries = get_countries(publication) g.add_nodes_from(publication_countries) papers_count.update(publication_countries) collaborations = list(itertools.combinations( sorted(publication_countries), 2)) collaborations_count.update(collaborations) g.add_edges_from(collaborations) # Set papers count for country, count in papers_count.iteritems(): g.node[country]['papers'] = count # Set edge weight for (c1, c2), count in collaborations_count.iteritems(): g[c1][c2]['weight'] = count return g
import sys import itertools import collections import networkx as nx from irco import logging log = logging.get_logger() def get_countries(publication): publication_countries = set() for affiliation in publication.affiliations: country = affiliation.institution.country if country is None: print >>sys.stderr, 'Undefined country for "{}"'.format( affiliation.institution.name) else: publication_countries.add(country) return publication_countries def create(session, publications): g = nx.Graph() papers_count = collections.Counter() collaborations_count = collections.Counter() for publication in publications: publication_countries = get_countries(publication) g.add_nodes_from(publication_countries) papers_count.update(publication_countries) collaborations = list(itertools.combinations(publication_countries, 2)) collaborations_count.update(collaborations) g.add_edges_from(collaborations) # Set papers count for country, count in papers_count.iteritems(): g.node[country]['papers'] = count # Set edge weight for (c1, c2), count in collaborations_count.iteritems(): g[c1][c2]['weight'] = count return g