text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix return value in write context | <?php
class Zenc_EmailLogger_Block_Render_Html
extends Mage_Core_Block_Abstract
implements Zenc_EmailLogger_Block_Render_Interface
{
public function getContentType()
{
return 'text/html';
}
protected function _toHtml()
{
$data = $this->getValue();
switch (true) {
case !empty($data['body_html']):
return $data['body_html'];
case !empty($data['body_text']):
return $data['body_text'];
default:
return 'Email has no visible content';
}
}
}
| <?php
class Zenc_EmailLogger_Block_Render_Html
extends Mage_Core_Block_Abstract
implements Zenc_EmailLogger_Block_Render_Interface
{
public function getContentType()
{
return 'text/html';
}
protected function _toHtml()
{
$data = $this->getValue();
switch (true) {
case !empty(trim($data['body_html'])):
return $data['body_html'];
case !empty(trim($data['body_text'])):
return $data['body_text'];
default:
return 'Email has no visible content';
}
}
}
|
Fix key length for MySQL compatibility | <?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Validator;
class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot() {
// Fix for MariaDB < 10.2.2 and MySQL < 5.7.7
\Schema::defaultStringLength(191);
Validator::extend('without_spaces', function($attr, $value){
return preg_match('/^\S*$/u', $value);
});
}
/**
* Register any application services.
*
* @return void
*/
public function register() {
if ($this->app->environment() == 'local') {
$this->app->register('Laracasts\Generators\GeneratorsServiceProvider');
}
}
}
| <?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Validator;
class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot() {
Validator::extend('without_spaces', function($attr, $value){
return preg_match('/^\S*$/u', $value);
});
}
/**
* Register any application services.
*
* @return void
*/
public function register() {
if ($this->app->environment() == 'local') {
$this->app->register('Laracasts\Generators\GeneratorsServiceProvider');
}
}
}
|
Update exports loader to Webpack 3 syntax
Closes #67. | import webpack from "webpack";
import path from "path";
export default {
module: {
rules: [
{
test: /\.((png)|(eot)|(woff)|(woff2)|(ttf)|(svg)|(gif))(\?v=\d+\.\d+\.\d+)?$/,
loader: "file-loader?name=/[hash].[ext]"
},
{test: /\.json$/, loader: "json-loader"},
{
loader: "babel-loader",
test: /\.js?$/,
exclude: /node_modules/,
query: {cacheDirectory: true}
}
]
},
plugins: [
new webpack.ProvidePlugin({
"fetch": "imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch"
})
],
context: path.join(__dirname, "src"),
entry: {
app: ["./js/app"]
},
output: {
path: path.join(__dirname, "dist"),
publicPath: "/",
filename: "[name].js"
},
externals: [/^vendor\/.+\.js$/]
};
| import webpack from "webpack";
import path from "path";
export default {
module: {
rules: [
{
test: /\.((png)|(eot)|(woff)|(woff2)|(ttf)|(svg)|(gif))(\?v=\d+\.\d+\.\d+)?$/,
loader: "file-loader?name=/[hash].[ext]"
},
{test: /\.json$/, loader: "json-loader"},
{
loader: "babel-loader",
test: /\.js?$/,
exclude: /node_modules/,
query: {cacheDirectory: true}
}
]
},
plugins: [
new webpack.ProvidePlugin({
"fetch": "imports-loader?this=>global!exports?global.fetch!whatwg-fetch"
})
],
context: path.join(__dirname, "src"),
entry: {
app: ["./js/app"]
},
output: {
path: path.join(__dirname, "dist"),
publicPath: "/",
filename: "[name].js"
},
externals: [/^vendor\/.+\.js$/]
};
|
Fix radio children not appearing | import Inferno from 'inferno';
import Component from 'inferno-component';
import Option from './Option';
import Radio from './Radio';
import Chrome from '../../modules/chrome';
export default class RadioGroup extends Option {
constructor (props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange (val) {
const key = this.props.optkey;
Chrome.setSetting(key, val);
this.setState({ value: val });
}
render () {
return (
<div>
{ this.props.children.map((radio, i) => {
return (
<Radio
key={i}
label={radio.props.label}
tooltip={radio.props.tooltip}
value={radio.props.value}
checked={this.state.value === radio.props.value}
group={this.props.group}
onChange={this.handleChange}>
{radio.props.children}
</Radio>
);
}) }
</div>
);
}
}
| import Inferno from 'inferno';
import Component from 'inferno-component';
import Option from './Option';
import Radio from './Radio';
import Chrome from '../../modules/chrome';
export default class RadioGroup extends Option {
constructor (props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange (val) {
const key = this.props.optkey;
Chrome.setSetting(key, val);
this.setState({ value: val });
}
render () {
return (
<div>
{ this.props.children.map((radio, i) => {
return (
<Radio
key={i}
label={radio.props.label}
tooltip={radio.props.tooltip}
value={radio.props.value}
checked={this.state.value === radio.props.value}
group={this.props.group}
onChange={this.handleChange} />
);
}) }
</div>
);
}
}
|
Add signal for shutdown procs | package com.breakersoft.plow;
public class Signal {
/**
* Exit signal for an aborted dispatch.
*/
public static final int NORMAL = 0;
/**
* Exit signal when a node is shutdown.
*/
public static final int NODE_SHUTDOWN = 86;
/**
* Exit signal for an aborted dispatch.
*/
public static final int ABORTED_TASK = 667;
/**
* Exit signal for an orphaned task.
*/
public static final int ORPANED_TASK = 668;
/**
* Task was manually killed
*/
public static final int MANUAL_KILL = 669;
/**
* Task was manually retried
*/
public static final int MANUAL_RETRY = 670;
/**
* The node went down.
*/
public static final int NODE_DOWN = 671;
}
| package com.breakersoft.plow;
public class Signal {
/**
* Exit signal for an aborted dispatch.
*/
public static final int NORMAL = 0;
/**
* Exit signal for an aborted dispatch.
*/
public static final int ABORTED_TASK = 667;
/**
* Exit signal for an orphaned task.
*/
public static final int ORPANED_TASK = 668;
/**
* Task was manually killed
*/
public static final int MANUAL_KILL = 669;
/**
* Task was manually retried
*/
public static final int MANUAL_RETRY = 670;
/**
* The node went down.
*/
public static final int NODE_DOWN = 671;
}
|
tools: Make Utility.console_log accept Unicode and byte strings as well | from __future__ import print_function
import sys
_COLOR_CODES = {
"white": u'\033[0m',
"red": u'\033[31m',
"green": u'\033[32m',
"orange": u'\033[33m',
"blue": u'\033[34m',
"purple": u'\033[35m',
"W": u'\033[0m',
"R": u'\033[31m',
"G": u'\033[32m',
"O": u'\033[33m',
"B": u'\033[34m',
"P": u'\033[35m'
}
def console_log(data, color="white", end="\n"):
"""
log data to console.
(if not flush console log, Gitlab-CI won't update logs during job execution)
:param data: data content
:param color: color
"""
if color not in _COLOR_CODES:
color = "white"
color_codes = _COLOR_CODES[color]
if type(data) is type(b''):
data = data.decode('utf-8', 'replace')
print(color_codes + data, end=end)
if color not in ["white", "W"]:
# reset color to white for later logs
print(_COLOR_CODES["white"] + u"\r")
sys.stdout.flush()
| from __future__ import print_function
import sys
_COLOR_CODES = {
"white": '\033[0m',
"red": '\033[31m',
"green": '\033[32m',
"orange": '\033[33m',
"blue": '\033[34m',
"purple": '\033[35m',
"W": '\033[0m',
"R": '\033[31m',
"G": '\033[32m',
"O": '\033[33m',
"B": '\033[34m',
"P": '\033[35m'
}
def console_log(data, color="white", end="\n"):
"""
log data to console.
(if not flush console log, Gitlab-CI won't update logs during job execution)
:param data: data content
:param color: color
"""
if color not in _COLOR_CODES:
color = "white"
color_codes = _COLOR_CODES[color]
print(color_codes + data, end=end)
if color not in ["white", "W"]:
# reset color to white for later logs
print(_COLOR_CODES["white"] + "\r")
sys.stdout.flush()
|
Exclude Slideshow from javascript concatenation. | //= require_directory ./AbstractDocument
//= require_directory ./BrowserWidget
//= require_directory ./BusyWidget
//= require_directory ./ComponentStateManager
//= require_directory ./Desktop
//= require_directory ./DiagramWidget
//= require_directory ./DocumentEditor
//= require_directory ./FundamentalTypes
//= require_directory ./HierarchicalMenuWidget
//= require_directory ./HtmlDocument
//= require_directory ./Internationalization
//= require_directory ./jStorage
//= require_directory ./LanguageSelectorWidget
//= require_directory ./MochaUI
//= require_directory ./MooEditable
//= require_directory ./NewsReaderWidget
//= require_directory ./PartyEventWidget
//= require_directory ./PhotoGaleryWidget
//= require_directory ./ResourceManager
//= require_directory ./ScrollingBehaviour
//= require_directory ./Singleton
//= require_directory ./SkinSelectorWidget
//= require_directory ./SmartDocument
//= require_directory ./SplashForm
//= require_directory ./TabWidget
//= require_directory ./TextAreaEditor
//= require_directory ./ToolBarWidget
//= require_directory ./TreeWidget
//= require_directory ./VideoPlayerWidget
//= require_directory ./WebUIConfiguration
//= require_directory ./WebUIController
//= require_directory ./WebUILogger
//= require_directory ./WebUIMessageBus
| //= require_directory ./AbstractDocument
//= require_directory ./BrowserWidget
//= require_directory ./BusyWidget
//= require_directory ./ComponentStateManager
//= require_directory ./Desktop
//= require_directory ./DiagramWidget
//= require_directory ./DocumentEditor
//= require_directory ./FundamentalTypes
//= require_directory ./HierarchicalMenuWidget
//= require_directory ./HtmlDocument
//= require_directory ./Internationalization
//= require_directory ./jStorage
//= require_directory ./LanguageSelectorWidget
//= require_directory ./MochaUI
//= require_directory ./MooEditable
//= require_directory ./NewsReaderWidget
//= require_directory ./PartyEventWidget
//= require_directory ./PhotoGaleryWidget
//= require_directory ./ResourceManager
//= require_directory ./ScrollingBehaviour
//= require_directory ./Singleton
//= require_directory ./SkinSelectorWidget
//= require_directory ./SlideShow
//= require_directory ./SmartDocument
//= require_directory ./SplashForm
//= require_directory ./TabWidget
//= require_directory ./TextAreaEditor
//= require_directory ./ToolBarWidget
//= require_directory ./TreeWidget
//= require_directory ./VideoPlayerWidget
//= require_directory ./WebUIConfiguration
//= require_directory ./WebUIController
//= require_directory ./WebUILogger
//= require_directory ./WebUIMessageBus
|
Update api url for recent 100 instead of default 30 | import requests
import collections
API_URL = 'https://api.github.com/users/{}/repos?per_page=100'
def main(user):
return parse(request(user))
def request(user):
return requests.get(url=API_URL.format(user))
def parse(response):
repos = response.json()
data = []
if repos is None:
return None
for repo in repos:
if 'name' in repo and not repo['fork']:
data.append(
collections.OrderedDict([('name', repo['name']),
('desc', repo['description']),
('lang', repo['language']),
('stars', repo['stargazers_count'])]))
return data
if __name__ == '__main__':
import pprint
u = 'kshvmdn'
pprint.pprint(main(u))
| import requests
import collections
API_URL = 'https://api.github.com/users/{}/repos'
def main(user):
return parse(request(user))
def request(user):
return requests.get(url=API_URL.format(user))
def parse(response):
repos = response.json()
data = []
if repos is None:
return None
for repo in repos:
if 'name' in repo and not repo['fork']:
data.append(
collections.OrderedDict([('name', repo['name']),
('desc', repo['description']),
('lang', repo['language']),
('stars', repo['stargazers_count'])]))
return data
if __name__ == '__main__':
import pprint
u = 'kshvmdn'
pprint.pprint(main(u))
|
Embed video in welcome page | import React, { Component } from 'react';
import Paper from 'material-ui/Paper';
import './index.css'
const style = {
paper: {
display: 'flex',
float: 'right',
margin: '20px 32px 16px 0',
height: '80%'
}
};
export default class Welcome extends Component {
render = () => {
return (
<Paper style={style.paper}>
<div style={{margin: '20px'}} className={'mdb-welcome-text'}>
<p>
Materials Data Bank (MDB) archives the information about the 3D atomic structures (3D atomic coordinates and chemical species)
determined by atomic electron tomography (AET).
</p>
<p>
This databank is designed to provide useful resources for research and education in studying the true 3D atomic structure and
associated materials properties arising from non-crystalline structures such as defects, dislocations, strain, complex grain structure,
local chemical ordering, and phase boundaries.
</p>
<div style={{ 'text-align': 'center'}}>
<iframe src="https://player.vimeo.com/video/202250016" width="640" height="480" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
</div>
</Paper>
);
}
}
| import React, { Component } from 'react';
import Paper from 'material-ui/Paper';
import './index.css'
const style = {
paper: {
display: 'flex',
float: 'right',
margin: '20px 32px 16px 0',
height: '80%'
}
};
export default class Welcome extends Component {
render = () => {
return (
<Paper style={style.paper}>
<div style={{margin: '20px'}} className={'mdb-welcome-text'}>
<p>
Materials Data Bank (MDB) archives the information about the 3D atomic structures (3D atomic coordinates and chemical species)
determined by atomic electron tomography (AET).
</p>
<p>
This databank is designed to provide useful resources for research and education in studying the true 3D atomic structure and
associated materials properties arising from non-crystalline structures such as defects, dislocations, strain, complex grain structure,
local chemical ordering, and phase boundaries.
</p>
</div>
</Paper>
);
}
}
|
Switch from fsnotify to fsevents | package main
import (
"fmt"
"github.com/sdegutis/go.fsevents"
"log"
"os"
"os/exec"
)
func main() {
if len(os.Args) < 3 {
fmt.Fprintln(os.Stderr, "Usage: aroc DIRECTORY COMMAND [ARGS…]")
os.Exit(1)
}
ch := fsevents.WatchPaths([]string{os.Args[1]})
var cmd *exec.Cmd
go func() {
for _ = range ch {
log.Println("Changes in directory, restarting")
cmd.Process.Signal(os.Interrupt)
}
}()
for {
cmd = exec.Command(os.Args[2])
cmd.Args = os.Args[2:]
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
err := cmd.Run()
if err != nil {
if err, ok := err.(*exec.ExitError); !ok {
log.Fatal(err)
}
}
}
}
| package main
import (
"fmt"
"github.com/howeyc/fsnotify"
"log"
"os"
"os/exec"
)
func main() {
if len(os.Args) < 3 {
fmt.Fprintln(os.Stderr, "Usage: aroc DIRECTORY COMMAND [ARGS…]")
os.Exit(1)
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
err = watcher.Watch(os.Args[1])
if err != nil {
log.Fatal(err)
}
var cmd *exec.Cmd
go func() {
for {
select {
case _ = <-watcher.Event:
log.Println("Changes in directory, restarting")
cmd.Process.Signal(os.Interrupt)
case err := <-watcher.Error:
log.Fatal("error:", err)
}
}
}()
for {
cmd = exec.Command(os.Args[2])
cmd.Args = os.Args[2:]
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
err := cmd.Run()
if err != nil {
if err, ok := err.(*exec.ExitError); !ok {
log.Fatal(err)
}
}
}
}
|
Use Case for persona b (pet seeker) | <!DOCTYPE html>
<head>
<title>Conceptual-Model</title>
</head>
<body>
<main>
<h2>Entities and Attributes</h2>
<p><strong>Profile</strong></p>
<ul>
<li>profileId</li>
<li>profileAtHandle</li>
<li>profileEmail</li>
<li>profilePhone</li>
</ul>
<p><strong>Pet Profile</strong></p>
<ul>
<li>petId</li>
<li>petProfileId</li>
<li>petDescription</li>
<li>petType</li>
<li>petBreed</li>
<li>PetLocation</li>
</ul>
<p><strong>images</strong></p>
<ul>
<li>petProfileImage</li>
</ul>
<p><strong>Relations</strong></p>
<ul>
<li>One <strong>Profile </strong>favorites products - (m to n)</li>
</ul>
<br>
</main>
</body> | <!DOCTYPE html>
<head>
<title>Conceptual-Model</title>
</head>
<body>
<main>
<h2>Entities and Attributes</h2>
<p><strong>Profile</strong></p>
<ul>
<li>profileId</li>
<li>profileAtHandle</li>
<li>profileEmail</li>
<li>profilePhone</li>
</ul>
<p><strong>Pet Profile</strong></p>
<ul>
<li>petId</li>
<li>petProfileId</li>
<li>petDescription</li>
<li>petType</li>
<li>petBreed</li>
<li>PetLocation</li>
</ul>
<p><strong>images</strong></p>
<ul>
<li>petProfileImage</li>
</ul>
<p><strong>Relations</strong></p>
<ul>
<li>One <strong>Profile </strong>favorites products - (m to n)</li>
</ul>
<br>
<img src="https://bootcamp-coders.cnm.edu/~mharrison13/data-design/public_html/images/erd-data-design.svg">
</main>
</body> |
Fix naming error Astronomy._behaviors to Behaviors | var prototype = Astronomy.Schema.prototype;
prototype.addBehavior = function(behaviorName, behaviorOptions) {
if (!_.isString(behaviorName)) {
return;
}
behaviorOptions = behaviorOptions || {};
// Check if bahavior with given name exists.
if (!_.has(Behaviors, behaviorName)) {
throw new Error('Behavior with the name `' + behaviorName +
'` is not defined');
}
var behaviorDefinition = Behaviors[behaviorName];
this._behaviors[behaviorName] = behaviorOptions;
if (behaviorDefinition.events) {
this.addEvents(behaviorDefinition.events);
}
if (behaviorDefinition.fields) {
this.addFields(behaviorDefinition.fields);
}
if (behaviorDefinition.methods) {
this.addMethods(behaviorDefinition.methods);
}
if (behaviorDefinition.validators) {
this.addValidators(behaviorDefinition.validators);
}
};
prototype.addBehaviors = function(behaviors) {
if (_.isArray(behaviors)) {
_.each(behaviors, function(behaviorName) {
this.addBehavior(behaviorName, {});
}, this);
} else if (_.isObject(behaviors)) {
_.each(behaviors, function(behavior, behaviorName) {
this.addBehavior(behaviorName, behavior);
}, this);
}
};
| var prototype = Astronomy.Schema.prototype;
prototype.addBehavior = function(behaviorName, behaviorOptions) {
if (!_.isString(behaviorName)) {
return;
}
behaviorOptions = behaviorOptions || {};
// Check if bahavior with given name exists.
if (!_.has(Astronomy._behaviors, behaviorName)) {
throw new Error('Behavior with the name `' + behaviorName +
'` is not defined');
}
var behaviorDefinition = Astronomy._behaviors[behaviorName];
this._behaviors[behaviorName] = behaviorOptions;
if (behaviorDefinition.events) {
this.addEvents(behaviorDefinition.events);
}
if (behaviorDefinition.fields) {
this.addFields(behaviorDefinition.fields);
}
if (behaviorDefinition.methods) {
this.addMethods(behaviorDefinition.methods);
}
if (behaviorDefinition.validators) {
this.addValidators(behaviorDefinition.validators);
}
};
prototype.addBehaviors = function(behaviors) {
if (_.isArray(behaviors)) {
_.each(behaviors, function(behaviorName) {
this.addBehavior(behaviorName, {});
}, this);
} else if (_.isObject(behaviors)) {
_.each(behaviors, function(behavior, behaviorName) {
this.addBehavior(behaviorName, behavior);
}, this);
}
};
|
Use functional form of 'use strict'; | (function() {
'use strict';
chrome.runtime.onInstalled.addListener(function () {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function () {
chrome.declarativeContent.onPageChanged.addRules([{
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: {
hostEquals: 'arxiv.org',
pathPrefix: '/pdf'
}
})
],
actions: [ new chrome.declarativeContent.ShowPageAction() ]
}]);
});
});
chrome.pageAction.onClicked.addListener(function (tab) {
chrome.tabs.sendMessage(tab.id, "update-page-title.");
});
})();
| 'use strict';
chrome.runtime.onInstalled.addListener(function () {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function () {
chrome.declarativeContent.onPageChanged.addRules([{
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: {
hostEquals: 'arxiv.org',
pathPrefix: '/pdf'
}
})
],
actions: [ new chrome.declarativeContent.ShowPageAction() ]
}]);
});
});
chrome.pageAction.onClicked.addListener(function (tab) {
chrome.tabs.sendMessage(tab.id, "update-page-title.");
});
|
Change the value to return to stop the loop | <?php
declare(strict_types=1);
/**
* Return a value based on a condition.
*/
function condition (bool $test, callable $truthy, callable $falsy = null)
{
$falsy = $falsy ?? fn () => null;
return call_user_func($test ? $truthy : $falsy);
}
/**
* Loop over an iterable and yield new values.
*/
function loop (iterable $iterable, callable $callable): Generator
{
foreach ($iterable as $key => $item) {
$generator = ensure_generator(
call_user_func($callable, $key, $item)
);
foreach($generator as $gen_key => $gen_item) {
yield $gen_key => $gen_item;
}
if ($generator->getReturn() === false) {
break;
}
}
}
/**
* Execute a callback and catch exceptions.
*/
function rescue (callable $callable, array $exceptions)
{
try {
return call_user_func($callable);
} catch (Exception $e) {
foreach ($exceptions as $type => $e_callable) {
if (is_a($e, $type, true)) {
return call_user_func($e_callable);
}
}
throw $e;
}
}
| <?php
declare(strict_types=1);
/**
* Return a value based on a condition.
*/
function condition (bool $test, callable $truthy, callable $falsy = null)
{
$falsy = $falsy ?? fn () => null;
return call_user_func($test ? $truthy : $falsy);
}
/**
* Loop over an iterable and yield new values.
*/
function loop (iterable $iterable, callable $callable): Generator
{
foreach ($iterable as $key => $item) {
$generator = ensure_generator(
call_user_func($callable, $key, $item)
);
foreach($generator as $gen_key => $gen_item) {
yield $gen_key => $gen_item;
}
if ($generator->getReturn() === true) {
break;
}
}
}
/**
* Execute a callback and catch exceptions.
*/
function rescue (callable $callable, array $exceptions)
{
try {
return call_user_func($callable);
} catch (Exception $e) {
foreach ($exceptions as $type => $e_callable) {
if (is_a($e, $type, true)) {
return call_user_func($e_callable);
}
}
throw $e;
}
}
|
Add test for order sorting. | "use strict";
var fs = require("fs"),
assert = require("chai").assert,
lib = require("../tasks/lib/index");
var replacements = lib({
excludes: [],
replacements: []
});
function transform(filepath) {
return [fs.readFileSync(filepath, "utf8")]
.concat(replacements)
.reduce(function(source, item) {
return source.replace(item.pattern, item.replacement);
});
}
it("replacements in proper order", function () {
var curr = 0;
for (var i = 0; i < replacements.length; i++) {
assert.isTrue(curr <= replacements[i].order);
curr = replacements[i].order;
}
});
describe("test fixtures to expected", function () {
fs.readdirSync("test/fixtures/").forEach(file => {
it("should properly convert " + file, function() {
var expectedFile = "test/expected/" + file.replace(".less", ".scss");
assert.isTrue(fs.existsSync(expectedFile, "utf8"));
assert.equal(
fs.readFileSync(expectedFile, "utf8"),
transform("test/fixtures/" + file)
);
});
});
});
| "use strict";
const fs = require("fs"),
assert = require("chai").assert,
lib = require("../tasks/lib/index");
const replacements = lib({
excludes: [],
replacements: []
});
function transform(filepath) {
return [fs.readFileSync(filepath, "utf8")]
.concat(replacements)
.reduce(function(source, item) {
return source.replace(item.pattern, item.replacement);
});
}
describe("Fixtures to Expected", () => {
fs.readdirSync("test/fixtures/").forEach(file => {
it("should properly convert " + file, function() {
const expectedFile = "test/expected/" + file.replace(".less", ".scss");
assert.isTrue(fs.existsSync(expectedFile, "utf8"));
assert.equal(
fs.readFileSync(expectedFile, "utf8"),
transform("test/fixtures/" + file)
);
});
});
});
|
Call _render before _step to support BipedalWalker | def make_rendered(env, *render_args, **render_kwargs):
base_step = env._step
def _step(action):
ret = base_step(action)
env.render(*render_args, **render_kwargs)
return ret
env._step = _step
def make_timestep_limited(env, timestep_limit):
t = 1
old__step = env._step
old__reset = env._reset
def _step(action):
nonlocal t
observation, reward, done, info = old__step(action)
if t >= timestep_limit:
done = True
t += 1
return observation, reward, done, info
def _reset():
nonlocal t
t = 1
return old__reset()
env._step = _step
env._reset = _reset
def make_action_filtered(env, action_filter):
old_step = env.step
def step(action):
return old_step(action_filter(action))
env.step = step
def make_reward_filtered(env, reward_filter):
old__step = env._step
def _step(action):
observation, reward, done, info = old__step(action)
reward = reward_filter(reward)
return observation, reward, done, info
env._step = _step
| def make_rendered(env, *render_args, **render_kwargs):
base_step = env._step
def _step(action):
env.render(*render_args, **render_kwargs)
return base_step(action)
env._step = _step
def make_timestep_limited(env, timestep_limit):
t = 1
old__step = env._step
old__reset = env._reset
def _step(action):
nonlocal t
observation, reward, done, info = old__step(action)
if t >= timestep_limit:
done = True
t += 1
return observation, reward, done, info
def _reset():
nonlocal t
t = 1
return old__reset()
env._step = _step
env._reset = _reset
def make_action_filtered(env, action_filter):
old_step = env.step
def step(action):
return old_step(action_filter(action))
env.step = step
def make_reward_filtered(env, reward_filter):
old__step = env._step
def _step(action):
observation, reward, done, info = old__step(action)
reward = reward_filter(reward)
return observation, reward, done, info
env._step = _step
|
Allow calling `scrollVertical` with only the target
All the options are optional, but if an empty object is not passed
the `scrollVertical` method blows up with cannot reat offset of undefined.
Now we can scrollVertical('#id') instead of having scrollVertical('#id',{}); | import Em from 'ember';
const DURATION = 750;
const EASING = 'swing';
const OFFSET = 0;
export default Em.Service.extend({
// ----- Static properties -----
duration: DURATION,
easing: EASING,
offset: OFFSET,
// ----- Computed properties -----
scrollable: Em.computed(function() {
return Em.$('html, body');
}),
// ----- Methods -----
getJQueryElement (target) {
const jQueryElement = Em.$(target);
if (!jQueryElement) {
Em.Logger.warn("element couldn't be found:", target);
return;
}
return jQueryElement;
},
getVerticalCoord (target, offset = 0) {
const jQueryElement = this.getJQueryElement(target);
return jQueryElement.offset().top + offset;
},
scrollVertical (target, opts = {}) {
this.get('scrollable').animate({
scrollTop: this.getVerticalCoord(target, opts.offset)
},
opts.duration || this.get('duration'),
opts.easing || this.get('easing'),
opts.complete
);
}
});
| import Em from 'ember';
const DURATION = 750;
const EASING = 'swing';
const OFFSET = 0;
export default Em.Service.extend({
// ----- Static properties -----
duration: DURATION,
easing: EASING,
offset: OFFSET,
// ----- Computed properties -----
scrollable: Em.computed(function() {
return Em.$('html, body');
}),
// ----- Methods -----
getJQueryElement (target) {
const jQueryElement = Em.$(target);
if (!jQueryElement) {
Em.Logger.warn("element couldn't be found:", target);
return;
}
return jQueryElement;
},
getVerticalCoord (target, offset = 0) {
const jQueryElement = this.getJQueryElement(target);
return jQueryElement.offset().top + offset;
},
scrollVertical (target, opts) {
this.get('scrollable').animate({
scrollTop: this.getVerticalCoord(target, opts.offset)
},
opts.duration || this.get('duration'),
opts.easing || this.get('easing'),
opts.complete
);
}
});
|
Use a named function instead of anon | 'use strict';
var EventEmitter = require('events').EventEmitter;
var Promise = require('bluebird');
function emitThen (event) {
var args = Array.prototype.slice.call(arguments, 1);
/* jshint validthis:true */
return Promise
.bind(this)
.return(this)
.call('listeners', event)
.map(function (listener) {
var a1 = args[0], a2 = args[1];
switch (args.length) {
case 0: return listener.call(this);
case 1: return listener.call(this, a1)
case 2: return listener.call(this, a1, a2);
default: return listener.apply(this, args);
}
})
.return(null);
}
emitThen.register = function () {
EventEmitter.prototype.emitThen = emitThen;
};
module.exports = emitThen; | 'use strict';
var EventEmitter = require('events').EventEmitter;
var Promise = require('bluebird');
var emitThen = function (event) {
var args = Array.prototype.slice.call(arguments, 1);
return Promise
.bind(this)
.return(this)
.call('listeners', event)
.map(function (listener) {
var a1 = args[0], a2 = args[1];
switch (args.length) {
case 0: return listener.call(this);
case 1: return listener.call(this, a1)
case 2: return listener.call(this, a1, a2);
default: return listener.apply(this, args);
}
})
.return(null);
};
emitThen.register = function () {
EventEmitter.prototype.emitThen = emitThen;
};
module.exports = emitThen; |
Add gulp command for running server | var browserify = require('browserify');
var gulp = require('gulp');
var glob = require('glob');
var reactify = require('reactify');
var source = require('vinyl-source-stream');
var shell = require('gulp-shell');
/*
gulp browserify:
Bundles all .js files in the /js/ directory into one file in /build/bundle.js
that will be imported onto all pages
*/
gulp.task('browserify', function() {
var files = glob.sync('./js/**/*.js');
var b = browserify();
for (var i = 0; i < files.length; i++) {
var matches = /(\w+)\.js$/.exec(files[i]);
b.require(files[i], {expose: matches[1]});
}
b.require('xhpjs');
return b
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./build/'));
});
gulp.task('install-php', shell.task([
'hhvm composer.phar install'
]));
gulp.task('autoload', shell.task([
'hhvm composer.phar dump-autoload'
]));
gulp.task('serve', shell.task([
'hhvm -m server -p 8080'
]));
gulp.task('default', ['install-php','browserify','serve']);
| var browserify = require('browserify');
var gulp = require('gulp');
var glob = require('glob');
var reactify = require('reactify');
var source = require('vinyl-source-stream');
var shell = require('gulp-shell');
/*
gulp browserify:
Bundles all .js files in the /js/ directory into one file in /build/bundle.js
that will be imported onto all pages
*/
gulp.task('browserify', function() {
var files = glob.sync('./js/**/*.js');
var b = browserify();
for (var i = 0; i < files.length; i++) {
var matches = /(\w+)\.js$/.exec(files[i]);
b.require(files[i], {expose: matches[1]});
}
b.require('xhpjs');
return b
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./build/'));
});
gulp.task('install-php', shell.task([
'hhvm composer.phar install'
]));
gulp.task('autoload', shell.task([
'hhvm composer.phar dump-autoload'
]));
gulp.task('default', ['install-php','browserify']);
|
Add util to parse response from GitHub access token request | /**
* Create a copy of an object, omitting provided keys.
* @param {Object} obj Object to copy
* @param {Array} arr Keys to omit
* @returns {Object}
*/
export const omit = (obj, arr) => Object.keys(obj).reduce((res, key) => {
if (arr.indexOf(key) === -1) {
res[key] = obj[key]
}
return res
}, {})
/**
* Get key value from url query strings
* @param {string} key Key to get value from
* @returns {string}
*/
export const getQueryStringValue = (key) => {
return decodeURIComponent(window.location.search.replace(new RegExp('^(?:.*[&\\?]' + encodeURIComponent(key).replace(/[.+*]/g, '\\$&') + '(?:\\=([^&]*))?)?.*$', 'i'), '$1'))
}
/**
* Get key value from location hash
* @param {string} key Key to get value from
* @returns {string|null}
*/
export const getHashValue = (key) => {
const matches = window.location.hash.match(new RegExp(`${key}=([^&]*)`))
return matches ? matches[1] : null
}
export const responseTextToObject = (text, key) => {
const keyValuePairs = text.split('&')
if (!keyValuePairs || keyValuePairs.length === 0) {
return {}
}
return keyValuePairs.reduce((result, pair) => {
const [key, value] = pair.split('=')
result[key] = decodeURIComponent(value)
return result
}, {})
}
| /**
* Create a copy of an object, omitting provided keys.
* @param {Object} obj Object to copy
* @param {Array} arr Keys to omit
* @returns {Object}
*/
export const omit = (obj, arr) => Object.keys(obj).reduce((res, key) => {
if (arr.indexOf(key) === -1) {
res[key] = obj[key]
}
return res
}, {})
export const getQueryStringValue = (key) => {
return decodeURIComponent(window.location.search.replace(new RegExp('^(?:.*[&\\?]' + encodeURIComponent(key).replace(/[.+*]/g, '\\$&') + '(?:\\=([^&]*))?)?.*$', 'i'), '$1'))
}
/**
* Get key value from location hash
* @param {string} key Key to get value from
* @returns {string|null}
*/
export const getHashValue = (key) => {
const matches = window.location.hash.match(new RegExp(`${key}=([^&]*)`))
return matches ? matches[1] : null
}
|
Fix the Main Header Text font size according to the size of the screen. | (function() {
"use strict"; // Start of use strict
// Offset for Main Navigation
$('#mainNav').affix({
offset: {
top: 900
}
})
// jQuery for page scrolling feature - requires jQuery Easing plugin
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 50)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top',
offset: 51
})
// Fit Text Plugin for Main Header
$("h1").fitText(
1.2, {
minFontSize: '30px',
maxFontSize: '60px'
}
);
})(); // End of use strict
| (function() {
"use strict"; // Start of use strict
// Offset for Main Navigation
$('#mainNav').affix({
offset: {
top: 900
}
})
// jQuery for page scrolling feature - requires jQuery Easing plugin
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 50)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top',
offset: 51
})
})(); // End of use strict
|
Add ACTION_NONE to the definitions | <?php
define( 'DIRECTION_NONE', 0 );
define( 'DIRECTION_NORTH', 1 );
define( 'DIRECTION_EAST', 2 );
define( 'DIRECTION_SOUTH', 3 );
define( 'DIRECTION_WEST', 4 );
define( 'ACTION_NONE', 0 );
define( 'ACTION_MOVE', 1 );
define( 'ACTION_ATACK', 2 );
class Intent {
public $action;
public $direction;
public function __construct( $action, $direction ) {
$this->direction = array(
'DIRECTION_NONE' => DIRECTION_NONE,
'DIRECTION_NORTH' => DIRECTION_NORTH,
'DIRECTION_EAST' => DIRECTION_EAST,
'DIRECTION_SOUTH' => DIRECTION_SOUTH,
'DIRECTION_WEST' => DIRECTION_WEST
)[ $direction ];
$this->action = array(
'ACTION_NONE' => ACTION_NONE,
'ACTION_MOVE' => ACTION_ATACK,
'ACTION_ATACK' => ACTION_MOVE
)[ $action ];
}
}
?>
| <?php
define( 'DIRECTION_NONE', 0 );
define( 'DIRECTION_NORTH', 1 );
define( 'DIRECTION_EAST', 2 );
define( 'DIRECTION_SOUTH', 3 );
define( 'DIRECTION_WEST', 4 );
define( 'ACTION_ATACK', 0 );
define( 'ACTION_MOVE', 1 );
class Intent {
public $action;
public $direction;
public function __construct( $action, $direction ) {
$this->direction = array(
'DIRECTION_NONE' => DIRECTION_NONE,
'DIRECTION_NORTH' => DIRECTION_NORTH,
'DIRECTION_EAST' => DIRECTION_EAST,
'DIRECTION_SOUTH' => DIRECTION_SOUTH,
'DIRECTION_WEST' => DIRECTION_WEST
)[ $direction ];
$this->action = array(
'ACTION_ATACK' => ACTION_ATACK,
'ACTION_MOVE' => ACTION_MOVE
)[ $action ];
}
}
?>
|
Refactor internal use of constants | 'use strict';
module.exports = visit;
var is = require('unist-util-is');
var CONTINUE = true;
var SKIP = 'skip';
var EXIT = false;
visit.CONTINUE = CONTINUE;
visit.SKIP = SKIP;
visit.EXIT = EXIT;
function visit(tree, test, visitor, reverse) {
if (typeof test === 'function' && typeof visitor !== 'function') {
reverse = visitor;
visitor = test;
test = null;
}
one(tree);
/* Visit a single node. */
function one(node, index, parent) {
var result;
index = index || (parent ? 0 : null);
if (!test || node.type === test || is(test, node, index, parent || null)) {
result = visitor(node, index, parent || null);
}
if (result === EXIT) {
return result;
}
if (node.children && result !== SKIP) {
return all(node.children, node);
}
return CONTINUE;
}
/* Visit children in `parent`. */
function all(children, parent) {
var step = reverse ? -1 : 1;
var max = children.length;
var min = -1;
var index = (reverse ? max : min) + step;
var child;
var result;
while (index > min && index < max) {
child = children[index];
result = child && one(child, index, parent);
if (result === EXIT) {
return result;
}
index += step;
}
return CONTINUE;
}
}
| 'use strict';
/* Expose. */
module.exports = visit;
visit.CONTINUE = true;
visit.SKIP = 'skip';
visit.EXIT = false;
var is = require('unist-util-is');
/* Visit. */
function visit(tree, test, visitor, reverse) {
if (typeof test === 'function' && typeof visitor !== 'function') {
reverse = visitor;
visitor = test;
test = null;
}
one(tree);
/* Visit a single node. */
function one(node, index, parent) {
var result;
index = index || (parent ? 0 : null);
if (!test || node.type === test || is(test, node, index, parent || null)) {
result = visitor(node, index, parent || null);
}
if (result === visit.EXIT) {
return result;
}
if (node.children && result !== visit.SKIP) {
return all(node.children, node);
}
return visit.CONTINUE;
}
/* Visit children in `parent`. */
function all(children, parent) {
var step = reverse ? -1 : 1;
var max = children.length;
var min = -1;
var index = (reverse ? max : min) + step;
var child;
var result;
while (index > min && index < max) {
child = children[index];
result = child && one(child, index, parent);
if (result === visit.EXIT) {
return result;
}
index += step;
}
return visit.CONTINUE;
}
}
|
Add @DoNotInstrument to Opus extension test
PiperOrigin-RevId: 370740311 | /*
* Copyright (C) 2019 The Android Open Source Project
*
* 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.android.exoplayer2.ext.opus;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.testutil.DefaultRenderersFactoryAsserts;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.internal.DoNotInstrument;
/** Unit test for {@link DefaultRenderersFactoryTest} with {@link LibopusAudioRenderer}. */
@RunWith(AndroidJUnit4.class)
@DoNotInstrument
public final class DefaultRenderersFactoryTest {
@Test
public void createRenderers_instantiatesOpusRenderer() {
DefaultRenderersFactoryAsserts.assertExtensionRendererCreated(
LibopusAudioRenderer.class, C.TRACK_TYPE_AUDIO);
}
}
| /*
* Copyright (C) 2019 The Android Open Source Project
*
* 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.android.exoplayer2.ext.opus;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.testutil.DefaultRenderersFactoryAsserts;
import org.junit.Test;
import org.junit.runner.RunWith;
/** Unit test for {@link DefaultRenderersFactoryTest} with {@link LibopusAudioRenderer}. */
@RunWith(AndroidJUnit4.class)
public final class DefaultRenderersFactoryTest {
@Test
public void createRenderers_instantiatesOpusRenderer() {
DefaultRenderersFactoryAsserts.assertExtensionRendererCreated(
LibopusAudioRenderer.class, C.TRACK_TYPE_AUDIO);
}
}
|
Remove unused link to cookie.js
update SVN external
git-svn-id: d66344a971a0a943c9b1d460f97ab888aaee4784@27864 ee427ae8-e902-0410-961c-c3ed070cd9f9 | <?php
function get_nested_set_manager($model, $field, $root = 0){
sfContext::getInstance()->getResponse()->addStylesheet('/sfJqueryTreeDoctrineManagerPlugin/jsTree/themes/default/style.css');
sfContext::getInstance()->getResponse()->addStylesheet('/sfJqueryTreeDoctrineManagerPlugin/css/screen.css');
sfContext::getInstance()->getResponse()->addJavascript('/sfJqueryTreeDoctrineManagerPlugin/jsTree/lib/jquery.js');
sfContext::getInstance()->getResponse()->addJavascript('/sfJqueryTreeDoctrineManagerPlugin/jsTree/jquery.tree.min.js');
sfContext::getInstance()->getResponse()->addJavascript('/sfJqueryTreeDoctrineManagerPlugin/jsTree/plugins/jquery.tree.cookie.js');
return get_component('sfJqueryTreeDoctrineManager', 'manager', array('model' => $model, 'field' => $field, 'root' => $root));
} | <?php
function get_nested_set_manager($model, $field, $root = 0){
sfContext::getInstance()->getResponse()->addStylesheet('/sfJqueryTreeDoctrineManagerPlugin/jsTree/themes/default/style.css');
sfContext::getInstance()->getResponse()->addStylesheet('/sfJqueryTreeDoctrineManagerPlugin/css/screen.css');
sfContext::getInstance()->getResponse()->addJavascript('/sfJqueryTreeDoctrineManagerPlugin/jsTree/lib/jquery.js');
sfContext::getInstance()->getResponse()->addJavascript('/sfJqueryTreeDoctrineManagerPlugin/jsTree/lib/jquery.cookie.js');
sfContext::getInstance()->getResponse()->addJavascript('/sfJqueryTreeDoctrineManagerPlugin/jsTree/jquery.tree.min.js');
sfContext::getInstance()->getResponse()->addJavascript('/sfJqueryTreeDoctrineManagerPlugin/jsTree/plugins/jquery.tree.cookie.js');
return get_component('sfJqueryTreeDoctrineManager', 'manager', array('model' => $model, 'field' => $field, 'root' => $root));
} |
Return the number of ms, not seconds. | # File: badgeeventreminder.py
# Version: 1
# Description: Easter egg
# License: MIT
# Authors: Renze Nicolai <renze@rnplus.nl>
import virtualtimers, time, appglue, badge
# Tue Aug 8 13:30:00 2017 (CEST)
whenToTrigger = 1502191800 - 600
def ber_task():
global whenToTrigger
now = time.time()
if now>=whenToTrigger:
badge.nvs_set_u8('badge','evrt',1)
print("BADGE EVENT REMINDER ACTIVATED")
appglue.start_app("badge_event_reminder")
idleFor = whenToTrigger - now
if idleFor<0:
idleFor = 0
return idleFor * 1000
def enable():
if badge.nvs_get_u8('badge','evrt',0)==0:
virtualtimers.new(1, ber_task)
def disable():
virtualtimers.delete(ber_task)
| # File: badgeeventreminder.py
# Version: 1
# Description: Easter egg
# License: MIT
# Authors: Renze Nicolai <renze@rnplus.nl>
import virtualtimers, time, appglue, badge
# Tue Aug 8 13:30:00 2017 (CEST)
whenToTrigger = 1502191800 - 600
def ber_task():
global whenToTrigger
now = time.time()
if now>=whenToTrigger:
badge.nvs_set_u8('badge','evrt',1)
print("BADGE EVENT REMINDER ACTIVATED")
appglue.start_app("badge_event_reminder")
idleFor = whenToTrigger - now
if idleFor<0:
idleFor = 0
return idleFor
def enable():
if badge.nvs_get_u8('badge','evrt',0)==0:
virtualtimers.new(1, ber_task)
def disable():
virtualtimers.delete(ber_task)
|
Add `rel="noopener noreferrer"` to external links on GDPR banner
See https://www.jitbit.com/alexblog/256-targetblank---the-most-underestimated-vulnerability-ever/
Thanks @ketan | (function ($, dc) {
"use strict";
$(function gdprBanner() {
if (!dc.hasItem("gdpr-accept")) {
var gdpr = $("<div class='gdpr-cookie-banner'>").on("click", ".gdpr-close", function(e) {
dc.setItem("gdpr-accept", "yes");
$(document.body).removeClass("with-gdpr");
gdpr.remove();
}).append("<i class='gdpr-close fa fa-close'/>").
append("<p>Our site uses <a href='https://www.thoughtworks.com/privacy-policy#cookie-section' target='_blank' rel='noopener noreferrer'>cookies</a> for analytics. If you're unsure about it, take a look at our <a href='https://www.thoughtworks.com/privacy-policy' target='_blank' rel='noopener noreferrer'>privacy policy</a>.</p>");
$(document.body).addClass("with-gdpr").find("header").append(gdpr);
dc.setItem("gdpr-accept", "yes");
}
});
})(jQuery, docCookies);
| (function ($, dc) {
"use strict";
$(function gdprBanner() {
if (!dc.hasItem("gdpr-accept")) {
var gdpr = $("<div class='gdpr-cookie-banner'>").on("click", ".gdpr-close", function(e) {
dc.setItem("gdpr-accept", "yes");
$(document.body).removeClass("with-gdpr");
gdpr.remove();
}).append("<i class='gdpr-close fa fa-close'/>").
append("<p>Our site uses <a href='https://www.thoughtworks.com/privacy-policy#cookie-section' target='_blank'>cookies</a> for analytics. If you're unsure about it, take a look at our <a href='https://www.thoughtworks.com/privacy-policy' target='_blank'>privacy policy</a>.</p>");
$(document.body).addClass("with-gdpr").find("header").append(gdpr);
dc.setItem("gdpr-accept", "yes");
}
});
})(jQuery, docCookies);
|
Clean up a non-empty string guard | <?php
namespace Peppercorn\St1;
use Phava\Base;
use Phava\Base\Preconditions;
use Phava\Base\Strings;
class File
{
/**
* Contains all lines from this file
*
* @var array
*/
private $lines;
public function __construct($content)
{
Preconditions::checkArgument(Strings::isNotEmpty($content));
$this->lines = self::splitContentIntoLines($content);
}
private static function splitContentIntoLines($content)
{
$rawLines = explode("\n", $content);
$lines = array();
foreach ($rawLines as $rawLine) {
$line = trim($rawLine);
if (Strings::isNotEmpty($line)) {
$lines[] = $line;
}
}
return $lines;
}
public function getLineCount()
{
return count($this->lines);
}
public function getLine($index)
{
Preconditions::checkArgumentIsInteger($index);
Preconditions::checkArgumentIsKeyInArray($index, $this->lines);
return $this->lines[$index];
}
} | <?php
namespace Peppercorn\St1;
use Phava\Base;
use Phava\Base\Preconditions;
use Phava\Base\Strings;
class File
{
/**
* Contains all lines from this file
*
* @var array
*/
private $lines;
public function __construct($content)
{
Preconditions::checkArgument(Strings::isNotEmpty($content));
$this->lines = self::splitContentIntoLines($content);
}
private static function splitContentIntoLines($content)
{
$rawLines = explode("\n", $content);
$lines = array();
foreach ($rawLines as $rawLine) {
$line = trim($rawLine);
if (strlen($line) > 0) { // omit empty lines
$lines[] = $line;
}
}
return $lines;
}
public function getLineCount()
{
return count($this->lines);
}
public function getLine($index)
{
Preconditions::checkArgumentIsInteger($index);
Preconditions::checkArgumentIsKeyInArray($index, $this->lines);
return $this->lines[$index];
}
} |
Use initial capacity of 1. Max is often just 1 or maybe 2. LJMC might get slower, but everyone should use less RAM and some might get faster. Any slowdown should only affect startup, not long-term performance of a simulation. | /*
* History
* Created on Nov 23, 2004 by kofke
*/
package etomica.nbr.cell;
import etomica.atom.Atom;
import etomica.atom.AtomArrayList;
import etomica.atom.AtomList;
import etomica.lattice.AbstractLattice;
import etomica.lattice.RectangularLattice;
import etomica.lattice.SiteFactory;
/**
* Site used to form array of cells for cell-based neighbor listing. Each
* cell is capable of holding lists of atoms that are in them.
*/
public class Cell implements java.io.Serializable {
public Cell(int latticeArrayIndex) {
this.latticeArrayIndex = latticeArrayIndex;
}
public AtomArrayList occupants() {return occupants;}
public void addAtom(Atom atom) {
occupants.add(atom);
}
public void removeAtom(Atom atom) {
occupants.removeAndReplace(occupants.indexOf(atom));
}
public int getLatticeArrayIndex() {
return latticeArrayIndex;
}
private final AtomArrayList occupants = new AtomArrayList(1);
final int latticeArrayIndex;//identifies site in lattice
public static final SiteFactory FACTORY = new CellFactory();
public static class CellFactory implements SiteFactory, java.io.Serializable {
public Object makeSite(AbstractLattice lattice, int[] coord) {
return new Cell(((RectangularLattice)lattice).arrayIndex(coord));
}
};
}
| /*
* History
* Created on Nov 23, 2004 by kofke
*/
package etomica.nbr.cell;
import etomica.atom.Atom;
import etomica.atom.AtomArrayList;
import etomica.atom.AtomList;
import etomica.lattice.AbstractLattice;
import etomica.lattice.RectangularLattice;
import etomica.lattice.SiteFactory;
/**
* Site used to form array of cells for cell-based neighbor listing. Each
* cell is capable of holding lists of atoms that are in them.
*/
public class Cell implements java.io.Serializable {
public Cell(int latticeArrayIndex) {
this.latticeArrayIndex = latticeArrayIndex;
}
public AtomArrayList occupants() {return occupants;}
public void addAtom(Atom atom) {
occupants.add(atom);
}
public void removeAtom(Atom atom) {
occupants.removeAndReplace(occupants.indexOf(atom));
}
public int getLatticeArrayIndex() {
return latticeArrayIndex;
}
private final AtomArrayList occupants = new AtomArrayList();
final int latticeArrayIndex;//identifies site in lattice
public static final SiteFactory FACTORY = new CellFactory();
public static class CellFactory implements SiteFactory, java.io.Serializable {
public Object makeSite(AbstractLattice lattice, int[] coord) {
return new Cell(((RectangularLattice)lattice).arrayIndex(coord));
}
};
}
|
Correct opdracht classes begin, verbetering Giele | <?php
class Percent
{
public $absolute;
public $relative;
public $hundred;
public $nominal;
public function __construct( $new, $unit )
{
$this->absolute = $this->formatNumber( $new / $unit );
$this->relative = $this->formatNumber( $this->absolute -1 );
$this->hundred = $this->formatNumber( $this->relative * 100 );
$this->nominal = "status-quo";
if ( $this->hundred > 0)
{
$this->nominal = "positive";
}
elseif ( $this->hundred < 0 )
{
$this->nominal = "negative";
}
}
public function formatNumber( $number )
{
return number_format($number, 2, '.', ' ');
}
}
?> | <?php
class Percent
{
public $absolute;
public $relative;
public $hundred;
public $nominal;
public function __construct( $new, $unit )
{
$this->absolute = $this->formatNumber( $new / $unit );
$this->relative = $this->formatNumber( $this->absolute - 1 );
$this->hundred = $this->formatNumber( $this->absolute * 100 );
$this->nominal = "status-quo";
if ( $this->hundred > 0)
{
$this->nominal = "positive";
}
elseif ( $this->hundred < 0 )
{
$this->nominal = "negative";
}
}
public function formatNumber( $number )
{
return number_format($number, 2, '.', ' ');
}
}
?> |
Disable linting for fireworks-react webpack | /* eslint-disable */
const { resolve } = require('path');
const webpack = require('webpack');
module.exports = {
context: resolve(__dirname, 'src'),
entry: [
'./Fireworks.js'
// the entry point of our app
],
output: {
filename: 'fireworks.bundle.js',
// the output bundle
path: resolve(__dirname, 'dist'),
},
module: {
rules: [
{
enforce: "pre",
test: /\.jsx?$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
emitError: true
}
},
{
test: /\.jsx?$/,
use: [ 'babel-loader', ],
exclude: /node_modules/
},
],
}
}; | const { resolve } = require('path');
const webpack = require('webpack');
module.exports = {
context: resolve(__dirname, 'src'),
entry: [
'./Fireworks.js'
// the entry point of our app
],
output: {
filename: 'fireworks.bundle.js',
// the output bundle
path: resolve(__dirname, 'dist'),
},
module: {
rules: [
{
enforce: "pre",
test: /\.jsx?$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
emitError: true
}
},
{
test: /\.jsx?$/,
use: [ 'babel-loader', ],
exclude: /node_modules/
},
],
}
}; |
Put 'abstract' keyword before visibility to follow psr-2 standard | <?php
namespace App\Middleware;
use App\Service\JWTManager;
use Interop\Container\ContainerInterface;
use Cartalyst\Sentinel\Sentinel;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Router;
/**
* @property Router router
* @property Sentinel sentinel
* @property JWTManager jwt
*/
abstract class Middleware
{
/**
* Slim application container
*
* @var ContainerInterface
*/
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
abstract public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next);
public function __get($property)
{
return $this->container->get($property);
}
}
| <?php
namespace App\Middleware;
use App\Service\JWTManager;
use Interop\Container\ContainerInterface;
use Cartalyst\Sentinel\Sentinel;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Router;
/**
* @property Router router
* @property Sentinel sentinel
* @property JWTManager jwt
*/
abstract class Middleware
{
/**
* Slim application container
*
* @var ContainerInterface
*/
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public abstract function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next);
public function __get($property)
{
return $this->container->get($property);
}
}
|
Use webbrowser.open_new_tab() instead of platform dependent open | # Module: docs
# Date: 03rd April 2013
# Author: James Mills, j dot mills at griffith dot edu dot au
"""Documentation Tasks"""
from fabric.api import lcd, local, task
from .utils import pip, requires
PACKAGE = "src/ccav"
@task()
@requires("sphinx-apidoc")
def api():
"""Generate the API Documentation"""
if PACKAGE is not None:
local("sphinx-apidoc -f -T -o docs/source/api {0:s}".format(PACKAGE))
@task()
@requires("make")
def clean():
"""Delete Generated Documentation"""
with lcd("docs"):
local("make clean")
@task(default=True)
@requires("make")
def build(**options):
"""Build the Documentation"""
pip(requirements="docs/requirements.txt")
with lcd("docs"):
local("make html")
@task()
def view(**options):
"""View the Documentation"""
with lcd("docs"):
import webbrowser
webbrowser.open_new_tab("build/html/index.html")
| # Module: docs
# Date: 03rd April 2013
# Author: James Mills, j dot mills at griffith dot edu dot au
"""Documentation Tasks"""
from fabric.api import lcd, local, task
from .utils import pip, requires
PACKAGE = "src/ccav"
@task()
@requires("sphinx-apidoc")
def api():
"""Generate the API Documentation"""
if PACKAGE is not None:
local("sphinx-apidoc -f -T -o docs/source/api {0:s}".format(PACKAGE))
@task()
@requires("make")
def clean():
"""Delete Generated Documentation"""
with lcd("docs"):
local("make clean")
@task(default=True)
@requires("make")
def build(**options):
"""Build the Documentation"""
pip(requirements="docs/requirements.txt")
with lcd("docs"):
local("make html")
@task()
@requires("open")
def view(**options):
"""View the Documentation"""
with lcd("docs"):
local("open build/html/index.html")
|
Remove required matching in TokenPattern unit test | package org.panda_lang.panda.framework.language.interpreter.pattern.token;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.panda_lang.panda.framework.design.interpreter.token.TokenizedSource;
import org.panda_lang.panda.framework.language.interpreter.lexer.PandaLexer;
import org.panda_lang.panda.framework.language.interpreter.pattern.lexical.elements.LexicalPatternElement;
import org.panda_lang.panda.framework.language.interpreter.source.PandaSource;
import org.panda_lang.panda.framework.language.resource.PandaSyntax;
class TokenPatternTest {
private static final String CONTENT = "method void test(15, 25) { Console.print('test') }";
private static final TokenizedSource SOURCE = new PandaLexer(PandaSyntax.getInstance(), new PandaSource("Test", CONTENT)).convert();
@Test
public void testTokenPattern() {
TokenPattern pattern = TokenPattern.builder()
.compile("(method|hidden|local) [static] <return-type> <name>(<parameters>) \\{ <body> \\}[;]")
.build();
LexicalPatternElement content = pattern.getPatternContent();
Assertions.assertNotNull(content);
TokenExtractorResult result = pattern.extract(SOURCE);
Assertions.assertNotNull(result);
//Assertions.assertTrue(result.isMatched());
}
}
| package org.panda_lang.panda.framework.language.interpreter.pattern.token;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.panda_lang.panda.framework.design.interpreter.token.TokenizedSource;
import org.panda_lang.panda.framework.language.interpreter.lexer.PandaLexer;
import org.panda_lang.panda.framework.language.interpreter.pattern.lexical.elements.LexicalPatternElement;
import org.panda_lang.panda.framework.language.interpreter.source.PandaSource;
import org.panda_lang.panda.framework.language.resource.PandaSyntax;
class TokenPatternTest {
private static final String CONTENT = "method void test(15, 25) { Console.print('test') }";
private static final TokenizedSource SOURCE = new PandaLexer(PandaSyntax.getInstance(), new PandaSource("Test", CONTENT)).convert();
@Test
public void testTokenPattern() {
TokenPattern pattern = TokenPattern.builder()
.compile("(method|hidden|local) [static] <return-type> <name>(<parameters>) \\{ <body> \\}[;]")
.build();
LexicalPatternElement content = pattern.getPatternContent();
Assertions.assertNotNull(content);
TokenExtractorResult result = pattern.extract(SOURCE);
Assertions.assertNotNull(result);
Assertions.assertTrue(result.isMatched());
}
}
|
Update gate Jenkins endpoints for /v2/ changes | 'use strict';
let angular = require('angular');
module.exports = angular.module('spinnaker.core.ci.jenkins.igor.service', [
require('../../config/settings.js'),
require('exports?"restangular"!imports?_=lodash!restangular'),
])
.factory('igorService', function (settings, Restangular) {
var RestangularNoEncoding;
RestangularNoEncoding = Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setEncodeIds(false);
});
function listMasters() {
return Restangular.one('v2').one('builds').getList();
}
function listJobsForMaster(master) {
return Restangular.one('v2').one('builds', master).all('jobs').getList();
}
function listBuildsForJob(master, job) {
return RestangularNoEncoding.one('v2').one('builds', master).one('builds').one(job).getList();
}
function getJobConfig(master, job){
return RestangularNoEncoding.one('v2').one('builds', master).one('jobs', job).get();
}
return {
listMasters: listMasters,
listJobsForMaster: listJobsForMaster,
listBuildsForJob: listBuildsForJob,
getJobConfig: getJobConfig,
};
});
| 'use strict';
let angular = require('angular');
module.exports = angular.module('spinnaker.core.ci.jenkins.igor.service', [
require('../../config/settings.js'),
require('exports?"restangular"!imports?_=lodash!restangular'),
])
.factory('igorService', function (settings, Restangular) {
function listMasters() {
return Restangular.one('builds').getList();
}
function listJobsForMaster(master) {
return Restangular.one('builds', master).all('jobs').getList();
}
function listBuildsForJob(master, job) {
return Restangular.one('builds', master).one('jobs', job).all('builds').getList();
}
function getJobConfig(master, job){
return Restangular.one('builds', master).one('jobs', job).get();
}
return {
listMasters: listMasters,
listJobsForMaster: listJobsForMaster,
listBuildsForJob: listBuildsForJob,
getJobConfig: getJobConfig,
};
});
|
Remove NotExecutable check, bad on Windows | package se.vandmo.textchecker.maven;
import static java.util.Arrays.asList;
import java.io.File;
import java.util.Collection;
import se.vandmo.textchecker.maven.rules.ConsistentLineSeparator;
import se.vandmo.textchecker.maven.rules.EndsWithLineSeparator;
import se.vandmo.textchecker.maven.rules.NoTabs;
import se.vandmo.textchecker.maven.rules.NoTrailingWhitespaceOnNonBlankLines;
import se.vandmo.textchecker.maven.rules.NoWhitespaceOnBlankLines;
public final class RulesResolver {
public Collection<Rule> getRulesFor(File file) {
return asList(
new NoTabs(),
new NoTrailingWhitespaceOnNonBlankLines(),
new NoWhitespaceOnBlankLines(),
new ConsistentLineSeparator(),
new EndsWithLineSeparator());
}
}
| package se.vandmo.textchecker.maven;
import static java.util.Arrays.asList;
import java.io.File;
import java.util.Collection;
import se.vandmo.textchecker.maven.rules.ConsistentLineSeparator;
import se.vandmo.textchecker.maven.rules.EndsWithLineSeparator;
import se.vandmo.textchecker.maven.rules.NoTabs;
import se.vandmo.textchecker.maven.rules.NoTrailingWhitespaceOnNonBlankLines;
import se.vandmo.textchecker.maven.rules.NoWhitespaceOnBlankLines;
import se.vandmo.textchecker.maven.rules.NotExecutable;
public final class RulesResolver {
public Collection<Rule> getRulesFor(File file) {
return asList(
new NoTabs(),
new NoTrailingWhitespaceOnNonBlankLines(),
new NoWhitespaceOnBlankLines(),
new NotExecutable(),
new ConsistentLineSeparator(),
new EndsWithLineSeparator());
}
}
|
Remove unneeded components from home page | import React from 'react'
import Page from '../../components/page'
import Header from './header'
import PreviousEpisodeSection from './sections/previous-episodes'
import EpisodesSection from './sections/episodes'
import PanelistsSection from './sections/panelists'
import SponsorsSection from '../../components/sponsors'
import Footer from './sections/footer'
import FeatureShowScript from './scripts/feature-show'
export default Home
function Home(
{
futureEpisodes = [],
pastEpisodes = [],
sponsors,
panelists,
}
) {
return (
<Page>
<Header />
<EpisodesSection episodes={futureEpisodes} />
<PanelistsSection panelists={panelists} />
<Footer />
<div className="container">
<SponsorsSection {...sponsors} />
<PreviousEpisodeSection episodes={pastEpisodes} />
<FeatureShowScript />
</div>
</Page>
)
}
| import React from 'react'
import Page from '../../components/page'
import Header from './header'
import PreviousEpisodeSection from './sections/previous-episodes'
import EpisodesSection from './sections/episodes'
import PanelistsSection from './sections/panelists'
import SponsorsSection from '../../components/sponsors'
import LinksSection from './sections/footer/footer-links-list'
import Footer from './sections/footer'
import SocialIconGroupSection from './sections/footer/footer-social-links-list'
import FeatureShowScript from './scripts/feature-show'
export default Home
function Home(
{
futureEpisodes = [],
pastEpisodes = [],
sponsors,
panelists,
}
) {
return (
<Page>
<Header />
<EpisodesSection episodes={futureEpisodes} />
<PanelistsSection panelists={panelists} />
<Footer />
<div className="container">
<SponsorsSection {...sponsors} />
<PreviousEpisodeSection episodes={pastEpisodes} />
{pastEpisodes.length ? <hr /> : ''}
<SocialIconGroupSection />
<LinksSection />
<FeatureShowScript />
</div>
</Page>
)
}
|
Check to see if req.body has secret, otherwise read from env | 'use strict';
require('../../../env');
let payload = {};
payload.build = function() {
return (req, res, next) => {
// req.body.album = album;
req.body.api_key = process.env.API_KEY;
req.body.artist = req.query.artist;
req.body.format = 'json';
req.body.method = 'track.scrobble';
req.body.sk = process.env.SK;
req.body.timestamp = Math.floor(new Date() / 1000);
req.body.track = req.query.title;
next();
};
};
payload.squish = function() {
return (req, res, next) => {
let raw = '';
for (var key in req.body) {
if (req.body.hasOwnProperty(key) && key != 'format' && key != 'secret') {
raw += key + req.body[key];
};
};
if (req.body.secret) {
raw += req.body.secret;
} else {
raw += process.env.SECRET;
}
req.body.api_sig = raw;
next();
};
};
module.exports = payload; | 'use strict';
const config = require('../../../config');
let payload = {};
payload.build = function() {
return (req, res, next) => {
// req.body.album = album;
// req.body.api_key = config.api_key;
// req.body.artist = artist;
// req.body.format = 'json';
// req.body.method = method;
// req.body.sk = config.sk;
// req.body.timestamp = Math.floor(new Date() / 1000);
// req.body.track = track;
next();
};
};
payload.squish = function() {
return (req, res, next) => {
let raw = '';
for (var key in req.body) {
if (req.body.hasOwnProperty(key) && key != 'format' && key != 'secret') {
raw += key + req.body[key];
};
};
raw += req.body.secret;
req.body.api_sig = raw;
next();
};
};
module.exports = payload; |
Fix instantiating the preparation when plug-ins are done loading
The new position of the state variable. | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license differs from the license provided with this software, the license provided with this software should be applied.
"""
Provides a class that allows for creating global application preferences.
"""
import luna.listen #To prepare the preferences for use when plug-ins are loaded.
import luna.plugins #To get the configuration data type to extend from.
class Preferences:
"""
Offers a system to create global application preferences.
"""
def __init__(self):
luna.listen.listen(self.check_prepare, luna.plugins.instance, "state")
def check_prepare(self, _, new_state):
if new_state == luna.plugins.PluginsState.LOADED:
self.prepare()
def prepare(self):
"""
Finalizes the class initialisation using data that is only available at
run time.
"""
original_class = self.__class__
parent_class = luna.plugins.api("configuration").Configuration
self.__class__ = original_class.__class__(original_class.__name__ + "Configuration", (original_class, parent_class), {}) #Add the configuration class mixin.
super().__init__() #Execute the Configuration class' initialisation method to create the data structures. | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license differs from the license provided with this software, the license provided with this software should be applied.
"""
Provides a class that allows for creating global application preferences.
"""
import luna.listen #To prepare the preferences for use when plug-ins are loaded.
import luna.plugins #To get the configuration data type to extend from.
class Preferences:
"""
Offers a system to create global application preferences.
"""
def __init__(self):
luna.listen.listen(self.check_prepare, luna.plugins, "state")
def check_prepare(self, _, new_state):
if new_state == luna.plugins.PluginsState.LOADED:
self.prepare()
def prepare(self):
"""
Finalizes the class initialisation using data that is only available at
run time.
"""
original_class = self.__class__
parent_class = luna.plugins.api("configuration").Configuration
self.__class__ = original_class.__class__(original_class.__name__ + "Configuration", (original_class, parent_class), {}) #Add the configuration class mixin.
super().__init__() #Execute the Configuration class' initialisation method to create the data structures. |
Add phpdoc for isInRange() method | <?php
namespace OpenDominion\Calculators\Dominion;
use OpenDominion\Models\Dominion;
class RangeCalculator
{
/** @var LandCalculator */
protected $landCalculator;
/**
* RangeCalculator constructor.
*
* @param LandCalculator $landCalculator
*/
public function __construct(LandCalculator $landCalculator)
{
$this->landCalculator = $landCalculator;
}
/**
* Checks whether dominion $target is in range of dominion $self.
*
* @param Dominion $self
* @param Dominion $target
* @return bool
*/
public function isInRange(Dominion $self, Dominion $target): bool
{
// todo: if RG then $modifier = 0.6, else if EG then $modifier = 0.75, else $modifier = 0.4
$selfLand = $this->landCalculator->getTotalLand($self);
$targetLand = $this->landCalculator->getTotalLand($target);
$modifier = 0.6;
return (
($targetLand >= ($selfLand * $modifier)) &&
($targetLand <= ($selfLand / $modifier))
);
}
}
| <?php
namespace OpenDominion\Calculators\Dominion;
use OpenDominion\Models\Dominion;
class RangeCalculator
{
/** @var LandCalculator */
protected $landCalculator;
/**
* RangeCalculator constructor.
*
* @param LandCalculator $landCalculator
*/
public function __construct(LandCalculator $landCalculator)
{
$this->landCalculator = $landCalculator;
}
public function isInRange(Dominion $self, Dominion $target): bool
{
// todo: if RG then $modifier = 0.6, else if EG then $modifier = 0.75, else $modifier = 0.4
$selfLand = $this->landCalculator->getTotalLand($self);
$targetLand = $this->landCalculator->getTotalLand($target);
$modifier = 0.6;
return (
($targetLand >= ($selfLand * $modifier)) &&
($targetLand <= ($selfLand / $modifier))
);
}
}
|
Add command for updating the node.js modules needed by the JS sandbox. | from fabric.api import cd, sudo, env
env.path = '/var/praekelt/vumi-go'
def deploy_go():
with cd(env.path):
sudo('git pull', user='vumi')
_venv_command('./ve/bin/django-admin.py collectstatic --pythonpath=. '
'--settings=go.settings --noinput')
def deploy_vumi():
with cd('%s/ve/src/vumi/' % (env.path,)):
sudo('git pull', user='vumi')
def restart_celery():
with cd(env.path):
supervisorctl('restart vumi_celery:celery')
def restart_gunicorn():
"""
Intentionally restart the gunicorns 1 by 1 so HAProxy is given
time to load balance across gunicorns that have either already restarted
or are waiting to be restarted
"""
with cd(env.path):
for i in range(1, 5):
supervisorctl('restart vumi_web:goui_%s' % (i,))
def update_nodejs_modules():
"""
Update the Node.js modules that the JS sandbox depends on.
"""
npm_install("vumigo_v01")
def supervisorctl(command):
return sudo('supervisorctl %s' % (command,))
def npm_install(package):
return sudo('npm install --global %s' % (package,))
def _venv_command(command, user='vumi'):
return sudo('. ve/bin/activate && %s' % (command,), user=user)
| from fabric.api import cd, sudo, env
env.path = '/var/praekelt/vumi-go'
def deploy_go():
with cd(env.path):
sudo('git pull', user='vumi')
_venv_command('./ve/bin/django-admin.py collectstatic --pythonpath=. '
'--settings=go.settings --noinput')
def deploy_vumi():
with cd('%s/ve/src/vumi/' % (env.path,)):
sudo('git pull', user='vumi')
def restart_celery():
with cd(env.path):
supervisorctl('restart vumi_celery:celery')
def restart_gunicorn():
"""
Intentionally restart the gunicorns 1 by 1 so HAProxy is given
time to load balance across gunicorns that have either already restarted
or are waiting to be restarted
"""
with cd(env.path):
for i in range(1, 5):
supervisorctl('restart vumi_web:goui_%s' % (i,))
def supervisorctl(command):
return sudo('supervisorctl %s' % (command,))
def _venv_command(command, user='vumi'):
return sudo('. ve/bin/activate && %s' % (command,), user=user)
|
Change constructor documentation to use a capital S. | /**
* Creates a new Sprite.
*
* @constructor
* @param {string} image The URL of the image to make a sprite from.
*/
function Sprite(image, onload) {
this.image = new Image();
this.image.src = image;
var sprite = this;
this.image.onload = function OnImageLoad(event) {
sprite.size = new Vector2(sprite.image.width, sprite.image.height);
Log.info(sprite.size + " sprite loaded: " + sprite.image.src, "OnImageLoad");
if (typeof onload === 'function') {
onload();
} else if(typeof onload !== 'undefined') {
throw new InvalidArgumentError("onload", "onload should be a function! Received: " + onload);
}
}
}
/**
* Render this sprite to a screen.
*
* @param {Screen} screen The screen to render this sprite to.
* @param {Vector2} position The position to render this sprite on.
*/
Sprite.prototype.render = function (screen, position) {
screen.render(this.image, position, this.size);
};
/**
* @override
* @returns {string} The textual representation of this object.
*/
Sprite.prototype.toString = function () {
return "Sprite { " + this.image.src + " }"
}; | /**
* Creates a new sprite.
*
* @constructor
* @param {string} image The URL of the image to make a sprite from.
*/
function Sprite(image, onload) {
this.image = new Image();
this.image.src = image;
var sprite = this;
this.image.onload = function OnImageLoad(event) {
sprite.size = new Vector2(sprite.image.width, sprite.image.height);
Log.info(sprite.size + " sprite loaded: " + sprite.image.src, "OnImageLoad");
if (typeof onload === 'function') {
onload();
} else if(typeof onload !== 'undefined') {
throw new InvalidArgumentError("onload", "onload should be a function! Received: " + onload);
}
}
}
/**
* Render this sprite to a screen.
*
* @param {Screen} screen The screen to render this sprite to.
* @param {Vector2} position The position to render this sprite on.
*/
Sprite.prototype.render = function (screen, position) {
screen.render(this.image, position, this.size);
};
/**
* @override
* @returns {string} The textual representation of this object.
*/
Sprite.prototype.toString = function () {
return "Sprite { " + this.image.src + " }"
}; |
Add PyYAML as a direct dependency for tests. | from setuptools import setup, find_packages
setup(
name="go_auth",
version="0.1.0a",
url='http://github.com/praekelt/go_auth',
license='BSD',
description="Authentication services and utilities for Vumi Go APIs.",
long_description=open('README.rst', 'r').read(),
author='Praekelt Foundation',
author_email='dev@praekeltfoundation.org',
packages=find_packages(),
include_package_data=True,
install_requires=[
'cyclone',
'oauthlib',
'go_api',
'PyYAML',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Internet :: WWW/HTTP',
],
)
| from setuptools import setup, find_packages
setup(
name="go_auth",
version="0.1.0a",
url='http://github.com/praekelt/go_auth',
license='BSD',
description="Authentication services and utilities for Vumi Go APIs.",
long_description=open('README.rst', 'r').read(),
author='Praekelt Foundation',
author_email='dev@praekeltfoundation.org',
packages=find_packages(),
include_package_data=True,
install_requires=[
'cyclone',
'oauthlib',
'go_api',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Internet :: WWW/HTTP',
],
)
|
Change Promise to BBPromise as Promise is now a global variable in node and we don't want to overwrite it. | 'use strict';
var request = require('request');
var BBPromise = require('bluebird');
var ResourceBase = function(endpoint, config) {
this.uri = config.options.baseURI + endpoint;
this.config = config.options;
};
(function() {
this._transmit = function(method, uri, qs, form, formData, callback) {
var opts = {
url: this.uri + (uri ? '/' + uri : ''),
method: method,
auth: { user: this.config.apiKey, password: '' },
headers: this.config.headers,
json: true
};
if(qs) { opts.qs = qs; }
if(form) { opts.form = form; }
if(formData) { opts.formData = formData; }
return new BBPromise(function(resolve, reject) {
request(opts, function(err, resp, body) {
if(err) {
return reject(err);
}
if(body && body.errors) {
return reject(body.errors);
}
return resolve(body);
});
}).nodeify(callback);
};
}).call(ResourceBase.prototype);
module.exports = ResourceBase;
| 'use strict';
var request = require('request');
var Promise = require('bluebird');
var ResourceBase = function(endpoint, config) {
this.uri = config.options.baseURI + endpoint;
this.config = config.options;
};
(function() {
this._transmit = function(method, uri, qs, form, formData, callback) {
var opts = {
url: this.uri + (uri ? '/' + uri : ''),
method: method,
auth: { user: this.config.apiKey, password: '' },
headers: this.config.headers,
json: true
};
if(qs) { opts.qs = qs; }
if(form) { opts.form = form; }
if(formData) { opts.formData = formData; }
return new Promise(function(resolve, reject) {
request(opts, function(err, resp, body) {
if(err) {
return reject(err);
}
if(body && body.errors) {
return reject(body.errors);
}
return resolve(body);
});
}).nodeify(callback);
};
}).call(ResourceBase.prototype);
module.exports = ResourceBase;
|
Remove tileset load debug message | package me.hugmanrique.pokedata.tiles;
import lombok.Getter;
import me.hugmanrique.pokedata.Data;
import me.hugmanrique.pokedata.roms.ROM;
/**
* http://datacrystal.romhacking.net/wiki/Pok%C3%A9mon_3rd_Generation#Maps
* @author Hugmanrique
* @since 02/07/2017
*/
@Getter
public class TilesetHeader extends Data {
private boolean compressed;
private boolean primary;
private long tilesetImgPtr;
private long palettesPtr;
private long blocksPtr;
private long animationPtr;
private long behaviorPtr;
public TilesetHeader(ROM rom) {
compressed = rom.readByte() == 1;
primary = rom.readByte() == 0;
// Skip two unknown bytes
rom.addInternalOffset(2);
tilesetImgPtr = rom.getPointer();
palettesPtr = rom.getPointer();
blocksPtr = rom.getPointer();
if (rom.getGame().isElements()) {
animationPtr = rom.getPointer();
behaviorPtr = rom.getPointer();
} else {
behaviorPtr = rom.getPointer();
animationPtr = rom.getPointer();
}
}
}
| package me.hugmanrique.pokedata.tiles;
import lombok.Getter;
import me.hugmanrique.pokedata.Data;
import me.hugmanrique.pokedata.roms.ROM;
/**
* http://datacrystal.romhacking.net/wiki/Pok%C3%A9mon_3rd_Generation#Maps
* @author Hugmanrique
* @since 02/07/2017
*/
@Getter
public class TilesetHeader extends Data {
private boolean compressed;
private boolean primary;
private long tilesetImgPtr;
private long palettesPtr;
private long blocksPtr;
private long animationPtr;
private long behaviorPtr;
public TilesetHeader(ROM rom) {
compressed = rom.readByte() == 1;
primary = rom.readByte() == 0;
// Skip two unknown bytes
rom.addInternalOffset(2);
tilesetImgPtr = rom.getPointer();
palettesPtr = rom.getPointer();
blocksPtr = rom.getPointer();
System.out.println("Read: Tileset imgs -> " + tilesetImgPtr + " Palettes -> " + palettesPtr + " Blocks -> " + blocksPtr);
if (rom.getGame().isElements()) {
animationPtr = rom.getPointer();
behaviorPtr = rom.getPointer();
} else {
behaviorPtr = rom.getPointer();
animationPtr = rom.getPointer();
}
}
}
|
Add tests directory to packages list in install file | from setuptools import setup
import glob
import os.path as op
from os import listdir
from pyuvdata import version
import json
data = [version.git_origin, version.git_hash, version.git_description, version.git_branch]
with open(op.join('pyuvdata', 'GIT_INFO'), 'w') as outfile:
json.dump(data, outfile)
setup_args = {
'name': 'pyuvdata',
'author': 'HERA Team',
'url': 'https://github.com/HERA-Team/pyuvdata',
'license': 'BSD',
'description': 'an interface for astronomical interferometeric datasets in python',
'package_dir': {'pyuvdata': 'pyuvdata'},
'packages': ['pyuvdata', 'pyuvdata.tests'],
'scripts': glob.glob('scripts/*'),
'version': version.version,
'include_package_data': True,
'install_requires': ['numpy>=1.10', 'scipy', 'astropy>=1.2', 'pyephem', 'aipy'],
'classifiers': ['Development Status :: 5 - Production/Stable',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering :: Astronomy'],
'keywords': 'radio astronomy interferometry'
}
if __name__ == '__main__':
apply(setup, (), setup_args)
| from setuptools import setup
import glob
import os.path as op
from os import listdir
from pyuvdata import version
import json
data = [version.git_origin, version.git_hash, version.git_description, version.git_branch]
with open(op.join('pyuvdata', 'GIT_INFO'), 'w') as outfile:
json.dump(data, outfile)
setup_args = {
'name': 'pyuvdata',
'author': 'HERA Team',
'url': 'https://github.com/HERA-Team/pyuvdata',
'license': 'BSD',
'description': 'an interface for astronomical interferometeric datasets in python',
'package_dir': {'pyuvdata': 'pyuvdata'},
'packages': ['pyuvdata'],
'scripts': glob.glob('scripts/*'),
'version': version.version,
'include_package_data': True,
'install_requires': ['numpy>=1.10', 'scipy', 'astropy>=1.2', 'pyephem', 'aipy'],
'classifiers': ['Development Status :: 5 - Production/Stable',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering :: Astronomy'],
'keywords': 'radio astronomy interferometry'
}
if __name__ == '__main__':
apply(setup, (), setup_args)
|
Update eBay highlight script to work with new classes | // ==UserScript==
// @name eBay - Hilight Items With Bids
// @namespace http://mathemaniac.org
// @include http://*.ebay.*/*
// @grant none
// @version 2.3.2
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js
// @description Hilights items that have bids with a red border and yellow background.
// ==/UserScript==
// Based on http://userscripts.org/users/126140 v.2.2.1
// Updated for newer eBay layout.
$('document').ready(function() {
$(".lvprices .lvformat").each(function() {
// Skip listings with no bids.
if ($(this).text().match(/\b0 bids/) || !$(this).text().match(/\d+ bids/)) return;
$(this).closest('li[listingid]').css({
"border": "3px solid red",
"background-color": "yellow"
});
});
});
| // ==UserScript==
// @name eBay - Hilight Items With Bids
// @namespace http://mathemaniac.org
// @include http://*.ebay.*/*
// @grant none
// @version 2.3.1
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js
// @description Hilights items that have bids with a red border and yellow background.
// ==/UserScript==
// Based on http://userscripts-mirror.org/scripts/show/66089.html v.2.2.1
// Updated for newer eBay layout.
$('document').ready(function() {
$(".bids span").each(function() {
// Skip listings with no bids.
if ($(this).text().match(/\b0 bids/)) return;
$(this).closest('li[listingid]').css({
"border": "3px solid red",
"background-color": "yellow"
});
});
});
|
Add SECURE_REDIRECT_EXEMPT to old HTTP callbacks | from os import environ
import dj_database_url
from .base import *
INSTALLED_APPS += (
'djangosecure',
)
PRODUCTION_MIDDLEWARE_CLASSES = (
'djangosecure.middleware.SecurityMiddleware',
)
MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES
DATABASES = {'default': dj_database_url.config()}
SECRET_KEY = environ.get('SECRET_KEY')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = [DOMAIN]
# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_REDIRECT_EXEMPT = [
'^(?!hub/).*'
]
| from os import environ
import dj_database_url
from .base import *
INSTALLED_APPS += (
'djangosecure',
)
PRODUCTION_MIDDLEWARE_CLASSES = (
'djangosecure.middleware.SecurityMiddleware',
)
MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES
DATABASES = {'default': dj_database_url.config()}
SECRET_KEY = environ.get('SECRET_KEY')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = [DOMAIN]
# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
|
Fix AES-CTR encryption to actually encrypt input data instead of slice of zeroes | // Challenge 51 - Compression Ratio Side-Channel Attacks
// http://cryptopals.com/sets/7/challenges/51
package cryptopals
import (
"bytes"
"compress/flate"
"crypto/aes"
"crypto/cipher"
"io"
"text/template"
)
type challenge51 struct {
}
var t = template.Must(template.New("request").Parse(`POST / HTTP/1.1
Host: hapless.com
Cookie: sessionid=TmV2ZXIgcmV2ZWFsIHRoZSBXdS1UYW5nIFNlY3JldCE=
Content-Length: {{ len . }}
{{ . }}`))
func (challenge51) CompressionOracle(data string) int {
req := new(bytes.Buffer)
t.Execute(req, data)
b := new(bytes.Buffer)
w, _ := flate.NewWriter(b, flate.BestCompression)
io.Copy(w, req)
w.Close()
block, _ := aes.NewCipher(randBytes(aes.BlockSize))
ctr := cipher.NewCTR(block, randBytes(aes.BlockSize))
var ciphertext []byte
ciphertext = append(ciphertext, b.Bytes()...)
ctr.XORKeyStream(ciphertext, ciphertext)
return len(ciphertext)
}
| // Challenge 51 - Compression Ratio Side-Channel Attacks
// http://cryptopals.com/sets/7/challenges/51
package cryptopals
import (
"bytes"
"compress/flate"
"crypto/aes"
"crypto/cipher"
"io"
"text/template"
)
type challenge51 struct {
}
var t = template.Must(template.New("request").Parse(`POST / HTTP/1.1
Host: hapless.com
Cookie: sessionid=TmV2ZXIgcmV2ZWFsIHRoZSBXdS1UYW5nIFNlY3JldCE=
Content-Length: {{ len . }}
{{ . }}`))
func (challenge51) CompressionOracle(data string) int {
req := new(bytes.Buffer)
t.Execute(req, data)
b := new(bytes.Buffer)
w, _ := flate.NewWriter(b, flate.BestCompression)
io.Copy(w, req)
w.Close()
block, _ := aes.NewCipher(randBytes(aes.BlockSize))
ctr := cipher.NewCTR(block, randBytes(aes.BlockSize))
ciphertext := make([]byte, len(b.Bytes()))
ctr.XORKeyStream(ciphertext, ciphertext)
return len(ciphertext)
}
|
Use alternate way of setting git author | import {exec} from 'node-promise-es6/child-process';
import fs from 'node-promise-es6/fs';
async function run() {
const {linkDependencies = {}} = await fs.readJson('package.json');
for (const dependencyName of Object.keys(linkDependencies)) {
const dependencyPath = linkDependencies[dependencyName];
const {stdout: diff} = await exec(
'git diff-index HEAD', {cwd: dependencyPath});
if (diff.trim().indexOf('package.json') === -1) { continue; }
await exec(
`git config user.email 'vinsonchuong@gmail.com'`,
{cwd: dependencyPath}
);
await exec(
`git config user.name 'Vinson Chuong'`,
{cwd: dependencyPath}
);
await exec(
[
'git commit',
`-m 'Automatically update dependencies'`,
'package.json'
].join(' '),
{cwd: dependencyPath}
);
await exec(
[
'git push',
`https://${process.env.GITHUB_TOKEN}@github.com/vinsonchuong/${dependencyName}`,
'master'
].join(' '),
{cwd: dependencyPath}
);
}
}
run().catch(e => {
process.stderr.write(`${e.stack}\n`);
process.exit(1);
});
| import {exec} from 'node-promise-es6/child-process';
import fs from 'node-promise-es6/fs';
async function run() {
const {linkDependencies = {}} = await fs.readJson('package.json');
for (const dependencyName of Object.keys(linkDependencies)) {
const dependencyPath = linkDependencies[dependencyName];
const {stdout: diff} = await exec(
'git diff-index HEAD', {cwd: dependencyPath});
if (diff.trim().indexOf('package.json') === -1) { continue; }
await exec(
[
'git commit',
`--author 'Vinson Chuong <vinsonchuong@gmail.com>'`,
`-m 'Automatically update dependencies'`,
'package.json'
].join(' '),
{cwd: dependencyPath}
);
await exec(
[
'git push',
`https://${process.env.GITHUB_TOKEN}@github.com/vinsonchuong/${dependencyName}`,
'master'
].join(' '),
{cwd: dependencyPath}
);
}
}
run().catch(e => {
process.stderr.write(`${e.stack}\n`);
process.exit(1);
});
|
Fix semester url regex bug | """kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^(\w{3,6})/semester/([1-9]|10)/$', semester),
]
| """kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^(\w{3,6})/semester/([1-10])/$', semester),
]
|
Fix typo in error message | <?php
/*
* SolusVM SuspendAccount
*
* Suspend VPS instance
*
* @package SolusVM
* @category WHMCS Provisioning Modules
* @author Trajche Petrov
* @link https://qbit.solutions/
*/
class SolusVM_SuspendAccount extends SolusVM
{
function _exec()
{
try
{
// check if the VPS is into the module database
if(!$this->input['vm_id'])
throw new Exception("Can't find VPS ID into module database");
// try to fetch client login keys
$suspend = $this->_api(array
(
'action' => 'vserver-suspend',
'vserverid' => $this->input['vm_id']
));
// validate API response
if($suspend->status == 'success')
return 'success';
elseif(!is_object($suspend) or !isset($suspend))
throw new Exception("Some API transport error occured please check module debug log!");
else
throw new Exception($suspend->statusmsg);
} catch ( Exception $error ) {
// log the errors
$this->_log( 'SuspendAccount', $this->input, $suspend, $error );
return $error->getMessage();
}
}
} | <?php
/*
* SolusVM SuspendAccount
*
* Suspend VPS instance
*
* @package SolusVM
* @category WHMCS Provisioning Modules
* @author Trajche Petrov
* @link https://qbit.solutions/
*/
class SolusVM_SuspendAccount extends SolusVM
{
function _exec()
{
try
{
// check if the VPS is into the module database
if(!$this->input['vm_id'])
throw new Exception("Can't find VPS ID into module database'");
// try to fetch client login keys
$suspend = $this->_api(array
(
'action' => 'vserver-suspend',
'vserverid' => $this->input['vm_id']
));
// validate API response
if($suspend->status == 'success')
return 'success';
elseif(!is_object($suspend) or !isset($suspend))
throw new Exception("Some API transport error occured please check module debug log!");
else
throw new Exception($suspend->statusmsg);
} catch ( Exception $error ) {
// log the errors
$this->_log( 'SuspendAccount', $this->input, $suspend, $error );
return $error->getMessage();
}
}
} |
Make our IFrameWidget more configurable | # This file is part of Moksha.
# Copyright (C) 2008-2009 Red Hat, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
:mod:`moksha.widgets.iframe` - An IFrame Widget
===============================================
.. moduleauthor:: Luke Macken <lmacken@redhat.com>
"""
from tw.api import Widget
class IFrameWidget(Widget):
params = ['id', 'url', 'title', 'height', 'width']
template = """
<h1>${title}</h1>
<iframe id="${id}" src="${url}" width="${width}" height="${height}">
<p>Your browser does not support iframes.</p>
</iframe>
"""
title = ''
height = width = '100%'
engine_name = 'mako'
iframe_widget = IFrameWidget('iframe_widget')
| # This file is part of Moksha.
# Copyright (C) 2008-2009 Red Hat, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
:mod:`moksha.widgets.iframe` - An IFrame Widget
===============================================
.. moduleauthor:: Luke Macken <lmacken@redhat.com>
"""
from tw.api import Widget
class IFrameWidget(Widget):
params = ['id', 'url']
template = """
<iframe id="${id}" src="${url}" width="100%" height="100%">
<p>Your browser does not support iframes.</p>
</iframe>
"""
engine_name = 'mako'
|
Test case 6 - matching via RegExp
Bear in mind that the \ to define a RegExp must be passed twice.
E.g. \d+ should be passed as \\d+
So, for a while this is the first restriction for matching. | ;((rc) => {
'use strict';
var tagContent = 'router2-content';
var div = document.createElement('div');
div.innerHTML = `
<${tagContent} id="case6-1" hash="case\\d+">
Case 6 via RegExp
</${tagContent}>
`;
var async1 = async_test('Case 6: hash changed to content[hash="case(\d+)"]');
async1.next = async1.step_func(_ => {
var check_hash = async1.step_func((e) => {
window.removeEventListener('hashchange', check_hash);
var content1 = document.querySelector('#case6-1');
assert_false(content1.hidden);
document.body.removeChild(div);
async1.done();
rc.next();
});
window.addEventListener('hashchange', check_hash);
window.location.hash = "case6";
});
rc.push(_ => {
async1.step(_ => {
document.body.appendChild(div);
async1.next();
});
})
})(window.routeCases);
| ;((rc) => {
'use strict';
var tagContent = 'router2-content';
var div = document.createElement('div');
div.innerHTML = `
<${tagContent} hash="case6">
</${tagContent}>
`;
var async1 = async_test('Case 6: hash changed to content[hash="case6"]');
async1.next = async1.step_func(_ => {
var check_hash = async1.step_func((e) => {
window.removeEventListener('hashchange', check_hash);
document.body.removeChild(div);
async1.done();
rc.next();
});
window.addEventListener('hashchange', check_hash);
window.location.hash = "case6";
});
rc.push(_ => {
async1.step(_ => {
document.body.appendChild(div);
async1.next();
});
})
})(window.routeCases);
|
Fix MultiFields admin mit unterkomponenten
statt NonTableForm Form mit OwnModel verwenden, das es ja jetzt gibt.
Macht alles viel einfacher.
problem war dass die list row _nach_ der child row gespeichert wurde und die
child row daher keine id hatte
(von niko) | <?php
class Vpc_Abstract_List_Form extends Vpc_Abstract_Form
{
public function __construct($name, $class)
{
parent::__construct($name, $class);
$this->setProperty('class', $class);
$this->add($this->_getMultiFields());
}
protected function _getMultiFields()
{
$multifields = new Vps_Form_Field_MultiFields('Children');
$multifields->setMinEntries(0);
$multifields->fields->add(new Vps_Form_Field_Checkbox('visible', trlVps('Visible')));
$multifields->setPosition(true);
$form = Vpc_Abstract_Form::createChildComponentForm($this->getClass(), 'child');
$form->setIdTemplate('{component_id}-{id}');
$multifields->fields->add($form);
return $multifields;
}
} | <?php
class Vpc_Abstract_List_Form extends Vps_Form_NonTableForm
{
public function __construct($name, $class)
{
parent::__construct($name, $class);
$this->setProperty('class', $class);
$this->add($this->_getMultiFields());
}
protected function _getMultiFields()
{
$multifields = new Vpc_Abstract_Field_MultiFields($this->getClass());
$multifields->setReferences(array(
'columns' => array('component_id'),
'refColumns' => array('id')
));
$multifields->setMinEntries(0);
$multifields->fields->add(new Vps_Form_Field_Checkbox('visible', trlVps('Visible')));
$multifields->setPosition(true);
$form = Vpc_Abstract_Form::createChildComponentForm($this->getClass(), 'child');
$form->setIdTemplate('{component_id}-{id}');
$multifields->fields->add($form);
return $multifields;
}
} |
Remove the plural from the url | # Copyright 2013 Donald Stufft
#
# 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.
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
from werkzeug.routing import Rule, EndpointPrefix
urls = [
EndpointPrefix("warehouse.packaging.views.", [
Rule(
"/project/<project_name>/",
methods=["GET"],
endpoint="project_detail",
),
Rule(
"/project/<project_name>/<version>/",
methods=["GET"],
endpoint="project_detail",
),
]),
]
| # Copyright 2013 Donald Stufft
#
# 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.
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
from werkzeug.routing import Rule, EndpointPrefix
urls = [
EndpointPrefix("warehouse.packaging.views.", [
Rule(
"/projects/<project_name>/",
methods=["GET"],
endpoint="project_detail",
),
Rule(
"/projects/<project_name>/<version>/",
methods=["GET"],
endpoint="project_detail",
),
]),
]
|
Use safer condition for survey start notification | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from celery.schedules import crontab
from indico.core.celery import celery
from indico.core.db import db
from indico.modules.events.surveys.models.surveys import Survey
@celery.periodic_task(name='survey_start_notifications', run_every=crontab(minute='*/30'))
def send_start_notifications():
active_surveys = Survey.find_all(Survey.is_active, ~Survey.start_notification_sent, Survey.notifications_enabled)
try:
for survey in active_surveys:
survey.send_start_notification()
finally:
db.session.commit()
| # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from celery.schedules import crontab
from indico.core.celery import celery
from indico.core.db import db
from indico.modules.events.surveys.models.surveys import Survey
@celery.periodic_task(name='survey_start_notifications', run_every=crontab(minute='*/30'))
def send_start_notifications():
opened_surveys = Survey.find_all(~Survey.is_deleted, ~Survey.start_notification_sent, Survey.has_started,
Survey.notifications_enabled)
try:
for survey in opened_surveys:
survey.send_start_notification()
finally:
db.session.commit()
|
Return a text attribute for an hover only module | import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['vulnerability'], 'output': ['text']}
moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion hover module to expand information about CVE id.', 'module-type': ['hover']}
moduleconfig = []
cveapi_url = 'https://cve.circl.lu/api/cve/'
def handler(q=False):
if q is False:
return False
print (q)
request = json.loads(q)
if not request.get('vulnerability'):
misperrors['error'] = 'Vulnerability id missing'
return misperrors
r = requests.get(cveapi_url+request.get('vulnerability'))
if r.status_code == 200:
vulnerability = json.loads(r.text)
if vulnerability.get('summary'):
summary = vulnerability['summary']
else:
misperrors['error'] = 'cve.circl.lu API not accessible'
return misperrors['error']
r = {'results': [{'types': mispattributes['output'], 'values': summary}]}
return r
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
| import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['vulnerability'], 'output': ['']}
moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion hover module to expand information about CVE id.', 'module-type': ['hover']}
moduleconfig = []
cveapi_url = 'https://cve.circl.lu/api/cve/'
def handler(q=False):
if q is False:
return False
print (q)
request = json.loads(q)
if not request.get('vulnerability'):
misperrors['error'] = 'Vulnerability id missing'
return misperrors
r = requests.get(cveapi_url+request.get('vulnerability'))
if r.status_code == 200:
vulnerability = json.loads(r.text)
else:
misperrors['error'] = 'cve.circl.lu API not accessible'
return misperrors['error']
return vulnerability
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
|
Fix spec broken previously to test exception | <?php
namespace Spec\PHPSpec2;
use PHPSpec2\SpecificationInterface;
class Stub implements SpecificationInterface
{
public function described_with($stub)
{
$stub->is_an_instance_of('PHPSpec2\Stub');
}
public function registers_matcher_if_it_has_aliases($stub, $matcher)
{
$matcher->is_a_mock_of('PHPSpec2\Matcher\MatcherInterface');
$matcher->getAliases()->should_return(array('should_be_equal'));
$stub->__registerMatcher($matcher);
$stub->__getMatchers()->should_contain(1);
}
public function does_not_registers_matcher_if_it_has_no_aliases($stub, $matcher)
{
$matcher->is_a_mock_of('PHPSpec2\Matcher\MatcherInterface');
$matcher->getAliases()->should_return(array());
$stub->__registerMatcher($matcher);
$stub->__getMatchers()->should_contain(0);
}
}
| <?php
namespace Spec\PHPSpec2;
use PHPSpec2\SpecificationInterface;
class Stub implements SpecificationInterface
{
public function described_with($stub)
{
$stub->is_an_instance_of('PHPSpec2\Stub');
}
public function registers_matcher_if_it_has_aliases($stub, $matcher)
{
$matcher->is_a_mock_of('PHPSpec2\Matcher\MatcherInterface');
$matcher->getAliases()->should_return(array('should_be_equal'));
$stub->__registerMatcher($matcher);
$stub->__getMatchers()->should_contain(2);
}
public function does_not_registers_matcher_if_it_has_no_aliases($stub, $matcher)
{
$matcher->is_a_mock_of('PHPSpec2\Matcher\MatcherInterface');
$matcher->getAliases()->should_return(array());
$stub->__registerMatcher($matcher);
$stub->__getMatchers()->should_contain(0);
}
}
|
Fix migration table class name | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSchedulesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
private $table_name = 'schedules';
public function up()
{
if (Schema::hasTable($this->table_name)) { return; }
Schema::create($this->table_name, function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('command');
$table->string('frequency');
$table->string('ping_before')->nullable();
$table->string('ping_after')->nullable();
$table->integer('active');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop($this->table_name);
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePluginsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
private $table_name = 'schedules';
public function up()
{
if (Schema::hasTable($this->table_name)) { return; }
Schema::create($this->table_name, function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('command');
$table->string('frequency');
$table->string('ping_before')->nullable();
$table->string('ping_after')->nullable();
$table->integer('active');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop($this->table_name);
}
}
|
Implement addition of stops via function; Sort stops by location; | var color = require("color");
var Radient = function(obj) {
if (obj instanceof Radient) return obj;
this.stops = [];
for (var i = 0; i < arguments.length; i++)
this.stops.push({ color: new color(arguments[i]), location: null });
this.distribute();
}
Radient.prototype.distribute = function()
{
n = 1 / (this.stops.length - 1);
for (var i = 0; i < this.stops.length; i++)
this.stops[i].location = i * n;
}
Radient.prototype.stop = function(c, l)
{
l = parseFloat(l);
if(isNaN(l)) throw new Error("Unable to determine stop location: " + l);
this.stops.push({ color: new color(c), location: l });
this.sort();
}
Radient.prototype.sort = function()
{
this.stops.sort(function (a, b) {
return a.location - b.location;
});
}
Radient.prototype.color = function(location)
{
}
Radient.prototype.angle = function(degrees)
{
}
Radient.prototype.array = function(stops)
{
if (this.stops.length < 2) throw new Error("Gradients must have at least two stops");
}
Radient.prototype.toString = function()
{
if (this.stops.length == 0) return 'empty gradient';
r = [];
this.stops.forEach(function(element) {
r.push(element.location + ' ' + element.color.hexString());
});
return r.join("\n");
}
module.exports = Radient;
var g = new Radient();
g.stop('#fff', .2);
g.stop('#fff', 0);
console.log(g + '');
| var color = require("color");
var Radient = function(obj) {
if (obj instanceof Radient) return obj;
this.stops = [];
for (var i = 0; i < arguments.length; i++)
this.stops.push({ color: new color(arguments[i]), location: null });
this.distribute();
}
Radient.prototype.distribute = function()
{
n = 1 / (this.stops.length - 1);
for (var i = 0; i < this.stops.length; i++)
this.stops[i].location = i * n;
}
Radient.prototype.stop = function(color, location)
{
}
Radient.prototype.color = function(location)
{
}
Radient.prototype.angle = function(degrees)
{
}
Radient.prototype.array = function(stops)
{
}
Radient.prototype.toString = function()
{
if (this.stops.length == 0) throw new Error("Gradients must have at least two stops");
r = [] ;
this.stops.forEach(function(element) {
r.push(element.location + ' ' + element.color.hexString());
});
return r.join("\n");
}
module.exports = Radient;
|
Fix up to date checks for PyTarget | from ..target import Target
import hashlib
import dill
import joblib
class PyTarget(Target):
def __init__(self, name, obj=None):
self._name = name
self._obj = obj
super(PyTarget, self).__init__()
if not obj is None:
self.set(obj)
def identifier(self):
return self._name
def get(self):
return self._obj
def set(self, obj):
self._obj = obj
def is_damaged(self):
stored = self.stored()
if stored:
if self._obj is None:
self._obj = stored._obj
return stored._obj is None
else:
return joblib.hash(self._obj) == joblib.hash(stored._obj)
else:
return self._obj is None
| from ..target import Target
import hashlib
import dill
import joblib
class PyTarget(Target):
def __init__(self, name, obj=None):
self._name = name
self._obj = obj
super(PyTarget, self).__init__()
if not obj is None:
self.set(obj)
def identifier(self):
return self._name
def get(self):
return self._obj
def set(self, obj):
self._obj = obj
def checksum(self):
digest = super(PyTarget, self).checksum()
if not self._obj is None:
m = hashlib.sha1()
m.update(digest.encode())
m.update(joblib.hash(self._obj).encode())
return m.hexdigest()
else:
return digest
def is_damaged(self):
if not self._obj is None:
return False
stored = self.stored()
if stored and not stored._obj is None:
self._obj = stored._obj
return False
return True
|
Configure logging in client tests, so client logs show up. | import copy
import json
import os
import unittest
from client.client import Client
from tools.main_util import configure_logging
# To run the tests against the test instance instead,
# set environment variable PMI_DRC_RDR_INSTANCE.
_DEFAULT_INSTANCE = 'http://localhost:8080'
_OFFLINE_BASE_PATH = 'offline'
class BaseClientTest(unittest.TestCase):
def setUp(self):
super(BaseClientTest, self).setUp()
configure_logging()
self.maxDiff = None
instance = os.environ.get('PMI_DRC_RDR_INSTANCE') or _DEFAULT_INSTANCE
creds_file = os.environ.get('TESTING_CREDS_FILE')
self.client = Client(parse_cli=False, default_instance=instance, creds_file=creds_file)
self.offline_client = Client(
base_path=_OFFLINE_BASE_PATH,
parse_cli=False,
default_instance=instance,
creds_file=creds_file)
def assertJsonEquals(self, obj_a, obj_b):
obj_b = copy.deepcopy(obj_b)
for transient_key in ('etag', 'kind', 'meta'):
if transient_key in obj_b:
del obj_b[transient_key]
self.assertMultiLineEqual(_pretty(obj_a), _pretty(obj_b))
def _pretty(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
| import copy
import json
import os
import unittest
from client.client import Client
# To run the tests against the test instance instead,
# set environment variable PMI_DRC_RDR_INSTANCE.
_DEFAULT_INSTANCE = 'http://localhost:8080'
_OFFLINE_BASE_PATH = 'offline'
class BaseClientTest(unittest.TestCase):
def setUp(self):
super(BaseClientTest, self).setUp()
self.maxDiff = None
instance = os.environ.get('PMI_DRC_RDR_INSTANCE') or _DEFAULT_INSTANCE
creds_file = os.environ.get('TESTING_CREDS_FILE')
self.client = Client(parse_cli=False, default_instance=instance, creds_file=creds_file)
self.offline_client = Client(
base_path=_OFFLINE_BASE_PATH,
parse_cli=False,
default_instance=instance,
creds_file=creds_file)
def assertJsonEquals(self, obj_a, obj_b):
obj_b = copy.deepcopy(obj_b)
for transient_key in ('etag', 'kind', 'meta'):
if transient_key in obj_b:
del obj_b[transient_key]
self.assertMultiLineEqual(_pretty(obj_a), _pretty(obj_b))
def _pretty(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
|
Tweak some example fixture ids | # test set for plugin testing
# from IPython import embed
import pytest
class Dut(object):
'fake a device under test'
_allowed = ('a', 'b', 'c')
def __init__(self, mode=None):
self._mode = mode
def get_mode(self):
return self._mode
def set_mode(self, val):
self._mode = val
def check_mode(self):
assert self._mode in self._allowed
# fixtures
@pytest.fixture
def dut(request):
return Dut('c')
@pytest.yield_fixture(params=('a', 'b', 'c'))
def mode(request, dut):
orig_mode = dut.get_mode()
dut.set_mode(request.param)
yield dut
dut.set_mode(orig_mode)
@pytest.yield_fixture(params=['dog', 'cat', 'mouse'])
def inputs(request):
yield request.param
def test_modes(mode):
assert mode.check_mode()
def test_inputs(inputs):
assert inputs < 2
class TestBoth(object):
def test_m(self, mode, inputs):
assert mode.check_mode()
assert inputs < 2
| # test set for plugin testing
# from IPython import embed
import pytest
class Dut(object):
'fake a device under test'
_allowed = ('a', 'b', 'c')
def __init__(self, mode=None):
self._mode = mode
def get_mode(self):
return self._mode
def set_mode(self, val):
self._mode = val
def check_mode(self):
assert self._mode in self._allowed
# fixtures
@pytest.fixture
def dut(request):
return Dut('c')
@pytest.yield_fixture(params=('a', 'b', 'c'))
def mode(request, dut):
orig_mode = dut.get_mode()
dut.set_mode(request.param)
yield dut
dut.set_mode(orig_mode)
@pytest.yield_fixture(params=[1, 2, 3])
def inputs(request):
yield request.param
def test_modes(mode):
assert mode.check_mode()
def test_inputs(inputs):
assert inputs < 2
class TestBoth(object):
def test_m(self, mode, inputs):
assert mode.check_mode()
assert inputs < 2
|
Add ban for pgp/gpg private key blocks | from __future__ import print_function
import argparse
import sys
BLACKLIST = [
b'BEGIN RSA PRIVATE KEY',
b'BEGIN DSA PRIVATE KEY',
b'BEGIN EC PRIVATE KEY',
b'BEGIN OPENSSH PRIVATE KEY',
b'BEGIN PRIVATE KEY',
b'PuTTY-User-Key-File-2',
b'BEGIN SSH2 ENCRYPTED PRIVATE KEY',
b'BEGIN PGP PRIVATE KEY BLOCK',
]
def detect_private_key(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to check')
args = parser.parse_args(argv)
private_key_files = []
for filename in args.filenames:
with open(filename, 'rb') as f:
content = f.read()
if any(line in content for line in BLACKLIST):
private_key_files.append(filename)
if private_key_files:
for private_key_file in private_key_files:
print('Private key found: {}'.format(private_key_file))
return 1
else:
return 0
if __name__ == '__main__':
sys.exit(detect_private_key())
| from __future__ import print_function
import argparse
import sys
BLACKLIST = [
b'BEGIN RSA PRIVATE KEY',
b'BEGIN DSA PRIVATE KEY',
b'BEGIN EC PRIVATE KEY',
b'BEGIN OPENSSH PRIVATE KEY',
b'BEGIN PRIVATE KEY',
b'PuTTY-User-Key-File-2',
b'BEGIN SSH2 ENCRYPTED PRIVATE KEY',
]
def detect_private_key(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to check')
args = parser.parse_args(argv)
private_key_files = []
for filename in args.filenames:
with open(filename, 'rb') as f:
content = f.read()
if any(line in content for line in BLACKLIST):
private_key_files.append(filename)
if private_key_files:
for private_key_file in private_key_files:
print('Private key found: {}'.format(private_key_file))
return 1
else:
return 0
if __name__ == '__main__':
sys.exit(detect_private_key())
|
Revert "Resize only when UA matches iPad"
This reverts commit d5260394049c993a4f4ddcea3cbe694212c36f38. | (function() {
var target = $('.archives li').slice(7);
target.each(function() {
$(this).css("display", "none");
})
$('#show_more_archive_list').click(function() {
target.each(function() {
$(this).slideDown();
})
$(this).hide();
$('#show_less_archive_list').show();
})
$('#show_less_archive_list').click(function() {
target.each(function() {
$(this).slideUp();
})
$(this).hide();
$('#show_more_archive_list').show();
})
var init = function(node) {
// fit image for iPhone
/* if (navigator.userAgent.match(/iPad/)) { */
/* } */
}
document.body.addEventListener('AutoPagerize_DOMNodeInserted',function(evt){
var node = evt.target;
var requestURL = evt.newValue;
var parentNode = evt.relatedNode;
init(node);
}, false);
init(document);
})();
window.onload = function() {
$('.article img').each(function() {
var newWidth = document.body.offsetWidth - 60;
var imageRatio = this.naturalHeight / this.naturalWidth;
if (this.naturalWidth > newWidth) {
this.width = newWidth;
this.height = newWidth * imageRatio;
}
});
};
| (function() {
var target = $('.archives li').slice(7);
target.each(function() {
$(this).css("display", "none");
})
$('#show_more_archive_list').click(function() {
target.each(function() {
$(this).slideDown();
})
$(this).hide();
$('#show_less_archive_list').show();
})
$('#show_less_archive_list').click(function() {
target.each(function() {
$(this).slideUp();
})
$(this).hide();
$('#show_more_archive_list').show();
})
var init = function(node) {
}
document.body.addEventListener('AutoPagerize_DOMNodeInserted',function(evt){
var node = evt.target;
var requestURL = evt.newValue;
var parentNode = evt.relatedNode;
init(node);
}, false);
init(document);
})();
window.onload = function() {
// fit image for iPad
if (navigator.userAgent.match(/iPad/)) {
$('.article img').each(function() {
var newWidth = document.body.offsetWidth - 60;
var imageRatio = this.naturalHeight / this.naturalWidth;
if (this.naturalWidth > newWidth) {
this.width = newWidth;
this.height = newWidth * imageRatio;
}
});
}
};
|
Handle correctly error from epubcheck | var _ = require('lodash');
var path = require('path');
var exec = require('child_process').exec;
var LOG_TYPES = [
"ERROR", "WARNING"
];
module.exports = function(filepath, options, callback) {
if (!callback) {
callback = options;
options = {};
}
options = _.defaults(options || {}, {
epubcheck: "epubcheck"
});
filepath = path.resolve(process.cwd(), filepath);
var command = options.epubcheck+" "+filepath+" -q";
exec(command, function (error, stdout, stderr) {
var output = stderr.toString();
var lines = stderr.split("\n");
var err = null;
lines = _.chain(lines)
.map(function(line) {
var parts = line.split(":");
if (!_.contains(LOG_TYPES, parts[0])) return null;
var type = parts[0].toLowerCase();
var content = parts.slice(1).join(":");
if (type == "error") {
err = new Error(content);
}
return {
'type': type,
'content': content
};
})
.compact()
.value();
if (error && !err) err = error;
callback(err, {
messages: lines
});
});
};
| var _ = require('lodash');
var path = require('path');
var exec = require('child_process').exec;
var LOG_TYPES = [
"ERROR", "WARNING"
];
module.exports = function(filepath, options, callback) {
if (!callback) {
callback = options;
options = {};
}
options = _.defaults(options || {}, {
epubcheck: "epubcheck"
});
filepath = path.resolve(process.cwd(), filepath);
var command = options.epubcheck+" "+filepath+" -q";
exec(command, function (error, stdout, stderr) {
var output = stderr.toString();
var lines = stderr.split("\n");
error = null;
lines = _.chain(lines)
.map(function(line) {
var parts = line.split(":");
if (!_.contains(LOG_TYPES, parts[0])) return null;
var type = parts[0].toLowerCase();
var content = parts.slice(1).join(":");
if (type == "error") {
error = new Error(content);
}
return {
'type': type,
'content': content
};
})
.compact()
.value();
callback(error, {
messages: lines
});
});
};
|
Add quotes to long form output | import binascii
import os
import time
from optparse import OptionParser
def gen_random_object_id():
timestamp = '{0:x}'.format(int(time.time()))
rest = binascii.b2a_hex(os.urandom(8))
return timestamp + rest
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('-l', '--longform',
action="store_true",
dest="long_form",
help="prints the ID surrounded by ObjectId(...)")
(options, args) = parser.parse_args()
object_id = gen_random_object_id()
if options.long_form:
print 'ObjectId("{}")'.format(object_id)
else:
print object_id
| import binascii
import os
import time
from optparse import OptionParser
def gen_random_object_id():
timestamp = '{0:x}'.format(int(time.time()))
rest = binascii.b2a_hex(os.urandom(8))
return timestamp + rest
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('-l', '--longform',
action="store_true",
dest="long_form",
help="prints the ID surrounded by ObjectId(...)")
(options, args) = parser.parse_args()
object_id = gen_random_object_id()
if options.long_form:
print 'ObjectId({})'.format(object_id)
else:
print object_id
|
Use env port for app to listen on | module.exports = (function () {
'use strict';
var config = {
development: {
server: {
port: 3000
},
wsapp: {
port: 3334
}
},
testing: {
server: {
port: 3001
},
wsapp: {
port: 3334
}
},
production: {
server: {
port: process.env.PORT || 8080
},
wsapp: {
port: 3334
}
}
};
return config[process.env.NODE_ENV || 'development'];
})();
| module.exports = (function () {
'use strict';
var config = {
development: {
server: {
port: 3000
},
wsapp: {
port: 3334
}
},
testing: {
server: {
port: 3001
},
wsapp: {
port: 3334
}
},
production: {
server: {
port: 8080
},
wsapp: {
port: 3334
}
}
};
return config[process.env.NODE_ENV || 'development'];
})();
|
Make sure we only travers arrays | module.exports = function (vnode) {
var result = {}
function parser (res, vnode) {
var attrs = vnode.attrs || {}
function append (name, value) {
(res[name] = res[name] || []).push(value)
}
if (!(attrs.name == null)) {
if (['checkbox', 'radio'].indexOf(attrs.type) > -1) {
if (attrs.checked) {
if (!(attrs.value == null)) {
append(attrs.name, attrs.value)
} else {
append(attrs.name, true)
}
}
} else if (!(attrs.value == null)) {
append(attrs.name, attrs.value)
}
}
if (vnode.children instanceof Array) {
(vnode.children || []).reduce(parser, res)
}
return res
}
parser(result, vnode)
Object.keys(result).forEach(function (key) {
if (result[key].length === 1) result[key] = result[key][0]
})
return result
}
| module.exports = function (vnode) {
var result = {}
function parser (res, vnode) {
var attrs = vnode.attrs || {}
function append (name, value) {
(res[name] = res[name] || []).push(value)
}
if (!(attrs.name == null)) {
if (['checkbox', 'radio'].indexOf(attrs.type) > -1) {
if (attrs.checked) {
if (!(attrs.value == null)) {
append(attrs.name, attrs.value)
} else {
append(attrs.name, true)
}
}
} else if (!(attrs.value == null)) {
append(attrs.name, attrs.value)
}
}
(vnode.children || []).reduce(parser, res)
return res
}
parser(result, vnode)
Object.keys(result).forEach(function (key) {
if (result[key].length === 1) result[key] = result[key][0]
})
return result
}
|
Store output instead of calculating it each time | from random import random
class Neuron:
output = None
def __init__(self, parents=[]):
self.parents = parents
self.weights = [random() for parent in parents]
def calculate(self):
self.output = sum([parent.output * self.weights[i] for i, parent in enumerate(self.parents)]) >= 1
class NeuronNetwork:
neurons = []
def __init__(self, inputs, outputs, rows, columns):
self.neurons = []
for row in xrange(rows + 2):
self.neurons.append([])
if row == 0:
for input_ in xrange(inputs):
self.neurons[row].append(Neuron(parents=[]))
elif row == rows + 1:
for output in xrange(outputs):
self.neurons[row].append(Neuron(parents=self.neurons[row - 1]))
else:
for column in xrange(columns):
self.neurons[row].append(Neuron(parents=self.neurons[row - 1]))
| from random import random
class Neuron:
def __init__(self, parents=[]):
self.parents = parents
self.weights = [random() for parent in parents]
def get_output(self):
return sum([parent.output * self.weights[i] for i, parent in enumerate(self.parents)]) >= 1
output = property(get_output)
class NeuronNetwork:
neurons = []
def __init__(self, inputs, outputs, rows, columns):
self.neurons = []
for row in xrange(rows + 2):
self.neurons.append([])
if row == 0:
for input_ in xrange(inputs):
self.neurons[row].append(Neuron(parents=[]))
elif row == rows + 1:
for output in xrange(outputs):
self.neurons[row].append(Neuron(parents=self.neurons[row - 1]))
else:
for column in xrange(columns):
self.neurons[row].append(Neuron(parents=self.neurons[row - 1]))
|
Update SessionMiddleware to bypass CSRF if request token is present
For non-session-based authentication, Serrano resources handle
authenticating using a token based approach. If it is present, CSRF
must be turned off to exempt the resources from the check. | from .tokens import get_request_token
class SessionMiddleware(object):
def process_request(self, request):
if getattr(request, 'user', None) and request.user.is_authenticated():
return
# Token-based authentication is attempting to be used, bypass CSRF
# check
if get_request_token(request):
request.csrf_processing_done = True
return
session = request.session
# Ensure the session is created view processing, but only if a cookie
# had been previously set. This is to prevent creating exorbitant
# numbers of sessions for non-browser clients, such as bots.
if session.session_key is None:
if session.test_cookie_worked():
session.delete_test_cookie()
request.session.create()
else:
session.set_test_cookie()
| class SessionMiddleware(object):
def process_request(self, request):
if getattr(request, 'user', None) and request.user.is_authenticated():
return
session = request.session
# Ensure the session is created view processing, but only if a cookie
# had been previously set. This is to prevent creating exorbitant
# numbers of sessions non-browser clients, such as bots.
if session.session_key is None:
if session.test_cookie_worked():
session.delete_test_cookie()
request.session.create()
else:
session.set_test_cookie()
|
Change initial year in map for 100 years ago from now | $().ready(function(){
function init(){
var initialYear = new Date().getFullYear() - 100;
renderMap();
requestYears(function(years, formattedYears){
renderSlider(years, formattedYears, {
onChange: function(currentYear){
requestInfluences(currentYear, function(influences){
renderInfluencesInMap(influences);
});
},
onInit: function(){
requestInfluences(initialYear, function(influences){
renderInfluencesInMap(influences);
});
}
});
});
listenSearch({
onSearch: function(term){
requestYearByInfluenceName(term, function(year){
changeSliderTo(year);
requestInfluences(year, function(influences){
renderInfluencesInMap(influences);
});
})
}
});
listenRequestYear({
onSearch: function(year){
changeSliderTo(year);
requestInfluences(year, function(influences){
renderInfluencesInMap(influences);
});
}
});
}
init();
});
| $().ready(function(){
function init(){
renderMap();
requestYears(function(years, formattedYears){
renderSlider(years, formattedYears, {
onChange: function(currentYear){
requestInfluences(currentYear, function(influences){
renderInfluencesInMap(influences);
});
},
onInit: function(){
requestInfluences(years[0], function(influences){
renderInfluencesInMap(influences);
});
}
});
});
listenSearch({
onSearch: function(term){
requestYearByInfluenceName(term, function(year){
changeSliderTo(year);
requestInfluences(year, function(influences){
renderInfluencesInMap(influences);
});
})
}
});
listenRequestYear({
onSearch: function(year){
changeSliderTo(year);
requestInfluences(year, function(influences){
renderInfluencesInMap(influences);
});
}
});
}
init();
});
|
Remove legacy fields from exhibition test | <?php
namespace Tests\Unit;
use App\Models\Collections\Exhibition;
use App\Models\Collections\Place;
use App\Models\Collections\Agent;
class ExhibitionTest extends ApiTestCase
{
protected $model = Exhibition::class;
protected $keys = ['lake_guid'];
/**
* @link https://github.com/art-institute-of-chicago/aic-mobile-cms/blob/b74ddc9/sites/all/modules/custom/aicapp/includes/aicapp.admin.inc#L788
* @link https://github.com/art-institute-of-chicago/aic-mobile-ios/blob/72bb520/aic/aic/Data/SearchDataManager.swift#L132
*/
protected $fieldsUsedByMobile = [
'id',
'title',
'status',
// 'description',
'short_description',
// 'image_iiif_url',
'gallery_id',
'web_url',
'aic_start_at',
'aic_end_at',
];
public function setUp()
{
parent::setUp();
$this->make(Place::class, ['type' => 'AIC Gallery']);
$this->times(5)->make(Agent::class);
}
}
| <?php
namespace Tests\Unit;
use App\Models\Collections\Exhibition;
use App\Models\Collections\Place;
use App\Models\Collections\Agent;
class ExhibitionTest extends ApiTestCase
{
protected $model = Exhibition::class;
protected $keys = ['lake_guid'];
/**
* @link https://github.com/art-institute-of-chicago/aic-mobile-cms/blob/b74ddc9/sites/all/modules/custom/aicapp/includes/aicapp.admin.inc#L788
* @link https://github.com/art-institute-of-chicago/aic-mobile-ios/blob/72bb520/aic/aic/Data/SearchDataManager.swift#L132
*/
protected $fieldsUsedByMobile = [
'id',
'title',
'status',
// 'description',
'short_description',
// 'image_iiif_url',
'legacy_image_mobile_url',
'legacy_image_desktop_url',
'gallery_id',
'web_url',
'aic_start_at',
'aic_end_at',
];
public function setUp()
{
parent::setUp();
$this->make(Place::class, ['type' => 'AIC Gallery']);
$this->times(5)->make(Agent::class);
}
}
|
Use correct order of postcss plugins | /**
* Module dependencies
*/
var autoprefixer = require('autoprefixer');
var postcss = require('postcss');
var atImport = require('postcss-import');
var calc = require('postcss-calc');
var customMedia = require('postcss-custom-media');
var customProperties = require('postcss-custom-properties');
var reporter = require('postcss-reporter');
var bemLinter = require('postcss-bem-linter');
/**
* Module export
*/
module.exports = preprocessor;
/**
* Process CSS
*
* @param {String} css
* @return {String}
*/
function preprocessor(css, options) {
if (typeof css !== 'string') {
throw new Error('suitcss-preprocessor: did not receive a String');
}
options = options || {};
css = postcss([
atImport({
root: options.root,
transform: function(css, filename) {
return postcss([bemLinter, reporter]).process(css, {from: filename}).css;
}
}),
customProperties,
calc,
customMedia,
autoprefixer({browsers: options.browsers}),
reporter({clearMessages: true})
]).process(css).css;
return css;
}
| /**
* Module dependencies
*/
var autoprefixer = require('autoprefixer');
var postcss = require('postcss');
var atImport = require('postcss-import');
var calc = require('postcss-calc');
var customMedia = require('postcss-custom-media');
var customProperties = require('postcss-custom-properties');
var reporter = require('postcss-reporter');
var bemLinter = require('postcss-bem-linter');
/**
* Module export
*/
module.exports = preprocessor;
/**
* Process CSS
*
* @param {String} css
* @return {String}
*/
function preprocessor(css, options) {
if (typeof css !== 'string') {
throw new Error('suitcss-preprocessor: did not receive a String');
}
options = options || {};
css = postcss([
atImport({
root: options.root,
transform: function(css, filename) {
return postcss([bemLinter, reporter]).process(css, {from: filename}).css;
}
}),
calc,
customProperties,
customMedia,
autoprefixer({browsers: options.browsers}),
reporter({clearMessages: true})
]).process(css).css;
return css;
}
|
Send messages to broadcast connected topic. | package registration
import (
"github.com/opsee/portmapper"
)
const (
ipFilePathDefault = "/gozer/state/ip"
nsqdTopic = "_.connected"
)
var (
// The location of the file produced by OpenVPN containing the instance IP.
IPFilePath string
)
func init() {
IPFilePath = ipFilePathDefault
}
// /opsee.co/routes/customer_id/instance_id/svcname = ip:port
type connectedMessage struct {
CustomerID string `json:"customer_id"`
BastionID string `json:"bastion_id"`
InstanceID string `json:"instance_id"`
IPAddress string `json:"ip_address"`
Services []*portmapper.Service `json:"services"`
Timestamp int64 `json:"timestamp"`
}
// Service provides registration with Opsee of components exposed by
// portmapper.
type Service interface {
Start() error
Stop() error
}
| package registration
import (
"github.com/opsee/portmapper"
)
const (
ipFilePathDefault = "/gozer/state/ip"
nsqdTopic = "connected"
)
var (
// The location of the file produced by OpenVPN containing the instance IP.
IPFilePath string
)
func init() {
IPFilePath = ipFilePathDefault
}
// /opsee.co/routes/customer_id/instance_id/svcname = ip:port
type connectedMessage struct {
CustomerID string `json:"customer_id"`
BastionID string `json:"bastion_id"`
InstanceID string `json:"instance_id"`
IPAddress string `json:"ip_address"`
Services []*portmapper.Service `json:"services"`
Timestamp int64 `json:"timestamp"`
}
// Service provides registration with Opsee of components exposed by
// portmapper.
type Service interface {
Start() error
Stop() error
}
|
Tidy up and expect warning | # coding: utf-8
from __future__ import unicode_literals
import pytest
from spacy.kb import KnowledgeBase
from spacy.util import ensure_path
from spacy.lang.en import English
from ..tests.util import make_tempdir
def test_issue4674():
"""Test that setting entities with overlapping identifiers does not mess up IO"""
nlp = English()
kb = KnowledgeBase(nlp.vocab, entity_vector_length=3)
vector1 = [0.9, 1.1, 1.01]
vector2 = [1.8, 2.25, 2.01]
with pytest.warns(UserWarning):
kb.set_entities(
entity_list=["Q1", "Q1"],
freq_list=[32, 111],
vector_list=[vector1, vector2],
)
assert kb.get_size_entities() == 1
# dumping to file & loading back in
with make_tempdir() as d:
dir_path = ensure_path(d)
if not dir_path.exists():
dir_path.mkdir()
file_path = dir_path / "kb"
kb.dump(str(file_path))
kb2 = KnowledgeBase(vocab=nlp.vocab, entity_vector_length=3)
kb2.load_bulk(str(file_path))
assert kb2.get_size_entities() == 1
| # coding: utf-8
from __future__ import unicode_literals
from spacy.kb import KnowledgeBase
from spacy.util import ensure_path
from spacy.lang.en import English
from spacy.tests.util import make_tempdir
def test_issue4674():
"""Test that setting entities with overlapping identifiers does not mess up IO"""
nlp = English()
kb = KnowledgeBase(nlp.vocab, entity_vector_length=3)
vector1 = [0.9, 1.1, 1.01]
vector2 = [1.8, 2.25, 2.01]
kb.set_entities(
entity_list=["Q1", "Q1"], freq_list=[32, 111], vector_list=[vector1, vector2]
)
assert kb.get_size_entities() == 1
# dumping to file & loading back in
with make_tempdir() as d:
dir_path = ensure_path(d)
if not dir_path.exists():
dir_path.mkdir()
file_path = dir_path / "kb"
kb.dump(str(file_path))
kb2 = KnowledgeBase(vocab=nlp.vocab, entity_vector_length=3)
kb2.load_bulk(str(file_path))
assert kb2.get_size_entities() == 1
|
[FIX] Fix rendering for stories with no icon | import React from 'react';
import PropTypes from 'prop-types';
import autobind from 'core-decorators/es/autobind';
import MarkdownRenderer from '../../../../lib/react/components/MarkdownRenderer';
import '../scss/components/_story.scss';
class Story extends React.Component {
static propTypes = {
story: PropTypes.shape({
_id: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
createdBy: PropTypes.string.isRequired,
publishDate: PropTypes.string.isRequired,
iconName: PropTypes.string.isRequired,
intent: PropTypes.string.isRequired,
content: PropTypes.string.isRequired,
likes: PropTypes.array.isRequired
}),
disableLike: PropTypes.bool
}
static defaultProps = {
disableLike: false
}
render() {
const { _id, type, createdBy, publishDate, iconName, intent, content, likes } = this.props.story;
return (
<div className={`pt-callout pt-intent-${intent} ${iconName?`pt-icon-${iconName}`:``} story`}>
<div className='instruction-panel'>
<MarkdownRenderer className='markdown-content' src={content}/>
<div style={{marginTop:'0.2rem',display:'flex',flexDirection:'row-reverse'}}>
<small className='pt-text-muted'>
{createdBy ? `${createdBy}` : `Auto-generated`}
</small>
</div>
</div>
</div>
);
}
}
export default Story;
| import React from 'react';
import PropTypes from 'prop-types';
import autobind from 'core-decorators/es/autobind';
import MarkdownRenderer from '../../../../lib/react/components/MarkdownRenderer';
import '../scss/components/_story.scss';
class Story extends React.Component {
static propTypes = {
story: PropTypes.shape({
_id: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
createdBy: PropTypes.string.isRequired,
publishDate: PropTypes.string.isRequired,
iconName: PropTypes.string.isRequired,
intent: PropTypes.string.isRequired,
content: PropTypes.string.isRequired,
likes: PropTypes.array.isRequired
}),
disableLike: PropTypes.bool
}
static defaultProps = {
disableLike: false
}
render() {
const { _id, type, createdBy, publishDate, iconName, intent, content, likes } = this.props.story;
return (
<div className={`pt-callout pt-intent-${intent} pt-icon-${iconName} story`}>
<div className='instruction-panel'>
<MarkdownRenderer className='markdown-content' src={content}/>
<div style={{marginTop:'0.2rem',display:'flex',flexDirection:'row-reverse'}}>
<small className='pt-text-muted'>
{createdBy ? `${createdBy}` : `Auto-generated`}
</small>
</div>
</div>
</div>
);
}
}
export default Story;
|
Fix: Add missing parameter to method signature | <?php
/*
* Copyright (c) 2016 Refinery29, Inc.
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace spec\Refinery29\Piston\Stub;
use Refinery29\ApiOutput\Resource\ResourceFactory;
use Refinery29\Piston\ApiResponse;
use Refinery29\Piston\Request;
use Zend\Diactoros\Response\HtmlResponse;
class FooController
{
public function fooAction(Request $req, ApiResponse $resp)
{
return $resp;
}
public function test(Request $req, ApiResponse $response, array $vars)
{
$response->setResult(ResourceFactory::result(['something' => 'yolo']));
return $response;
}
public function testHTMLResponse()
{
return new HTMLResponse('<p>Hello World</p>');
}
}
| <?php
/*
* Copyright (c) 2016 Refinery29, Inc.
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace spec\Refinery29\Piston\Stub;
use Refinery29\ApiOutput\Resource\ResourceFactory;
use Refinery29\Piston\ApiResponse;
use Refinery29\Piston\Request;
use Zend\Diactoros\Response\HtmlResponse;
class FooController
{
public function fooAction(Request $req, ApiResponse $resp)
{
return $resp;
}
public function test(Request $req, ApiResponse $response)
{
$response->setResult(ResourceFactory::result(['something' => 'yolo']));
return $response;
}
public function testHTMLResponse()
{
return new HTMLResponse('<p>Hello World</p>');
}
}
|
[TASK] Add index option to grunt-conncet server | module.exports = function (grunt) {
grunt.config.merge({
connect: {
server: {
options: {
base: {
path: 'build',
options: {
index: 'index.html'
}
},
livereload: true
}
}
},
watch: {
sources: {
options: {
livereload: true
},
files: ["*.css", "app.js", "lib/**/*.js", "*.html"],
tasks: ["default"]
},
config: {
options: {
reload: true
},
files: ["Gruntfile.js", "tasks/*.js"],
tasks: []
}
}
});
grunt.loadNpmTasks("grunt-contrib-connect");
grunt.loadNpmTasks("grunt-contrib-watch");
};
| module.exports = function (grunt) {
grunt.config.merge({
connect: {
server: {
options: {
base: "build/", //TODO: once grunt-contrib-connect 0.9 is released, set index file
livereload: true
}
}
},
watch: {
sources: {
options: {
livereload: true
},
files: ["*.css", "app.js", "lib/**/*.js", "*.html"],
tasks: ["default"]
},
config: {
options: {
reload: true
},
files: ["Gruntfile.js", "tasks/*.js"],
tasks: []
}
}
});
grunt.loadNpmTasks("grunt-contrib-connect");
grunt.loadNpmTasks("grunt-contrib-watch");
};
|
Add final modifier to internet date-time field. | package app.android.gambit.remote;
import java.util.Date;
import android.text.format.Time;
public class InternetDateTime
{
private final Time time;
public InternetDateTime() {
time = new Time(Time.TIMEZONE_UTC);
time.setToNow();
}
public InternetDateTime(String dateTimeAsString) {
time = new Time(Time.TIMEZONE_UTC);
time.parse3339(dateTimeAsString);
}
public InternetDateTime(Date dateTimeAsUtcDate) {
time = new Time(Time.TIMEZONE_UTC);
time.set(dateTimeAsUtcDate.getTime());
}
@Override
public String toString() {
return time.format3339(false);
}
public Date toDate() {
return new Date(time.toMillis(false));
}
public boolean isAfter(InternetDateTime dateTime) {
return time.after(dateTime.time);
}
public boolean isBefore(InternetDateTime dateTime) {
return time.before(dateTime.time);
}
}
| package app.android.gambit.remote;
import java.util.Date;
import android.text.format.Time;
public class InternetDateTime
{
private Time time;
public InternetDateTime() {
time = new Time(Time.TIMEZONE_UTC);
time.setToNow();
}
public InternetDateTime(String dateTimeAsString) {
time = new Time(Time.TIMEZONE_UTC);
time.parse3339(dateTimeAsString);
}
public InternetDateTime(Date dateTimeAsUtcDate) {
time = new Time(Time.TIMEZONE_UTC);
time.set(dateTimeAsUtcDate.getTime());
}
@Override
public String toString() {
return time.format3339(false);
}
public Date toDate() {
return new Date(time.toMillis(false));
}
public boolean isAfter(InternetDateTime dateTime) {
return time.after(dateTime.time);
}
public boolean isBefore(InternetDateTime dateTime) {
return time.before(dateTime.time);
}
}
|
JCR-2357: Duplicate entries in the index
- javadoc
git-svn-id: 02b679d096242155780e1604e997947d154ee04a@828343 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.core.observation;
import javax.jcr.observation.EventIterator;
import javax.jcr.observation.EventListener;
/**
* Defines a marker interface for {@link javax.jcr.observation.EventListener}
* implementations that wish a synchronous notification of changes to the
* workspace. That is, a <code>SynchronousEventListener</code> is called before
* the call to {@link javax.jcr.Item#save()} returns. In contrast, a regular
* {@link javax.jcr.observation.EventListener} might be called after
* <code>save()</code> returns.
* <p/>
* <b>Important note</b>: an implementation of {@link SynchronousEventListener}
* <b>must not</b> modify content with the thread that calls {@link
* #onEvent(EventIterator)} otherwise inconsistencies may occur.
*/
public interface SynchronousEventListener extends EventListener {
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.core.observation;
import javax.jcr.observation.EventListener;
/**
* Defines a marker interface for {@link javax.jcr.observation.EventListener}
* implementations that wish a synchronous notification of changes to the
* workspace. That is, a <code>SynchronousEventListener</code> is called before
* the call to {@link javax.jcr.Item#save()} returns. In contrast, a regular
* {@link javax.jcr.observation.EventListener} might be called after
* <code>save()</code> returns.
*/
public interface SynchronousEventListener extends EventListener {
}
|
Add newsig.c as a dependency to sigtools module. | #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h', 'newsig.c']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
BlazeApkBuildStep: Build android_binary targets on rabbit
This CL implements an alternate flow for building android_binary
targets that is specific to Google3/Blaze. In this iteration, it
only supports building on rabbit and then deploying locally via
Studio. It is only enabled in a very limited set of conditions:
the IDE is running off corp, and mdproxy is running w/o sshfs
enabled.
Other types of build (blaze and rabbit via mdproxy) will be
supported once b/225936997 is fixed.
Tests will be added in a follow up CL.
PiperOrigin-RevId: 436469354 | /*
* Copyright 2020 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.android.run.binary.mobileinstall;
import com.google.idea.common.experiments.FeatureRolloutExperiment;
/**
* A utility class that manages the experiment to use studio's built in deployer for deploying apks
* instead of using the one present in mobile-install.
*/
public class StudioDeployerExperiment {
/** Indicates if we should deploy via Studio or via MI. */
private static final FeatureRolloutExperiment useStudioDeployer =
new FeatureRolloutExperiment("aswb.use.studio.deployer");
/** Returns whether mobile install deployments should happen via the studio deployer. */
public static boolean isEnabled() {
return useStudioDeployer.isEnabled();
}
private StudioDeployerExperiment() {}
}
| /*
* Copyright 2020 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.android.run.binary.mobileinstall;
import com.google.idea.common.experiments.FeatureRolloutExperiment;
import com.intellij.openapi.util.SystemInfo;
/**
* A utility class that manages the experiment to use studio's built in deployer for deploying apks
* instead of using the one present in mobile-install.
*/
public class StudioDeployerExperiment {
/** Indicates if we should deploy via Studio or via MI. */
private static final FeatureRolloutExperiment useStudioDeployer =
new FeatureRolloutExperiment("aswb.use.studio.deployer");
/** Returns whether mobile install deployments should happen via the studio deployer. */
public static boolean isEnabled() {
if (!SystemInfo.isLinux) {
// TODO(b/197761450): Enable this for Macs after mdproxy related issues are sorted out.
return false;
}
return useStudioDeployer.isEnabled();
}
private StudioDeployerExperiment() {}
}
|
Allow tests to find mothership module | import os, sys
import pytest
""" So PYTHONPATH enviroment variable doesn't have to
be set for pytest to find mothership module. """
curdir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(curdir,'..'))
from mothership import create_app, settings
from mothership import db as _db
@pytest.fixture(scope='session')
def app(request):
app = create_app('mothership.settings.TestConfig')
# Establish an application context before running the tests.
ctx = app.app_context()
ctx.push()
def teardown():
ctx.pop()
request.addfinalizer(teardown)
return app
@pytest.fixture(scope='session')
def db(app, request):
"""Session-wide test database."""
if os.path.exists(settings.db_file.name):
os.unlink(settings.db_file.name)
_db.app = app
_db.create_all()
request.addfinalizer(_db.drop_all)
return _db
@pytest.fixture(scope='function')
def session(db, request):
"""Creates a new database session for a test."""
connection = db.engine.connect()
transaction = connection.begin()
options = dict(bind=connection, binds={})
session = db.create_scoped_session(options=options)
db.session = session
def teardown():
transaction.rollback()
connection.close()
session.remove()
request.addfinalizer(teardown)
return session | import os
import pytest
from mothership import create_app, settings
from mothership import db as _db
@pytest.fixture(scope='session')
def app(request):
app = create_app('mothership.settings.TestConfig')
# Establish an application context before running the tests.
ctx = app.app_context()
ctx.push()
def teardown():
ctx.pop()
request.addfinalizer(teardown)
return app
@pytest.fixture(scope='session')
def db(app, request):
"""Session-wide test database."""
if os.path.exists(settings.db_file.name):
os.unlink(settings.db_file.name)
_db.app = app
_db.create_all()
request.addfinalizer(_db.drop_all)
return _db
@pytest.fixture(scope='function')
def session(db, request):
"""Creates a new database session for a test."""
connection = db.engine.connect()
transaction = connection.begin()
options = dict(bind=connection, binds={})
session = db.create_scoped_session(options=options)
db.session = session
def teardown():
transaction.rollback()
connection.close()
session.remove()
request.addfinalizer(teardown)
return session |
Resolve conflict by keeping voteCount response argument. | $(document).ready( function () {
$(".upvote").click( function() {
var commentId = $(".upvote").data("id");
event.preventDefault();
$.ajax({
url: '/response/up_vote',
method: 'POST',
data: { id: commentId },
dataType: 'JSON'
}).done( function (voteCount) {
if (voteCount == 1) {
$("span[data-id=" + commentId + "]").html(voteCount + " vote");
} else {
$("span[data-id=" + commentId + "]").html(voteCount + " vote");
}
}).fail( function (voteCount) {
console.log("Failed. Here is the voteCount:");
console.log(voteCount);
})
})
})
| $(document).ready( function () {
$(".upvote").click( function() {
var commentId = $(".upvote").data("id");
event.preventDefault();
$.ajax({
url: '/response/up_vote',
method: 'POST',
data: { id: commentId },
dataType: 'JSON'
}).done( function (voteCount) {
if (voteCount == 1) {
$("span[data-id=" + commentId + "]").html(voteCount + " vote");
} else {
$("span[data-id=" + commentId + "]").html(voteCount + " vote");
}
<<<<<<< HEAD
}).fail( function (failureInfo) {
console.log("Failed. Here is why:");
console.log(failureInfo.responseText);
=======
}).fail( function (voteCount) {
console.log("Failed. Here is the voteCount:");
console.log(voteCount);
>>>>>>> a76a56efe80d8fc8fbcd580fa39d90ee5616421d
})
})
})
|
Add version + build to window title | package main
import (
"flag"
"log"
"os"
"runtime/pprof"
"github.com/hajimehoshi/ebiten"
"github.com/ranchblt/labyrinthofthechimera/labyrinth"
)
// Version is autoset from the build script
var Version string
// Build is autoset from the build script
var Build string
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
var debug = flag.Bool("debug", false, "Turns on debug lines and debug messaging")
func main() {
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatal(err)
}
defer pprof.StopCPUProfile()
}
game := labyrinth.NewGame(debug)
update := game.Update
if err := ebiten.Run(update, labyrinth.ScreenWidth, labyrinth.ScreenHeight, 1, "Labrinth of the Chimera "+Version+" "+Build); err != nil {
log.Fatal(err)
}
}
| package main
import (
"flag"
"log"
"os"
"runtime/pprof"
"github.com/hajimehoshi/ebiten"
"github.com/ranchblt/labyrinthofthechimera/labyrinth"
)
// Version is autoset from the build script
var Version string
// Build is autoset from the build script
var Build string
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
var debug = flag.Bool("debug", false, "Turns on debug lines and debug messaging")
func main() {
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatal(err)
}
defer pprof.StopCPUProfile()
}
game := labyrinth.NewGame(debug)
update := game.Update
if err := ebiten.Run(update, labyrinth.ScreenWidth, labyrinth.ScreenHeight, 1, "Labrinth of the Chimera"); err != nil {
log.Fatal(err)
}
}
|
Make Sure the Article ID is an Integer | <?php
/*
* This file is part of pmg/three-repositories
*
* Copyright (c) PMG <https://www.pmg.com>
*
* For full copyright information see the LICENSE file distributed
* with this source code.
*
* @license http://opensource.org/licenses/MIT MIT
*/
namespace PMG\ThreeRepositories;
/**
* An implementation of articles that's just private properties and the
* interface implementation.
*
* @since 0.1
*/
class SimpleArticle implements Article
{
private $id;
private $title;
private $body;
private $year;
public function __construct($id=null)
{
$this->id = null === $id ? $id : intval($id);
}
public function getIdentifier()
{
return $this->id;
}
public function getTitle()
{
return $this->title;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getBody()
{
return $this->body;
}
public function setBody($body)
{
$this->body = $body;
}
public function getYear()
{
return $this->year;
}
public function setYear($year)
{
$this->year = $year;
}
}
| <?php
/*
* This file is part of pmg/three-repositories
*
* Copyright (c) PMG <https://www.pmg.com>
*
* For full copyright information see the LICENSE file distributed
* with this source code.
*
* @license http://opensource.org/licenses/MIT MIT
*/
namespace PMG\ThreeRepositories;
/**
* An implementation of articles that's just private properties and the
* interface implementation.
*
* @since 0.1
*/
class SimpleArticle implements Article
{
private $id;
private $title;
private $body;
private $year;
public function __construct($id=null)
{
$this->id = $id;
}
public function getIdentifier()
{
return $this->id;
}
public function getTitle()
{
return $this->title;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getBody()
{
return $this->body;
}
public function setBody($body)
{
$this->body = $body;
}
public function getYear()
{
return $this->year;
}
public function setYear($year)
{
$this->year = $year;
}
}
|
Convert bin/storage workflow to presume utf8mb4 as the default encoding
Summary: see comments on rP68904d941c54
Test Plan: run ,/bin/storage upgrade
Reviewers: epriestley, #blessed_reviewers
Reviewed By: epriestley, #blessed_reviewers
Subscribers: Korvin
Differential Revision: https://secure.phabricator.com/D16370 | <?php
final class PhabricatorStorageManagementShellWorkflow
extends PhabricatorStorageManagementWorkflow {
protected function didConstruct() {
$this
->setName('shell')
->setExamples('**shell** [__options__]')
->setSynopsis(pht('Launch an interactive shell.'));
}
protected function isReadOnlyWorkflow() {
return true;
}
public function execute(PhutilArgumentParser $args) {
$api = $this->getAPI();
list($host, $port) = $this->getBareHostAndPort($api->getHost());
$flag_port = $port
? csprintf('--port %d', $port)
: '';
$flag_password = '';
$password = $api->getPassword();
if ($password) {
if (strlen($password->openEnvelope())) {
$flag_password = csprintf('--password=%P', $password);
}
}
return phutil_passthru(
'mysql --protocol=TCP --default-character-set=utf8mb4 '.
'-u %s %C -h %s %C',
$api->getUser(),
$flag_password,
$host,
$flag_port);
}
}
| <?php
final class PhabricatorStorageManagementShellWorkflow
extends PhabricatorStorageManagementWorkflow {
protected function didConstruct() {
$this
->setName('shell')
->setExamples('**shell** [__options__]')
->setSynopsis(pht('Launch an interactive shell.'));
}
protected function isReadOnlyWorkflow() {
return true;
}
public function execute(PhutilArgumentParser $args) {
$api = $this->getAPI();
list($host, $port) = $this->getBareHostAndPort($api->getHost());
$flag_port = $port
? csprintf('--port %d', $port)
: '';
$flag_password = '';
$password = $api->getPassword();
if ($password) {
if (strlen($password->openEnvelope())) {
$flag_password = csprintf('--password=%P', $password);
}
}
return phutil_passthru(
'mysql --protocol=TCP --default-character-set=utf8 '.
'-u %s %C -h %s %C',
$api->getUser(),
$flag_password,
$host,
$flag_port);
}
}
|
Use -1 for metadata about missing resources instead of throwing exceptions. | /*
* Copyright 2011 the original author or 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.
*/
package org.gradle.api.internal.externalresource;
import java.io.IOException;
import java.io.InputStream;
public class MissingExternalResource extends AbstractExternalResource {
private final String source;
public MissingExternalResource(String source) {
this.source = source;
}
@Override
public String toString() {
return "MissingResource: " + getName();
}
public String getName() {
return source;
}
public boolean exists() {
return false;
}
public long getLastModified() {
return -1;
}
public long getContentLength() {
return -1;
}
public boolean isLocal() {
throw new UnsupportedOperationException();
}
public InputStream openStream() throws IOException {
throw new UnsupportedOperationException();
}
}
| /*
* Copyright 2011 the original author or 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.
*/
package org.gradle.api.internal.externalresource;
import java.io.IOException;
import java.io.InputStream;
public class MissingExternalResource extends AbstractExternalResource {
private final String source;
public MissingExternalResource(String source) {
this.source = source;
}
@Override
public String toString() {
return "MissingResource: " + getName();
}
public String getName() {
return source;
}
public boolean exists() {
return false;
}
public long getLastModified() {
throw new UnsupportedOperationException();
}
public long getContentLength() {
throw new UnsupportedOperationException();
}
public boolean isLocal() {
throw new UnsupportedOperationException();
}
public InputStream openStream() throws IOException {
throw new UnsupportedOperationException();
}
}
|
Fix output of remote collection items that lack YAML variables | <?php namespace TightenCo\Jigsaw\Collection;
use Symfony\Component\Yaml\Yaml;
use TightenCo\Jigsaw\Parsers\FrontMatterParser;
class CollectionRemoteItem
{
private $item;
private $index;
private $prefix;
public function __construct($item, $index, $collectionName = null)
{
$this->item = $item;
$this->index = $index;
$this->prefix = $collectionName . '_';
}
public function getContent()
{
return is_array($this->item) ?
$this->getHeader() . array_get($this->item, 'content') :
$this->item;
}
public function getFilename()
{
return array_get($this->item, 'filename', $this->prefix . ($this->index + 1)) . '.md';
}
protected function getHeader()
{
$variables = collect($this->item)->except('content')->toArray();
return count($variables) ? "---\n" . Yaml::dump($variables) . "---\n" : null;
}
}
| <?php namespace TightenCo\Jigsaw\Collection;
use Symfony\Component\Yaml\Yaml;
use TightenCo\Jigsaw\Parsers\FrontMatterParser;
class CollectionRemoteItem
{
private $item;
private $index;
private $prefix;
public function __construct($item, $index, $collectionName = null)
{
$this->item = $item;
$this->index = $index;
$this->prefix = $collectionName . '_';
}
public function getContent()
{
return is_array($this->item) ?
$this->getHeader() . array_get($this->item, 'content') :
$this->item;
}
public function getFilename()
{
return array_get($this->item, 'filename', $this->prefix . ($this->index + 1)) . '.md';
}
protected function getHeader()
{
$yaml = Yaml::dump(collect($this->item)->except('content')->toArray());
return $yaml ? "---\n" . $yaml . "---\n" : null;
}
}
|
Set test files with "*-test.js" pattern. | "use strict";
module.exports = function (grunt) {
grunt.initConfig({
eslint: {
options: {
config: ".eslintrc"
},
src: [
"Gruntfile.js",
"lib/**/*.js",
"test/**/*.js"
]
},
mochaTest: {
all: {
src: "test/*-test.js",
options: {
reporter: "spec"
}
}
}
});
grunt.loadNpmTasks("grunt-eslint");
grunt.loadNpmTasks("grunt-mocha-test");
grunt.registerTask("default", [
"eslint",
"mochaTest"
]);
};
| "use strict";
module.exports = function (grunt) {
grunt.initConfig({
eslint: {
options: {
config: ".eslintrc"
},
src: [
"Gruntfile.js",
"lib/**/*.js",
"test/**/*.js"
]
},
mochaTest: {
all: {
src: "test/*.js",
options: {
reporter: "spec"
}
}
}
});
grunt.loadNpmTasks("grunt-eslint");
grunt.loadNpmTasks("grunt-mocha-test");
grunt.registerTask("default", [
"eslint",
"mochaTest"
]);
};
|
Implement Autoloader in PSR-0 standard | <?php
/**
* Class AutoLoader
* @file AutoLoader.php
*
* PHP version 5.3.9+
*
* @author Alexander Yancharuk <alex@itvault.info>
* @date Fri Jun 01 10:19:04 2012
* @copyright The BSD 3-Clause License
*/
namespace Veles;
/**
* Class AutoLoader
*
* @author Alexander Yancharuk <alex@itvault.info>
*/
class AutoLoader
{
/**
* Initialisation
*/
final public static function init()
{
spl_autoload_register(__NAMESPACE__ . '\AutoLoader::load');
}
/**
* AutoLoader
*
* @param string $class_name
*/
final public static function load($class_name)
{
$class_name = ltrim($class_name, '\\');
$namespace = $file_name = '';
if ($last_ns_pos = strrpos($class_name, '\\')) {
$namespace = substr($class_name, 0, $last_ns_pos);
$class_name = substr($class_name, $last_ns_pos + 1);
$file_name = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$file_name = stream_resolve_include_path(
$file_name . str_replace('_', DIRECTORY_SEPARATOR, $class_name) . '.php'
);
if ($file_name) {
include $file_name;
}
}
}
| <?php
/**
* Class AutoLoader
* @file AutoLoader.php
*
* PHP version 5.3.9+
*
* @author Alexander Yancharuk <alex@itvault.info>
* @date Fri Jun 01 10:19:04 2012
* @copyright The BSD 3-Clause License
*/
namespace Veles;
/**
* Class AutoLoader
*
* @author Alexander Yancharuk <alex@itvault.info>
*/
class AutoLoader
{
/**
* Initialisation
*/
final public static function init()
{
spl_autoload_register(__NAMESPACE__ . '\AutoLoader::load');
}
/**
* AutoLoader
*
* @param string $name
*/
final public static function load($name)
{
$name = str_replace('\\', DIRECTORY_SEPARATOR, $name);
// For using external libs with their own autoloaders
// do not use strict require function
include "$name.php";
}
}
|
Use os.SameFile for file comparison | // +build !windows
package input
import (
"os"
"syscall"
"github.com/elastic/libbeat/logp"
)
func IsSameFile(path string, info os.FileInfo, state *FileState) bool {
fstat := info.Sys().(*syscall.Stat_t)
return (fstat.Ino == state.Inode && fstat.Dev == state.Device)
}
// Checks if the two files are the same.
func (f1 *File) IsSameFile(f2 *File) bool {
return os.SameFile(f1.FileInfo, f2.FileInfo)
}
// Compare file stats. Inode id and device are compared
func compareFileStats(s1 *syscall.Stat_t, s2 *syscall.Stat_t) bool {
return (s1.Dev == s2.Dev && s1.Ino == s2.Ino)
}
// SafeFileRotate safely rotates an existing file under path and replaces it with the tempfile
func SafeFileRotate(path, tempfile string) error {
if e := os.Rename(tempfile, path); e != nil {
logp.Info("registry rotate: rename of %s to %s - %s", tempfile, path, e)
return e
}
return nil
}
| // +build !windows
package input
import (
"os"
"syscall"
"github.com/elastic/libbeat/logp"
)
func IsSameFile(path string, info os.FileInfo, state *FileState) bool {
fstat := info.Sys().(*syscall.Stat_t)
return (fstat.Ino == state.Inode && fstat.Dev == state.Device)
}
// Checks if the two files are the same.
func (f1 *File) IsSameFile(f2 *File) bool {
f1Stat := f1.FileInfo.Sys().(*syscall.Stat_t)
f2Stat := f2.FileInfo.Sys().(*syscall.Stat_t)
return compareFileStats(f1Stat, f2Stat)
}
// Compare file stats. Inode id and device are compared
func compareFileStats(s1 *syscall.Stat_t, s2 *syscall.Stat_t) bool {
return (s1.Dev == s2.Dev && s1.Ino == s2.Ino)
}
// SafeFileRotate safely rotates an existing file under path and replaces it with the tempfile
func SafeFileRotate(path, tempfile string) error {
if e := os.Rename(tempfile, path); e != nil {
logp.Info("registry rotate: rename of %s to %s - %s", tempfile, path, e)
return e
}
return nil
}
|
Comment out now unused imports previously needed for CSRF | /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const models = require('../models/index')
const insecurity = require('../lib/insecurity')
// const utils = require('../lib/utils')
// const cache = require('../data/datacache')
// const challenges = cache.challenges
module.exports = function updateUserProfile () {
return (req, res, next) => {
const loggedInUser = insecurity.authenticatedUsers.get(req.cookies.token)
if (loggedInUser) {
models.User.findByPk(loggedInUser.data.id).then(user => {
// utils.solveIf(challenges.csrfChallenge, () => { return req.headers.origin.includes('://htmledit.squarefree.com') && req.body.username !== user.username })
return user.update({ username: req.body.username })
}).catch(error => {
next(error)
})
} else {
next(new Error('Blocked illegal activity by ' + req.connection.remoteAddress))
}
res.location('/profile')
res.redirect('/profile')
}
}
| /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const models = require('../models/index')
const insecurity = require('../lib/insecurity')
const utils = require('../lib/utils')
const cache = require('../data/datacache')
const challenges = cache.challenges
module.exports = function updateUserProfile () {
return (req, res, next) => {
const loggedInUser = insecurity.authenticatedUsers.get(req.cookies.token)
if (loggedInUser) {
models.User.findByPk(loggedInUser.data.id).then(user => {
// utils.solveIf(challenges.csrfChallenge, () => { return req.headers.origin.includes('://htmledit.squarefree.com') && req.body.username !== user.username })
return user.update({ username: req.body.username })
}).catch(error => {
next(error)
})
} else {
next(new Error('Blocked illegal activity by ' + req.connection.remoteAddress))
}
res.location('/profile')
res.redirect('/profile')
}
}
|
Remove now extraneous warning disabling.
Thank to `babel-eslint@3.1.10` update. | import React from 'react';
import Button from './Button';
import FormGroup from './FormGroup';
import InputBase from './InputBase';
import childrenValueValidation from './utils/childrenValueInputValidation';
class ButtonInput extends InputBase {
renderFormGroup(children) {
let {bsStyle, value, ...other} = this.props; // eslint-disable-line object-shorthand
return <FormGroup {...other}>{children}</FormGroup>;
}
renderInput() {
let {children, value, ...other} = this.props; // eslint-disable-line object-shorthand
let val = children ? children : value;
return <Button {...other} componentClass="input" ref="input" key="input" value={val} />;
}
}
ButtonInput.types = ['button', 'reset', 'submit'];
ButtonInput.defaultProps = {
type: 'button'
};
ButtonInput.propTypes = {
type: React.PropTypes.oneOf(ButtonInput.types),
bsStyle(props) {
//defer to Button propTypes of bsStyle
return null;
},
children: childrenValueValidation,
value: childrenValueValidation
};
export default ButtonInput;
| import React from 'react';
import Button from './Button';
import FormGroup from './FormGroup';
import InputBase from './InputBase';
import childrenValueValidation from './utils/childrenValueInputValidation';
class ButtonInput extends InputBase {
renderFormGroup(children) {
let {bsStyle, value, ...other} = this.props; // eslint-disable-line object-shorthand, no-unused-vars
return <FormGroup {...other}>{children}</FormGroup>;
}
renderInput() {
let {children, value, ...other} = this.props; // eslint-disable-line object-shorthand
let val = children ? children : value;
return <Button {...other} componentClass="input" ref="input" key="input" value={val} />;
}
}
ButtonInput.types = ['button', 'reset', 'submit'];
ButtonInput.defaultProps = {
type: 'button'
};
ButtonInput.propTypes = {
type: React.PropTypes.oneOf(ButtonInput.types),
bsStyle(props) {
//defer to Button propTypes of bsStyle
return null;
},
children: childrenValueValidation,
value: childrenValueValidation
};
export default ButtonInput;
|
Fix regex for tern complete_strings plugin | # -*- coding: utf-8 -*-
import json
import os.path
import re
from completor import Completor
from completor.compat import to_unicode
dirname = os.path.dirname(__file__)
class Tern(Completor):
filetype = 'javascript'
daemon = True
ident = re.compile(r"""(\w+)|(["'][^"']*)""", re.U)
trigger = r"""\w+$|[\w\)\]\}\'\"]+\.\w*$|["']\w*$"""
def format_cmd(self):
binary = self.get_option('node_binary') or 'node'
tern_config = self.find_config_file('.tern-project')
cmd = [binary, os.path.join(dirname, 'tern_wrapper.js')]
if tern_config:
cmd.append(os.path.dirname(tern_config))
return cmd
def parse(self, data):
try:
data = to_unicode(data[0], 'utf-8')
return [i for i in json.loads(data)
if not self.input_data.endswith(i['word'])]
except Exception:
return []
| # -*- coding: utf-8 -*-
import json
import os.path
import re
from completor import Completor
from completor.compat import to_unicode
dirname = os.path.dirname(__file__)
class Tern(Completor):
filetype = 'javascript'
daemon = True
ident = re.compile(r"""(\w+)|(('|").+)""", re.U)
trigger = r"""\w+$|[\w\)\]\}\'\"]+\.\w*$|('|").*$"""
def format_cmd(self):
binary = self.get_option('node_binary') or 'node'
tern_config = self.find_config_file('.tern-project')
cmd = [binary, os.path.join(dirname, 'tern_wrapper.js')]
if tern_config:
cmd.append(os.path.dirname(tern_config))
return cmd
def parse(self, data):
try:
data = to_unicode(data[0], 'utf-8')
return [i for i in json.loads(data)
if not self.input_data.endswith(i['word'])]
except Exception:
return []
|
Add date and request headers in CSP report log | <?php
class CspReport
{
public function process($post)
{
$report = json_decode($post);
if ($report) {
$report->date = date("Y-m-d H:i:s");
foreach (getallheaders() as $name => $value) {
$report->headers[$name] = $value;
}
$data = json_encode(
$report,
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
);
$this->log($data);
}
}
private function log($data)
{
$logfile = dirname(__DIR__) . '/csp-report.log';
file_put_contents($logfile, $data . "\n", LOCK_EX | FILE_APPEND);
}
}
| <?php
class CspReport
{
public function process($post)
{
$report = json_decode($post);
if ($report) {
$report->{'user-agent'} = $_SERVER['HTTP_USER_AGENT'];
$data = json_encode(
$report,
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
);
$this->log($data);
}
}
private function log($data)
{
$logfile = dirname(__DIR__) . '/csp-report.log';
file_put_contents($logfile, $data . "\n", LOCK_EX | FILE_APPEND);
}
}
|
Update copyright notice with MIT license | /*++
NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--*/
package com.nasmlanguage;
import com.intellij.openapi.fileTypes.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
public class NASMSyntaxHighlighterFactory extends SyntaxHighlighterFactory {
@NotNull
@Override
public SyntaxHighlighter getSyntaxHighlighter(Project project, VirtualFile virtualFile) {
return new NASMSyntaxHighlighter();
}
}
| /*++
NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury. All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
--*/
package com.nasmlanguage;
import com.intellij.openapi.fileTypes.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
public class NASMSyntaxHighlighterFactory extends SyntaxHighlighterFactory {
@NotNull
@Override
public SyntaxHighlighter getSyntaxHighlighter(Project project, VirtualFile virtualFile) {
return new NASMSyntaxHighlighter();
}
}
|
[Maintenance] Adjust variable names to interfaces | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Payment\Factory;
use Sylius\Component\Payment\Model\PaymentInterface;
use Sylius\Component\Resource\Factory\FactoryInterface;
final class PaymentFactory implements PaymentFactoryInterface
{
/** @var FactoryInterface */
private $factory;
public function __construct(FactoryInterface $factory)
{
$this->factory = $factory;
}
public function createNew(): PaymentInterface
{
return $this->factory->createNew();
}
public function createWithAmountAndCurrencyCode(int $amount, string $currency): PaymentInterface
{
/** @var PaymentInterface $payment */
$payment = $this->factory->createNew();
$payment->setAmount($amount);
$payment->setCurrencyCode($currency);
return $payment;
}
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Payment\Factory;
use Sylius\Component\Payment\Model\PaymentInterface;
use Sylius\Component\Resource\Factory\FactoryInterface;
final class PaymentFactory implements PaymentFactoryInterface
{
/** @var FactoryInterface */
private $factory;
public function __construct(FactoryInterface $factory)
{
$this->factory = $factory;
}
public function createNew(): PaymentInterface
{
return $this->factory->createNew();
}
public function createWithAmountAndCurrencyCode(int $amount, string $currencyCode): PaymentInterface
{
/** @var PaymentInterface $payment */
$payment = $this->factory->createNew();
$payment->setAmount($amount);
$payment->setCurrencyCode($currencyCode);
return $payment;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.