text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Support for Leaflet v 1.0
Fixes https://github.com/mapbox/leaflet-pip/issues/19
|
/* global L */
'use strict';
var gju = require('geojson-utils');
var leafletPip = {
bassackwards: false,
pointInLayer: function(p, layer, first) {
if (p instanceof L.LatLng) p = [p.lng, p.lat];
else if (leafletPip.bassackwards) p = p.concat().reverse();
var results = [];
layer.eachLayer(function(l) {
if (first && results.length) return;
if (isPoly(l) &&
gju.pointInPolygon({
type: 'Point',
coordinates: p
}, l.toGeoJSON().geometry)) {
results.push(l);
}
});
return results;
}
};
function isPoly(l) {
if (L.MultiPolygon) {
return (l instanceof L.MultiPolygon || l instanceof L.Polygon);
} else { //leaftletjs >= 1.0
return (l.feature && l.feature.geometry && l.feature.geometry.type && -1 != ['Polygon', 'MultiPolygon'].indexOf(l.feature.geometry.type));
}
}
module.exports = leafletPip;
|
/* global L */
'use strict';
var gju = require('geojson-utils');
var leafletPip = {
bassackwards: false,
pointInLayer: function(p, layer, first) {
if (p instanceof L.LatLng) p = [p.lng, p.lat];
else if (leafletPip.bassackwards) p = p.concat().reverse();
var results = [];
layer.eachLayer(function(l) {
if (first && results.length) return;
if ((l instanceof L.MultiPolygon ||
l instanceof L.Polygon) &&
gju.pointInPolygon({
type: 'Point',
coordinates: p
}, l.toGeoJSON().geometry)) {
results.push(l);
}
});
return results;
}
};
module.exports = leafletPip;
|
Add atom type info output.
|
import logging
from vaspy.iter import OutCar
_logger = logging.getLogger("vaspy.script")
if "__main__" == __name__:
outcar = OutCar()
poscar = outcar.poscar
freq_types = outcar.freq_types
# Frequency info.
_logger.info("{:<10s}{:<10s}{:<20s}".format("atom", "type", "freq_type"))
_logger.info("-"*35)
# Get atom types.
atom_types = []
for t, n in zip(poscar.atoms, poscar.atoms_num):
atom_types += [t]*n
idx = 0
tfs = poscar.tf.tolist()
for atom_idx, tf in enumerate(tfs):
if tf == ["T", "T", "T"]:
msg = "{:<10d}{:<10s}{:<5s}{:<5s}{:<5s}"
msg = msg.format(atom_idx+1, atom_types[atom_idx], *freq_types[idx])
_logger.info(msg)
idx += 1
# Zero point energy.
_logger.info("")
_logger.info("ZPE = {}".format(outcar.zpe))
|
import logging
from vaspy.iter import OutCar
_logger = logging.getLogger("vaspy.script")
if "__main__" == __name__:
outcar = OutCar()
poscar = outcar.poscar
freq_types = outcar.freq_types
# Frequency info.
_logger.info("{:<10s}{:<20s}".format("atom", "freq_type"))
_logger.info("-"*25)
idx = 0
tfs = poscar.tf.tolist()
for atom_idx, tf in enumerate(tfs):
if tf == ["T", "T", "T"]:
_logger.info("{:<10d}{:<5s}{:<5s}{:<5s}".format(atom_idx+1, *freq_types[idx]))
idx += 1
# Zero point energy.
_logger.info("")
_logger.info("ZPE = {}".format(outcar.zpe))
|
Fix LIST crashing on certain input
|
from txircd.modbase import Mode
class PrivateMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
return data
if "cdata" not in data:
return data
cdata = data["cdata"]
if "p" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
cdata["name"] = "*"
cdata["topic"] = ""
# other +p stuff is in other modules
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.mode_p = None
def spawn(self):
self.mode_p = PrivateMode()
return {
"modes": {
"cnp": self.mode_p
},
"actions": {
"commandextra": [self.mode_p.listOutput]
},
"common": True
}
def cleanup(self):
self.ircd.removeMode("cnp")
self.ircd.actions["commandextra"].remove(self.mode_p.listOutput)
|
from txircd.modbase import Mode
class PrivateMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
return data
cdata = data["cdata"]
if "p" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
cdata["name"] = "*"
cdata["topic"] = ""
# other +p stuff is in other modules
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.mode_p = None
def spawn(self):
self.mode_p = PrivateMode()
return {
"modes": {
"cnp": self.mode_p
},
"actions": {
"commandextra": [self.mode_p.listOutput]
},
"common": True
}
def cleanup(self):
self.ircd.removeMode("cnp")
self.ircd.actions["commandextra"].remove(self.mode_p.listOutput)
|
Enable compose fading for CUSTOMER4.
(imported from commit 3be5b169b530c7bf6d5a9499710950fefa3cbde1)
|
var feature_flags = (function () {
var exports = {};
exports.mark_read_at_bottom = true;
exports.summarize_read_while_narrowed = true;
exports.twenty_four_hour_time = _.contains([],
page_params.email);
exports.dropbox_integration = page_params.staging || _.contains(['dropbox.com'], page_params.domain);
exports.mandatory_topics = _.contains([
'customer7.invalid'
],
page_params.domain
);
exports.collapsible = page_params.staging;
exports.propagate_topic_edits = page_params.staging ||
_.contains(['customer7.invalid'], page_params.domain);
var customer4_realms = [
'customer4.invalid',
'users.customer4.invalid'
];
var is_customer4 = _.contains(customer4_realms, page_params.domain);
exports.fade_users_when_composing = page_params.staging || is_customer4;
exports.alert_words =
_.contains(['reddit.com', 'mit.edu', 'zulip.com'], page_params.domain);
var zulip_mit_emails = [];
var is_zulip_mit_user = _.contains(zulip_mit_emails, page_params.email);
exports.muting = page_params.staging || is_zulip_mit_user;
exports.left_side_userlist = page_params.staging ||
_.contains(['customer7.invalid'], page_params.domain);
return exports;
}());
|
var feature_flags = (function () {
var exports = {};
exports.mark_read_at_bottom = true;
exports.summarize_read_while_narrowed = true;
exports.twenty_four_hour_time = _.contains([],
page_params.email);
exports.dropbox_integration = page_params.staging || _.contains(['dropbox.com'], page_params.domain);
exports.mandatory_topics = _.contains([
'customer7.invalid'
],
page_params.domain
);
exports.collapsible = page_params.staging;
exports.propagate_topic_edits = page_params.staging ||
_.contains(['customer7.invalid'], page_params.domain);
exports.fade_users_when_composing = page_params.staging;
exports.alert_words =
_.contains(['reddit.com', 'mit.edu', 'zulip.com'], page_params.domain);
var zulip_mit_emails = [];
var is_zulip_mit_user = _.contains(zulip_mit_emails, page_params.email);
exports.muting = page_params.staging || is_zulip_mit_user;
exports.left_side_userlist = page_params.staging ||
_.contains(['customer7.invalid'], page_params.domain);
return exports;
}());
|
Fix master branch build error.
master branch build failing with error
```
[INFO] Running "jshint:all" (jshint) task
[INFO]
[INFO] src/app/home/home.controller.js
[INFO] line 27 col 4 Missing semicolon.
[INFO]
[INFO] ✖ 1 problem
[INFO]
[INFO] Warning: Task "jshint:all" failed. Use --force to continue.
[INFO]
[INFO] Aborted due to warnings.
```
This patch fixes the build.
Author: Lee moon soo <moon@apache.org>
Closes #217 from Leemoonsoo/hotfix and squashes the following commits:
85b2914 [Lee moon soo] Add missing ';'
|
/*
* 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.
*/
'use strict';
angular.module('zeppelinWebApp').controller('HomeCtrl', function($scope, notebookListDataFactory, websocketMsgSrv, $rootScope) {
var vm = this;
vm.notes = notebookListDataFactory;
vm.websocketMsgSrv = websocketMsgSrv;
$scope.notebookHome = false;
$scope.staticHome = false;
var initHome = function() {
websocketMsgSrv.getHomeNotebook();
};
initHome();
$scope.$on('setNoteContent', function(event, note) {
if (note) {
$scope.note = note;
// initialize look And Feel
$rootScope.$broadcast('setLookAndFeel', 'home');
// make it read only
$scope.viewOnly = true;
$scope.notebookHome = true;
} else {
$scope.staticHome = true;
}
});
});
|
/*
* 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.
*/
'use strict';
angular.module('zeppelinWebApp').controller('HomeCtrl', function($scope, notebookListDataFactory, websocketMsgSrv, $rootScope) {
var vm = this;
vm.notes = notebookListDataFactory;
vm.websocketMsgSrv = websocketMsgSrv;
$scope.notebookHome = false;
$scope.staticHome = false;
var initHome = function() {
websocketMsgSrv.getHomeNotebook();
}
initHome();
$scope.$on('setNoteContent', function(event, note) {
if (note) {
$scope.note = note;
// initialize look And Feel
$rootScope.$broadcast('setLookAndFeel', 'home');
// make it read only
$scope.viewOnly = true;
$scope.notebookHome = true;
} else {
$scope.staticHome = true;
}
});
});
|
Use ReactDOM.hydrate instead of render
|
import React from 'react'
import ReactDOM from 'react-dom'
import AppContainer from 'react-hot-loader/lib/AppContainer'
import injectTapEventPlugin from 'react-tap-event-plugin'
import Cookie from 'js-cookie'
import createRootAsync from './createRootAsync'
import withIntl from './intl/ismorphicIntlProvider'
injectTapEventPlugin()
async function render(createRoot) {
const Root = await createRoot()
ReactDOM.hydrate(
<AppContainer>
{
withIntl(<Root />, Cookie.get('locale'))
}
</AppContainer>,
// eslint-disable-next-line no-undef
document.getElementById('root'),
)
}
if (process.env.NODE_ENV === 'development' && module.hot) {
module.hot.accept('./createRootAsync.js', () => {
render(require('./createRootAsync').default)
})
}
render(createRootAsync)
|
import React from 'react'
import ReactDOM from 'react-dom'
import AppContainer from 'react-hot-loader/lib/AppContainer'
import injectTapEventPlugin from 'react-tap-event-plugin'
import Cookie from 'js-cookie'
import createRootAsync from './createRootAsync'
import withIntl from './intl/ismorphicIntlProvider'
injectTapEventPlugin()
async function render(createRoot) {
const Root = await createRoot()
ReactDOM.render(
<AppContainer>
{
withIntl(<Root />, Cookie.get('locale'))
}
</AppContainer>,
// eslint-disable-next-line no-undef
document.getElementById('root'),
)
}
if (process.env.NODE_ENV === 'development' && module.hot) {
module.hot.accept('./createRootAsync.js', () => {
render(require('./createRootAsync').default)
})
}
render(createRootAsync)
|
Support old microsoft specific mime types
|
'use strict';
var memoize = require('memoizee/plain')
, validDb = require('dbjs/valid-dbjs')
, defineFile = require('dbjs-ext/object/file')
, defineJpegFile = require('dbjs-ext/object/file/image-file/jpeg-file');
module.exports = memoize(function (db) {
var File, JpegFile;
validDb(db);
File = defineFile(db);
File.prototype.url = function () {
return this.path ? '/' + encodeURIComponent(this.path) : null;
};
JpegFile = defineJpegFile(db);
File.prototype.defineProperties({
preview: { type: File, value: function () {
return this.isPreviewGenerated ? this.generatedPreview : this;
} },
isPreviewGenerated: { type: db.Boolean, value: true },
generatedPreview: { type: File, nested: true },
thumb: { type: JpegFile, nested: true }
});
File.accept = ['image/jpeg', 'application/pdf', 'image/png', 'image/pjpeg', 'image/x-png'];
return File;
}, { normalizer: require('memoizee/normalizers/get-1')() });
|
'use strict';
var memoize = require('memoizee/plain')
, validDb = require('dbjs/valid-dbjs')
, defineFile = require('dbjs-ext/object/file')
, defineJpegFile = require('dbjs-ext/object/file/image-file/jpeg-file');
module.exports = memoize(function (db) {
var File, JpegFile;
validDb(db);
File = defineFile(db);
File.prototype.url = function () {
return this.path ? '/' + encodeURIComponent(this.path) : null;
};
JpegFile = defineJpegFile(db);
File.prototype.defineProperties({
preview: { type: File, value: function () {
return this.isPreviewGenerated ? this.generatedPreview : this;
} },
isPreviewGenerated: { type: db.Boolean, value: true },
generatedPreview: { type: File, nested: true },
thumb: { type: JpegFile, nested: true }
});
File.accept = ['image/jpeg', 'application/pdf', 'image/png'];
return File;
}, { normalizer: require('memoizee/normalizers/get-1')() });
|
Update methods on interface to allow adding reference objects
git-svn-id: fdf63cc6b6871a635be2b727c8623e4c3a9a9ed7@15418 6e01202a-0783-4428-890a-84243c50cc2b
|
package org.concord.framework.otrunk.view;
import java.util.Vector;
import org.concord.framework.otrunk.OTChangeListener;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.OTObjectService;
public interface OTLabbookManager
{
/*
* This object will be added directly to an entry, so the original should be cloned, preferably
* using the copy method in the OTLabbookViewProvider for the object
*/
public void add(OTObject otObject);
/*
* If a refence to the original object is included, it will be easier to tie the entry back
* to its origins.
*/
public void add(OTObject otObject, OTObject originalObject);
/*
* A container, such as the section the object was in, should be included to allow the lab
* book to sort based on contaner.
*/
public void add(OTObject otObject, OTObject originalObject, OTObject container);
public void addSnapshot(OTObject snapshot);
public void addDataCollector(OTObject dataCollector);
public void addDrawingTool(OTObject drawingTool);
public void addText(OTObject text);
public void remove(OTObject labbookEntry);
public Vector getSnapshots();
public Vector getGraphs();
public Vector getDrawings();
public Vector getText();
public Vector getAllEntries();
public boolean isEmpty();
public void addLabbookListener(OTChangeListener listener);
public void removeLabbookListener(OTChangeListener listener);
}
|
package org.concord.framework.otrunk.view;
import java.util.Vector;
import org.concord.framework.otrunk.OTChangeListener;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.OTObjectService;
public interface OTLabbookManager
{
public void add(OTObject otObject);
public void add(OTObject otObject, OTObject container);
public void addSnapshot(OTObject snapshot);
public void addDataCollector(OTObject dataCollector);
public void addDrawingTool(OTObject drawingTool);
public void addText(OTObject text);
public void remove(OTObject labbookEntry);
public Vector getSnapshots();
public Vector getGraphs();
public Vector getDrawings();
public Vector getText();
public Vector getAllEntries();
public boolean isEmpty();
public void addLabbookListener(OTChangeListener listener);
public void removeLabbookListener(OTChangeListener listener);
// public void setOTObjectService(OTObjectService objectService);
}
|
Fix typo in API docs
|
goog.provide('ol.net');
/**
* Simple JSONP helper. Supports error callbacks and a custom callback param.
* The error callback will be called when no JSONP is executed after 10 seconds.
*
* @param {string} url Request url. A 'callback' query parameter will be
* appended.
* @param {Function} callback Callback on success.
* @param {function()=} opt_errback Callback on error.
* @param {string=} opt_callbackParam Custom query parameter for the JSONP
* callback. Default is 'callback'.
*/
ol.net.jsonp = function(url, callback, opt_errback, opt_callbackParam) {
var script = goog.global.document.createElement('script');
var key = 'olc_' + goog.getUid(callback);
function cleanup() {
delete goog.global[key];
script.parentNode.removeChild(script);
}
script.async = true;
script.src = url + (url.indexOf('?') == -1 ? '?' : '&') +
(opt_callbackParam || 'callback') + '=' + key;
var timer = goog.global.setTimeout(function() {
cleanup();
if (opt_errback) {
opt_errback();
}
}, 10000);
goog.global[key] = function(data) {
goog.global.clearTimeout(timer);
cleanup();
callback(data);
};
goog.global.document.getElementsByTagName('head')[0].appendChild(script);
};
|
goog.provide('ol.net');
/**
* Simple JSONP helper. Supports error callbacks and a custom callback param.
* The error callback will be called when no JSONP is executed after 10 seconds.
*
* @param {string} url Request url. A 'callback' query parameter will be
* appended.
* @param {Function} callback Callback on success.
* @param {function()=} opt_errback Callback on error.
* @param {string=} opt_callbackParam Custom qurey parameter for the JSONP
* callback. Default is 'callback'.
*/
ol.net.jsonp = function(url, callback, opt_errback, opt_callbackParam) {
var script = goog.global.document.createElement('script');
var key = 'olc_' + goog.getUid(callback);
function cleanup() {
delete goog.global[key];
script.parentNode.removeChild(script);
}
script.async = true;
script.src = url + (url.indexOf('?') == -1 ? '?' : '&') +
(opt_callbackParam || 'callback') + '=' + key;
var timer = goog.global.setTimeout(function() {
cleanup();
if (opt_errback) {
opt_errback();
}
}, 10000);
goog.global[key] = function(data) {
goog.global.clearTimeout(timer);
cleanup();
callback(data);
};
goog.global.document.getElementsByTagName('head')[0].appendChild(script);
};
|
Add a warning if breakpoints are still define in app.js
|
import Media from 'ember-responsive/media';
/**
* An initializer that sets up `ember-responsive`.
*
* Refer to {{#crossLink "Ember.Application.responsive"}}{{/crossLink}}
* for examples of how to configure this library before the initializer
* before it's run by Ember.
*
* @static
* @constructor
* @module ember-responsive
* @namespace Ember.Application
* @class initializer
*/
export default {
/**
* @property name
* @type string
* @default responsive
*/
name: 'responsive',
/**
* @method initialize
* @param Ember.Container container
* @param Ember.Application app
*/
initialize: function(container, app) {
if (app.responsive) {
Ember.warn('Your breakpoints should be defined in /app/breakpoints.js');
}
var breakpoints = container.lookupFactory('breakpoints:main');
var media = Media.create();
if (breakpoints) {
for (var name in breakpoints) {
if (media.hasOwnProperty(name)) {
media.match(name, breakpoints[name]);
}
}
}
app.register('responsive:media', media, { instantiate: false });
app.inject('controller', 'media', 'responsive:media');
app.inject('component', 'media', 'responsive:media');
app.inject('route', 'media', 'responsive:media');
app.inject('view', 'media', 'responsive:media');
}
};
|
import Media from 'ember-responsive/media';
/**
* An initializer that sets up `ember-responsive`.
*
* Refer to {{#crossLink "Ember.Application.responsive"}}{{/crossLink}}
* for examples of how to configure this library before the initializer
* before it's run by Ember.
*
* @static
* @constructor
* @module ember-responsive
* @namespace Ember.Application
* @class initializer
*/
export default {
/**
* @property name
* @type string
* @default responsive
*/
name: 'responsive',
/**
* @method initialize
* @param Ember.Container container
* @param Ember.Application app
*/
initialize: function(container, app) {
var breakpoints = container.lookupFactory('breakpoints:main');
var media = Media.create();
if (breakpoints) {
for (var name in breakpoints) {
if (media.hasOwnProperty(name)) {
media.match(name, breakpoints[name]);
}
}
}
app.register('responsive:media', media, { instantiate: false });
app.inject('controller', 'media', 'responsive:media');
app.inject('component', 'media', 'responsive:media');
app.inject('route', 'media', 'responsive:media');
app.inject('view', 'media', 'responsive:media');
}
};
|
Remove references to VERBOSE constant
|
<?php
namespace DataStream\Configuration;
/**
* Contains functions to be executed when a property is set
*/
class Configuration extends DefaultConfiguration
{
/**
* Checks if the dataLocation provided is valid (i.e. files exist)
*/
public function onDataLocationSet($dataLocation)
{
if(is_array($dataLocation)) {
$dataLocation = array_map(function($path) {
return EMU_PATH . DIRECTORY_SEPARATOR . $path;
}, $dataLocation);
foreach($dataLocation as $location) {
if(!file_exists($location)) {
throw new \Exception('Could not find file ' . $location);
}
}
}else {
$dataLocation = EMU_PATH . DIRECTORY_SEPARATOR . $dataLocation;
if(!file_exists($dataLocation)) {
throw new \Exception('Could not find file ' . $dataLocation);
}
}
return $dataLocation;
}
}
|
<?php
namespace DataStream\Configuration;
/**
* Contains functions to be executed when a property is set
*/
class Configuration extends DefaultConfiguration
{
/**
* Checks if the dataLocation provided is valid (i.e. files exist)
*/
public function onDataLocationSet($dataLocation)
{
if(is_array($dataLocation)) {
$dataLocation = array_map(function($path) {
return EMU_PATH . DIRECTORY_SEPARATOR . $path;
}, $dataLocation);
foreach($dataLocation as $location) {
if(VERBOSE) {
out("Reading $location");
}
if(!file_exists($location)) {
throw new \Exception('Could not find file ' . $location);
}
}
}else {
$dataLocation = EMU_PATH . DIRECTORY_SEPARATOR . $dataLocation;
if(VERBOSE) {
out("Reading $dataLocation");
}
if(!file_exists($dataLocation)) {
throw new \Exception('Could not find file ' . $dataLocation);
}
}
return $dataLocation;
}
}
|
Update pennprov to 2.2.1 for Python 3.7 compatibility.
|
##################################################################################
# Copyright 2013-19 by the Trustees of the University of Pennsylvania
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##################################################################################
import setuptools
from distutils.core import setup, Extension
with open("README.md", "r") as fh:
long_description = fh.read()
setup(name='ieeg',
version='1.1',
description='API for the IEEG.org platform',
install_requires=['deprecation','requests','numpy','pandas', 'pennprov==2.2.1'],
packages=setuptools.find_packages(),
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/ieeg-portal/ieegpy",
classifiers=[
'Programming Language :: Python :: 2-3',
'License :: OSI Approved :: Apache License',
'Operating System :: OS Independent',
])
|
##################################################################################
# Copyright 2013-19 by the Trustees of the University of Pennsylvania
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##################################################################################
import setuptools
from distutils.core import setup, Extension
with open("README.md", "r") as fh:
long_description = fh.read()
setup(name='ieeg',
version='1.1',
description='API for the IEEG.org platform',
install_requires=['deprecation','requests','numpy','pandas', 'pennprov==2.2.0'],
packages=setuptools.find_packages(),
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/ieeg-portal/ieegpy",
classifiers=[
'Programming Language :: Python :: 2-3',
'License :: OSI Approved :: Apache License',
'Operating System :: OS Independent',
])
|
Add support for passing flags to Mocha
Update argv parsing to ignore flags passed to mocha. Without
this, enabling the Node.js debugger breaks Nodal's testing
framework.
|
'use strict';
const fs = require('fs');
const path = require('path');
class TestRunner {
constructor(dir, router) {
this.dir = dir;
this.router = router;
}
tests() {
let tests = [];
// Strip mocha and node flags out before looking for filter
let filter = process.argv.filter(str => !str.startsWith('--')).slice(3)[0]
if (filter) {
filter = filter.endsWith('.js') ? filter : `${filter}.js`;
}
let addTest = dir => {
return filename => {
if (!path.extname(filename) && filename[0] !== '.') {
let nextDir = path.resolve(dir, filename);
return fs.readdirSync(nextDir).forEach(addCommand(nextDir));
}
if (filter && filename !== filter) {
return;
}
let Test = require(path.resolve(dir, filename));
tests.push(new Test(this));
}
};
let testDir = path.resolve(process.cwd(), this.dir || '/');
fs.readdirSync(testDir).forEach(addTest(testDir));
return tests;
}
start(verb) {
this.tests().forEach(t => {
t.__test__(verb);
});
}
}
module.exports = TestRunner;
|
'use strict';
const fs = require('fs');
const path = require('path');
class TestRunner {
constructor(dir, router) {
this.dir = dir;
this.router = router;
}
tests() {
let tests = [];
let filter;
if (process.argv.length > 3) {
filter = process.argv[3];
filter = filter.endsWith('.js') ? filter : `${filter}.js`;
}
let addTest = dir => {
return filename => {
if (!path.extname(filename) && filename[0] !== '.') {
let nextDir = path.resolve(dir, filename);
return fs.readdirSync(nextDir).forEach(addCommand(nextDir));
}
if (filter && filename !== filter) {
return;
}
let Test = require(path.resolve(dir, filename));
tests.push(new Test(this));
}
};
let testDir = path.resolve(process.cwd(), this.dir || '/');
fs.readdirSync(testDir).forEach(addTest(testDir));
return tests;
}
start(verb) {
this.tests().forEach(t => {
t.__test__(verb);
});
}
}
module.exports = TestRunner;
|
Update font size error message
|
import styles from './UserInputError.less';
import React, { Component, PropTypes } from 'react';
import { MIN_FONT_SIZE } from 'flux/constants/config';
export default class UserInputError extends Component {
static propTypes = {
areColorsValid: PropTypes.bool.isRequired,
isFontSizeValid: PropTypes.bool.isRequired
};
render() {
const { areColorsValid, isFontSizeValid } = this.props;
return (
<div className={styles.container}>
<div className={styles.innerContainer}>
{
!areColorsValid &&
<p>
Please enter a valid hexadecimal color
</p>
}
{
!isFontSizeValid &&
<p>
Please enter a font size of {MIN_FONT_SIZE}px or above
</p>
}
</div>
</div>
);
}
}
|
import styles from './UserInputError.less';
import React, { Component, PropTypes } from 'react';
import { MIN_FONT_SIZE, MAX_FONT_SIZE } from 'flux/constants/config';
export default class UserInputError extends Component {
static propTypes = {
areColorsValid: PropTypes.bool.isRequired,
isFontSizeValid: PropTypes.bool.isRequired
};
render() {
const { areColorsValid, isFontSizeValid } = this.props;
return (
<div className={styles.container}>
<div className={styles.innerContainer}>
{
!areColorsValid &&
<p>
Please enter a valid hexadecimal color
</p>
}
{
!isFontSizeValid &&
<p>
Please enter a font size between {MIN_FONT_SIZE}px
and {MAX_FONT_SIZE}px
</p>
}
</div>
</div>
);
}
}
|
Remove Bootstrapify from list to make it truly opt-in.
|
// Opt-in repos (case sensitive)
// These repositories are loaded this way as a convenience, not because Disco has any special priority in this list.
// Opting these repositories in here reduces the number of Javascript calls we need to make to load external repos.
var optInRepos = [
'cartjs',
'django-shopify-auth',
'grunt-shopify-theme-settings',
'shopify-theme-scaffold',
'shopify-dev-frame'
];
// Add custom repos by full_name. Take the org/user and repo name
// - e.g. luciddesign/bootstrapify from https://github.com/luciddesign/bootstrapify
var customRepos = [
];
// Custom repo language, different than that defined by GitHub
var customRepoLanguage = {
'cartjs': 'JavaScript',
'shopify-theme-scaffold': 'Liquid'
};
// Specify how each repository should be classified.
// Currently, repositories can be classified as "Themes" or "Apps".
// "Themes" is the default so currently only repositories that should be classified under "Apps" should be in here.
var customRepoCategory = {
'django-shopify-auth': 'Apps',
'shopify-dev-frame': 'Apps'
};
// Custom repo avatars. Dimensions should be 40x40
// - Be sure a custom repo doesn't have the same name as a Shopify one, or a one will be overridden
var customRepoAvatar = {};
|
// Opt-in repos (case sensitive)
// These repositories are loaded this way as a convenience, not because Disco has any special priority in this list.
// Opting these repositories in here reduces the number of Javascript calls we need to make to load external repos.
var optInRepos = [
'cartjs',
'django-shopify-auth',
'grunt-shopify-theme-settings',
'shopify-theme-scaffold',
'shopify-dev-frame'
];
// Add custom repos by full_name. Take the org/user and repo name
// - e.g. luciddesign/bootstrapify from https://github.com/luciddesign/bootstrapify
var customRepos = [
'luciddesign/bootstrapify'
];
// Custom repo language, different than that defined by GitHub
var customRepoLanguage = {
'cartjs': 'JavaScript',
'shopify-theme-scaffold': 'Liquid',
'bootstrapify': 'Liquid'
};
// Specify how each repository should be classified.
// Currently, repositories can be classified as "Themes" or "Apps".
// "Themes" is the default so currently only repositories that should be classified under "Apps" should be in here.
var customRepoCategory = {
'django-shopify-auth': 'Apps',
'shopify-dev-frame': 'Apps'
};
// Custom repo avatars. Dimensions should be 40x40
// - Be sure a custom repo doesn't have the same name as a Shopify one, or a one will be overridden
var customRepoAvatar = {};
|
Use file instead of module.resource
|
'use strict';
var chalk = require('chalk');
var path = require('path');
function WebpackKarmaDieHardPlugin(options) {
if (typeof(options) === "undefined") {
options = {};
}
chalk.enabled = options.colors !== false
}
WebpackKarmaDieHardPlugin.prototype.apply = function(compiler) {
compiler.plugin('done', function(stats) {
// Need to report warnings and errors manually, since these will not bubble
// up to the user.
stats.compilation.warnings.forEach(function (warning) {
if (warning.file) {
console.warn(chalk.yellow("WARNING in ./"
+ path.relative("", warning.file)));
}
console.warn(chalk.yellow(warning.message || warning));
});
stats.compilation.errors.forEach(function (error) {
if (error.file) {
console.error(chalk.red("ERROR in ./"
+ path.relative("", error.file)));
}
console.error(chalk.red(error.message || error));
});
if (stats.compilation.errors.length > 0) {
// karma-webpack will hang indefinitely if no assets are produced, so just
// blow up noisily.
process.exit(1);
}
});
};
module.exports = WebpackKarmaDieHardPlugin;
|
'use strict';
var chalk = require('chalk');
var path = require('path');
function WebpackKarmaDieHardPlugin(options) {
if (typeof(options) === "undefined") {
options = {};
}
chalk.enabled = options.colors !== false
}
WebpackKarmaDieHardPlugin.prototype.apply = function(compiler) {
compiler.plugin('done', function(stats) {
// Need to report warnings and errors manually, since these will not bubble
// up to the user.
stats.compilation.warnings.forEach(function (warning) {
if (warning.module) {
console.warn(chalk.yellow("WARNING: ./"
+ path.relative("", warning.module.resource)));
}
console.warn(chalk.yellow(warning.message || warning));
});
stats.compilation.errors.forEach(function (error) {
if (error.module) {
console.error(chalk.red("ERROR: ./"
+ path.relative("", error.module.resource)));
}
console.error(chalk.red(error.message || error));
});
if (stats.compilation.errors.length > 0) {
// karma-webpack will hang indefinitely if no assets are produced, so just
// blow up noisily.
process.exit(1);
}
});
};
module.exports = WebpackKarmaDieHardPlugin;
|
Create the user if it isn't already in the database first, then make it an admin.
|
from pyramid.response import Response
from pi_director.models.models import (
DBSession,
MyModel,
)
from pi_director.models.UserModel import UserModel
def authorize_user(email):
user=DBSession.query(UserModel).filter(UserModel.email==email).one()
user.AccessLevel=2
DBSession.flush()
def delete_user(email):
DBSession.query(UserModel).filter(UserModel.email==email).delete()
def get_users():
UserList=DBSession.query(UserModel).all()
return UserList
def make_an_admin(request):
email=request.matchdict['email']
'''First, make sure there aren't already admins in the system'''
res=DBSession.query(UserModel).filter(UserModel.AccessLevel==2).first()
if res != None:
msg="User already an admin: {user}".format(user=res.email)
return False
user=DBSession.query(UserModel).filter(UserModel.email==email).first()
if user == None:
user=UserModel()
user.email=email
DBSession.add(user)
user.AccessLevel=2
DBSession.flush()
return True
|
from pyramid.response import Response
from pi_director.models.models import (
DBSession,
MyModel,
)
from pi_director.models.UserModel import UserModel
def authorize_user(email):
user=DBSession.query(UserModel).filter(UserModel.email==email).one()
user.AccessLevel=2
DBSession.flush()
def delete_user(email):
DBSession.query(UserModel).filter(UserModel.email==email).delete()
def get_users():
UserList=DBSession.query(UserModel).all()
return UserList
def make_an_admin(request):
email=request.matchdict['email']
'''First, make sure there aren't already admins in the system'''
res=DBSession.query(UserModel).filter(UserModel.AccessLevel==2).first()
if res != None:
msg="User already an admin: {user}".format(user=res.email)
return False
user=DBSession.query(UserModel).filter(UserModel.email==email).first()
user.AccessLevel=2
DBSession.flush()
return True
|
Remove entire playlist if too long
|
const utils = require('./../../utils.js');
module.exports.info = {
name: 'Playlist',
description: 'List the current sounds and music that is stored within the playlist.',
category: 'Music',
aliases: [
'list',
'playlist',
'queue'
],
use: [
{
name: '',
value: 'List the playlist'
}
]
};
module.exports.command = (message) => {
utils.music.list(message, (playlist, repeat) => {
if (playlist.length === 0) {
message.channel.createMessage('The playlist is empty.');
} else {
let reply = `https://discord.mss.ovh/music/${message.channel.guild.id}\n\`\`\`\n`;
reply += `Repeat mode is ${repeat ? 'enabled' : 'disabled'}\n`;
playlist.forEach((element, index) => {
reply += `[${index || 'Current'}] ${element.title}\n`;
});
reply += '```';
if (reply && reply.length > 1900) {
message.channel.createMessage(`https://discord.mss.ovh/music/${message.channel.guild.id}\nThe list is too long to display. Please view the playlist online.`);
} else {
message.channel.createMessage(reply);
}
}
});
};
|
const utils = require('./../../utils.js');
module.exports.info = {
name: 'Playlist',
description: 'List the current sounds and music that is stored within the playlist.',
category: 'Music',
aliases: [
'list',
'playlist',
'queue'
],
use: [
{
name: '',
value: 'List the playlist'
}
]
};
module.exports.command = (message) => {
utils.music.list(message, (playlist, repeat) => {
if (playlist.length === 0) {
message.channel.createMessage('The playlist is empty.');
} else {
let reply = `https://discord.mss.ovh/music/${message.channel.guild.id}\n\`\`\`\n`;
reply += `Repeat mode is ${repeat ? 'enabled' : 'disabled'}\n`;
playlist.forEach((element, index) => {
reply += `[${index || 'Current'}] ${element.title}\n`;
});
reply += '```';
message.channel.createMessage(reply);
}
});
};
|
Use version from git tags
|
#!/usr/bin/python3
from subprocess import check_output
from setuptools import setup, find_packages
git_version = check_output(["git", "describe", "--tags"]).strip()
setup(name='grafcli',
version=git_version,
description='Grafana CLI management tool',
author='Milosz Smolka',
author_email='m110@m110.pl',
url='https://github.com/m110/grafcli',
packages=find_packages(exclude=['tests']),
scripts=['scripts/grafcli'],
data_files=[('/etc/grafcli', ['grafcli.conf.example'])],
install_requires=['climb>=0.3.2'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python :: 3.4',
'Topic :: System :: Systems Administration',
])
|
#!/usr/bin/python3
from setuptools import setup, find_packages
setup(name='grafcli',
version='0.5.2',
description='Grafana CLI management tool',
author='Milosz Smolka',
author_email='m110@m110.pl',
url='https://github.com/m110/grafcli',
packages=find_packages(exclude=['tests']),
scripts=['scripts/grafcli'],
data_files=[('/etc/grafcli', ['grafcli.conf.example'])],
install_requires=['climb>=0.3.2'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python :: 3.4',
'Topic :: System :: Systems Administration',
])
|
Add acks late to task
|
import os
from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from django.db import connections
@periodic_task(run_every=crontab(minute=0, hour=0, day_of_week=7), acks_late=True)
def move_ucr_data_into_aggregation_tables():
with connections[settings.ICDS_UCR_DATABASE_ALIAS].cursor() as cursor:
path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_locations_table.sql')
with open(path, "r") as sql_file:
sql_to_execute = sql_file.read()
cursor.execute(sql_to_execute)
path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_monthly_aggregate_tables.sql')
with open(path, "r") as sql_file:
sql_to_execute = sql_file.read()
for interval in ["0 months", "1 months", "2 months"]:
cursor.execute(sql_to_execute, {"interval": interval})
|
import os
from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from django.db import connections
@periodic_task(run_every=crontab(minute=0, hour=0, day_of_week=7))
def move_ucr_data_into_aggregation_tables():
with connections[settings.ICDS_UCR_DATABASE_ALIAS].cursor() as cursor:
path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_locations_table.sql')
with open(path, "r") as sql_file:
sql_to_execute = sql_file.read()
cursor.execute(sql_to_execute)
path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_monthly_aggregate_tables.sql')
with open(path, "r") as sql_file:
sql_to_execute = sql_file.read()
for interval in ["0 months", "1 months", "2 months"]:
cursor.execute(sql_to_execute, {"interval": interval})
|
Fix a typo in the new "ApplicationEmailHeraldField"
Summary: This rule isn't quite right.
Test Plan: Shipped email in with a rule in effect, saw correct value in transcript.
Reviewers: btrahan, chad
Reviewed By: chad
Subscribers: epriestley
Differential Revision: https://secure.phabricator.com/D13578
|
<?php
final class PhabricatorMetaMTAApplicationEmailHeraldField
extends HeraldField {
const FIELDCONST = 'application-email';
public function getHeraldFieldName() {
return pht('Receiving email address');
}
public function supportsObject($object) {
return $this->getAdapter()->supportsApplicationEmail();
}
public function getHeraldFieldValue($object) {
$phids = array();
$email = $this->getAdapter()->getApplicationEmail();
if ($email) {
$phids[] = $email->getPHID();
}
return $phids;
}
protected function getHeraldFieldStandardConditions() {
return self::STANDARD_LIST;
}
public function getHeraldFieldValueType($condition) {
switch ($condition) {
case HeraldAdapter::CONDITION_EXISTS:
case HeraldAdapter::CONDITION_NOT_EXISTS:
return HeraldAdapter::VALUE_NONE;
default:
return HeraldAdapter::VALUE_APPLICATION_EMAIL;
}
}
}
|
<?php
final class PhabricatorMetaMTAApplicationEmailHeraldField
extends HeraldField {
const FIELDCONST = 'application-email';
public function getHeraldFieldName() {
return pht('Receiving email address');
}
public function supportsObject($object) {
return $this->getAdapter()->supportsApplicationEmail();
}
public function getHeraldFieldValue($object) {
$phids = array();
$email = $this->getAdapter()->getApplicationEmail();
if ($email) {
$phids[] = $email;
}
return $phids;
}
protected function getHeraldFieldStandardConditions() {
return self::STANDARD_LIST;
}
public function getHeraldFieldValueType($condition) {
switch ($condition) {
case HeraldAdapter::CONDITION_EXISTS:
case HeraldAdapter::CONDITION_NOT_EXISTS:
return HeraldAdapter::VALUE_NONE;
default:
return HeraldAdapter::VALUE_APPLICATION_EMAIL;
}
}
}
|
Remove C file from package sent to pip env
|
try:
from distutils.core import setup
except ImportError:
from setuptools import setup
open('MANIFEST.in', 'w').write("\n".join((
'include *.rst',
'include doc/*'
)))
from mss import __version__
setup(
name='mss',
version=__version__,
author='Tiger-222',
py_modules=['mss'],
author_email='contact@tiger-222.fr',
description='A cross-platform multi-screen shot module in pure python using ctypes',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: zlib/libpng License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.0',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Multimedia :: Graphics :: Capture :: Screen Capture',
],
url='https://github.com/BoboTiG/python-mss'
)
|
try:
from distutils.core import setup
except ImportError:
from setuptools import setup
open('MANIFEST.in', 'w').write("\n".join((
'include *.rst',
'include doc/*',
'include test/*.c'
)))
from mss import __version__
setup(
name='mss',
version=__version__,
author='Tiger-222',
py_modules=['mss'],
author_email='contact@tiger-222.fr',
description='A cross-platform multi-screen shot module in pure python using ctypes',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: zlib/libpng License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.0',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Multimedia :: Graphics :: Capture :: Screen Capture',
],
url='https://github.com/BoboTiG/python-mss'
)
|
Fix for django trying to rollback connections on request exceptions.
git-svn-id: 98eea730e22c7fb5f8b38c49248ce5c7e9bb5936@525 be7adf91-e322-0410-8f47-e6edb61c52aa
|
"""Contains code needed to initialize channelguide. This should be run at
startup, before any real work starts.
"""
import locale
import logging
import logging.handlers
import random
import os
import sys
import traceback
from django.conf import settings
from django.core import signals
from django.dispatch import dispatcher
import django.db
def init_logging():
logger = logging.getLogger()
logger.setLevel(logging.INFO)
log_path = os.path.join(settings.SITE_DIR, 'log', 'cg.log')
handler = logging.handlers.RotatingFileHandler(log_path, maxBytes=2**20)
handler.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s'))
logger.addHandler(handler)
def init_external_libraries():
sys.path.insert(0, settings.EXTERNAL_LIBRARY_DIR)
def initialize():
init_logging()
init_external_libraries()
random.seed()
locale.setlocale(locale.LC_ALL, '')
# hack for the fact that django tries to rollback its non-existant
# connection when requests finish.
dispatcher.disconnect(django.db._rollback_on_exception,
signal=signals.got_request_exception)
|
"""Contains code needed to initialize channelguide. This should be run at
startup, before any real work starts.
"""
import locale
import logging
import logging.handlers
import random
import os
import sys
import traceback
from django.conf import settings
from django.core import signals
from django.dispatch import dispatcher
def init_logging():
logger = logging.getLogger()
logger.setLevel(logging.INFO)
log_path = os.path.join(settings.SITE_DIR, 'log', 'cg.log')
handler = logging.handlers.RotatingFileHandler(log_path, maxBytes=2**20)
handler.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s'))
logger.addHandler(handler)
def init_external_libraries():
sys.path.insert(0, settings.EXTERNAL_LIBRARY_DIR)
def initialize():
init_logging()
init_external_libraries()
random.seed()
locale.setlocale(locale.LC_ALL, '')
|
Add disabled to text input
|
import React from 'react'
export default class Text extends React.Component {
static propTypes = {
onChange: React.PropTypes.func,
value: React.PropTypes.string,
fieldType: React.PropTypes.string,
passProps: React.PropTypes.object,
placeholder: React.PropTypes.node,
errorMessage: React.PropTypes.node,
disabled: React.PropTypes.boolean
}
static defaultProps = {
fieldType: 'text',
value: ''
}
render () {
return (
<div>
<div className='os-input-container'>
<input
ref='input'
className='os-input-text'
type={this.props.fieldType}
value={this.props.value}
placeholder={this.props.placeholder}
onChange={event => this.props.onChange(event.target.value)}
disabled={this.props.disabled}
{...this.props.passProps} />
</div>
<div className='os-input-error'>{this.props.errorMessage}</div>
</div>
)
}
}
|
import React from 'react'
export default class Text extends React.Component {
static propTypes = {
onChange: React.PropTypes.func,
value: React.PropTypes.string,
fieldType: React.PropTypes.string,
passProps: React.PropTypes.object,
placeholder: React.PropTypes.node,
errorMessage: React.PropTypes.node
}
static defaultProps = {
fieldType: 'text',
value: ''
}
render () {
return (
<div>
<div className='os-input-container'>
<input
ref='input'
className='os-input-text'
type={this.props.fieldType}
value={this.props.value}
placeholder={this.props.placeholder}
onChange={event => this.props.onChange(event.target.value)}
{...this.props.passProps} />
</div>
<div className='os-input-error'>{this.props.errorMessage}</div>
</div>
)
}
}
|
Switch login and logout on and off
|
<?php
namespace Aginev\LoginActivity;
use Illuminate\Events\Dispatcher;
class LoginActivityListener
{
/**
* Handle user login events.
* @param $event
*/
public function onUserLogin($event)
{
LoginActivityFacade::login($event);
}
/**
* Handle user logout events.
* @param $event
*/
public function onUserLogout($event)
{
LoginActivityFacade::logout($event);
}
/**
* Register the listeners for the subscriber.
*
* @param Dispatcher $events
*/
public function subscribe($events)
{
if (config('login-activity.track_login', false)) {
$events->listen(
\Illuminate\Auth\Events\Login::class,
'Aginev\LoginActivity\LoginActivityListener@onUserLogin'
);
}
if (config('login-activity.track_logout', false)) {
$events->listen(
\Illuminate\Auth\Events\Logout::class,
'Aginev\LoginActivity\LoginActivityListener@onUserLogout'
);
}
}
}
|
<?php
namespace Aginev\LoginActivity;
use Illuminate\Events\Dispatcher;
class LoginActivityListener
{
/**
* Handle user login events.
* @param $event
*/
public function onUserLogin($event)
{
LoginActivityFacade::login($event);
}
/**
* Handle user logout events.
* @param $event
*/
public function onUserLogout($event)
{
LoginActivityFacade::logout($event);
}
/**
* Register the listeners for the subscriber.
*
* @param Dispatcher $events
*/
public function subscribe($events)
{
$events->listen(
\Illuminate\Auth\Events\Login::class,
'Aginev\LoginActivity\LoginActivityListener@onUserLogin'
);
$events->listen(
\Illuminate\Auth\Events\Logout::class,
'Aginev\LoginActivity\LoginActivityListener@onUserLogout'
);
}
}
|
Make tests compatible with php 5.3
|
<?php
namespace MockaTests;
use Mocka\MethodMock;
class MethodMockTest extends \PHPUnit_Framework_TestCase {
public function testIntegrated() {
$method = new MethodMock();
$method->set(function () {
return 'foo';
});
$method->at(1, function () {
return 'bar';
});
$method->at(array(2, 5), function () {
return 'zoo';
});
$this->assertSame('foo', $method->invoke());
$this->assertSame('bar', $method->invoke());
$this->assertSame('zoo', $method->invoke());
$this->assertSame('foo', $method->invoke());
$method->set(function () {
return 'def';
});
$this->assertSame('def', $method->invoke());
$this->assertSame('zoo', $method->invoke());
}
}
|
<?php
namespace MockaTests;
use Mocka\MethodMock;
class MethodMockTest extends \PHPUnit_Framework_TestCase {
public function testIntegrated() {
$method = new MethodMock();
$method->set(function () {
return 'foo';
});
$method->at(1, function () {
return 'bar';
});
$method->at([2, 5], function () {
return 'zoo';
});
$this->assertSame('foo', $method->invoke());
$this->assertSame('bar', $method->invoke());
$this->assertSame('zoo', $method->invoke());
$this->assertSame('foo', $method->invoke());
$method->set(function () {
return 'def';
});
$this->assertSame('def', $method->invoke());
$this->assertSame('zoo', $method->invoke());
}
}
|
Improve velocity list initialisation in SGD
|
import numpy as np
from .base import Base
class SGD(Base):
def __init__(self, cost, params, lr=0.1, momentum=0.9):
super().__init__(cost, params, lr)
self.momentum = momentum
self.velocity = [np.zeros_like(param.const)for param in params]
def step(self, feed_dict):
exe_output = self.executor.run(feed_dict)
for i in range(len(self.params)):
self.velocity[i] = self.momentum * self.velocity[i] - self.lr * exe_output[1 + i]
self.params[i].const += self.velocity[i]
return exe_output[0]
|
import numpy as np
from .base import Base
class SGD(Base):
def __init__(self, cost, params, lr=0.1, momentum=0.9):
super().__init__(cost, params, lr)
self.momentum = momentum
self.velocity = self._init_velocity_vec(params)
def step(self, feed_dict):
exe_output = self.executor.run(feed_dict)
for i in range(len(self.params)):
self.velocity[i] = self.momentum * self.velocity[i] - self.lr * exe_output[1 + i]
self.params[i].const += self.velocity[i]
return exe_output[0]
@staticmethod
def _init_velocity_vec(params):
vector = []
for param in params:
vector.append(np.zeros_like(param.const))
return vector
|
Update room title on store change
|
import React from "react-native";
import RoomTitle from "../components/room-title";
import controller from "./controller";
const {
InteractionManager
} = React;
@controller
export default class RoomTitleController extends React.Component {
constructor(props) {
super(props);
const displayName = this.props.room.replace(/-+/g, " ").replace(/\w\S*/g, s => s.charAt(0).toUpperCase() + s.slice(1)).trim();
this.state = {
room: { displayName }
};
}
componentDidMount() {
this._updateData();
this.handle("statechange", changes => {
if (changes.entities && changes.entities[this.props.room]) {
this._updateData();
}
});
}
_updateData() {
InteractionManager.runAfterInteractions(() => {
if (this._mounted) {
const room = this.store.getRoom(this.props.room);
if (room.displayName) {
this.setState({ room });
}
}
});
}
render() {
return <RoomTitle {...this.state} />;
}
}
RoomTitleController.propTypes = {
room: React.PropTypes.string.isRequired
};
|
import React from "react-native";
import RoomTitle from "../components/room-title";
import controller from "./controller";
const {
InteractionManager
} = React;
@controller
export default class RoomTitleController extends React.Component {
constructor(props) {
super(props);
const displayName = this.props.room.replace(/-+/g, " ").replace(/\w\S*/g, s => s.charAt(0).toUpperCase() + s.slice(1)).trim();
this.state = {
room: { displayName }
};
}
componentDidMount() {
setTimeout(() => this._onDataArrived(this.store.getRoomById(this.props.room)), 0);
}
_onDataArrived(room) {
InteractionManager.runAfterInteractions(() => {
if (this._mounted) {
this.setState({ room });
}
});
}
render() {
return <RoomTitle {...this.state} />;
}
}
RoomTitleController.propTypes = {
room: React.PropTypes.string.isRequired
};
|
Update long description of language counts
|
var _ = require('underscore'),
SHORT = _.template('Languages: jw.org: <%= jworg.total %>, <%= jworg.hasWebContent %> L1+, <%= jworg.isSign %> SLs, <%= jworg.isRTL %> RTL, <%= jworg.isSignWithWeb %> L1+ SLs; jwb: <%= jwb.web.total %>, <%= jwb.web.isSign %> SLs, <%= jwb.appletv.total %> AppleTV, <%= jwb.roku.total %> Roku'),
LONG = _.template('jw.org has <%= jworg.total %> languages with downloadable content, <%= jworg.hasWebContent %> of which have part of the actual site in their language. This includes <%= jworg.isSign %> sign languages with downloadable content, <%= jworg.isSignWithWeb %> of which have part of the actual site in their language. <%= jworg.isRTL %> of these languages are right-to-left.\n\nJW Broadcasting is available in <%= jwb.web.total %> languages. This includes <%= jwb.web.isSign %> sign languages.');
module.exports = {
SHORT: SHORT,
LONG: LONG,
};
|
var _ = require('underscore'),
SHORT = _.template('Languages: jw.org: <%= jworg.total %>, <%= jworg.hasWebContent %> L1+, <%= jworg.isSign %> SLs, <%= jworg.isRTL %> RTL, <%= jworg.isSignWithWeb %> L1+ SLs; jwb: <%= jwb.web.total %>, <%= jwb.web.isSign %> SLs, <%= jwb.appletv.total %> AppleTV, <%= jwb.roku.total %> Roku'),
LONG = _.template('jw.org has <%= jworg.total %> languages with downloadable content, <%= jworg.hasWebContent %> of which have part of the actual site in their language. This includes <%= jworg.isSign %> sign languages with downloadable content, <%= jworg.isSignWithWeb %> of which have part of the actual site in their language. <%= jworg.isRTL %> of these languages are right-to-left.\n\nJW Broadcasting is available in <%= jwb.web.total %> languages, all of which have the monthly program. This includes <%= jwb.web.isSign %> sign languages.');
module.exports = {
SHORT: SHORT,
LONG: LONG,
};
|
Remove actions at the correct time.
|
package org.apollo.game.scheduling;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import org.apollo.util.CollectionUtil;
/**
* A class which manages {@link ScheduledTask}s.
*
* @author Graham
*/
public final class Scheduler {
/**
* The Queue of tasks that are pending execution.
*/
private final Queue<ScheduledTask> pending = new ArrayDeque<>();
/**
* The List of currently active tasks.
*/
private final List<ScheduledTask> active = new ArrayList<>();
/**
* Pulses the {@link Queue} of {@link ScheduledTask}s, removing those that are no longer running.
*/
public void pulse() {
CollectionUtil.pollAll(pending, active::add);
for (Iterator<ScheduledTask> iterator = active.iterator(); iterator.hasNext();) {
ScheduledTask task = iterator.next();
task.pulse();
if (!task.isRunning()) {
iterator.remove();
}
}
}
/**
* Schedules a new task.
*
* @param task The task to schedule.
* @return {@code true} if the task was added successfully.
*/
public boolean schedule(ScheduledTask task) {
return pending.add(task);
}
}
|
package org.apollo.game.scheduling;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import org.apollo.util.CollectionUtil;
/**
* A class which manages {@link ScheduledTask}s.
*
* @author Graham
*/
public final class Scheduler {
/**
* An {@link ArrayDeque} of tasks that are pending execution.
*/
private final Queue<ScheduledTask> pendingTasks = new ArrayDeque<>();
/**
* An {@link ArrayList} of currently active tasks.
*/
private final List<ScheduledTask> tasks = new ArrayList<>();
/**
* Called every pulse: executes tasks that are still pending, adds new tasks and stops old tasks.
*/
public void pulse() {
CollectionUtil.pollAll(pendingTasks, tasks::add);
for (Iterator<ScheduledTask> iterator = tasks.iterator(); iterator.hasNext();) {
ScheduledTask task = iterator.next();
task.pulse();
if (task.isRunning()) {
iterator.remove();
}
}
}
/**
* Schedules a new task.
*
* @param task The task to schedule.
* @return {@code true} if the task was added successfully.
*/
public boolean schedule(ScheduledTask task) {
return pendingTasks.add(task);
}
}
|
Drop distutils and alternate entry points.
|
import setuptools
from setuptools import setup
#from distutils.core import setup
setup(
name='pydeps',
version='0.9.2',
packages=['pydeps'],
install_requires=[
'enum34'
],
entry_points={
'console_scripts': [
#'py2dep = pydeps.py2depgraph:py2depgraph',
#'dep2dot = pydeps.depgraph2dot:depgraph2dot',
'pydeps = pydeps.pydeps:pydeps',
]
},
url='https://github.com/thebjorn/pydeps',
license='BSD',
author='bjorn',
author_email='bp@datakortet.no',
description='Display module dependencies'
)
|
import setuptools
from distutils.core import setup
setup(
name='pydeps',
version='0.9.2',
packages=['pydeps'],
install_requires=[
'enum34'
],
entry_points={
'console_scripts': [
'py2dep = pydeps.py2depgraph:py2depgraph',
'dep2dot = pydeps.depgraph2dot:depgraph2dot',
'pydeps = pydeps.pydeps:pydeps',
]
},
url='https://github.com/thebjorn/pydeps',
license='BSD',
author='bjorn',
author_email='bp@datakortet.no',
description='Display module dependencies'
)
|
Fix Updater with custom config.json-locations / allow ANTRAGSGRUEN_CONFIG with ./yii
|
<?php
$configDir = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'models' .
DIRECTORY_SEPARATOR . 'settings' . DIRECTORY_SEPARATOR;
require_once($configDir . 'JsonConfigTrait.php');
require_once($configDir . 'AntragsgruenApp.php');
if (isset($_SERVER['ANTRAGSGRUEN_CONFIG'])) {
$configFile = $_SERVER['ANTRAGSGRUEN_CONFIG'];
} elseif (isset($_ENV['ANTRAGSGRUEN_CONFIG'])) {
$configFile = $_SERVER['ANTRAGSGRUEN_CONFIG'];
} else {
$configFile = __DIR__ . DIRECTORY_SEPARATOR . 'config.json';
}
$config = file_get_contents($configFile);
$params = new \app\models\settings\AntragsgruenApp($config);
$common = require(__DIR__ . DIRECTORY_SEPARATOR . 'common.php');
unset($common['defaultRoute']);
return yii\helpers\ArrayHelper::merge(
$common,
[
'id' => 'basic-console',
'controllerNamespace' => 'app\commands',
]
);
|
<?php
$configDir = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'models' .
DIRECTORY_SEPARATOR . 'settings' . DIRECTORY_SEPARATOR;
require_once($configDir . 'JsonConfigTrait.php');
require_once($configDir . 'AntragsgruenApp.php');
$config = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'config.json');
$params = new \app\models\settings\AntragsgruenApp($config);
$common = require(__DIR__ . DIRECTORY_SEPARATOR . 'common.php');
unset($common['defaultRoute']);
return yii\helpers\ArrayHelper::merge(
$common,
[
'id' => 'basic-console',
'controllerNamespace' => 'app\commands',
]
);
|
Fix for EADDRNOTAVAIL 0.0.0.0:5980 on windows ws
|
'use strict'
var pick = require('lodash.pick')
var url = require('url')
var connect = require('pull-ws/client')
var util = require('../util')
module.exports = function (params, cb) {
params = pick(params, 'host', 'port', 'path', 'protocol')
var address = {
protocol: params.protocol,
port: params.port,
pathname: params.path,
slashes: true
}
if (params.path == null) {
if(util.isWindows()){
if(params.host ==='0.0.0.0')params.host='localhost'
if(params.host ==='::')params.host='localhost'
}
address.hostname = params.host
address.port = params.port
} else {
address = 'ws+unix://' + params.path
}
var c = connect(url.format(address), function (err) {
if (err) return cb(err)
c.type = 'connection'
if (cb) {
cb(null, c)
cb = null
}
})
}
|
'use strict'
var pick = require('lodash.pick')
var url = require('url')
var connect = require('pull-ws/client')
module.exports = function (params, cb) {
params = pick(params, 'host', 'port', 'path', 'protocol')
var address = {
protocol: params.protocol,
port: params.port,
pathname: params.path,
slashes: true
}
if (params.path == null) {
address.hostname = params.host
address.port = params.port
} else {
address = 'ws+unix://' + params.path
}
var c = connect(url.format(address), function (err) {
if (err) return cb(err)
c.type = 'connection'
if (cb) {
cb(null, c)
cb = null
}
})
}
|
Reduce number of files copied for TS web build
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
'use strict';
const CopyPlugin = require('copy-webpack-plugin');
const { lchmod } = require('graceful-fs');
const Terser = require('terser');
const withBrowserDefaults = require('../shared.webpack.config').browser;
module.exports = withBrowserDefaults({
context: __dirname,
entry: {
extension: './src/extension.browser.ts',
},
plugins: [
// @ts-ignore
new CopyPlugin({
patterns: [
{
from: 'node_modules/typescript-web-server/*.d.ts',
to: 'typescript-web/',
flatten: true
},
],
}),
// @ts-ignore
new CopyPlugin({
patterns: [
{
from: 'node_modules/typescript-web-server/tsserver.js',
to: 'typescript-web/tsserver.web.js',
transform: (content) => {
return Terser.minify(content.toString()).code;
},
transformPath: (targetPath) => {
return targetPath.replace('tsserver.js', 'tsserver.web.js');
}
}
],
}),
],
});
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
'use strict';
const CopyPlugin = require('copy-webpack-plugin');
const { lchmod } = require('graceful-fs');
const Terser = require('terser');
const withBrowserDefaults = require('../shared.webpack.config').browser;
module.exports = withBrowserDefaults({
context: __dirname,
entry: {
extension: './src/extension.browser.ts',
},
plugins: [
// @ts-ignore
new CopyPlugin({
patterns: [
{
from: 'node_modules/typescript-web-server',
to: 'typescript-web',
transform: (content, absoluteFrom) => {
if (absoluteFrom.endsWith('tsserver.js')) {
return Terser.minify(content.toString()).code;
}
return content;
},
transformPath: (targetPath) => {
if (targetPath.endsWith('tsserver.js')) {
return targetPath.replace('tsserver.js', 'tsserver.web.js');
}
return targetPath;
}
}
],
}),
],
});
|
Add maxDelay param in startAudioRx and startVideoRx.
|
/*
* Kurento Android Media: Android Media Library based on FFmpeg.
* Copyright (C) 2011 Tikal Technologies
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.kurento.kas.media.rx;
/**
*
* @author mparis
*
*/
public class MediaRx {
public static native int startVideoRx(String sdp_str, int maxDelay, VideoRx videoPlayer);
public static native int stopVideoRx();
public static native int startAudioRx(String sdp_str, int maxDelay, AudioRx audioPlayer);
public static native int stopAudioRx();
static {
System.loadLibrary("kas-media-native");
}
}
|
/*
* Kurento Android Media: Android Media Library based on FFmpeg.
* Copyright (C) 2011 Tikal Technologies
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.kurento.kas.media.rx;
/**
*
* @author mparis
*
*/
public class MediaRx {
public static native int startVideoRx(String sdp_str, VideoRx videoPlayer);
public static native int stopVideoRx();
public static native int startAudioRx(String sdp_str, AudioRx audioPlayer);
public static native int stopAudioRx();
static {
System.loadLibrary("kas-media-native");
}
}
|
Stop dispatching extraneous `pjax:complete` events, correct typo
|
module.exports = function(el) {
var code = (el.text || el.textContent || el.innerHTML || "")
var src = (el.src || "");
var parent = el.parentNode || document.querySelector("head") || document.documentElement
var script = document.createElement("script")
if (code.match("document.write")) {
if (console && console.log) {
console.log("Script contains document.write. Can’t be executed correctly. Code skipped ", el)
}
return false
}
script.type = "text/javascript"
if (src != "") {
script.src = src;
script.async = false; // force synchronous loading of peripheral js
}
if (code != "") {
try {
script.appendChild(document.createTextNode(code))
}
catch (e) {
// old IEs have funky script nodes
script.text = code
}
}
// execute
parent.appendChild(script);
// avoid pollution only in head or body tags
if (["head","body"].indexOf(parent.tagName.toLowerCase()) > 0) {
parent.removeChild(script)
}
return true;
}
|
module.exports = function(el) {
// console.log("going to execute script", el)
var code = (el.text || el.textContent || el.innerHTML || "")
var src = (el.src || "");
var parent = el.parentNode || document.querySelector("head") || document.documentElement
var script = document.createElement("script")
if (code.match("document.write")) {
if (console && console.log) {
console.log("Script contains document.write. Can’t be executed correctly. Code skipped ", el)
}
return false
}
script.type = "text/javascript"
if (src != "") {
script.src = src;
script.onload = function() { document.dispatchEvent((new Event("pjax:complete"))); }
script.async = false; // force asynchronous loading of peripheral js
}
if (code != "") {
try {
script.appendChild(document.createTextNode(code))
}
catch (e) {
// old IEs have funky script nodes
script.text = code
}
}
// execute
parent.appendChild(script);
// avoid pollution only in head or body tags
if (["head","body"].indexOf(parent.tagName.toLowerCase()) > 0) {
parent.removeChild(script)
}
return true;
}
|
Check for None before indexing.
|
class UnitOrders(object):
def __init__(self):
self.orders = {}
def giveOrders(self, unit, orders):
if orders is not None and not isinstance(orders, list):
orders = list(orders)
self.orders[unit] = orders
def getNextOrder(self, unit):
try:
orders = self.orders[unit]
if orders is None:
return None
else:
return orders[0]
except (KeyError, IndexError):
return None
def removeNextOrder(self, unit):
self.orders[unit] = self.orders[unit][1:]
if not self.orders[unit]:
del self.orders[unit]
def getAllUnitsNextOrders(self):
return {x: self.getNextOrder(x) for x in self.orders}
|
class UnitOrders(object):
def __init__(self):
self.orders = {}
def giveOrders(self, unit, orders):
if orders is not None and not isinstance(orders, list):
orders = list(orders)
self.orders[unit] = orders
def getNextOrder(self, unit):
try:
return self.orders[unit][0]
except (KeyError, IndexError):
return None
def removeNextOrder(self, unit):
self.orders[unit] = self.orders[unit][1:]
if not self.orders[unit]:
del self.orders[unit]
def getAllUnitsNextOrders(self):
return {x: self.getNextOrder(x) for x in self.orders}
|
Simplify all teams dt definition [SCI-936]
|
// Initialize teams DataTable
function initTeamsTable() {
teamsDatatable = $('#teams-table').DataTable({
order: [[0, 'asc']],
dom: 'RBltpi',
stateSave: true,
buttons: [],
processing: true,
serverSide: true,
ajax: {
url: $('#teams-table').data('source'),
type: 'POST'
},
colReorder: {
fixedColumnsLeft: 1000000 // Disable reordering
},
columnDefs: [{
targets: [0, 1, 2],
orderable: true,
searchable: false
}, {
targets: 3,
searchable: false,
orderable: false,
sWidth: '1%'
}]
});
}
initTeamsTable();
|
// Initialize teams DataTable
function initTeamsTable() {
teamsDatatable = $('#teams-table').DataTable({
order: [[0, 'asc']],
dom: 'RBltpi',
stateSave: true,
buttons: [],
processing: true,
serverSide: true,
ajax: {
url: $('#teams-table').data('source'),
type: 'POST'
},
colReorder: {
fixedColumnsLeft: 1000000 // Disable reordering
},
columnDefs: [{
targets: [0, 1],
orderable: true,
searchable: false
}, {
targets: 2,
searchable: false,
orderable: true
}, {
targets: 3,
searchable: false,
orderable: false,
sWidth: '1%'
}]
});
}
initTeamsTable();
|
Check for correct palette type and map to color objects in classify function
|
const Color = require('color');
const fetchQueryColors = require('./bing').fetchQueryColors;
const createDefaultPalette = require('./palette').createDefaultPalette;
const matchTermToColor = require('./matcher').matchTermToColor;
const ColorClassifier = {
classify: (term, options) => {
if (!term || (typeof term !== 'string') || term.length === 0) {
throw new Error('Must provide a valid search term string');
}
if (!options) {
throw new Error('Must provide an options object');
}
if (!options.bingApiKey) {
throw new Error('Must provide a Bing search API string');
}
if (options.pallette) {
if (Array.isArray(options.pallette)) {
throw new Error('options.pallette must be an array of colors');
} else if (options.pallette.length < 1) {
throw new Error('options.pallette array cannot be empty');
}
}
const numResults = options.numResults || 50;
const palette = options.palette ? options.palette.map(c => Color(c))
: createDefaultPalette();
return fetchQueryColors(options.bingApiKey, term, numResults)
.then(colors => matchTermToColor(colors, palette));
},
};
module.exports = ColorClassifier;
|
const fetchQueryColors = require('./bing').fetchQueryColors;
const createDefaultPalette = require('./palette').createDefaultPalette;
const matchTermToColor = require('./matcher').matchTermToColor;
const ColorClassifier = {
classify: (term, options) => {
if (!term || (typeof term !== 'string') || term.length === 0) {
throw new Error('Must provide a valid search term string');
}
if (!options) {
throw new Error('Must provide an options object');
}
if (!options.bingApiKey) {
throw new Error('Must provide a Bing search API string');
}
const numResults = options.numResults || 50;
const palette = options.palette || createDefaultPalette();
return fetchQueryColors(options.bingApiKey, term, numResults)
.then(colors => matchTermToColor(colors, palette));
},
};
module.exports = ColorClassifier;
|
Fix when using a <script> tag
|
;(function (f) {
// module name and requires
var name = '';
var requires = [];
// CommonJS
if (typeof exports === "object" && typeof module !== "undefined") {
module.exports = f.apply(null, requires.map(function(r) { return require(r); }));
// RequireJS
} else if (typeof define === "function" && define.amd) {
define(requires, f);
// <script>
} else {
var g
if (typeof window !== "undefined") {
g = window;
} else if (typeof global !== "undefined") {
g = global;
} else if (typeof self !== "undefined") {
g = self;
} else {
// works providing we're not in "use strict";
// needed for Java 8 Nashorn
// seee https://github.com/facebook/react/issues/3037
g = this;
}
g[name] = f.apply(null, requires.map(function(r) { return g[r]; }));
}
})(function () {
// code
return something;
});
|
;(function (f) {
// module name and requires
var name = '';
var requires = [];
// CommonJS
if (typeof exports === "object" && typeof module !== "undefined") {
module.exports = f.apply(null, requires.map(function(r) { return require(r); }));
// RequireJS
} else if (typeof define === "function" && define.amd) {
define(requires, f);
// <script>
} else {
var g
if (typeof window !== "undefined") {
g = window;
} else if (typeof global !== "undefined") {
g = global;
} else if (typeof self !== "undefined") {
g = self;
} else {
// works providing we're not in "use strict";
// needed for Java 8 Nashorn
// seee https://github.com/facebook/react/issues/3037
g = this;
}
g[name] = f.apply(null, requires.map(function(r) { return require(r); }));
}
})(function () {
// code
return something;
});
|
Update Toast page in docs
|
import React from 'react';
import Row from 'Row';
import Col from 'Col';
import ReactPlayground from './ReactPlayground';
import PropTable from './PropTable';
import Samples from './Samples';
import toast from '../../../examples/Toast';
import toastCode from '!raw-loader!Toast';
const ToastPage = () => (
<Row>
<Col m={9} s={12} l={10}>
<p className="caption">
Materialize provides an easy way for you to send unobtrusive alerts to
your users through toasts. These toasts are also placed and sized
responsively, try it out by clicking the button below on
different device sizes.
</p>
<Col s={12}>
<ReactPlayground code={Samples.toast} />
</Col>
<Col s={12}>
<PropTable header="Toast" component={toastCode} />
</Col>
</Col>
</Row>
);
export default ToastPage;
|
import React from 'react';
import Row from 'Row';
import Col from 'Col';
import ReactPlayground from './ReactPlayground';
import PropTable from './PropTable';
import Samples from './Samples';
import toast from '../../../examples/Toast';
import toastCode from '!raw-loader!Toast';
const ToastPage = () => (
<Row>
<Col m={9} s={12} l={10}>
<p className='caption'>
Materialize provides an easy way for you to send unobtrusive alerts to your users through toasts.
These toasts are also placed and sized responsively,
try it out by clicking the button below on different device sizes.
</p>
<Col s={12}>
<ReactPlayground code={Samples.toast}>
{toast}
</ReactPlayground>
</Col>
<Col s={12}>
<PropTable header='Toast' component={toastCode} />
</Col>
</Col>
</Row>
);
export default ToastPage;
|
Make it possible to chain if's
|
/**
* jQuery if-else plugin
*
* Creates if(), else() and fi() methods that can be used in
* a chain of methods on jQuery objects
*
* @author Vegard Løkken <vegard@headspin.no>
* @copyright 2013
* @version 0.2
* @licence MIT
*/
;(function( $ ) {
/* Undef object that all chained jQuery methods work on
* if they should not be executed */
var $undef = $();
/* The original object is stored here so we can restore
* it later */
var orig;
/* We store the condition given in the if() method */
var condition;
$.fn["if"] = function(options) {
orig = this;
condition = !!options;
if (!condition) {
return $undef;
} else {
return this;
}
};
$.fn["else"] = function( options) {
if (orig === undefined)
throw "else() can't be used before if()";
return this === $undef ? orig : $undef;
};
$.fn["fi"] = function(options) {
if (orig === undefined)
throw "fi() can't be used before if()";
return orig;
};
})(jQuery);
|
/**
* jQuery if-else plugin
*
* Creates if(), else() and fi() methods that can be used in
* a chain of methods on jQuery objects
*
* @author Vegard Løkken <vegard@headspin.no>
* @copyright 2013
* @version 0.1
* @licence MIT
*/
;(function( $ ) {
/* Undef object that all chained jQuery methods work on
* if they should not be executed */
var $undef = $();
/* The original object is stored here so we can restore
* it later */
var orig;
/* We store the condition given in the if() method */
var condition;
$.fn["if"] = function(options) {
orig = this;
condition = !!options;
if (!condition) {
return $undef;
} else {
return this;
}
};
$.fn["else"] = function( options) {
if (orig === undefined)
throw "else() can't be used before if()";
return this === $undef ? orig : $undef;
};
$.fn["fi"] = function(options) {
if (orig === undefined)
throw "fi() can't be used before if()";
var toReturn = orig;
orig = undefined;
return toReturn;
};
})(jQuery);
|
Change year to the current one
This was an error in previous commit.
Change-Id: I1e76eb98e416e109e395d0ce4e41d30b271e4543
|
/*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.copybara.jcommander;
import com.beust.jcommander.IParameterValidator;
import com.beust.jcommander.ParameterException;
/**
* Check if a parameter is greater than zero.
*/
public class GreaterThanZeroValidator implements IParameterValidator {
public void validate(String name, String value) throws ParameterException {
if (Integer.parseInt(value) < 1) {
throw new ParameterException(
String.format("Parameter %s should be greater than zero (found %s)", name, value));
}
}
}
|
/*
* Copyright (C) 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.copybara.jcommander;
import com.beust.jcommander.IParameterValidator;
import com.beust.jcommander.ParameterException;
/**
* Check if a parameter is greater than zero.
*/
public class GreaterThanZeroValidator implements IParameterValidator {
public void validate(String name, String value) throws ParameterException {
if (Integer.parseInt(value) < 1) {
throw new ParameterException(
String.format("Parameter %s should be greater than zero (found %s)", name, value));
}
}
}
|
Update up to changes in html-template-to-dom
|
'use strict';
var validDocument = require('dom-ext/html-document/valid-html-document')
, htmlToDom = require('dom-ext/html-document/#/html-to-dom')
, tokensToDom = require('html-template-to-dom/from-resolved-tokens')
, resolveInlineBlock = require('./lib/resolve-inline-block')
, mdToHtml = require('./lib/md-to-html')
, normalizeLinks = require('./lib/normalize-links')
, isArray = Array.isArray;
module.exports = function (document) {
validDocument(document);
return function (message/*, options*/) {
var dom, options = Object(arguments[1]);
if (isArray(message)) {
return tokensToDom(document, message, {
normalizeHtml: mdToHtml,
normalizeDomAfterInserts: function (dom) {
if (options.inline) dom = resolveInlineBlock(dom, document);
if (dom && dom.childNodes) normalizeLinks(dom);
return dom;
}
});
}
dom = htmlToDom.call(document, mdToHtml(message));
if (options.inline) dom = resolveInlineBlock(dom, document);
normalizeLinks(dom);
return dom;
};
};
|
'use strict';
var validDocument = require('dom-ext/html-document/valid-html-document')
, htmlToDom = require('dom-ext/html-document/#/html-to-dom')
, tokensToDom = require('html-template-to-dom/from-resolved-tokens')
, resolveInlineBlock = require('./lib/resolve-inline-block')
, mdToHtml = require('./lib/md-to-html')
, normalizeLinks = require('./lib/normalize-links')
, isArray = Array.isArray;
module.exports = function (document) {
validDocument(document);
return function (message/*, options*/) {
var dom, options = Object(arguments[1]);
if (isArray(message)) {
return tokensToDom(document, message, {
normalizeHtml: mdToHtml,
normalizeDom: function (dom) {
if (options.inline) dom = resolveInlineBlock(dom, document);
if (dom && dom.childNodes) normalizeLinks(dom);
return dom;
}
});
}
dom = htmlToDom.call(document, mdToHtml(message));
if (options.inline) dom = resolveInlineBlock(dom, document);
normalizeLinks(dom);
return dom;
};
};
|
Add resource name for sign up.
|
package com.thecoffeine.auth.controllers;
import com.thecoffeine.auth.view.form.RegistrationForm;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
/**
* Security Controller.
*
* @version 1.0
*/
@Controller
public class SecurityController {
/**
* Display LogIn form.
*
* @param request HTTP request.
* @param model View's model.
*
* @return View name.
*/
@RequestMapping( value = "/login" )
public String login( HttpServletRequest request, Model model ) {
//- Set params for view -//
model.addAttribute( "_csrf", request.getAttribute( "_csrf" ) );
model.addAttribute( "error", request.getParameterMap().containsKey( "error" ) );
return "login";
}
/**
* Handle Sign Up.
*
* @param request HTTP request.
*
* @return View name.
*/
@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String signUp(
@RequestBody
RegistrationForm form,
HttpServletRequest request
) {
return "sign-up.success";
}
}
|
package com.thecoffeine.auth.controllers;
import com.thecoffeine.auth.view.form.RegistrationForm;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
/**
* Security Controller.
*
* @version 1.0
*/
@Controller
public class SecurityController {
/**
* Display LogIn form.
*
* @param request HTTP request.
* @param model View's model.
*
* @return View name.
*/
@RequestMapping( value = "/login" )
public String login( HttpServletRequest request, Model model ) {
//- Set params for view -//
model.addAttribute( "_csrf", request.getAttribute( "_csrf" ) );
model.addAttribute( "error", request.getParameterMap().containsKey( "error" ) );
return "login";
}
/**
* Handle Sign Up.
*
* @param request HTTP request.
*
* @return View name.
*/
@RequestMapping(method = RequestMethod.POST)
public String signUp(
@RequestBody
RegistrationForm form,
HttpServletRequest request
) {
return "sign-up.success";
}
}
|
Add note about require statement
|
var util = require('util');
var ParentBot = require('../parentBot.js').ParentBot; //change to 'steam-parentbot' if not running from examples directory
var MySQL = require('mysql'); //require your own modules
var ChildBot = function () {
ChildBot.super_.apply(this, arguments);
}
util.inherits(ChildBot, ParentBot);
var Bot = new ChildBot('username', 'password'); //initiate the constructor, 1st arg is username, 2nd is password, 3rd (optional) is an options object
ChildBot.prototype._onFriendMsg = function (steamID, message, chatter, type) { //overwrite default event handlers
this.logger.info(steamID + ' sent: ' + message);
}
Bot.steamTrading.on('tradeProposed', function (tradeID, steamID) { //create your own listeners
Bot.steamTrading.respondToTrade(tradeID, false);
Bot.logger.verbose('Trade request from ' + steamID);
});
Bot.connection = MySQL.createConnection({ //add properties to the bot from an external module
host: 'localhost',
user: 'root',
password: 'password'
});
Bot.connection.connect(function (e) { //call methods on your new property
if (e) Bot.logger.error('Error connecting to MySQL: ' + e)
});
Bot.connect(); //connect to steam
|
var util = require('util');
var ParentBot = require('../parentBot.js').ParentBot;
var MySQL = require('mysql'); //require your own modules
var ChildBot = function () {
ChildBot.super_.apply(this, arguments);
}
util.inherits(ChildBot, ParentBot);
var Bot = new ChildBot('username', 'password'); //initiate the constructor, 1st arg is username, 2nd is password, 3rd (optional) is an options object
ChildBot.prototype._onFriendMsg = function (steamID, message, chatter, type) { //overwrite default event handlers
this.logger.info(steamID + ' sent: ' + message);
}
Bot.steamTrading.on('tradeProposed', function (tradeID, steamID) { //create your own listeners
Bot.steamTrading.respondToTrade(tradeID, false);
Bot.logger.verbose('Trade request from ' + steamID);
});
Bot.connection = MySQL.createConnection({ //add properties to the bot from an external module
host: 'localhost',
user: 'root',
password: 'password'
});
Bot.connection.connect(function (e) { //call methods on your new property
if (e) Bot.logger.error('Error connecting to MySQL: ' + e)
});
Bot.connect(); //connect to steam
|
Fix bug in last commit that caused block to not break.
|
package net.minecraftforge.event.entity.player;
import net.minecraft.src.Block;
import net.minecraft.src.Entity;
import net.minecraft.src.EntityPlayer;
import net.minecraftforge.event.Cancelable;
import net.minecraftforge.event.entity.living.LivingEvent;
public class PlayerEvent extends LivingEvent
{
public final EntityPlayer entityPlayer;
public PlayerEvent(EntityPlayer player)
{
super(player);
entityPlayer = player;
}
public static class HarvestCheck extends PlayerEvent
{
public final Block block;
public boolean success;
public HarvestCheck(EntityPlayer player, Block block, boolean success)
{
super(player);
this.block = block;
this.success = success;
}
}
@Cancelable
public static class BreakSpeed extends PlayerEvent
{
public final Block block;
public final int metadata;
public final float originalSpeed;
public float newSpeed = 0.0f;
public BreakSpeed(EntityPlayer player, Block block, int metadata, float original)
{
super(player);
this.block = block;
this.metadata = metadata;
this.originalSpeed = original;
this.newSpeed = original;
}
}
}
|
package net.minecraftforge.event.entity.player;
import net.minecraft.src.Block;
import net.minecraft.src.Entity;
import net.minecraft.src.EntityPlayer;
import net.minecraftforge.event.Cancelable;
import net.minecraftforge.event.entity.living.LivingEvent;
public class PlayerEvent extends LivingEvent
{
public final EntityPlayer entityPlayer;
public PlayerEvent(EntityPlayer player)
{
super(player);
entityPlayer = player;
}
public static class HarvestCheck extends PlayerEvent
{
public final Block block;
public boolean success;
public HarvestCheck(EntityPlayer player, Block block, boolean success)
{
super(player);
this.block = block;
this.success = success;
}
}
@Cancelable
public static class BreakSpeed extends PlayerEvent
{
public final Block block;
public final int metadata;
public final float originalSpeed;
public float newSpeed = 0.0f;
public BreakSpeed(EntityPlayer player, Block block, int metadata, float original)
{
super(player);
this.block = block;
this.metadata = metadata;
this.originalSpeed = original;
}
}
}
|
Increment version number of console application fixes T71
Reviewers: stevie, glenn
Reviewed By: stevie
Maniphest Tasks: T71
Differential Revision: https://phabricator.heyday.net.nz/D42
|
<?php
namespace Heystack\Subsystem\Core\Console;
use Monolog\Logger;
use Symfony\Component\Console\Application as BaseApplication;
/**
* Class Application
* @package Heystack\Subsystem\Core\Console
*/
class Application extends BaseApplication
{
/**
* @var
*/
protected $logger;
/**
*
*/
public function __construct()
{
parent::__construct('Heystack', '2.1.1');
}
/**
* @param Logger $logger
*/
public function setLogger(Logger $logger)
{
$this->logger = $logger;
}
/**
* @return Logger
*/
public function getLogger()
{
return $this->logger;
}
}
|
<?php
namespace Heystack\Subsystem\Core\Console;
use Monolog\Logger;
use Symfony\Component\Console\Application as BaseApplication;
/**
* Class Application
* @package Heystack\Subsystem\Core\Console
*/
class Application extends BaseApplication
{
/**
* @var
*/
protected $logger;
/**
*
*/
public function __construct()
{
parent::__construct('Heystack', '1.1');
}
/**
* @param Logger $logger
*/
public function setLogger(Logger $logger)
{
$this->logger = $logger;
}
/**
* @return Logger
*/
public function getLogger()
{
return $this->logger;
}
}
|
Add new fields to photo table
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMachinephotosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('machinephotos', function (Blueprint $table) {
$table->increments('id');
$table->integer('machine_id')->unsigned()->default(0);
$table->string('machine_photo_path')->nullable();
$table->string('machine_photo_thumb')->nullable();
$table->string('photo_description')->nullable();
$table->softDeletes();
$table->timestamps();
$table->foreign('machine_id')->references('id')->on('machines');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('machinephotos');
}
}
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMachinephotosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('machinephotos', function (Blueprint $table) {
$table->increments('id');
$table->integer('machine_id')->unsigned()->default(0);
$table->string('machine_photo')->nullable();
$table->softDeletes();
$table->timestamps();
$table->foreign('machine_id')->references('id')->on('machines');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('machinephotos');
}
}
|
Add Container with Most Water
|
package problems;
public class ContainerWithMostWater {
public int maxArea(int[] height) {
if (height.length <= 1)
return 0;
int a = 0, b = height.length - 1;
int max = 0;
while (b > a) {
int volumn = Math.min(height[a], height[b]) * (b - a);
if (volumn > max)
max = volumn;
if (height[a] <= height[b])
a++;
else
b--;
}
return max;
}
public static void main(String[] args) {
ContainerWithMostWater cw = new ContainerWithMostWater();
int[] height = { 1, 3, 2, 5, 3 };
System.out.println(cw.maxArea(height));
}
}
|
package problems;
public class ContainerWithMostWater {
public int maxArea(int[] height) {
if (height.length <= 1)
return 0;
int a = 0, b = height.length - 1;
int max = 0;
while (b > a) {
int volumn = Math.min(height[a], height[b]) * (b - a);
if (volumn > max)
max = volumn;
if (height[a] <= height[b])
a++;
else
b--;
}
return max;
}
public static void main(String[] args) {
ContainerWithMostWater cw = new ContainerWithMostWater();
int[] height = {1, 3, 2, 5, 3};
System.out.println(cw.maxArea(height));
}
}
|
Remove TODO, will probably not need to do this now
|
<?php
Route::group(['before' => 'auth', 'prefix' => 'dashboard'], function() {
Route::get('/', ['as' => 'dashboard', 'uses' => 'DashboardController@showDashboard']);
Route::get('components', ['as' => 'dashboard.components', 'uses' => 'DashComponentController@showComponents']);
Route::get('components/add', ['as' => 'dashboard.components.add', 'uses' => 'DashComponentController@showAddComponent']);
Route::post('components/add', 'DashComponentController@createComponentAction');
Route::get('components/{component}/delete', 'DashComponentController@deleteComponentAction');
Route::get('incidents', ['as' => 'dashboard.incidents', 'uses' => 'DashIncidentController@showIncidents']);
Route::get('incidents/add', ['as' => 'dashboard.incidents.add', 'uses' => 'DashIncidentController@showAddIncident']);
Route::post('incidents/add', 'DashIncidentController@createIncidentAction');
Route::get('metrics', ['as' => 'dashboard.metrics', 'uses' => 'DashboardController@showMetrics']);
Route::get('notifications', ['as' => 'dashboard.notifications', 'uses' => 'DashboardController@showNotifications']);
Route::get('status-page', ['as' => 'dashboard.status-page', 'uses' => 'DashboardController@showStatusPage']);
Route::get('settings', ['as' => 'dashboard.settings', 'uses' => 'DashSettingsController@showSettings']);
Route::post('settings', 'DashSettingsController@postSettings');
});
|
<?php
Route::group(['before' => 'auth', 'prefix' => 'dashboard'], function() {
Route::get('/', ['as' => 'dashboard', 'uses' => 'DashboardController@showDashboard']);
// TODO: Switch for Route::controller?
Route::get('components', ['as' => 'dashboard.components', 'uses' => 'DashComponentController@showComponents']);
Route::get('components/add', ['as' => 'dashboard.components.add', 'uses' => 'DashComponentController@showAddComponent']);
Route::post('components/add', 'DashComponentController@createComponentAction');
Route::get('components/{component}/delete', 'DashComponentController@deleteComponentAction');
Route::get('incidents', ['as' => 'dashboard.incidents', 'uses' => 'DashIncidentController@showIncidents']);
Route::get('incidents/add', ['as' => 'dashboard.incidents.add', 'uses' => 'DashIncidentController@showAddIncident']);
Route::post('incidents/add', 'DashIncidentController@createIncidentAction');
Route::get('metrics', ['as' => 'dashboard.metrics', 'uses' => 'DashboardController@showMetrics']);
Route::get('notifications', ['as' => 'dashboard.notifications', 'uses' => 'DashboardController@showNotifications']);
Route::get('status-page', ['as' => 'dashboard.status-page', 'uses' => 'DashboardController@showStatusPage']);
Route::get('settings', ['as' => 'dashboard.settings', 'uses' => 'DashSettingsController@showSettings']);
Route::post('settings', 'DashSettingsController@postSettings');
});
|
Add missing open source header
|
<?php
/*
* This file is part of the PayBreak/basket package.
*
* (c) PayBreak <dev@paybreak.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PayBreak\Sdk\Gateways;
/**
* Customer Intelligence Gateway
*
* @author GK
*/
class CustomerIntelligenceGateway extends AbstractGateway
{
/**
* @author GK
* @param string $installation
* @param array $body
* @param string $token
* @return array
* @throws \WNowicki\Generic\Exception
*/
public function performLeadScore($installation, array $body, $token)
{
return $this->postDocument(
'/v4/installations/' . $installation . '/lead-score',
$body,
$token,
'LeadScore'
);
}
}
|
<?php
namespace PayBreak\Sdk\Gateways;
/**
* Customer Intelligence Gateway
*
* @author GK
*/
class CustomerIntelligenceGateway extends AbstractGateway
{
/**
* @author GK
* @param string $installation
* @param array $body
* @param string $token
* @return array
* @throws \WNowicki\Generic\Exception
*/
public function performLeadScore($installation, array $body, $token)
{
return $this->postDocument(
'/v4/installations/' . $installation . '/lead-score',
$body,
$token,
'LeadScore'
);
}
}
|
Remove test for refresh button that is currently not enabled
|
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('ics-feed', 'Integration | Component | ics feed', {
integration: true
});
test('it show instructions', function(assert) {
assert.expect(1);
let instructions = 'SOME TEST INS';
this.set('instructions', instructions);
this.render(hbs`{{ics-feed instructions=instructions}}`);
assert.equal(this.$().text().trim(), instructions);
});
test('it show url', function(assert) {
assert.expect(1);
let url = 'http://example.com/url';
this.set('url', url);
this.render(hbs`{{ics-feed url=url}}`);
assert.equal(this.$('input').val().trim(), url);
});
// test('refresh calls action', function(assert) {
// assert.expect(1);
// let url = 'http://example.com/url';
// this.set('url', url);
// // Set any properties with this.set('myProperty', 'value');
// // Handle any actions with this.on('myAction', function(val) { ... });
// this.on('refresh', function(){
// assert.ok(true);
// });
// this.render(hbs`{{ics-feed refresh='refresh'}}`);
//
// this.$('button:eq(1)').click();
// });
|
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('ics-feed', 'Integration | Component | ics feed', {
integration: true
});
test('it show instructions', function(assert) {
assert.expect(1);
let instructions = 'SOME TEST INS';
this.set('instructions', instructions);
this.render(hbs`{{ics-feed instructions=instructions}}`);
assert.equal(this.$().text().trim(), instructions);
});
test('it show url', function(assert) {
assert.expect(1);
let url = 'http://example.com/url';
this.set('url', url);
this.render(hbs`{{ics-feed url=url}}`);
assert.equal(this.$('input').val().trim(), url);
});
test('refresh calls action', function(assert) {
assert.expect(1);
let url = 'http://example.com/url';
this.set('url', url);
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.on('refresh', function(){
assert.ok(true);
});
this.render(hbs`{{ics-feed refresh='refresh'}}`);
this.$('button:eq(1)').click();
});
|
Fix escaping servers which replace the ` ` with a space
We have seen some servers which replace the non-breaking space character with an actual space.
This should ensure that even when there is a space the div actually renders
|
import { MJMLElement } from 'mjml-core'
import React, { Component } from 'react'
const tagName = 'mj-spacer'
const parentTag = ['mj-column', 'mj-hero-content']
const selfClosingTag = true
const defaultMJMLDefinition = {
attributes: {
'align': null,
'container-background-color': null,
'height': '20px',
'padding-bottom': null,
'padding-left': null,
'padding-right': null,
'padding-top': null,
'vertical-align': null
}
}
@MJMLElement
class Spacer extends Component {
styles = this.getStyles()
getStyles () {
const { mjAttribute, defaultUnit } = this.props
return {
div: {
fontSize: '1px',
lineHeight: defaultUnit(mjAttribute('height')),
whiteSpace: 'nowrap'
}
}
}
render () {
return (
<div
dangerouslySetInnerHTML={{ __html: ' ' }}
style={this.styles.div} />
)
}
}
Spacer.tagName = tagName
Spacer.parentTag = parentTag
Spacer.selfClosingTag = selfClosingTag
Spacer.defaultMJMLDefinition = defaultMJMLDefinition
export default Spacer
|
import { MJMLElement } from 'mjml-core'
import React, { Component } from 'react'
const tagName = 'mj-spacer'
const parentTag = ['mj-column', 'mj-hero-content']
const selfClosingTag = true
const defaultMJMLDefinition = {
attributes: {
'align': null,
'container-background-color': null,
'height': '20px',
'padding-bottom': null,
'padding-left': null,
'padding-right': null,
'padding-top': null,
'vertical-align': null
}
}
@MJMLElement
class Spacer extends Component {
styles = this.getStyles()
getStyles () {
const { mjAttribute, defaultUnit } = this.props
return {
div: {
fontSize: '1px',
lineHeight: defaultUnit(mjAttribute('height'))
}
}
}
render () {
return (
<div
dangerouslySetInnerHTML={{ __html: ' ' }}
style={this.styles.div} />
)
}
}
Spacer.tagName = tagName
Spacer.parentTag = parentTag
Spacer.selfClosingTag = selfClosingTag
Spacer.defaultMJMLDefinition = defaultMJMLDefinition
export default Spacer
|
:bug: Make sure the download analyze is done
Use magic delay seconds to implement that, may improve in the futrue
|
const { resolve: pathResolve } = require('path')
const { readFileSync } = require('fs')
const chromeLauncher = require('./chrome-launcher')
async function getDownloadUrl (lessonUrl) {
const client = await chromeLauncher()
const { Page, Runtime } = client
// Use `tubeninja.net` to analyze download url
await Page.navigate({
url: `https://www.tubeninja.net/?url=${encodeURIComponent(lessonUrl)}`
})
return new Promise(resolve => {
Page.loadEventFired(() => {
const getDownloadUrlScript = readFileSync(pathResolve(__dirname, '../scripts/get-download-url.js'), 'utf-8')
// NOTE: Use magic delay seconds to make sure the ayalyze is done.
setTimeout(async () => {
const messageFormChrome = await Runtime.evaluate({
expression: getDownloadUrlScript
})
client.close()
resolve(messageFormChrome.result.value)
}, 3000)
})
})
}
module.exports = getDownloadUrl
|
const { resolve: pathResolve } = require('path')
const { readFileSync } = require('fs')
const chromeLauncher = require('./chrome-launcher')
async function getDownloadUrl (lessonUrl) {
const client = await chromeLauncher()
const { Page, Runtime } = client
// Use `tubeninja.net` to analyze download url
await Page.navigate({
url: `https://www.tubeninja.net/?url=${encodeURIComponent(lessonUrl)}`
})
return new Promise(resolve => {
Page.loadEventFired(async () => {
const getDownloadUrlScript = readFileSync(pathResolve(__dirname, '../scripts/get-download-url.js'), 'utf-8')
const messageFormChrome = await Runtime.evaluate({
expression: getDownloadUrlScript
})
client.close()
resolve(messageFormChrome.result.value)
})
})
}
module.exports = getDownloadUrl
|
Move header logo to the left
Signed-off-by: HichamELBSI <89c0764379da71f693bb6b7c10b76731e7cadd4f@gmail.com>
|
import styled from 'styled-components';
import PropTypes from 'prop-types';
import Logo from '../../assets/images/logo-strapi.png';
const Wrapper = styled.div`
background-color: #007eff;
padding-left: 2rem;
height: ${props => props.theme.main.sizes.leftMenu.height};
.leftMenuHeaderLink {
&:hover {
text-decoration: none;
}
}
.projectName {
display: block;
width: 100%;
height: ${props => props.theme.main.sizes.leftMenu.height};
font-size: 2rem;
letter-spacing: 0.2rem;
color: $white;
background-image: url(${Logo});
background-repeat: no-repeat;
background-position: left center;
background-size: auto 2.5rem;
}
`;
Wrapper.defaultProps = {
theme: {
main: {
colors: {
leftMenu: {},
},
sizes: {
header: {},
leftMenu: {},
},
},
},
};
Wrapper.propTypes = {
theme: PropTypes.object,
};
export default Wrapper;
|
import styled from 'styled-components';
import PropTypes from 'prop-types';
import Logo from '../../assets/images/logo-strapi.png';
const Wrapper = styled.div`
background-color: #007eff;
height: ${props => props.theme.main.sizes.leftMenu.height};
.leftMenuHeaderLink {
&:hover {
text-decoration: none;
}
}
.projectName {
display: block;
width: 100%;
text-align: center;
height: ${props => props.theme.main.sizes.leftMenu.height};
vertical-align: middle;
font-size: 2rem;
letter-spacing: 0.2rem;
color: $white;
background-image: url(${Logo});
background-repeat: no-repeat;
background-position: center center;
background-size: auto 3rem;
}
`;
Wrapper.defaultProps = {
theme: {
main: {
colors: {
leftMenu: {},
},
sizes: {
header: {},
leftMenu: {},
},
},
},
};
Wrapper.propTypes = {
theme: PropTypes.object,
};
export default Wrapper;
|
Change url name of tab
|
export const TABS = [
{
name: 'latest',
urlName: 'enkeltaar',
title: 'Enkeltår',
chartKind: 'bar',
year: 'latest'
},
{
name: 'chronological',
urlName: 'historikk',
title: 'Over tid',
chartKind: 'line',
year: 'all'
},
//{
// name: 'map',
// title: 'Kart',
// chartKind: 'map',
// year: 'latest'
//},
{
name: 'benchmark',
urlName: 'sammenliknet',
title: 'Sammenliknet',
chartKind: 'benchmark',
year: 'latest'
},
// {
// name: 'table',
// title: 'Tabell',
// chartKind: 'table',
// year: 'latest'
// }
]
|
export const TABS = [
{
name: 'latest',
urlName: 'siste',
title: 'Enkeltår',
chartKind: 'bar',
year: 'latest'
},
{
name: 'chronological',
urlName: 'historikk',
title: 'Over tid',
chartKind: 'line',
year: 'all'
},
//{
// name: 'map',
// title: 'Kart',
// chartKind: 'map',
// year: 'latest'
//},
{
name: 'benchmark',
urlName: 'sammenliknet',
title: 'Sammenliknet',
chartKind: 'benchmark',
year: 'latest'
},
// {
// name: 'table',
// title: 'Tabell',
// chartKind: 'table',
// year: 'latest'
// }
]
|
Add parse_angle() example to calculations page.
|
# Copyright (c) 2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""
Parse angles
============
Demonstrate how to convert direction strings to angles.
The code below shows how to parse directional text into angles.
It also demonstrates the function's flexibility
in handling various string formatting.
"""
import metpy.calc as mpcalc
###########################################
# Create a test value of a directional text
dir_str = 'SOUTH SOUTH EAST'
print(dir_str)
###########################################
# Now throw that string into the function to calculate
# the corresponding angle
angle_deg = mpcalc.parse_angle(dir_str)
print(angle_deg)
###########################################
# The function can also handle arrays of string
# in many different abbrieviations and capitalizations
dir_str_list = ['ne', 'NE', 'NORTHEAST', 'NORTH_EAST', 'NORTH east']
angle_deg_list = mpcalc.parse_angle(dir_str_list)
print(angle_deg_list)
|
# Copyright (c) 2015-2018 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""
Parse angles
============
Demonstrate how to convert direction strings to angles.
The code below shows how to parse directional text into angles.
It also demonstrates the function's flexibility
in handling various string formatting.
"""
import metpy.calc as mpcalc
###########################################
# Create a test value of a directional text
dir_str = 'SOUTH SOUTH EAST'
print(dir_str)
###########################################
# Now throw that string into the function to calculate
# the corresponding angle
angle_deg = mpcalc.parse_angle(dir_str)
print(angle_deg)
###########################################
# The function can also handle arrays of string
# in many different abbrieviations and capitalizations
dir_str_list = ['ne', 'NE', 'NORTHEAST', 'NORTH_EAST', 'NORTH east']
angle_deg_list = mpcalc.parse_angle(dir_str_list)
print(angle_deg_list)
|
Add icon files to the archive also
|
var gulp = require('gulp');
var zip = require('gulp-zip');
gulp.task('default', ['package'], function() {
// place code for your default task here
});
gulp.task('package', function() {
return gulp.src([
'./*',
'vendor/*',
'icons/*',
'!archive.zip',
'!gulpfile.js',
'!package.json'
], { base: '.' })
.pipe(zip('archive.zip'))
.pipe(gulp.dest('.//'));
});
gulp.task('vendor', ['vendor-rtc', 'vendor-rtc-ios']);
gulp.task('vendor-rtc', function() {
return gulp
.src('node_modules/rtc/dist/*')
.pipe(gulp.dest('vendor/'));
});
gulp.task('vendor-rtc-ios', function() {
return gulp
.src('node_modules/rtc-plugin-nicta-ios/dist/*')
.pipe(gulp.dest('vendor/'));
});
|
var gulp = require('gulp');
var zip = require('gulp-zip');
gulp.task('default', ['package'], function() {
// place code for your default task here
});
gulp.task('package', function() {
return gulp.src(['./*', 'vendor/*', '!archive.zip', '!gulpfile.js', '!package.json'], { base: '.' })
.pipe(zip('archive.zip'))
.pipe(gulp.dest('.//'));
});
gulp.task('vendor', ['vendor-rtc', 'vendor-rtc-ios']);
gulp.task('vendor-rtc', function() {
return gulp
.src('node_modules/rtc/dist/*')
.pipe(gulp.dest('vendor/'));
});
gulp.task('vendor-rtc-ios', function() {
return gulp
.src('node_modules/rtc-plugin-nicta-ios/dist/*')
.pipe(gulp.dest('vendor/'));
});
|
Add go binary existence check
|
package main
import (
"flag"
"fmt"
"os"
"os/exec"
)
var output string
func init() {
flag.Usage = func() {
fmt.Printf("Usage: %s [-out=out.path] in.path\n\n", os.Args[0])
flag.PrintDefaults()
}
flag.StringVar(&output, "out", "out.go", "Specify a path to the output file")
flag.Parse()
}
func main() {
checkRequirements()
file, err := os.Open(flag.Arg(0))
if err != nil {
fmt.Printf("Error! %s\n", err)
os.Exit(2)
}
defer file.Close()
prog := "go"
path, err := exec.LookPath(prog)
if err != nil {
fmt.Printf("Please, install %s first.", prog)
}
fmt.Printf("%s is available at %s\n", prog, path)
fmt.Printf("input file: %s, output file: %s\n", flag.Arg(0), output)
}
func checkRequirements() {
args := flag.Args()
if len(args) == 0 {
flag.Usage()
fmt.Printf("Error! The input file is required\n")
os.Exit(1)
} else if len(args) > 1 {
fmt.Printf("Notice! To many positional arguments, ignoring %v\n", args[1:])
}
}
|
package main
import (
"flag"
"fmt"
"os"
)
var output string
func init() {
flag.Usage = func() {
fmt.Printf("Usage: %s [-out=out.path] in.path\n\n", os.Args[0])
flag.PrintDefaults()
}
flag.StringVar(&output, "out", "out.go", "Specify a path to the output file")
flag.Parse()
}
func main() {
checkRequirements()
file, err := os.Open(flag.Arg(0))
if err != nil {
fmt.Printf("Error! %s\n", err)
os.Exit(2)
}
defer file.Close()
fmt.Printf("input file: %s, output file: %s\n", flag.Arg(0), output)
}
func checkRequirements() {
args := flag.Args()
if len(args) == 0 {
flag.Usage()
fmt.Printf("Error! The input file is required\n")
os.Exit(1)
} else if len(args) > 1 {
fmt.Printf("Notice! To many positional arguments, ignoring %v\n", args[1:])
}
}
|
Use Carbon instead of default PHP Date
|
<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Experience extends Model
{
//
public $table ='experiences';
protected $fillable = ['id','user_id','experience_type','company_name',
'internship_field_id','work_type','work_from','work_to','stipend',
'salary','job_description','location','organization','link','certificate','mark'];
public function user(){
return $this->belongsTo('App\User');
}
public function setWorkFromAttribute($value){
$this->attributes['work_from'] = $this->validateDateString($value);
}
public function setWorkToAttribute($value){
$this->attributes['work_to'] = $this->validateDateString($value);
}
// Private
private function validateDateString($value){
$checkDate = Carbon::createFromFormat('Y-m-d',$value);
$checkDate = $checkDate->format('Y-m-d');
return $checkDate == $value?$value:null;
}
}
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Experience extends Model
{
//
public $table ='experiences';
protected $fillable = ['id','user_id','experience_type','company_name',
'internship_field_id','work_type','work_from','work_to','stipend',
'salary','job_description','location','organization','link','certificate','mark'];
public function user(){
return $this->belongsTo('App\User');
}
public function setWorkFromAttribute($value){
$this->attributes['work_from'] = $this->validateDateString($value);
}
public function setWorkToAttribute($value){
$this->attributes['work_to'] = $this->validateDateString($value);
}
// Private
private function validateDateString($value){
$checkDate = \DateTime::createFromFormat('Y-m-d',$value);
return $checkDate == $value?$value:null;
}
}
|
Move eslint in to test grunt task
|
module.exports = function(grunt) {
grunt.config.init({
pkg: grunt.file.readJSON('package.json')
});
grunt.loadNpmTasks('grunt-eslint');
grunt.config('eslint', {
dist: {
options: {
configFile: '.eslintrc',
},
src: ['touchtap-event.js']
}
});
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.config('jasmine', {
test: {
src: 'touchtap-event.js',
options: {
specs: 'test/*-spec.js'
}
}
});
grunt.registerTask('test', [
'eslint',
'jasmine:test',
]);
grunt.registerTask('default', [
'test'
]);
};
|
module.exports = function(grunt) {
grunt.config.init({
pkg: grunt.file.readJSON('package.json')
});
grunt.loadNpmTasks('grunt-eslint');
grunt.config('eslint', {
dist: {
options: {
configFile: '.eslintrc',
},
src: ['touchtap-event.js']
}
});
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.config('jasmine', {
test: {
src: 'touchtap-event.js',
options: {
specs: 'test/*-spec.js'
}
}
});
grunt.registerTask('test', [
'jasmine:test',
]);
grunt.registerTask('default', [
'eslint',
'test'
]);
};
|
Rename task 'up' and 'down' to 'deploy:up' and 'deploy:down'
|
<?php
/* (c) Anton Medvedev <anton@elfet.ru>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require_once __DIR__ . '/common.php';
// This recipe support Laravel 5.1+, with orther version, please see document https://github.com/deployphp/docs
// Laravel shared dirs
set('shared_dirs', [
'storage/app',
'storage/framework/cache',
'storage/framework/sessions',
'storage/framework/views',
'storage/logs',
]);
// Laravel 5 shared file
set('shared_files', ['.env']);
// Laravel writable dirs
set('writable_dirs', ['bootstrap/cache', 'storage']);
/**
* Main task
*/
task('deploy', [
'deploy:prepare',
'deploy:release',
'deploy:update_code',
'deploy:vendors',
'deploy:shared',
'deploy:symlink',
'cleanup',
])->desc('Deploy your project');
after('deploy', 'success');
/**
* Helper tasks
*/
task('deploy:up', function () {
$output = run('php {{deploy_path}}/current/artisan up');
writeln('<info>'.$output.'</info>');
})->desc('Disable maintenance mode');
task('deploy:down', function () {
$output = run('php {{deploy_path}}/current/artisan down');
writeln('<error>'.$output.'</error>');
})->desc('Enable maintenance mode');
|
<?php
/* (c) Anton Medvedev <anton@elfet.ru>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require_once __DIR__ . '/common.php';
// Laravel shared dirs
set('shared_dirs', [
'storage/app',
'storage/framework/cache',
'storage/framework/sessions',
'storage/framework/views',
'storage/logs',
]);
// Laravel 5 shared file
set('shared_files', ['.env']);
// Laravel writable dirs
set('writable_dirs', ['bootstrap/cache', 'storage']);
/**
* Main task
*/
task('deploy', [
'deploy:prepare',
'deploy:release',
'deploy:update_code',
'deploy:vendors',
'deploy:shared',
'deploy:symlink',
'cleanup',
])->desc('Deploy your project');
after('deploy', 'success');
/**
* Helper tasks
*/
task('up', function () {
$output = run('php {{deploy_path}}/current/artisan up');
writeln('<info>'.$output.'</info>');
})->desc('Disable maintenance mode');
task('down', function () {
$output = run('php {{deploy_path}}/current/artisan down');
writeln('<error>'.$output.'</error>');
})->desc('Enable maintenance mode');
|
Consolidate local OpenAPI specs and APIServices' spec into one data structure
Remove APIService OpenAPI spec when it is deleted
Add eTag support and returning httpStatus to OpenAPI spec downloader
Update aggregated OpenAPI spec periodically
Use delegate chain
Refactor OpenAPI aggregator to have separate controller and aggregation function
Enable OpenAPI spec for extensions api server
Do not filter paths. higher priority specs wins the conflicting paths
Move OpenAPI aggregation controller to pkg/controller/openapi
Kubernetes-commit: 76e24f216f5d83de1f79be4288f0ee6b0d2c0565
|
/*
Copyright 2017 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.
*/
// +k8s:deepcopy-gen=package,register
// +k8s:conversion-gen=k8s.io/kubernetes/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions
// +k8s:defaulter-gen=TypeMeta
// Package v1beta1 is the v1beta1 version of the API.
// +groupName=apiextensions.k8s.io
// +k8s:openapi-gen=true
package v1beta1 // import "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
|
/*
Copyright 2017 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.
*/
// +k8s:deepcopy-gen=package,register
// +k8s:conversion-gen=k8s.io/kubernetes/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions
// +k8s:defaulter-gen=TypeMeta
// Package v1beta1 is the v1beta1 version of the API.
// +groupName=apiextensions.k8s.io
package v1beta1 // import "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
|
Fix Buffer tests in <= 0.10
|
var test = require('tap').test;
var browserify = require('browserify');
var vm = require('vm');
var path = require('path');
if (!ArrayBuffer.isView) ArrayBuffer.isView = function () { return false; };
test('sync string encoding', function (t) {
t.plan(2);
var b = browserify(__dirname + '/files/buffer.js');
b.require('buffer', { expose: 'buffer' });
b.transform(path.dirname(__dirname));
b.bundle(function (err, src) {
if (err) t.fail(err);
var context = {
setTimeout: setTimeout,
console: { log: log },
ArrayBuffer: ArrayBuffer,
Uint8Array: Uint8Array,
DataView: DataView
};
var buffers = [];
vm.runInNewContext(src, context);
t.ok(context.require('buffer').Buffer.isBuffer(buffers[0]), 'isBuffer');
t.equal(buffers[0].toString('utf8'), '<b>beep boop</b>\n');
function log (msg) { buffers.push(msg) }
});
});
|
var test = require('tap').test;
var browserify = require('browserify');
var vm = require('vm');
var path = require('path');
test('sync string encoding', function (t) {
t.plan(2);
var b = browserify(__dirname + '/files/buffer.js');
b.require('buffer', { expose: 'buffer' });
b.transform(path.dirname(__dirname));
b.bundle(function (err, src) {
if (err) t.fail(err);
var context = {
setTimeout: setTimeout,
console: { log: log }
};
var buffers = [];
vm.runInNewContext(src, context);
t.ok(context.require('buffer').Buffer.isBuffer(buffers[0]), 'isBuffer');
t.equal(buffers[0].toString('utf8'), '<b>beep boop</b>\n');
function log (msg) { buffers.push(msg) }
});
});
|
Add more variables and bug fixes
|
__author__ = 'mcsquaredjr'
import os
import socket
node_file = os.environ["NODES"]
cad_file = os.environ["CAD"]
procs_per_nod = os.environ["PROCS_PER_NODE"]
itemcount = os.environ["ITEMCOUNT"]
ddp = os.environment["DDP"]
def my_lines(i):
ip = socket.gethostbyname(socket.gethostname())
with open(cad_file, "r") as cad:
lines = []
for line in cad:
ip_str, port = line.split(":")
if ip_str == str(ip):
lines.append(line)
def chunk_number(i):
if i == 0 or i == 1:
return 0
else:
return i -1
def chunk_count(i):
with open(cad_file) as cad:
for i, l in enumerate(cad):
pass
return i + 1 - 2
|
__author__ = 'mcsquaredjr'
import os
node_file = os.environ["NODES"]
cad_file = os.environ["CAD"]
procs_per_nod = os.environ["PROCS_PER_NODE"]
def my_lines(ip):
with open(cad_file, "r") as cad:
lines = []
for line in cad:
ip, port = line.split(":")
if ip == str(ip):
line.append(line)
def chunk_number(i):
if i == 0 or i == 1:
return 0
else:
return i -1
def chunk_count(i):
with open(cad_file) as cad:
for i, l in enumerate(cad):
pass
return i + 1
|
Add useResolvedTree flag to SplitBuildAndLayoutTestConfiguration
Reviewed By: pentiumao
Differential Revision: D36164793
fbshipit-source-id: 2d20899587d177c8dd657a7d3f32d623c629ec7c
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho.testing.testrunner;
import com.facebook.litho.config.ComponentsConfiguration;
import org.junit.runners.model.FrameworkMethod;
public class SplitBuildAndLayoutTestRunConfiguration implements LithoTestRunConfiguration {
private final boolean defaultApplyStateUpdateEarly =
ComponentsConfiguration.applyStateUpdateEarly;
private final boolean defaultIsBuildAndLayoutSplitEnabled =
ComponentsConfiguration.isBuildAndLayoutSplitEnabled;
private final boolean defaultUseResolvedTree = ComponentsConfiguration.useResolvedTree;
@Override
public void beforeTest(FrameworkMethod method) {
ComponentsConfiguration.isBuildAndLayoutSplitEnabled = true;
ComponentsConfiguration.applyStateUpdateEarly = true;
ComponentsConfiguration.useResolvedTree = true;
}
@Override
public void afterTest(FrameworkMethod method) {
ComponentsConfiguration.isBuildAndLayoutSplitEnabled = defaultIsBuildAndLayoutSplitEnabled;
ComponentsConfiguration.applyStateUpdateEarly = defaultApplyStateUpdateEarly;
ComponentsConfiguration.useResolvedTree = defaultUseResolvedTree;
}
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho.testing.testrunner;
import com.facebook.litho.config.ComponentsConfiguration;
import org.junit.runners.model.FrameworkMethod;
public class SplitBuildAndLayoutTestRunConfiguration implements LithoTestRunConfiguration {
private final boolean defaultApplyStateUpdateEarly =
ComponentsConfiguration.applyStateUpdateEarly;
private final boolean defaultIsBuildAndLayoutSplitEnabled =
ComponentsConfiguration.isBuildAndLayoutSplitEnabled;
@Override
public void beforeTest(FrameworkMethod method) {
ComponentsConfiguration.isBuildAndLayoutSplitEnabled = true;
ComponentsConfiguration.applyStateUpdateEarly = true;
}
@Override
public void afterTest(FrameworkMethod method) {
ComponentsConfiguration.isBuildAndLayoutSplitEnabled = defaultIsBuildAndLayoutSplitEnabled;
ComponentsConfiguration.applyStateUpdateEarly = defaultApplyStateUpdateEarly;
}
}
|
Add option , parse with JSON.parse by default
|
var originalDataModule = require('data-module');
var gutil = require('gulp-util');
var through2 = require('through2');
var DataModuleError = gutil.PluginError.bind(null, 'gulp-data-module');
var dataModule = function dataModule (options) { 'use strict';
if (!options) options = {};
var parsing = options.parsing || JSON.parse;
var dataModuleOptions = {};
if (typeof options.formatting == 'function') {
dataModuleOptions.formatting = options.formatting;
}
return through2.obj(function dataModuleStream (file, encoding, done) {
var source;
if (file.isBuffer()) {
source = parsing(file.contents.toString());
file.contents = originalDataModule
( source
, dataModuleOptions
).toBuffer();
file.path = file.path.replace(/(?:\.[^\/\\\.]$|$)/, '.js');
}
else if (file.isStream()) return done(new DataModuleError
( 'Streams not supported'
));
this.push(file);
return done();
});
};
dataModule.formatting =
{ diffy: dataModule.diffy
};
module.exports = dataModule;
|
var dataModule = require('data-module');
var gutil = require('gulp-util');
var through2 = require('through2');
var DataModuleError = gutil.PluginError.bind(null, 'gulp-data-module');
var gulpDataModule = function gulpDataModule (options) { 'use strict';
if (!options) options = {};
var dataModuleOptions = {};
if (typeof options.formatting == 'function') {
dataModuleOptions.formatting = options.formatting;
}
return through2.obj(function dataModuleStream (file, encoding, done) {
if (file.isBuffer()) {
file.contents = dataModule
( file.contents.toString()
, dataModuleOptions
).toBuffer();
file.path = file.path.replace(/(?:\.[^\/\\\.]$|$)/, '.js');
}
else if (file.isStream()) return done(new DataModuleError
( 'Streams not supported'
));
this.push(file);
return done();
});
};
gulpDataModule.formatting =
{ diffy: dataModule.diffy
};
module.exports = gulpDataModule;
|
Update patrol launcher to recent changes
|
#!/usr/bin/python
"""
Cyril Robin -- LAAS-CNRS -- 2014
TODO Descriptif
"""
from mission import *
from constant import *
from sys import argv, exit
from timer import Timer
if __name__ == "__main__":
with Timer('Loading mission file'):
json_mission = loaded_mission(argv[1])
mission = Mission ( json_mission )
print "Starting Loop !"
#mission.loop(20,False,'Perception-based TSP')
#mission.loop(10,False,'Perception-based TOP')
mission.decentralized_loop(20,False,'Perception-based TSP')
#mission.sample_objective()
#mission.sample_all_positions()
#for robot in mission.team:
#robot.display_weighted_map()
#mission.display_situation()
print "Last update..."
mission.update()
mission.dump_situation()
mission.display_situation()
mission.print_metrics()
print "Done."
|
#!/usr/bin/python
"""
Cyril Robin -- LAAS-CNRS -- 2014
TODO Descriptif
"""
from mission import *
from constant import *
from sys import argv, exit
from timer import Timer
if __name__ == "__main__":
with Timer('Loading mission file'):
json_mission = loaded_mission(argv[1])
mission = Mission ( json_mission )
print "Starting Loop !"
#mission.loop_once('Perception-based TSP')
#mission.loop(10,True,'Perception-based TSP')
#mission.decentralized_loop_once()
mission.decentralized_loop(5,False,'Perception-based TSP')
print "Updating..."
mission.update()
mission.dump_situation()
#for robot in mission.team:
#robot.display_weighted_map()
mission.display_situation()
mission.print_metrics()
print "Done."
|
Support php executed in cgi mode
|
<?php
header('Lain: Hot');
if (strnatcmp(phpversion(),'5.5') < 0)
exit("PHP 5.5 or newer is required");
include('config.php');
function PhoxyStart()
{
global $_SERVER;
if (phoxy_conf()["api_xss_prevent"] && $_SERVER['HTTP_X_LAIN'] !== 'Wake up')
die("Requiest aborted due API direct XSS warning");
global $_GET;
$get_param = phoxy_conf()["get_api_param"];
$file = $_GET[$get_param];
unset($_GET[$get_param]);
if ($file == 'htaccess')
exit('Rewrite engine work SUCCESS');
include_once('rpc_string_parser.php');
$parser = new \phoxy\rpc_string_parser();
global $_phoxy_process_obj;
$_phoxy_process_obj = $obj = $parser->GetRpcObject($file, $_GET);
$a = $obj['obj'];
$method = $obj['method'];
if (is_string($method))
$method = [$method, []];
try
{
echo $a->APICall($method[0], $method[1]);
} catch (phoxy_protected_call_error $e)
{
echo new phoxy_return_worker($e->result);
}
}
if (phoxy_conf()['autostart'])
PhoxyStart();
|
<?php
header('Lain: Hot');
if (strnatcmp(phpversion(),'5.5') < 0)
exit("PHP 5.5 or newer is required");
include('config.php');
function PhoxyStart()
{
if (phoxy_conf()["api_xss_prevent"] && getallheaders()['X-Lain'] !== 'Wake up')
die("Requiest aborted due API direct XSS warning");
global $_GET;
$get_param = phoxy_conf()["get_api_param"];
$file = $_GET[$get_param];
unset($_GET[$get_param]);
if ($file == 'htaccess')
exit('Rewrite engine work SUCCESS');
include_once('rpc_string_parser.php');
$parser = new \phoxy\rpc_string_parser();
global $_phoxy_process_obj;
$_phoxy_process_obj = $obj = $parser->GetRpcObject($file, $_GET);
$a = $obj['obj'];
$method = $obj['method'];
if (is_string($method))
$method = [$method, []];
try
{
echo $a->APICall($method[0], $method[1]);
} catch (phoxy_protected_call_error $e)
{
echo new phoxy_return_worker($e->result);
}
}
if (phoxy_conf()['autostart'])
PhoxyStart();
|
[Add] Create and return a new empty media
|
package medias
import (
"encoding/json"
"errors"
"github.com/mitchellh/mapstructure"
"io/ioutil"
"log"
"github.com/Zenika/MARCEL/backend/commons"
)
var Medias []Media
const path_to_config string = "data/medias.config.json"
func LoadMedias() {
//Medias configurations are loaded from a JSON file on the FS.
content, err := ioutil.ReadFile(path_to_config)
check(err)
var obj []interface{}
json.Unmarshal([]byte(content), &obj)
//Map the json to the Media structure
for _, b := range obj {
var media Media
err = mapstructure.Decode(b.(map[string]interface{}), &media)
if err != nil {
panic(err)
}
Medias = append(Medias, media)
}
log.Print("Medias configurations is loaded...")
}
func GetMedia(idMedia string) (*Media, error) {
for _, media := range Medias {
if idMedia == media.ID {
return &media, nil
}
}
return nil, errors.New("NO_MEDIA_FOUND")
}
func CreateMedia() (*Media) {
newMedia := new(Media)
newMedia.ID = commons.GetUID()
//SaveMedia(newMedia)
return newMedia
}
|
package medias
import (
"io/ioutil"
"encoding/json"
"errors"
"log"
"github.com/mitchellh/mapstructure"
)
var Medias []Media
const path_to_config string = "data/medias.config.json"
func LoadMedias() {
//Medias configurations are loaded from a JSON file on the FS.
content, err := ioutil.ReadFile(path_to_config)
check(err)
var obj []interface{}
json.Unmarshal([]byte(content), &obj)
//Map the json to the Media structure
for _, b := range obj {
var media Media
err = mapstructure.Decode(b.(map[string]interface{}), &media)
if err != nil {
panic(err)
}
Medias = append(Medias, media)
}
log.Print("Medias configurations is loaded...")
}
func GetMedia(idMedia string) (*Media, error) {
for _, media := range Medias {
if idMedia == media.ID {
return &media, nil
}
}
return nil, errors.New("NO_MEDIA_FOUND")
}
|
Add applicationPort to detailed FtepService projection
Change-Id: Ib4f954fef140540590cc49120d0100d2d1f46562
|
package com.cgi.eoss.ftep.model.projections;
import com.cgi.eoss.ftep.security.FtepAccess;
import com.cgi.eoss.ftep.model.FtepService;
import com.cgi.eoss.ftep.model.FtepServiceDescriptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.rest.core.config.Projection;
import org.springframework.hateoas.Identifiable;
/**
* <p>Comprehensive representation of an FtepService entity, including the full description of input and output fields, for embedding in REST
* responses.</p>
*/
@Projection(name = "detailedFtepService", types = FtepService.class)
public interface DetailedFtepService extends Identifiable<Long> {
String getName();
String getDescription();
ShortUser getOwner();
FtepService.Type getType();
String getDockerTag();
FtepService.Licence getLicence();
FtepService.Status getStatus();
String getApplicationPort();
FtepServiceDescriptor getServiceDescriptor();
@Value("#{@ftepSecurityService.getCurrentAccess(T(com.cgi.eoss.ftep.model.FtepService), target.id)}")
FtepAccess getAccess();
}
|
package com.cgi.eoss.ftep.model.projections;
import com.cgi.eoss.ftep.security.FtepAccess;
import com.cgi.eoss.ftep.model.FtepService;
import com.cgi.eoss.ftep.model.FtepServiceDescriptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.rest.core.config.Projection;
import org.springframework.hateoas.Identifiable;
/**
* <p>Comprehensive representation of an FtepService entity, including the full description of input and output fields, for embedding in REST
* responses.</p>
*/
@Projection(name = "detailedFtepService", types = FtepService.class)
public interface DetailedFtepService extends Identifiable<Long> {
String getName();
String getDescription();
ShortUser getOwner();
FtepService.Type getType();
String getDockerTag();
FtepService.Licence getLicence();
FtepService.Status getStatus();
FtepServiceDescriptor getServiceDescriptor();
@Value("#{@ftepSecurityService.getCurrentAccess(T(com.cgi.eoss.ftep.model.FtepService), target.id)}")
FtepAccess getAccess();
}
|
Allow pub to be used in docroot
|
<?php
namespace pub;
use Symfony\Component\Yaml;
use Illuminate\Filesystem\Filesystem;
/**
* Class Project Config
*
* Manages our project-config.yml for project based configuration.
*
* @package pub
*/
class ProjectConfig {
// TODO: Figure out how to make this work with symfony2 finder depth.
// based on my testing there's a bug I need to track down in the Finder component.
// for now it's easier ot just hard-code it.
public $project_config_file = 'project-config.yml';
public $settings = NULL;
/**
* Returns TRUE or FALSE based on the config file existing.
*
* @return bool
*/
public function exists() {
$retval = FALSE;
$fs = new Filesystem();
if ($fs->exists($this->project_config_file)) {
$retval = TRUE;
}
else {
$this->project_config_file = '../' . $this->project_config_file;
if ($fs->exists($this->project_config_file)) {
$retval = TRUE;
}
}
return $retval;
}
/**
* Load the Project config yaml into memory.
*
* @return mixed
* @throws \Exception
*/
public function load() {
$fs = new Filesystem();
$yaml = new Yaml\Parser();
if (!$this->exists()) {
throw new \Exception("{$this->project_config_file} does not exists");
}
$this->settings = $yaml->parse($fs->get($this->project_config_file));
return $this->settings;
}
}
|
<?php
namespace pub;
use Symfony\Component\Yaml;
use Illuminate\Filesystem\Filesystem;
/**
* Class Project Config
*
* Manages our project-config.yml for project based configuration.
*
* @package pub
*/
class ProjectConfig {
// TODO: Figure out how to make this work with symfony2 finder depth.
// based on my testing there's a bug I need to track down in the Finder component.
// for now it's easier ot just hard-code it.
public $project_config_file = 'project-config.yml';
public $settings = NULL;
/**
* Returns TRUE or FALSE based on the config file existing.
*
* @return bool
*/
public function exists() {
$retval = FALSE;
$fs = new Filesystem();
if ($fs->exists($this->project_config_file)) {
$retval = TRUE;
}
return $retval;
}
/**
* Load the Project config yaml into memory.
*
* @return mixed
* @throws \Exception
*/
public function load() {
$fs = new Filesystem();
$yaml = new Yaml\Parser();
if (!$this->exists()) {
throw new \Exception("{$this->project_config_file} does not exists");
}
$this->settings = $yaml->parse($fs->get($this->project_config_file));
return $this->settings;
}
}
|
Add tests for non-constructor pattern.
|
'use strict';
var path = require('path');
var expect = require('expect.js');
var walkSync = require('walk-sync');
var broccoli = require('broccoli');
var fs = require('fs');
// require('mocha-jshint')();
var Tar = require('..');
describe('broccoli-targz', function(){
var fixturePath = path.join(__dirname, 'fixtures');
var builder;
afterEach(function() {
if (builder) {
return builder.cleanup();
}
});
it('emits an archive.gz file', function() {
var inputPath = path.join(fixturePath);
var tree = new Tar(inputPath);
builder = new broccoli.Builder(tree);
return builder.build()
.then(function(results) {
var outputPath = results.directory;
expect(fs.existsSync(outputPath + '/archive.tar.gz'));
});
});
it('the tar contains the file from input the input tree');
it('emits an <name>.gz file if options.name is set', function(){
var inputPath = path.join(fixturePath);
var tree = new Tar(inputPath);
builder = new broccoli.Builder(tree, 'name');
return builder.build()
.then(function(results) {
var outputPath = results.directory;
expect(fs.existsSync(outputPath + '/name.tar.gz'));
});
});
it('supports non-constructor pattern', function () {
var inputPath = path.join(fixturePath);
var tree = Tar(inputPath);
expect(tree).to.be.a(Tar);
});
});
|
'use strict';
var path = require('path');
var expect = require('expect.js');
var walkSync = require('walk-sync');
var broccoli = require('broccoli');
var fs = require('fs');
// require('mocha-jshint')();
var Tar = require('..');
describe('broccoli-targz', function(){
var fixturePath = path.join(__dirname, 'fixtures');
var builder;
afterEach(function() {
if (builder) {
return builder.cleanup();
}
});
it('emits an archive.gz file', function() {
var inputPath = path.join(fixturePath);
var tree = new Tar(inputPath);
builder = new broccoli.Builder(tree);
return builder.build()
.then(function(results) {
var outputPath = results.directory;
expect(fs.existsSync(outputPath + '/archive.tar.gz'));
});
});
it('the tar contains the file from input the input tree');
it('emits an <name>.gz file if options.name is set', function(){
var inputPath = path.join(fixturePath);
var tree = new Tar(inputPath);
builder = new broccoli.Builder(tree, 'name');
return builder.build()
.then(function(results) {
var outputPath = results.directory;
expect(fs.existsSync(outputPath + '/name.tar.gz'));
});
})
});
|
Hide emailToken from the view
|
'use strict';
/**
* Render the main applicaion page
*/
exports.renderIndex = function(req, res) {
var currentUser = null;
// Expose user
if(req.user) {
currentUser = req.user;
// Don't just expose everything to the view...
delete currentUser.emailToken;
}
res.render('modules/core/server/views/index', {
user: currentUser
});
};
/**
* Render the server error response
* Performs content-negotiation on the Accept HTTP header
*/
exports.renderServerError = function(req, res) {
res.status(500).format({
'text/html': function(){
res.render('modules/core/server/views/500');
},
'application/json': function(){
res.json({ message: 'Oops! Something went wrong...' });
},
'default': function(){
res.send('Oops! Something went wrong...');
}
});
};
/**
* Render the server not found responses
* Performs content-negotiation on the Accept HTTP header
*/
exports.renderNotFound = function(req, res) {
res.status(404).format({
'text/html': function(){
res.render('modules/core/server/views/404');
},
'application/json': function(){
res.json({ message: 'Not found.' });
},
'default': function(){
res.send('Not found.');
}
});
};
|
'use strict';
/**
* Render the main applicaion page
*/
exports.renderIndex = function(req, res) {
res.render('modules/core/server/views/index', {
user: req.user || null
});
};
/**
* Render the server error response
* Performs content-negotiation on the Accept HTTP header
*/
exports.renderServerError = function(req, res) {
res.status(500).format({
'text/html': function(){
res.render('modules/core/server/views/500');
},
'application/json': function(){
res.json({ message: 'Oops! Something went wrong...' });
},
'default': function(){
res.send('Oops! Something went wrong...');
}
});
};
/**
* Render the server not found responses
* Performs content-negotiation on the Accept HTTP header
*/
exports.renderNotFound = function(req, res) {
res.status(404).format({
'text/html': function(){
res.render('modules/core/server/views/404');
},
'application/json': function(){
res.json({ message: 'Not found.' });
},
'default': function(){
res.send('Not found.');
}
});
};
|
Call RelaxNgWriter as a temporary hack.
git-svn-id: ca8e9bb6f3f9b50a093b443c23951d3c25ca0913@283 369101cc-9a96-11dd-8e58-870c635edf7a
|
package com.thaiopensource.xml.dtd.app;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import com.thaiopensource.xml.out.CharRepertoire;
import com.thaiopensource.xml.out.XmlWriter;
import com.thaiopensource.xml.util.EncodingMap;
import com.thaiopensource.xml.dtd.om.DtdParser;
import com.thaiopensource.xml.dtd.om.Dtd;
import com.thaiopensource.xml.dtd.parse.DtdParserImpl;
public class Driver {
public static void main (String args[]) throws IOException {
DtdParser dtdParser = new DtdParserImpl();
Dtd dtd = dtdParser.parse(args[0], new FileEntityManager());
new RelaxNgWriter(null).writeDtd(dtd);
String enc = EncodingMap.getJavaName(dtd.getEncoding());
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out,
enc));
CharRepertoire cr = CharRepertoire.getInstance(enc);
new SchemaWriter(new XmlWriter(w, cr)).writeDtd(dtd);
w.flush();
}
}
|
package com.thaiopensource.xml.dtd.app;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import com.thaiopensource.xml.out.CharRepertoire;
import com.thaiopensource.xml.out.XmlWriter;
import com.thaiopensource.xml.util.EncodingMap;
import com.thaiopensource.xml.dtd.om.DtdParser;
import com.thaiopensource.xml.dtd.om.Dtd;
import com.thaiopensource.xml.dtd.parse.DtdParserImpl;
public class Driver {
public static void main (String args[]) throws IOException {
DtdParser dtdParser = new DtdParserImpl();
Dtd dtd = dtdParser.parse(args[0], new FileEntityManager());
String enc = EncodingMap.getJavaName(dtd.getEncoding());
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out,
enc));
CharRepertoire cr = CharRepertoire.getInstance(enc);
new SchemaWriter(new XmlWriter(w, cr)).writeDtd(dtd);
w.flush();
}
}
|
Make timeline view a global for debugging.
|
// Copyright (c) 2011 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.
var g_timelineView;
(function() {
var include = function(path) {
document.write('<script src="' + path + '"></script>');
};
include("/chrome/tracing/overlay.js");
include("/chrome/tracing/timeline_model.js");
include("/chrome/tracing/sorted_array_utils.js");
include("/chrome/tracing/timeline.js");
include("/chrome/tracing/timeline_track.js");
include("/chrome/tracing/fast_rect_renderer.js");
include("/chrome/tracing/timeline_view.js");
var timelineView;
function onDOMContentLoaded() {
timelineView = $('timeline-view');
g_timelineView = timelineView;
cr.ui.decorate(timelineView, tracing.TimelineView);
chrome.send('ready');
}
function loadTrace(trace) {
if (timelineView == undefined)
throw Error('timelineview is null');
// some old traces were just arrays without an outer object
if (!trace.traceEvents) {
if (trace instanceof Array)
timelineView.traceEvents = trace;
else
throw Error('trace does not have an events array');
} else {
timelineView.traceEvents = trace.traceEvents;
}
return true;
}
window.loadTrace = loadTrace;
document.addEventListener('DOMContentLoaded', onDOMContentLoaded);
})();
|
// Copyright (c) 2011 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.
(function() {
var include = function(path) {
document.write('<script src="' + path + '"></script>');
};
include("/chrome/tracing/overlay.js");
include("/chrome/tracing/timeline_model.js");
include("/chrome/tracing/sorted_array_utils.js");
include("/chrome/tracing/timeline.js");
include("/chrome/tracing/timeline_track.js");
include("/chrome/tracing/fast_rect_renderer.js");
include("/chrome/tracing/timeline_view.js");
var timelineView;
function onDOMContentLoaded() {
timelineView = $('timeline-view');
cr.ui.decorate(timelineView, tracing.TimelineView);
chrome.send('ready');
}
function loadTrace(trace) {
if (timelineView == undefined)
throw Error('timelineview is null');
// some old traces were just arrays without an outer object
if (!trace.traceEvents) {
if (trace instanceof Array)
timelineView.traceEvents = trace;
else
throw Error('trace does not have an events array');
} else {
timelineView.traceEvents = trace.traceEvents;
}
return true;
}
window.loadTrace = loadTrace;
document.addEventListener('DOMContentLoaded', onDOMContentLoaded);
})();
|
TASK: Add support for relative source file in ReceiverSource
|
<?php
/**
* Created by IntelliJ IDEA.
* User: sebastian
* Date: 27.05.15
* Time: 13:15
*/
namespace Sandstorm\Newsletter\Domain\Model;
use Doctrine\Common\Collections\ArrayCollection;
use TYPO3\Flow\Annotations as Flow;
use TYPO3\Flow\Persistence\PersistenceManagerInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* Class CsvReceiverSource
* @package Sandstorm\Newsletter\Domain\Model
* @Flow\Entity
*/
class JsonReceiverSource extends ReceiverSource {
/**
* @var string
* @Flow\Validate(type="Sandstorm\Newsletter\Validator\ExistingFileValidator")
* @Flow\Validate(type="NotEmpty")
*/
protected $sourceFileName;
/**
* @return string
*/
public function getSourceFileName() {
$sourceFileName = trim($this->sourceFileName);
if ($sourceFileName !== '' && $sourceFileName[0] === '/') {
return $this->sourceFileName;
} else {
return \FLOW_PATH_ROOT . $sourceFileName;
}
}
/**
* @param string $sourceFileName
*/
public function setSourceFileName($sourceFileName) {
$this->sourceFileName = $sourceFileName;
}
public function getConfigurationAsString() {
return $this->sourceFileName;
}
public function getType() {
return 'json';
}
}
|
<?php
/**
* Created by IntelliJ IDEA.
* User: sebastian
* Date: 27.05.15
* Time: 13:15
*/
namespace Sandstorm\Newsletter\Domain\Model;
use Doctrine\Common\Collections\ArrayCollection;
use TYPO3\Flow\Annotations as Flow;
use TYPO3\Flow\Persistence\PersistenceManagerInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* Class CsvReceiverSource
* @package Sandstorm\Newsletter\Domain\Model
* @Flow\Entity
*/
class JsonReceiverSource extends ReceiverSource {
/**
* @var string
* @Flow\Validate(type="Sandstorm\Newsletter\Validator\ExistingFileValidator")
* @Flow\Validate(type="NotEmpty")
*/
protected $sourceFileName;
/**
* @return string
*/
public function getSourceFileName() {
return $this->sourceFileName;
}
/**
* @param string $sourceFileName
*/
public function setSourceFileName($sourceFileName) {
$this->sourceFileName = $sourceFileName;
}
public function getConfigurationAsString() {
return $this->sourceFileName;
}
public function getType() {
return 'json';
}
}
|
Fix disabling KNP translatable event subscriber compiler pass.
|
<?php declare(strict_types=1);
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2017-2019, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\ContentBundle\DependencyInjection\Compiler;
use Knp\DoctrineBehaviors\EventSubscriber\TranslatableEventSubscriber;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Disable KNP translatable event subscriber compiler pass
*/
class DisableKnpTranslatableSubscriberPass implements CompilerPassInterface
{
/**
* {@inheritDoc}
*/
public function process(ContainerBuilder $container): void
{
if ($container->hasDefinition(TranslatableEventSubscriber::class)) {
$container->getDefinition('darvin_content.translatable.event_subscriber.map')
->setDecoratedService(TranslatableEventSubscriber::class);
}
}
}
|
<?php declare(strict_types=1);
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2017-2019, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\ContentBundle\DependencyInjection\Compiler;
use Knp\DoctrineBehaviors\EventSubscriber\TranslatableEventSubscriber;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Disable KNP translatable event subscriber compiler pass
*/
class DisableKnpTranslatableSubscriberPass implements CompilerPassInterface
{
/**
* {@inheritDoc}
*/
public function process(ContainerBuilder $container): void
{
if ($container->hasDefinition(TranslatableEventSubscriber::class)) {
$container->getDefinition(TranslatableEventSubscriber::class)->clearTag('doctrine.event_subscriber');
}
}
}
|
Allow error details to be any type
|
package de.innoaccel.wamp.server.message;
public class CallErrorMessage implements Message
{
private String callId;
private String errorURI;
private String errorDesc;
private Object errorDetails;
public CallErrorMessage(String callId, String errorURI, String errorDesc)
{
this(callId, errorURI, errorDesc, null);
}
public CallErrorMessage(String callId, String errorURI, String errorDesc, Object errorDetails)
{
this.callId = callId;
this.errorURI = errorURI;
this.errorDesc = errorDesc;
this.errorDetails = errorDetails;
}
@Override
public int getMessageCode()
{
return Message.CALL_ERROR;
}
public String getCallId()
{
return this.callId;
}
public String getErrorURI()
{
return this.errorURI;
}
public String getErrorDesc()
{
return this.errorDesc;
}
public Object getErrorDetails()
{
return this.errorDetails;
}
}
|
package de.innoaccel.wamp.server.message;
public class CallErrorMessage implements Message
{
private String callId;
private String errorURI;
private String errorDesc;
private String errorDetails;
public CallErrorMessage(String callId, String errorURI, String errorDesc)
{
this(callId, errorURI, errorDesc, null);
}
public CallErrorMessage(String callId, String errorURI, String errorDesc, String errorDetails)
{
this.callId = callId;
this.errorURI = errorURI;
this.errorDesc = errorDesc;
this.errorDetails = errorDetails;
}
@Override
public int getMessageCode()
{
return Message.CALL_ERROR;
}
public String getCallId()
{
return this.callId;
}
public String getErrorURI()
{
return this.errorURI;
}
public String getErrorDesc()
{
return this.errorDesc;
}
public String getErrorDetails()
{
return this.errorDetails;
}
}
|
Add all header elements to httoop.header
|
# -*- coding: utf-8 -*-
"""HTTP headers
.. seealso:: :rfc:`2616#section-2.2`
.. seealso:: :rfc:`2616#section-4.2`
.. seealso:: :rfc:`2616#section-14`
"""
__all__ = ['Headers']
# FIXME: python3?
# TODO: add a MAXIMUM of 500 headers?
import inspect
from httoop.header.element import HEADER, HeaderElement, HeaderType
from httoop.header.messaging import Server, UserAgent
from httoop.header.headers import Headers
from httoop.header import semantics
from httoop.header import messaging
from httoop.header import conditional
from httoop.header import range
from httoop.header import cache
from httoop.header import auth
types = (semantics, messaging, conditional, range, cache, auth)
for _, member in (member for type_ in types for member in inspect.getmembers(type_, inspect.isclass)):
if isinstance(member, HeaderType) and member is not HeaderElement:
HEADER[member.__name__] = member
globals()[_] = member
|
# -*- coding: utf-8 -*-
"""HTTP headers
.. seealso:: :rfc:`2616#section-2.2`
.. seealso:: :rfc:`2616#section-4.2`
.. seealso:: :rfc:`2616#section-14`
"""
__all__ = ['Headers']
# FIXME: python3?
# TODO: add a MAXIMUM of 500 headers?
import inspect
from httoop.header.element import HEADER, HeaderElement, HeaderType
from httoop.header.messaging import Server, UserAgent
from httoop.header.headers import Headers
from httoop.header import semantics
from httoop.header import messaging
from httoop.header import conditional
from httoop.header import range
from httoop.header import cache
from httoop.header import auth
types = (semantics, messaging, conditional, range, cache, auth)
for _, member in (member for type_ in types for member in inspect.getmembers(type_, inspect.isclass)):
if isinstance(member, HeaderType) and member is not HeaderElement:
HEADER[member.__name__] = member
|
Fix package_data to include templates
|
#!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name="portinus",
version="0.9.3",
author="Justin Dray",
author_email="justin@dray.be",
url="https://github.com/justin8/portinus",
description="This utility creates a systemd service file for a docker-compose file",
packages=find_packages(),
package_data={'portinus': ['templates/*']},
license="MIT",
install_requires=[
"click",
"docker",
],
tests_require=["nose",
"coverage",
"mock",
],
test_suite="nose.collector",
entry_points={
"console_scripts": [
"portinus=portinus.cli:task",
"portinus-monitor=portinus.monitor.cli:task",
]
},
classifiers=[
"Operating System :: OS Independent",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3",
"Environment :: Console",
"License :: OSI Approved :: MIT License",
"Development Status :: 5 - Production/Stable",
"Programming Language :: Python",
],
)
|
#!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name="portinus",
version="0.9.2",
author="Justin Dray",
author_email="justin@dray.be",
url="https://github.com/justin8/portinus",
description="This utility creates a systemd service file for a docker-compose file",
packages=find_packages(),
license="MIT",
install_requires=[
"click",
"docker",
],
tests_require=["nose",
"coverage",
"mock",
],
test_suite="nose.collector",
entry_points={
"console_scripts": [
"portinus=portinus.cli:task",
"portinus-monitor=portinus.monitor.cli:task",
]
},
classifiers=[
"Operating System :: OS Independent",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3",
"Environment :: Console",
"License :: OSI Approved :: MIT License",
"Development Status :: 5 - Production/Stable",
"Programming Language :: Python",
],
)
|
Remove adding track-id class in loadSound
|
function startMixer(){
return new Mixer
}
// function loadSound(mix, trackId, divId) {
// //var tracktoAdd = eventually this will look up track from server based on id
// var trackSource = _.find(sounds, function(sound) {
// return sound.id === trackId
// });
// var trackToAdd = new Wad({
// source: trackSource.src,
// env: {hold: 9001}
// });
// mix.add(trackToAdd);
// mostRecent = _.last(mix.wads);
// mostRecent.label = divId;
// var targetDiv = _.find($("div"), function(div) {
// return Number($(div).attr("id")) === divId;
// });
// $(targetDiv).append("<p>" + trackSource.name + "</p>")
// $(targetDiv).attr("track-id", trackId)
// }
// var sounds = [];
|
function startMixer(){
return new Mixer
}
// function loadSound(mix, trackId, divId) {
// //var tracktoAdd = eventually this will look up track from server based on id
// var trackSource = _.find(sounds, function(sound) {
// return sound.id === trackId
// });
// var trackToAdd = new Wad({
// source: trackSource.src,
// env: {hold: 9001}
// });
// mix.add(trackToAdd);
// mostRecent = _.last(mix.wads);
// mostRecent.label = divId;
// var targetDiv = _.find($("div"), function(div) {
// return Number($(div).attr("id")) === divId;
// });
// $(targetDiv).append("<p>" + trackSource.name + "</p>")
$(targetDiv).attr("track-id", trackId)
}
// var sounds = [];
|
Update hard-coded rate of challenge completion to reflect recent acceleration
|
import dedent from 'dedent';
import moment from 'moment';
import { observeMethod } from '../utils/rx';
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
export default function about(app) {
const router = app.loopback.Router();
const User = app.models.User;
const userCount$ = observeMethod(User, 'count');
function showAbout(req, res, next) {
const daysRunning = moment().diff(new Date('10/15/2014'), 'days');
userCount$()
.map(camperCount => numberWithCommas(camperCount))
.doOnNext(camperCount => {
res.render('resources/about', {
camperCount,
daysRunning,
title: dedent`
About our Open Source Community, our social media presence,
and how to contact us`.split('\n').join(' '),
globalCompletedCount: numberWithCommas(
5612952 + (Math.floor((Date.now() - 1446268581061) / 1800))
)
});
})
.subscribe(() => {}, next);
}
router.get('/about', showAbout);
app.use(router);
}
|
import dedent from 'dedent';
import moment from 'moment';
import { observeMethod } from '../utils/rx';
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
export default function about(app) {
const router = app.loopback.Router();
const User = app.models.User;
const userCount$ = observeMethod(User, 'count');
function showAbout(req, res, next) {
const daysRunning = moment().diff(new Date('10/15/2014'), 'days');
userCount$()
.map(camperCount => numberWithCommas(camperCount))
.doOnNext(camperCount => {
res.render('resources/about', {
camperCount,
daysRunning,
title: dedent`
About our Open Source Community, our social media presence,
and how to contact us`.split('\n').join(' '),
globalCompletedCount: numberWithCommas(
5612952 + (Math.floor((Date.now() - 1446268581061) / 2000))
)
});
})
.subscribe(() => {}, next);
}
router.get('/about', showAbout);
app.use(router);
}
|
Convert files from dos format to unix format
|
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @package Zend_Db
*/
namespace Zend\Db\Adapter\Driver\Sqlsrv;
/**
* @category Zend
* @package Zend_Db
* @subpackage Adapter
*/
class ErrorException extends \Exception
{
/**
* Errors
*
* @var array
*/
protected $errors = array();
/**
* Construct
*
* @param boolean $errors
*/
public function __construct($errors = false)
{
$this->errors = ($errors === false) ? sqlsrv_errors() : $errors;
}
}
|
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @package Zend_Db
*/
namespace Zend\Db\Adapter\Driver\Sqlsrv;
/**
* @category Zend
* @package Zend_Db
* @subpackage Adapter
*/
class ErrorException extends \Exception
{
/**
* Errors
*
* @var array
*/
protected $errors = array();
/**
* Construct
*
* @param boolean $errors
*/
public function __construct($errors = false)
{
$this->errors = ($errors === false) ? sqlsrv_errors() : $errors;
}
}
|
Test json file with api key is in API service class
|
import pytest
from bcbio.distributed import objectstore
from bcbio.distributed.objectstore import GoogleDrive
@pytest.fixture
def mock_api(mocker):
mocker.patch('bcbio.distributed.objectstore.ServiceAccountCredentials')
mocker.patch('bcbio.distributed.objectstore.Http')
mocker.patch('bcbio.distributed.objectstore.build')
mocker.patch('bcbio.distributed.objectstore.http')
yield None
def test_create_google_drive_service(mock_api):
service = GoogleDrive()
assert service
def test_creates_http_auth(mock_api):
GoogleDrive()
objectstore.ServiceAccountCredentials.from_json_keyfile_name\
.assert_called_once_with(
GoogleDrive.GOOGLE_API_KEY_FILE, scopes=GoogleDrive.SCOPES)
def test_api_scope_includes_google_drive(mock_api):
drive_scope = 'https://www.googleapis.com/auth/drive'
assert drive_scope in GoogleDrive.SCOPES
def test_filename_with_json_key_is_present(mock_api):
assert GoogleDrive.GOOGLE_API_KEY_FILE
assert GoogleDrive.GOOGLE_API_KEY_FILE.endswith('.json')
|
import pytest
from bcbio.distributed import objectstore
from bcbio.distributed.objectstore import GoogleDrive
@pytest.fixture
def mock_api(mocker):
mocker.patch('bcbio.distributed.objectstore.ServiceAccountCredentials')
mocker.patch('bcbio.distributed.objectstore.Http')
mocker.patch('bcbio.distributed.objectstore.build')
mocker.patch('bcbio.distributed.objectstore.http')
yield None
def test_create_google_drive_service(mock_api):
service = GoogleDrive()
assert service
def test_creates_http_auth(mock_api):
GoogleDrive()
objectstore.ServiceAccountCredentials.from_json_keyfile_name\
.assert_called_once_with(
GoogleDrive.GOOGLE_API_KEY_FILE, scopes=GoogleDrive.SCOPES)
def test_api_scope_includes_google_drive(mock_api):
drive_scope = 'https://www.googleapis.com/auth/drive'
assert drive_scope in GoogleDrive.SCOPES
|
Change 'cap' in 'run' to accept True, 'stdout', or 'stderr'
In 2e6873e I made cap=True equivalent to the new 'capture_output'.
This was a mistake. Turns out fzf writes its UI to stderr (makes sense),
so that was suppressed. Now you can be specific about what to capture.
|
import logging
import re
import subprocess
log = logging.getLogger(__name__)
def run(cmd, check=True, cap=False, input=None, exe='/bin/bash', cwd=None, env=None):
log.debug(f"Executing: {cmd!r}")
shell = isinstance(cmd, str)
result = subprocess.run(
cmd,
check=check,
shell=shell,
stdout=subprocess.PIPE if cap in (True, 'stdout') else None,
stderr=subprocess.PIPE if cap in (True, 'stderr') else None,
executable=exe if shell else None,
input=input.encode() if input else None,
cwd=cwd,
env=env,
)
if cap:
return result.stdout.decode()
else:
return result
def partition(pred, list):
trues, falses = [], []
for item in list:
(trues if pred(item) else falses).append(item)
return trues, falses
def partition_by_regex(regex, list):
r = re.compile(regex or '')
return partition(r.search, list)
|
import logging
import re
import subprocess
log = logging.getLogger(__name__)
def run(cmd, check=True, cap=False, input=None, exe='/bin/bash', cwd=None, env=None):
log.debug(f"Executing: {cmd!r}")
shell = isinstance(cmd, str)
result = subprocess.run(
cmd,
check=check,
shell=shell,
capture_output=cap,
executable=exe if shell else None,
input=input.encode() if input else None,
cwd=cwd,
env=env,
)
if cap:
return result.stdout.decode()
else:
return result
def partition(pred, list):
trues, falses = [], []
for item in list:
(trues if pred(item) else falses).append(item)
return trues, falses
def partition_by_regex(regex, list):
r = re.compile(regex or '')
return partition(r.search, list)
|
Switch to using protected getter
|
package net.michaelsavich.notification;
import java.util.HashSet;
/**
* An instance of NotificationCenter that dispatches {@link Notification notifications} to their {@link NotificationObserver observers} serially.
* Note that an instance of this object is returned by the static method {@link NotificationCenter#primary()}. This class is exposed as public primarily because it
* may be useful to subclass SynchronousNotificationCenter to implement custom bookkeeping. Furthermore, if for some reason you don't want to use
* the singleton-like behavior of the static methods in NotificationCenter, you can instantiate this class directly and manage it yourself.
*/
public class SynchronousNotificationCenter extends NotificationCenter {
/**
* {@inheritDoc}
* <p>
* The implementation of this method provided by SynchronousNotificationCenter is
* synchronous, and will halt everything until all objects have finished responding.
* As such, avoid adding {@link NotificationObserver observers} with long-running callbacks to a SynchronousNotificationCenter.
* </p>
* <p>
* When calling this method, remember that no guarantee is made regarding the order in which are notified.
* </p>
*/
@Override
public void post(Notification notification) {
getObservers(notification.getName())
.forEach(o -> o.receiveNotification(notification));
}
}
|
package net.michaelsavich.notification;
import java.util.HashSet;
/**
* An instance of NotificationCenter that dispatches {@link Notification notifications} to their {@link NotificationObserver observers} serially.
* Note that an instance of this object is returned by the static method {@link NotificationCenter#primary()}. This class is exposed as public primarily because it
* may be useful to subclass SynchronousNotificationCenter to implement custom bookkeeping. Furthermore, if for some reason you don't want to use
* the singleton-like behavior of the static methods in NotificationCenter, you can instantiate this class directly and manage it yourself.
*/
public class SynchronousNotificationCenter extends NotificationCenter {
/**
* {@inheritDoc}
* <p>
* The implementation of this method provided by SynchronousNotificationCenter is
* synchronous, and will halt everything until all objects have finished responding.
* As such, avoid adding {@link NotificationObserver observers} with long-running callbacks to a SynchronousNotificationCenter.
* </p>
* <p>
* When calling this method, remember that no guarantee is made regarding the order in which are notified.
* </p>
*/
@Override
public void post(Notification notification) {
dispatchTable.getOrDefault(notification.getName(), new HashSet<>())
.forEach(o -> o.receiveNotification(notification));
}
}
|
Reset the border when calibrating
IE9 has a gray border on about:blank which causes incorrect calibration.
|
(function(window) {
/*jshint browser:true, node:false*/
'use strict';
function createRedStripe(side) {
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.width = '1px';
div.style.backgroundColor = '#ff0000';
div.style.height = '100%';
div.style.top = '0';
div.style[side] = '3px';
document.body.appendChild(div);
}
var bodyStyle = document.body.style;
bodyStyle.margin = 0;
bodyStyle.padding = 0;
bodyStyle.border = 0;
bodyStyle.backgroundColor = '#00ff00';
bodyStyle.width = '100%';
bodyStyle.height = '100%';
createRedStripe('left');
createRedStripe('right');
}(window));
|
(function(window) {
/*jshint browser:true, node:false*/
'use strict';
function createRedStripe(side) {
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.width = '1px';
div.style.backgroundColor = '#ff0000';
div.style.height = '100%';
div.style.top = '0';
div.style[side] = '3px';
document.body.appendChild(div);
}
var bodyStyle = document.body.style;
bodyStyle.margin = 0;
bodyStyle.padding = 0;
bodyStyle.backgroundColor = '#00ff00';
bodyStyle.width = '100%';
bodyStyle.height = '100%';
createRedStripe('left');
createRedStripe('right');
}(window));
|
Make topic_* field on public body search index optional
|
from __future__ import print_function
from django.conf import settings
from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from .models import PublicBody
PUBLIC_BODY_BOOSTS = settings.FROIDE_CONFIG.get("public_body_boosts", {})
class PublicBodyIndex(CelerySearchIndex, indexes.Indexable):
text = indexes.EdgeNgramField(document=True, use_template=True)
name = indexes.CharField(model_attr='name', boost=1.5)
jurisdiction = indexes.CharField(model_attr='jurisdiction__name', default='')
topic_auto = indexes.EdgeNgramField(model_attr='topic__name', default='')
topic_slug = indexes.CharField(model_attr='topic__slug', default='')
name_auto = indexes.EdgeNgramField(model_attr='name')
url = indexes.CharField(model_attr='get_absolute_url')
def get_model(self):
return PublicBody
def index_queryset(self, **kwargs):
"""Used when the entire index for model is updated."""
return self.get_model().objects.get_for_search_index()
def prepare(self, obj):
data = super(PublicBodyIndex, self).prepare(obj)
if obj.classification in PUBLIC_BODY_BOOSTS:
data['boost'] = PUBLIC_BODY_BOOSTS[obj.classification]
print("Boosting %s at %f" % (obj, data['boost']))
return data
|
from __future__ import print_function
from django.conf import settings
from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from .models import PublicBody
PUBLIC_BODY_BOOSTS = settings.FROIDE_CONFIG.get("public_body_boosts", {})
class PublicBodyIndex(CelerySearchIndex, indexes.Indexable):
text = indexes.EdgeNgramField(document=True, use_template=True)
name = indexes.CharField(model_attr='name', boost=1.5)
jurisdiction = indexes.CharField(model_attr='jurisdiction__name', default='')
topic_auto = indexes.EdgeNgramField(model_attr='topic_name')
topic_slug = indexes.CharField(model_attr='topic__slug')
name_auto = indexes.EdgeNgramField(model_attr='name')
url = indexes.CharField(model_attr='get_absolute_url')
def get_model(self):
return PublicBody
def index_queryset(self, **kwargs):
"""Used when the entire index for model is updated."""
return self.get_model().objects.get_for_search_index()
def prepare(self, obj):
data = super(PublicBodyIndex, self).prepare(obj)
if obj.classification in PUBLIC_BODY_BOOSTS:
data['boost'] = PUBLIC_BODY_BOOSTS[obj.classification]
print("Boosting %s at %f" % (obj, data['boost']))
return data
|
Fix test_format_xml with dot in path
When the path contains dot ".", replacing all dots will generate a non-exist result and raises a FileNotFoundError. Replacing only the last dot fixes this.
|
import pytest
from mitmproxy.contentviews import xml_html
from mitmproxy.test import tutils
from . import full_eval
data = tutils.test_data.push("mitmproxy/contentviews/test_xml_html_data/")
def test_simple():
v = full_eval(xml_html.ViewXmlHtml())
assert v(b"foo") == ('XML', [[('text', 'foo')]])
assert v(b"<html></html>") == ('HTML', [[('text', '<html></html>')]])
@pytest.mark.parametrize("filename", [
"simple.html",
"cdata.xml",
"comment.xml",
"inline.html",
])
def test_format_xml(filename):
path = data.path(filename)
with open(path) as f:
input = f.read()
with open("-formatted.".join(path.rsplit(".", 1))) as f:
expected = f.read()
tokens = xml_html.tokenize(input)
assert xml_html.format_xml(tokens) == expected
|
import pytest
from mitmproxy.contentviews import xml_html
from mitmproxy.test import tutils
from . import full_eval
data = tutils.test_data.push("mitmproxy/contentviews/test_xml_html_data/")
def test_simple():
v = full_eval(xml_html.ViewXmlHtml())
assert v(b"foo") == ('XML', [[('text', 'foo')]])
assert v(b"<html></html>") == ('HTML', [[('text', '<html></html>')]])
@pytest.mark.parametrize("filename", [
"simple.html",
"cdata.xml",
"comment.xml",
"inline.html",
])
def test_format_xml(filename):
path = data.path(filename)
with open(path) as f:
input = f.read()
with open(path.replace(".", "-formatted.")) as f:
expected = f.read()
tokens = xml_html.tokenize(input)
assert xml_html.format_xml(tokens) == expected
|
Add missing 'format' key in the bit.ly API request.
Bit.ly have recently made a change on their side to ignore the jsonp callback argument
if format=json was not specified, and that made our requests fail.
|
import fetchJsonP from 'fetch-jsonp';
import queryString from 'query-string';
import url from 'url';
export default function shortenURL(urlToShorten) {
let longURL = urlToShorten;
if (!longURL.startsWith('https://perf-html.io/')) {
const parsedURL = url.parse(longURL);
const parsedURLOnCanonicalHost = Object.assign({}, parsedURL, {
protocol: 'https:',
host: 'perf-html.io',
});
longURL = url.format(parsedURLOnCanonicalHost);
}
const bitlyQueryURL = 'https://api-ssl.bitly.com/v3/shorten?' +
queryString.stringify({
'longUrl': longURL,
'domain': 'perfht.ml',
'format': 'json',
'access_token': 'b177b00a130faf3ecda6960e8b59fde73e902422',
});
return fetchJsonP(bitlyQueryURL).then(response => response.json()).then(json => json.data.url);
}
|
import fetchJsonP from 'fetch-jsonp';
import queryString from 'query-string';
import url from 'url';
export default function shortenURL(urlToShorten) {
let longURL = urlToShorten;
if (!longURL.startsWith('https://perf-html.io/')) {
const parsedURL = url.parse(longURL);
const parsedURLOnCanonicalHost = Object.assign({}, parsedURL, {
protocol: 'https:',
host: 'perf-html.io',
});
longURL = url.format(parsedURLOnCanonicalHost);
}
const bitlyQueryURL = 'https://api-ssl.bitly.com/v3/shorten?' +
queryString.stringify({
'longUrl': longURL,
'domain': 'perfht.ml',
'access_token': 'b177b00a130faf3ecda6960e8b59fde73e902422',
});
return fetchJsonP(bitlyQueryURL).then(response => response.json()).then(json => json.data.url);
}
|
Add basic model for keys
|
export default function(state, ctx, model, helpers) {
const ConcretizeIfNative = helpers.ConcretizeIfNative;
//TODO: Test IsNative for apply, bind & call
model.add(Function.prototype.apply, ConcretizeIfNative(Function.prototype.apply));
model.add(Function.prototype.call, ConcretizeIfNative(Function.prototype.call));
model.add(Function.prototype.bind, ConcretizeIfNative(Function.prototype.bind));
model.add(Object.prototype.hasOwnProperty, function(base, args) {
for (let i = 0; i < args.length; i++) {
args[i] = state.getConcrete(args[i]);
}
Function.prototype.hasOwnProperty.apply(state.getConcrete(base), args);
});
model.add(Object.prototype.keys, function(base, args) {
for (let i = 0; i < args.length; i++) {
args[i] = state.getConcrete(args[i]);
}
return Object.prototype.keys.apply(this.getConcrete(base), args);
});
model.add(console.log, function(base, args) {
for (let i = 0; i < args.length; i++) {
args[i] = state.getConcrete(args[i]);
}
console.log.apply(base, args);
});
}
|
export default function(state, ctx, model, helpers) {
const ConcretizeIfNative = helpers.ConcretizeIfNative;
//TODO: Test IsNative for apply, bind & call
model.add(Function.prototype.apply, ConcretizeIfNative(Function.prototype.apply));
model.add(Function.prototype.call, ConcretizeIfNative(Function.prototype.call));
model.add(Function.prototype.bind, ConcretizeIfNative(Function.prototype.bind));
model.add(Function.prototype.hasOwnProperty, function(base, args) {
for (let i = 0; i < args.length; i++) {
args[i] = state.getConcrete(args[i]);
}
Function.prototype.hasOwnProperty.apply(state.getConcrete(base), args);
});
model.add(console.log, function(base, args) {
for (let i = 0; i < args.length; i++) {
args[i] = state.getConcrete(args[i]);
}
console.log.apply(base, args);
});
}
|
Add app_name for django < 1.7 compatibility
|
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
DEFAULT_ICEBERG_ENV = getattr(settings, 'ICEBERG_DEFAULT_ENVIRO', "prod")
class IcebergBaseModel(models.Model):
ICEBERG_PROD, ICEBERG_SANDBOX, ICEBERG_STAGE, ICEBERG_SANDBOX_STAGE = "prod", "sandbox", "stage", "sandbox_stage"
ENVIRONMENT_CHOICES = (
(ICEBERG_PROD, _('Iceberg - Prod')),
(ICEBERG_STAGE, _('Iceberg - Prod Stage')), # PreProd
(ICEBERG_SANDBOX, _('Iceberg - Sandbox')),
(ICEBERG_SANDBOX_STAGE, _('Iceberg - Sandbox Stage')),
)
environment = models.CharField(choices=ENVIRONMENT_CHOICES, default=DEFAULT_ICEBERG_ENV, max_length = 20)
iceberg_id = models.PositiveIntegerField(blank=True, null=True)
last_updated = models.DateTimeField(auto_now = True)
API_RESOURCE_NAME = None
class Meta:
app_label = "django_iceberg"
abstract = True
def iceberg_sync(self, api_handler):
"""
Sync the local object from Iceberg version
"""
raise NotImplementedError
|
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
DEFAULT_ICEBERG_ENV = getattr(settings, 'ICEBERG_DEFAULT_ENVIRO', "prod")
class IcebergBaseModel(models.Model):
ICEBERG_PROD, ICEBERG_SANDBOX, ICEBERG_STAGE, ICEBERG_SANDBOX_STAGE = "prod", "sandbox", "stage", "sandbox_stage"
ENVIRONMENT_CHOICES = (
(ICEBERG_PROD, _('Iceberg - Prod')),
(ICEBERG_STAGE, _('Iceberg - Prod Stage')), # PreProd
(ICEBERG_SANDBOX, _('Iceberg - Sandbox')),
(ICEBERG_SANDBOX_STAGE, _('Iceberg - Sandbox Stage')),
)
environment = models.CharField(choices=ENVIRONMENT_CHOICES, default=DEFAULT_ICEBERG_ENV, max_length = 20)
iceberg_id = models.PositiveIntegerField(blank=True, null=True)
last_updated = models.DateTimeField(auto_now = True)
API_RESOURCE_NAME = None
class Meta:
abstract = True
def iceberg_sync(self, api_handler):
"""
Sync the local object from Iceberg version
"""
raise NotImplementedError
|
fix: Delete manual Pipeline before creating
See also: #72
|
# Foremast - Pipeline Tooling
#
# Copyright 2016 Gogo, LLC
#
# 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.
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .clean_pipelines import delete_pipeline
from .create_pipeline import SpinnakerPipeline
class SpinnakerPipelineManual(SpinnakerPipeline):
"""Manual JSON configured Spinnaker Pipelines."""
def create_pipeline(self):
"""Use JSON files to create Pipelines."""
self.log.info('Uploading manual Pipelines: %s')
lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)
for json_file in self.settings['pipeline']['pipeline_files']:
delete_pipeline(app=self.app_name, pipeline_name=json_file)
json_dict = lookup.json(filename=json_file)
json_dict['name'] = json_file
self.post_pipeline(json_dict)
return True
|
# Foremast - Pipeline Tooling
#
# Copyright 2016 Gogo, LLC
#
# 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.
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .create_pipeline import SpinnakerPipeline
class SpinnakerPipelineManual(SpinnakerPipeline):
"""Manual JSON configured Spinnaker Pipelines."""
def create_pipeline(self):
"""Use JSON files to create Pipelines."""
self.log.info('Uploading manual Pipelines: %s')
lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)
for json_file in self.settings['pipeline']['pipeline_files']:
json_dict = lookup.json(filename=json_file)
json_dict['name'] = json_file
self.post_pipeline(json_dict)
return True
|
Fix regular expressions for disp.cc and moptt.tw
|
'use strict';
var selector = document.location.pathname.startsWith('/m/') ? '.fgG0' : '.record';
var elements = document.querySelectorAll(selector);
if (elements.length) {
var line = Array.prototype.filter.call(elements, function (record) {
return record.textContent.indexOf('文章網址') !== -1;
})[0].textContent;
var matched = line.match(/(https*:\/\/[\w\.\/-]+)/);
if (matched) {
window.location.href = matched[1];
}
}
if (window.location.hostname == "webptt.com") {
var search = window.location.search.split("n=");
if (search.length > 1) {
window.location.href = "https://www.ptt.cc/" + search[1];
}
}
if (window.location.hostname == "moptt.tw") {
let regexp = /\/p\/([^\.]+)\.(.+)/;
if (regexp.test(window.location.pathname)) {
window.location.href = window.location.pathname.replace(regexp, "https://www.ptt.cc/bbs/$1/$2.html");
}
}
|
'use strict';
var selector = document.location.pathname.startsWith('/m/') ? '.fgG0' : '.record';
var elements = document.querySelectorAll(selector);
if (elements.length) {
var line = Array.prototype.filter.call(elements, function (record) {
return record.textContent.indexOf('文章網址') !== -1;
})[0].textContent;
var matched = line.match(/(https*:\/\/[\w\.\/]+)/);
if (matched) {
window.location.href = matched[1];
}
}
if (window.location.hostname == "webptt.com") {
var search = window.location.search.split("n=");
if (search.length > 1) {
window.location.href = "https://www.ptt.cc/" + search[1];
}
}
if (window.location.hostname == "moptt.tw") {
let regexp = /\/p\/([^\.]+)\.(.*)/;
if (regexp.test(window.location.pathname)) {
window.location.href = window.location.pathname.replace(regexp, "https://www.ptt.cc/bbs/$1/$2.html");
}
}
|
Allow passing arguments through dont_me to tread_on
|
#!python3
import os
from PIL import Image, ImageDraw, ImageFont
localdir = os.path.dirname(__file__)
BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png"))
LORA_FONT = ImageFont.truetype(
os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120
)
def tread_on(caption, color="black"):
"""Caption the "Don't Tread on Me" snake with `caption`"""
flag = BLANK_FLAG.copy()
draw = ImageDraw.Draw(flag)
text = caption.upper()
font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088)
draw.text(font_pos, text, font=LORA_FONT, fill=color)
return flag
def dont_me(phrase, *args, **kwargs):
"""Caption the "Don't tread on me" flag with "Don't [phrase] me" """
return tread_on("don't {} me".format(phrase), *args, **kwargs)
|
#!python3
import os
from PIL import Image, ImageDraw, ImageFont
localdir = os.path.dirname(__file__)
BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png"))
LORA_FONT = ImageFont.truetype(
os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120
)
def tread_on(caption, color="black"):
"""Caption the "Don't Tread on Me" snake with `caption`"""
flag = BLANK_FLAG.copy()
draw = ImageDraw.Draw(flag)
text = caption.upper()
font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088)
draw.text(font_pos, text, font=LORA_FONT, fill=color)
return flag
def dont_me(phrase):
"""Caption the "Don't tread on me" flag with "Don't [phrase] me" """
return tread_on("don't {} me".format(phrase))
|
Fix typo in Python script
|
def transform_scalars(dataset):
"""Reinterpret a signed integral array type as its unsigned counterpart.
This can be used when the bytes of a data array have been interpreted as a
signed array when it should have been interpreted as an unsigned array."""
from tomviz import utils
import numpy as np
scalars = utils.get_scalars(dataset)
if scalars is None:
raise RuntimeError("No scalars found!")
dtype = scalars.dtype
dtype = dtype.type
typeMap = {
np.int8: np.uint8,
np.int16: np.uint16,
np.int32: np.uint32
}
typeAddend = {
np.int8: 128,
np.int16: 32768,
np.int32: 2147483648
}
if dtype not in typeMap:
raise RuntimeError("Scalars are not int8, int16, or int32")
newType = typeMap[dtype]
addend = typeAddend[dtype]
newScalars = scalars.astype(dtype=newType) + addend
utils.set_scalars(dataset, newScalars)
|
def transform_scalars(dataset):
"""Reinterpret a signed integral array type as its unsigned counterpart.
This can be used when the bytes of a data array have been interpreted as a
signed array when it should have been interpreted as an unsigned array."""
from tomviz import utils
import numpy as np
scalars = utils.get_scalars(dataset)
if scalars is None:
raise RuntimeError("No scalars found!")
dtype = scaldars.dtype
dtype = dtype.type
typeMap = {
np.int8: np.uint8,
np.int16: np.uint16,
np.int32: np.uint32
}
typeAddend = {
np.int8: 128,
np.int16: 32768,
np.int32: 2147483648
}
if dtype not in typeMap:
raise RuntimeError("Scalars are not int8, int16, or int32")
newType = typeMap[dtype]
addend = typeAddend[dtype]
newScalars = scalars.astype(dtype=newType) + addend
utils.set_scalars(dataset, newScalars)
|
Replace finish order requirement with a duration requirement
|
import nose.plugins.attrib
import time as _time
import subprocess
import sys
import redisdl
import unittest
import json
import os.path
from . import util
from . import big_data
@nose.plugins.attrib.attr('slow')
class RaceDeletingKeysTest(unittest.TestCase):
def setUp(self):
import redis
self.r = redis.Redis()
for key in self.r.keys('*'):
self.r.delete(key)
def test_delete_race(self):
bd = big_data.BigData(self.r)
count = bd.determine_key_count()
# data is already inserted
big_data_path = os.path.join(os.path.dirname(__file__), 'big_data.py')
p = subprocess.Popen(
[sys.executable, big_data_path, 'delete', str(count)],
stdout=subprocess.PIPE,
)
_time.sleep(1)
start = _time.time()
dump = redisdl.dumps()
finish = _time.time()
out, err = p.communicate()
delete_start, delete_finish = [int(time) for time in out.split(' ')]
assert delete_start < start
assert finish > start + 5
assert delete_finish > start + 5
|
import nose.plugins.attrib
import time as _time
import subprocess
import sys
import redisdl
import unittest
import json
import os.path
from . import util
from . import big_data
@nose.plugins.attrib.attr('slow')
class RaceDeletingKeysTest(unittest.TestCase):
def setUp(self):
import redis
self.r = redis.Redis()
for key in self.r.keys('*'):
self.r.delete(key)
def test_delete_race(self):
bd = big_data.BigData(self.r)
count = bd.determine_key_count()
# data is already inserted
big_data_path = os.path.join(os.path.dirname(__file__), 'big_data.py')
p = subprocess.Popen(
[sys.executable, big_data_path, 'delete', str(count)],
stdout=subprocess.PIPE,
)
_time.sleep(1)
start = _time.time()
dump = redisdl.dumps()
finish = _time.time()
out, err = p.communicate()
delete_start, delete_finish = [int(time) for time in out.split(' ')]
assert delete_start < start
assert delete_finish > finish
|
Set server.max_request_body_size in cherrypy settings to allow more then 100M uploads.
|
#!/usr/bin/env python
# coding=utf8
# This is an example of how to run dope (or any other WSGI app) in CherryPy.
# Running it will start dope at the document root, and the server on port 80.
#
# Assuming a virtual environment in which cherrypy is installed, this would be
# the way to run it:
#
# $ /path/to/virtualenv/bin/python /path/to/virtualenv/bin/cherryd -i dope_cherry
from dope import app
import cherrypy
# graft to tree root
cherrypy.tree.graft(app)
# configure
cherrypy.config.update({
'server.socket_port': 80,
'server.socket_host': '0.0.0.0',
'server.max_request_body_size': 0, # unlimited
'run_as_user': 'nobody',
'run_as_group': 'nogroup',
})
cherrypy.config.update('dope_cherry.cfg')
# drop priviledges
cherrypy.process.plugins.DropPrivileges(cherrypy.engine, uid = cherrypy.config['run_as_user'], gid = cherrypy.config['run_as_group']).subscribe()
|
#!/usr/bin/env python
# coding=utf8
# This is an example of how to run dope (or any other WSGI app) in CherryPy.
# Running it will start dope at the document root, and the server on port 80.
#
# Assuming a virtual environment in which cherrypy is installed, this would be
# the way to run it:
#
# $ /path/to/virtualenv/bin/python /path/to/virtualenv/bin/cherryd -i dope_cherry
from dope import app
import cherrypy
# graft to tree root
cherrypy.tree.graft(app)
# configure
cherrypy.config.update({
'server.socket_port': 80,
'server.socket_host': '0.0.0.0',
'run_as_user': 'nobody',
'run_as_group': 'nogroup',
})
cherrypy.config.update('dope_cherry.cfg')
# drop priviledges
cherrypy.process.plugins.DropPrivileges(cherrypy.engine, uid = cherrypy.config['run_as_user'], gid = cherrypy.config['run_as_group']).subscribe()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.