text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add slurm to command line plugin choices | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-subjects", nargs="*", dest="subjects",
help=("list of subject ids, name of file in lyman "
"directory, or full path to text file with "
"subject ids"))
parser.add_argument("-plugin", default="multiproc",
choices=["linear", "multiproc", "ipython",
"torque", "sge", "slurm"],
help="worklow execution plugin")
parser.add_argument("-nprocs", default=4, type=int,
help="number of MultiProc processes to use")
parser.add_argument("-queue", help="which queue for PBS/SGE execution")
parser.add_argument("-dontrun", action="store_true",
help="don't actually execute the workflows")
| import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-subjects", nargs="*", dest="subjects",
help=("list of subject ids, name of file in lyman "
"directory, or full path to text file with "
"subject ids"))
parser.add_argument("-plugin", default="multiproc",
choices=["linear", "multiproc",
"ipython", "torque", "sge"],
help="worklow execution plugin")
parser.add_argument("-nprocs", default=4, type=int,
help="number of MultiProc processes to use")
parser.add_argument("-queue", help="which queue for PBS/SGE execution")
parser.add_argument("-dontrun", action="store_true",
help="don't actually execute the workflows")
|
Disable auto mock by default (otherwise there wont be code coverage data) | jest.autoMockOff();
jest.unmock('../path.jsx');
const path = require('../path.jsx');
describe('join', () => {
it('joins "d" and "s" to equal "d/s"', () => {
expect(path.join("d", "s")).toBe("d/s");
});
it('joins "d" and "/s" to equal "d/s"', () => {
expect(path.join("d", "/s")).toBe("/s");
});
it('joins "d" and "/s" to equal "d/s"', () => {
expect(path.join("/d", "s")).toBe("/d/s");
});
});
describe('normalize', () => {
it('normalizes "/a/../b/" to equal "/b"', () => {
expect(path.normalize("/a/../b/")).toBe("/b");
});
it('normalizes "/a//./b" to equal "/a/b"', () => {
expect(path.normalize("/a//./b")).toBe("/a/b");
});
it('normalizes "/a/../b/c/d/../f/../../g" to equal "/b/g"', () => {
expect(path.normalize("/a/../b/c/d/../f/../../g")).toBe("/b/g");
});
}); | jest.unmock('../path.jsx');
const path = require('../path.jsx');
describe('join', () => {
it('joins "d" and "s" to equal "d/s"', () => {
expect(path.join("d", "s")).toBe("d/s");
});
it('joins "d" and "/s" to equal "d/s"', () => {
expect(path.join("d", "/s")).toBe("/s");
});
it('joins "d" and "/s" to equal "d/s"', () => {
expect(path.join("/d", "s")).toBe("/d/s");
});
});
describe('normalize', () => {
it('normalizes "/a/../b/" to equal "/b"', () => {
expect(path.normalize("/a/../b/")).toBe("/b");
});
it('normalizes "/a//./b" to equal "/a/b"', () => {
expect(path.normalize("/a//./b")).toBe("/a/b");
});
it('normalizes "/a/../b/c/d/../f/../../g" to equal "/b/g"', () => {
expect(path.normalize("/a/../b/c/d/../f/../../g")).toBe("/b/g");
});
}); |
Remove unnecessary heading from docstring | import re
from .utils import validator
regex = (
r'^[a-z]+://([^/:]+{tld}|([0-9]{{1,3}}\.)'
r'{{3}}[0-9]{{1,3}})(:[0-9]+)?(\/.*)?$'
)
pattern_with_tld = re.compile(regex.format(tld=r'\.[a-z]{2,10}'))
pattern_without_tld = re.compile(regex.format(tld=''))
@validator
def url(value, require_tld=True):
"""
Returns whether or not given value is a valid URL. If the value is
valid URL this function returns ``True``, otherwise
:class:`~validators.utils.ValidationFailure`.
This validator is based on `WTForms URL validator`_.
.. _WTForms URL validator:
https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py
Examples::
>>> import validators
>>> assert validators.url('http://foobar.dk')
>>> assert validators.url('http://localhost/foobar', require_tld=False)
>>> assert not validators.url('http://foobar.d')
.. versionadded:: 0.2
:param value: URL address string to validate
"""
if require_tld:
return pattern_with_tld.match(value)
return pattern_without_tld.match(value)
| import re
from .utils import validator
regex = (
r'^[a-z]+://([^/:]+{tld}|([0-9]{{1,3}}\.)'
r'{{3}}[0-9]{{1,3}})(:[0-9]+)?(\/.*)?$'
)
pattern_with_tld = re.compile(regex.format(tld=r'\.[a-z]{2,10}'))
pattern_without_tld = re.compile(regex.format(tld=''))
@validator
def url(value, require_tld=True):
"""
url
---
Returns whether or not given value is a valid URL. If the value is
valid URL this function returns ``True``, otherwise
:class:`~validators.utils.ValidationFailure`.
This validator is based on `WTForms URL validator`_.
.. _WTForms URL validator:
https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py
Examples::
>>> import validators
>>> assert validators.url('http://foobar.dk')
>>> assert validators.url('http://localhost/foobar', require_tld=False)
>>> assert not validators.url('http://foobar.d')
.. versionadded:: 0.2
:param value: URL address string to validate
"""
if require_tld:
return pattern_with_tld.match(value)
return pattern_without_tld.match(value)
|
Correct imports, switch to postgresql | import tempfile
import pytest
from toolshed import create_app
from toolshed.extensions import db as _db
dbfile = tempfile.NamedTemporaryFile(delete=False)
dbfile.close()
TEST_DATABASE_FILE = dbfile.name
TEST_DATABASE_URI = "postgres://localhost/" + TEST_DATABASE_FILE
TESTING = True
DEBUG = False
DEBUG_TB_ENABLED = False
DEBUG_TB_INTERCEPT_REDIRECTS = False
SQLALCHEMY_DATABASE_URI = TEST_DATABASE_URI
WTF_CSRF_ENABLED = False
@pytest.fixture
def app():
app = create_app()
app.config.from_object(__name__)
return app
@pytest.fixture
def db(app, request):
def teardown():
_db.drop_all()
_db.app = app
_db.create_all()
request.addfinalizer(teardown)
_db.app = app
return _db | import tempfile
import pytest
from coaction import create_app
from coaction.extensions import db as _db
dbfile = tempfile.NamedTemporaryFile(delete=False)
dbfile.close()
TEST_DATABASE_FILE = dbfile.name
TEST_DATABASE_URI = "sqlite:///" + TEST_DATABASE_FILE
TESTING = True
DEBUG = False
DEBUG_TB_ENABLED = False
DEBUG_TB_INTERCEPT_REDIRECTS = False
SQLALCHEMY_DATABASE_URI = TEST_DATABASE_URI
WTF_CSRF_ENABLED = False
@pytest.fixture
def app():
app = create_app()
app.config.from_object(__name__)
return app
@pytest.fixture
def db(app, request):
def teardown():
_db.drop_all()
_db.app = app
_db.create_all()
request.addfinalizer(teardown)
_db.app = app
return _db |
feat(form): Allow custom content for switch button | import React, { Component, PropTypes } from 'react'
import { Button } from 'react-bootstrap'
import { connect } from 'react-redux'
import { switchLocations } from '../../actions/map'
class SwitchButton extends Component {
static propTypes = {
onClick: PropTypes.func,
switchLocations: PropTypes.func
}
static defaultProps = {
content: 'Switch'
}
_onClick = () => {
this.props.switchLocations()
}
render () {
const { content } = this.props
return (
<Button className='switch-button'
onClick={this._onClick || this.props.onClick}
>{content}</Button>
)
}
}
const mapStateToProps = (state, ownProps) => {
return {}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
switchLocations: () => { dispatch(switchLocations()) }
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SwitchButton)
| import React, { Component, PropTypes } from 'react'
import { Button } from 'react-bootstrap'
import { connect } from 'react-redux'
import { switchLocations } from '../../actions/map'
class SwitchButton extends Component {
static propTypes = {
onClick: PropTypes.func
}
_onClick = () => {
this.props.switchLocations()
}
render () {
return (
<Button
onClick={this._onClick || this.props.onClick}
>Switch</Button>
)
}
}
const mapStateToProps = (state, ownProps) => {
return {}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
switchLocations: () => { dispatch(switchLocations()) }
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SwitchButton)
|
Add verbose print on split dataset script | import os
import numpy as np
data_dir = "data/dataset/"
jpg_filenames = list(filter(lambda x: x[-3:] == "jpg", os.listdir(data_dir)))
# Randomly select the test dataset
test_percentage = 0.1
n_test = int(round(len(jpg_filenames) * test_percentage))
if n_test == 0: n_test = 1
# Randomly select the images for testing
test_indexes = np.random.choice(len(jpg_filenames), n_test, replace=False)
test_indexes = test_indexes.astype(int)
jpg_filenames_copy = list(jpg_filenames)
with open("test.txt", "w") as f:
for index in test_indexes:
print(index, len(jpg_filenames_copy), len(jpg_filenames))
# Write filename
f.write(data_dir + jpg_filenames[index] + "\n")
# Remove from copy list
jpg_filenames_copy.pop(index)
# Write from the copy list
with open("train.txt", "w") as f:
for filename in jpg_filenames_copy:
f.write(data_dir + filename + "\n")
| import os
import numpy as np
data_dir = "data/dataset/"
jpg_filenames = list(filter(lambda x: x[-3:] == "jpg", os.listdir(data_dir)))
# Randomly select the test dataset
test_percentage = 0.1
n_test = int(round(len(jpg_filenames) * test_percentage))
if n_test == 0: n_test = 1
# Randomly select the images for testing
test_indexes = np.random.choice(len(jpg_filenames), n_test, replace=False)
test_indexes = test_indexes.astype(int)
jpg_filenames_copy = jpg_filenames[:]
with open("test.txt", "w") as f:
for index in test_indexes:
# Write filename
f.write(data_dir + jpg_filenames[index] + "\n")
# Remove from copy list
jpg_filenames_copy.pop(index)
# Write from the copy list
with open("train.txt", "w") as f:
for filename in jpg_filenames_copy:
f.write(data_dir + filename + "\n")
|
Revert "Allow running jobsteps to be deallocated"
This reverts commit 9b720026722ce92a8c0e05aa041d6e861c5e4e82. | from __future__ import absolute_import, division, unicode_literals
from changes.api.base import APIView
from changes.constants import Status
from changes.config import db
from changes.jobs.sync_job_step import sync_job_step
from changes.models import JobStep
class JobStepDeallocateAPIView(APIView):
def post(self, step_id):
to_deallocate = JobStep.query.get(step_id)
if to_deallocate is None:
return '', 404
if to_deallocate.status != Status.allocated:
return {
"error": "Only {0} job steps may be deallocated.",
"actual_status": to_deallocate.status.name
}, 400
to_deallocate.status = Status.pending_allocation
to_deallocate.date_started = None
to_deallocate.date_finished = None
db.session.add(to_deallocate)
db.session.commit()
sync_job_step.delay(
step_id=to_deallocate.id.hex,
task_id=to_deallocate.id.hex,
parent_task_id=to_deallocate.job_id.hex,
)
return self.respond(to_deallocate)
| from __future__ import absolute_import, division, unicode_literals
from changes.api.base import APIView
from changes.constants import Status
from changes.config import db
from changes.jobs.sync_job_step import sync_job_step
from changes.models import JobStep
class JobStepDeallocateAPIView(APIView):
def post(self, step_id):
to_deallocate = JobStep.query.get(step_id)
if to_deallocate is None:
return '', 404
if to_deallocate.status not in (Status.in_progress, Status.allocated):
return {
"error": "Only allocated and running job steps may be deallocated.",
"actual_status": to_deallocate.status.name
}, 400
to_deallocate.status = Status.pending_allocation
to_deallocate.date_started = None
to_deallocate.date_finished = None
db.session.add(to_deallocate)
db.session.commit()
sync_job_step.delay(
step_id=to_deallocate.id.hex,
task_id=to_deallocate.id.hex,
parent_task_id=to_deallocate.job_id.hex,
)
return self.respond(to_deallocate)
|
Allow low level titles when sanitising. | import bleach
ALLOWED_TAGS = [
'a',
'abbr',
'acronym',
'b',
'blockquote',
'code',
'em',
'i',
'li',
'ol',
'strong',
'ul',
'p',
'br',
'h3',
'h4',
'h5',
'h6',
]
ALLOWED_ATTRIBUTES = {
'a': ['href', 'title'],
'abbr': ['title'],
'acronym': ['title'],
}
ALLOWED_STYLES = []
def sanitize(text):
"""Cleans the HTML received."""
cleaned_text = bleach.clean(
text, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES,
styles=ALLOWED_STYLES, strip=True)
return cleaned_text
| import bleach
ALLOWED_TAGS = [
'a',
'abbr',
'acronym',
'b',
'blockquote',
'code',
'em',
'i',
'li',
'ol',
'strong',
'ul',
'p',
'br',
]
ALLOWED_ATTRIBUTES = {
'a': ['href', 'title'],
'abbr': ['title'],
'acronym': ['title'],
}
ALLOWED_STYLES = []
def sanitize(text):
"""Cleans the HTML received."""
cleaned_text = bleach.clean(
text, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES,
styles=ALLOWED_STYLES, strip=True)
return cleaned_text
|
Add line to make flake8 happy | from setuptools import find_packages, setup
import os
import re
def read(*parts):
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, *parts)) as f:
return f.read()
VERSION = re.search(
"^__version__ = '(.*)'$",
read('src', 'http_crawler', '__init__.py'),
re.MULTILINE
).group(1)
if __name__ == '__main__':
setup(
name='http-crawler',
version=VERSION,
description='A library for crawling websites',
long_description=read('README.rst'),
packages=find_packages(where='src'),
package_dir={'': 'src'},
install_requires=['lxml', 'requests', 'tinycss2'],
url='http://github.com/inglesp/http-crawler',
author='Peter Inglesby',
author_email='peter.inglesby@gmail.com',
license='License :: OSI Approved :: MIT License',
)
| from setuptools import find_packages, setup
import os
import re
def read(*parts):
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, *parts)) as f:
return f.read()
VERSION = re.search(
"^__version__ = '(.*)'$",
read('src', 'http_crawler', '__init__.py'),
re.MULTILINE
).group(1)
if __name__ == '__main__':
setup(
name='http-crawler',
version=VERSION,
description='A library for crawling websites',
long_description=read('README.rst'),
packages=find_packages(where='src'),
package_dir={'': 'src'},
install_requires=['lxml', 'requests', 'tinycss2'],
url='http://github.com/inglesp/http-crawler',
author='Peter Inglesby',
author_email='peter.inglesby@gmail.com',
license='License :: OSI Approved :: MIT License',
)
|
Send Http 404 Not Found header from proxy accordingly | <?php
// error_reporting(0);
// @ini_set('display_errors', 0);
// THREAD REQUEST
if(isset($_POST['url'])) {
$url = $_POST['url'];
}
else {
$url = $_GET['url'];
}
$agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:10.0) Gecko/20100101 Firefox/10.0';
$ch = curl_init( $url );
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_ENCODING ,"");
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
$raw = curl_exec($ch);
if($raw == false) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($raw, 0, $header_size);
$body = substr($raw, $header_size);
curl_close( $ch );
if($http_code == 404) {
header("HTTP/1.1 404 Not Found");
// http_response_code(404);
}
print $body;
?> | <?php
// error_reporting(0);
// @ini_set('display_errors', 0);
// THREAD REQUEST
if(isset($_POST['url'])) {
$url = $_POST['url'];
}
else {
$url = $_GET['url'];
}
$agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:10.0) Gecko/20100101 Firefox/10.0';
$ch = curl_init( $url );
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_ENCODING ,"");
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
$raw = curl_exec($ch);
curl_close( $ch );
if($raw == false) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
print $raw;
?> |
Update front page of the documentation | """
This module implements a forms system for creating, filling out, and
reviewing forms within an organization. This module depends on the
Constellation-Base package to function correctly.
Constellation Forms implements a fairly standard forms system. The
core features include:
* Click-to-Build form builder
* Form Lifecycles
* Form Versions
Advanced features are also available such as form approval and commenting.
These features can help support more advanced use cases where simply creating,
distributing, filing, and reading submissions is not a sufficient workflow.
This documentation is designed to be read by two distinct groups. The
primary group consuming this documentation are the developers of the
Forms module. While most of the source code is documented and the
files contain extensive inline comments, this documentation serves to
provide more in depth discussions of key features of components. This
also provides information on core design choices and why certain
choices have been made.
The second group of people expected to read
this documentation are end users of the system who would like to know
how to use components. This includes people who are managing the
forms system, and people who are tasked with creating forms.
"""
| """
This module implements a forms system for creating, filling out, and
reviewing forms within an organization. This module depends on the
Constellation-Base package to function correctly.
Constellation Forms implements a fairly standard forms system. The
core features include:
* Click-to-Build form builder
* Form Lifecycles
* Form Versions
More advanced features such as form approval status are planned. This
will allow for advanced tracking of forms used for internal processes
such as purchase approvals, access requests, and even appeals to
normal form processes.
This documentation is designed to be read by two distinct groups. The
primary group consuming this documentation are the developers of the
Forms module. While most of the source code is documented and the
files contain extensive inline comments, this documentation serves to
provide more in depth discussions of key features of components. This
also provides information on core design choices and why certain
choices have been made.
The second group of people expected to read
this documentation are end users of the system who would like to know
how to use components. This includes people who are managing the
forms system, and people who are tasked with creating forms.
"""
|
Allow to plug another implementation of scope() on top of scope bootstrap | // Static synchronous definition in global context
// Implementation of scopeornot API
// https://github.com/eric-brechemier/scopeornot
/*
Function: scope(code,needs,name)
Run code immediately, without taking needs into account, and set the return
value, if any, to a property with given name in the global context.
Parameters:
code - function(context), the code to run with the global context provided
as parameter
needs - array of strings, the names of the properties that this code would
like to find in the global context (for documentation purpose)
name - string, optional, name of the global context property to set the
value that the code may return
Note:
The global context is accessed using "this" when scope() is called. A
different context may be used if the scope() function is applied to another
object instead.
*/
var scope = (function(){
var
// global context
context = this,
// different scope() implementation?
contextScope = context.scope;
function scope(code,needs,name){
if (
typeof contextScope !== scope &&
typeof contextScope === "function"
){
// use the scope() implementation from the context instead
contextScope(code,needs,name);
return;
}
// call code synchronously, without taking needs into account
var result = code(context);
if (typeof name === "string"){
context[name] = result;
}
}
return scope;
}());
| // Static synchronous definition in global context
// Implementation of scopeornot API
// https://github.com/eric-brechemier/scopeornot
/*
Function: scope(code,needs,name)
Run code immediately, without taking needs into account, and set the return
value, if any, to a property with given name in the global context.
Parameters:
code - function(context), the code to run with the global context provided
as parameter
needs - array of strings, the names of the properties that this code would
like to find in the global context (for documentation purpose)
name - string, optional, name of the global context property to set the
value that the code may return
Note:
The global context is accessed using "this" when scope() is called. A
different context may be used if the scope() function is applied to another
object instead.
*/
var scope = (function(){
// global context
var context = this;
function scope(code,needs,name){
// call code synchronously, without taking needs into account
var result = code(context);
if (typeof name === "string"){
context[name] = result;
}
}
return scope;
}());
|
Set Profile.gender maxlength to 20 | from django.db import models
from django.utils.translation import ugettext_lazy as _
from ovp_users.helpers import get_settings, import_from_string
gender_choices = (
("male", "Male"),
("female", "Female"),
("unspecified", "Unspecified"),
)
class UserProfile(models.Model):
user = models.OneToOneField("User", blank=True, null=True, related_name="%(app_label)s_%(class)s_profile")
full_name = models.CharField(_("Full name"), max_length=300, null=True, blank=True)
skills = models.ManyToManyField("ovp_core.Skill")
causes = models.ManyToManyField("ovp_core.Cause")
about = models.TextField(_("About me"), null=True, blank=True)
gender = models.CharField(_("Gender"), max_length=20, choices=gender_choices, default='unspecified')
def get_profile_model():
s = get_settings()
class_path = s.get("PROFILE_MODEL", None)
if class_path:
return import_from_string(class_path)
return UserProfile
| from django.db import models
from django.utils.translation import ugettext_lazy as _
from ovp_users.helpers import get_settings, import_from_string
gender_choices = (
("male", "Male"),
("female", "Female"),
("unspecified", "Unspecified"),
)
class UserProfile(models.Model):
user = models.OneToOneField("User", blank=True, null=True, related_name="%(app_label)s_%(class)s_profile")
full_name = models.CharField(_("Full name"), max_length=300, null=True, blank=True)
skills = models.ManyToManyField("ovp_core.Skill")
causes = models.ManyToManyField("ovp_core.Cause")
about = models.TextField(_("About me"), null=True, blank=True)
gender = models.CharField(_("Gender"), max_length=10, choices=gender_choices, default='unspecified')
def get_profile_model():
s = get_settings()
class_path = s.get("PROFILE_MODEL", None)
if class_path:
return import_from_string(class_path)
return UserProfile
|
Fix social media icon links. | <?php
$options = get_option('plugin_options');
$social_media = array('facebook', 'twitter', 'google', 'mail', 'linkedin', 'xing', 'skype', 'youtube', 'vimeo', 'flickr', 'rss');
?>
<div class="social-media-wrapper">
<ul class="social-media-links">
<?php foreach ($social_media as $i => $name) {
if (!empty( $options['vobe_' . $name . '_link'] )) {
echo '<li><a href="' . $options['tf_'.$name.'_link'] . '" target="_blank" class="fa fa-' . $name . '"></a></li>';
}
}
?>
</ul>
<?php if ( function_exists(qtrans_generateLanguageSelectCode) ) echo qtrans_generateLanguageSelectCode(); ?>
</div> | <?php
$options = get_option('plugin_options');
$social_media = array('facebook', 'twitter', 'google', 'mail', 'linkedin', 'xing', 'skype', 'youtube', 'vimeo', 'flickr', 'rss');
?>
<div class="social-media-wrapper">
<ul class="social-media-links">
<?php foreach ($social_media as $i => $name) {
if (!empty( $options['vobe_' . $name . '_link'] )) {
echo '<li><a href=' . $options['tf_'.$name.'_link'] . ' target="_blank" class="fa fa-' . $name . '"></a></li>';
}
}
?>
</ul>
<?php if ( function_exists(qtrans_generateLanguageSelectCode) ) echo qtrans_generateLanguageSelectCode(); ?>
</div> |
Include payload data in exception
Signed-off-by: Rafael Luis Ibasco <80d89b34d8cf04643e39f61fb924744a8cfa1566@gmail.com> | /*
* Copyright (c) 2022 Asynchronous Game Query Library
*
* 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.ibasco.agql.core.exceptions;
public class InvalidPacketException extends ResponseProcessingException {
private final byte[] data;
public InvalidPacketException(String message, byte[] data) {
super(message);
this.data = data;
}
public byte[] getData() {
return data;
}
}
| /*
* Copyright 2018-2022 Asynchronous Game Query Library
*
* 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.ibasco.agql.core.exceptions;
public class InvalidPacketException extends ResponseProcessingException {
public InvalidPacketException() {
super();
}
public InvalidPacketException(String message) {
super(message);
}
public InvalidPacketException(String message, Throwable cause) {
super(message, cause);
}
public InvalidPacketException(Throwable cause) {
super(cause);
}
public InvalidPacketException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
Add message when edit for checkrights | <?php include_partial('widgets/list', array('widgets' => $widgets, 'category' => 'catalogue_bibliography','eid'=> $form->getObject()->getId() )); ?>
<?php slot('title', __('Edit Bibliography')); ?>
<div class="page">
<h1 class="edit_mode"><?php echo __('Edit Bibliography');?></h1>
<div class="warn_message">
<?php echo __('<strong>Warning!</strong><br /> This unit might be used in items where you do no have encoding rights.<br/>Be sure of what you do!');?>
</div>
<?php include_partial('form', array('form' => $form)) ?>
<?php include_partial('widgets/screen', array(
'widgets' => $widgets,
'category' => 'cataloguewidget',
'columns' => 1,
'options' => array('eid' => $form->getObject()->getId(), 'table' => 'bibliography')
)); ?>
</div>
| <?php include_partial('widgets/list', array('widgets' => $widgets, 'category' => 'catalogue_bibliography','eid'=> $form->getObject()->getId() )); ?>
<?php slot('title', __('Edit Bibliography')); ?>
<div class="page">
<h1 class="edit_mode"><?php echo __('Edit Bibliography');?></h1>
<?php if(count($no_right_col) > 0 && !$sf_user->isA(Users::ADMIN) ):?>
<?php include_partial('catalogue/warnedit', array('no_right_col' => $no_right_col)); ?>
<?php endif;?>
<?php include_partial('form', array('form' => $form)) ?>
<?php include_partial('widgets/screen', array(
'widgets' => $widgets,
'category' => 'cataloguewidget',
'columns' => 1,
'options' => array('eid' => $form->getObject()->getId(), 'table' => 'bibliography')
)); ?>
</div>
|
Switch student model to unicode | from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.ForeignKey(User, unique = True)
dionysos_username = models.CharField(max_length = 15, unique = True)
dionysos_password = models.CharField(max_length = 30)
eclass_username = models.CharField(max_length = 30, null = True, blank = True)
eclass_password = models.CharField(max_length = 30, null = True, blank = True)
eclass_lessons = models.TextField(null = True, blank = True)
introduction_year = models.CharField(max_length = 5)
registration_number = models.CharField(max_length = 8)
school = models.CharField(max_length = 5)
semester = models.CharField(max_length = 2)
webmail_username = models.CharField(max_length = 30, null = True, blank = True)
webmail_password = models.CharField(max_length = 30, null = True, blank = True)
teacher_announcements = models.TextField(null = True, blank = True)
other_announcements = models.TextField(null = True, blank = True)
declaration = models.TextField(null = True, blank = True)
grades = models.TextField(null = True, blank = True)
def __unicode__(self):
return self.user.username
| from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.ForeignKey(User, unique = True)
dionysos_username = models.CharField(max_length = 15, unique = True)
dionysos_password = models.CharField(max_length = 30)
eclass_username = models.CharField(max_length = 30, null = True, blank = True)
eclass_password = models.CharField(max_length = 30, null = True, blank = True)
eclass_lessons = models.TextField(null = True, blank = True)
introduction_year = models.CharField(max_length = 5)
registration_number = models.CharField(max_length = 8)
school = models.CharField(max_length = 5)
semester = models.CharField(max_length = 2)
webmail_username = models.CharField(max_length = 30, null = True, blank = True)
webmail_password = models.CharField(max_length = 30, null = True, blank = True)
teacher_announcements = models.TextField(null = True, blank = True)
other_announcements = models.TextField(null = True, blank = True)
declaration = models.TextField(null = True, blank = True)
grades = models.TextField(null = True, blank = True)
def __str__(self):
return self.user.username
|
Fix the build path for hosting on Github pages | // see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/codemash-vue',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}
| // see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}
|
Add six to test requirements. | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='pygcvs',
version=__import__('pygcvs').__version__,
description='A Python library for reading variable star data from GCVS.',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/pygcvs',
download_url='http://pypi.python.org/pypi/pygcvs',
license='MIT',
packages=find_packages(exclude=['tests']),
include_package_data=True,
tests_require=['nose', 'six'],
test_suite='nose.collector',
platforms='any',
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Scientific/Engineering :: Astronomy',
'Topic :: Utilities'
],
)
| import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='pygcvs',
version=__import__('pygcvs').__version__,
description='A Python library for reading variable star data from GCVS.',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/pygcvs',
download_url='http://pypi.python.org/pypi/pygcvs',
license='MIT',
packages=find_packages(exclude=['tests']),
include_package_data=True,
tests_require=['nose'],
test_suite='nose.collector',
platforms='any',
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Scientific/Engineering :: Astronomy',
'Topic :: Utilities'
],
)
|
Remove checkstyle warning about System.err
git-svn-id: f26ccc5efe72c2bd8e1c40f599fe313f2692e4de@9328 a612230a-c5fa-0310-af8b-88eea846685b | /*
*
*
* Copyright (C) 2007 SIPfoundry Inc.
* Licensed by SIPfoundry under the LGPL license.
*
* Copyright (C) 2007 Pingtel Corp.
* Licensed to SIPfoundry under a Contributor Agreement.
*
* $
*/
package org.sipfoundry.sipxconfig.common;
import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.context.ApplicationContext;
import org.springframework.context.access.ContextSingletonBeanFactoryLocator;
/**
* Triggers system to start up, then find a requested bean, then runs it.
*/
public class SystemTaskRunner {
public static void main(String[] args) {
if (args == null || args.length == 0) {
throw new IllegalArgumentException("bean to run is required as first argument");
}
new SystemTaskRunner().runMain(args);
}
void runMain(String[] args) {
BeanFactoryLocator bfl = ContextSingletonBeanFactoryLocator.getInstance();
BeanFactoryReference bfr = bfl.useBeanFactory("servicelayer-context");
ApplicationContext app = (ApplicationContext) bfr.getFactory();
SystemTaskEntryPoint task = (SystemTaskEntryPoint) app.getBean(args[0]);
task.runSystemTask(args);
}
}
| /*
*
*
* Copyright (C) 2007 SIPfoundry Inc.
* Licensed by SIPfoundry under the LGPL license.
*
* Copyright (C) 2007 Pingtel Corp.
* Licensed to SIPfoundry under a Contributor Agreement.
*
* $
*/
package org.sipfoundry.sipxconfig.common;
import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.context.ApplicationContext;
import org.springframework.context.access.ContextSingletonBeanFactoryLocator;
/**
* Triggers system to start up, then find a requested bean, then runs it.
*/
public class SystemTaskRunner {
@SuppressWarnings("unused")
public static void main(String[] args) {
if (args == null || args.length == 0) {
System.err.println("bean to run is required as first argument");
System.exit(1);
}
new SystemTaskRunner().runMain(args);
}
void runMain(String[] args) {
BeanFactoryLocator bfl = ContextSingletonBeanFactoryLocator.getInstance();
BeanFactoryReference bfr = bfl.useBeanFactory("servicelayer-context");
ApplicationContext app = (ApplicationContext) bfr.getFactory();
SystemTaskEntryPoint task = (SystemTaskEntryPoint) app.getBean(args[0]);
task.runSystemTask(args);
}
}
|
Clean main multi simulation script | # -*- coding:utf-8 -*-
"""
Script for running multiple simulation with different parameter set.
"""
from subprocess import check_output
from multiprocessing import Pool
from os import listdir, mkdir, path
from sys import argv
def run_simu((psfile, dir_runs)):
"""Runs the main script with specified parameter file."""
ndir = psfile[:-3]
mkdir(ndir)
simu_output = check_output(["python2.7", "multiglom_network.py", psfile,
"--full-ps"])
with open(path.join(ndir, "output.txt"), 'w') as f:
f.write(simu_output)
if __name__ == '__main__':
n_processes = int(argv[1])
dir_runs = argv[2]
psfiles = listdir(dir_runs)
psfile_filter = lambda fname: fname[-3:] == '.py' and fname != '__init__.py'
psfiles = filter(psfile_filter, psfiles)
psfiles = [(path.join(dir_runs, fname), dir_runs) for fname in psfiles]
pool = Pool(processes=n_processes)
pool.map(run_simu, psfiles)
| # -*- coding:utf-8 -*-
from subprocess import check_output
from multiprocessing import Pool
from os import listdir, mkdir, path
from sys import argv
def run_simu((psfile, dir_runs)):
"""Runs the main script with specified parameter file."""
ndir = psfile[:-3]
mkdir(ndir)
simu_output = check_output(["python2.7", "multiglom_network.py", psfile,
"--full-ps"])
with open(path.join(ndir, "output.txt"), 'w') as f:
f.write(simu_output)
if __name__ == '__main__':
n_processes = int(argv[1])
dir_runs = argv[2]
psfiles = listdir(dir_runs)
psfile_filter = lambda fname: fname[-3:] == '.py' and fname != '__init__.py'
psfiles = filter(psfile_filter, psfiles)
psfiles = [(path.join(dir_runs, fname), dir_runs) for fname in psfiles]
pool = Pool(processes=n_processes)
pool.map(run_simu, psfiles)
|
Correct the timer element issue | const Timer = React.createClass({
getInitialState: function () {
return { secondsToWait: this.props.secondsToWait };
},
runTimer: function () {
this.setState({
timer: setInterval(() => {
if (this.state.secondsToWait === 0) clearInterval(timer);
this.setState({ secondsToWait: this.state.secondsToWait - 1 });
}, 1000)
});
},
stopTimer: function () {
clearInterval(this.state.timer);
},
componentDidMount: function () {
this.runTimer();
},
componentWillUnmount: function () {
this.stopTimer();
},
render: function () {
if (this.state.secondsToWait > 0) {
let unit = (this.state.secondsToWait > 1)? 'seconds': 'second';
return <p><i className="fa fa-spinner"></i> Waiting {this.state.secondsToWait} {unit}...</p>;
}
return <p>Done!</p>;
}
});
| const Timer = React.createClass({
getInitialState: function () {
return { secondsToWait: this.props.secondsToWait };
},
runTimer: function () {
let timer = setInterval(() => {
if (this.state.secondsToWait === 0) clearInterval(timer);
this.setState({ secondsToWait: this.state.secondsToWait - 1 });
}, 1000);
},
componentDidMount: function () {
this.runTimer();
},
render: function () {
if (this.state.secondsToWait > 0) {
let unit = (this.state.secondsToWait > 1)? 'seconds': 'second';
return <p><i className="fa fa-spinner"></i> Waiting {this.state.secondsToWait} {unit}...</p>;
}
return <p>Done!</p>;
}
});
|
Update wrong path in CAuthenticator | <?php
namespace Jofe\Blackgate;
class CAuthenticatorTest extends \PHPUnit_Framework_TestCase
{
public function testApply(){
$options = new \Jofe\Blackgate\COptions();
$el = new \Jofe\Blackgate\CAuthenticator($options);
$res = $el->apply('doe', 'doe');
$exp = true;
$this->assertEquals($res, $exp, "Created element name missmatch.");
$res2 = $el->apply('', 'doe');
$exp2 = false;
$this->assertEquals($res2, $exp2, "Created element name missmatch.");
$res3 = $el->apply('doe', 'doee');
$exp3 = false;
$this->assertEquals($res3, $exp3, "Created element name missmatch.");
}
public function testGetOutput(){
$options = new \Jofe\Blackgate\COptions();
$el = new \Jofe\Blackgate\CAuthenticator($options);
$el->apply('doe', 'doe');
$res = $el->getOutPut();
$exp = "Access granted.";
$this->assertEquals($res, $exp, "Created element name missmatch.");
}
} | <?php
namespace Jofe\Blackgate;
class CAuthenticatorTest extends \PHPUnit_Framework_TestCase
{
public function testApply(){
$options = new \Jofe\BlackGate\COptions();
$el = new \Jofe\BlackGate\CAuthenticator($options);
$res = $el->apply('doe', 'doe');
$exp = true;
$this->assertEquals($res, $exp, "Created element name missmatch.");
$res2 = $el->apply('', 'doe');
$exp2 = false;
$this->assertEquals($res2, $exp2, "Created element name missmatch.");
$res3 = $el->apply('doe', 'doee');
$exp3 = false;
$this->assertEquals($res3, $exp3, "Created element name missmatch.");
}
public function testGetOutput(){
$options = new \Jofe\BlackGate\COptions();
$el = new \Jofe\BlackGate\CAuthenticator($options);
$el->apply('doe', 'doe');
$res = $el->getOutPut();
$exp = "Access granted.";
$this->assertEquals($res, $exp, "Created element name missmatch.");
}
} |
Fix duplicate profile key errors with a less specific query. | from celery.task import task
from namelist.scrape import get_user_profile_id, scrape_profile, NotFound
from namelist.models import Player, Category
@task()
def import_user(profile_name_or_id, category=None, user=None):
if isinstance(profile_name_or_id, basestring):
try:
profile_id = get_user_profile_id(profile_name_or_id)
except NotFound:
if user:
user.message_set.create(message="Couldn't create {0}".format(profile_name_or_id))
return
else:
profile_id = profile_name_or_id
info = scrape_profile(profile_id)
player, created = Player.objects.get_or_create(profile_id=profile_id)
if player[1]:
player[0].category = category
player[0].name = info[0]
player[0].group_name = info[1]
player[0].save()
| from celery.task import task
from namelist.scrape import get_user_profile_id, scrape_profile, NotFound
from namelist.models import Player, Category
@task()
def import_user(user, profile_name_or_id, category=None):
if isinstance(profile_name_or_id, basestring):
try:
profile_id = get_user_profile_id(profile_name_or_id)
except NotFound:
user.message_set.create(message="Couldn't create {0}".format(profile_name_or_id))
return
else:
profile_id = profile_name_or_id
info = scrape_profile(profile_id)
player = Player.objects.get_or_create(name=info[0], group_name=info[1], profile_id=profile_id)
if player[1]:
player[0].category = category
player[0].save()
|
Check the user is active before displaying password reset
This would only come into play if an inactive user already received a password reset email and then the system was upgraded to prevent those emails from being sent to inactive users | <?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
use App\Models\User;
use Illuminate\Http\Request;
class ResetPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Where to redirect users after resetting their password.
*
* @var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
public function showResetForm(Request $request, $token = null)
{
// Check that the user is active
if ($user = User::where('email', '=',$request->input('email'))->where('activated','=','1')->count() > 0) {
return view('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
return redirect()->route('password.request')->withErrors(['email' => 'No matching users']);
}
}
| <?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class ResetPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Where to redirect users after resetting their password.
*
* @var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
|
Use async functions instead to flatten nesting | const format = require('date-fns/format');
const addDays = require('date-fns/add_days');
const pdf2text = require('../lib/pdf-parser.js');
const download = require('download-file');
function downloadFile (url, options) {
return new Promise((resolve, reject) => {
download(url, options, function (err) {
if (err) reject(err);
resolve();
})
})
}
module.exports.getMenu = async function getMenu () {
const url = 'http://neudeli.at/wp-content/uploads/2016/10/Wochenkarte-kw42.pdf';
const options = {
directory: "./tmp/",
filename: "neudeli.pdf"
};
try {
const fileDownloaded = await downloadFile(url, options);
const text = await pdf2text.pdf2txt(options.directory + options.filename);
const today = new Date();
const todayString = format(today,'DD.MM');
const tomorrowString = format(addDays(today,1),'DD.MM');
const todaysMenu = text.substring(text.lastIndexOf(todayString), text.lastIndexOf(tomorrowString));
return todaysMenu;
} catch (err) {
throw err;
}
} | const format = require('date-fns/format');
const addDays = require('date-fns/add_days');
const pdf2text = require('../lib/pdf-parser.js');
const download = require('download-file');
function downloadFile (url, options) {
return new Promise((resolve, reject) => {
download(url, options, function (err) {
if (err) reject(err);
resolve();
})
})
}
module.exports.getMenu = function getMenu () {
const url = 'http://neudeli.at/wp-content/uploads/2016/10/Wochenkarte-kw42.pdf';
const options = {
directory: "./tmp/",
filename: "neudeli.pdf"
};
return new Promise((resolve, reject) => {
downloadFile(url, options)
.then(() =>
pdf2text.pdf2txt(options.directory + options.filename))
.then(text => {
const today = new Date();
const todayString = format(today,'DD.MM');
const tomorrowString = format(addDays(today,1),'DD.MM');
const todaysMenu = text.substring(text.lastIndexOf(todayString), text.lastIndexOf(tomorrowString));
resolve(todaysMenu);
}).catch(err => {
reject(err);
})
});
} |
Make sure modal dialog appears over topbar header | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import ModalDialog from 'react/components/UI/ModalDialog';
const ModalBackdrop = styled.div`
display: flex;
justify-content: center;
align-items: center;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(255, 255, 255, 0.9);
z-index: 6001;
transform: translate3d(0, 0, 1px);
`;
export default class Modal extends Component {
static propTypes = {
children: PropTypes.node.isRequired,
onClose: PropTypes.func.isRequired,
}
ModalDialog = ModalDialog
render() {
const { children, onClose, ...rest } = this.props;
return (
<ModalBackdrop {...rest} onClick={onClose}>
<this.ModalDialog
onClick={e => e.stopPropagation()}
role="dialog"
>
{children}
</this.ModalDialog>
</ModalBackdrop>
);
}
}
| import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import ModalDialog from 'react/components/UI/ModalDialog';
const ModalBackdrop = styled.div`
display: flex;
justify-content: center;
align-items: center;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(255, 255, 255, 0.9);
z-index: 6001;
`;
export default class Modal extends Component {
static propTypes = {
children: PropTypes.node.isRequired,
onClose: PropTypes.func.isRequired,
}
ModalDialog = ModalDialog
render() {
const { children, onClose, ...rest } = this.props;
return (
<ModalBackdrop {...rest} onClick={onClose}>
<this.ModalDialog
onClick={e => e.stopPropagation()}
role="dialog"
>
{children}
</this.ModalDialog>
</ModalBackdrop>
);
}
}
|
Change inline char syntax to array | <?php
namespace vektah\parser_combinator\parser;
class CharRangeParser extends CharParser
{
public function __construct(array $ranges, $min = null, $max = null, $capture = true)
{
$chars = '';
foreach ($ranges as $first => $last) {
// If the value is an array with one value then treat it as a sequence of chars instead of a range.
if (is_array($last)) {
$chars .= $last[0];
} else {
for ($i = ord($first); $i <= ord($last); $i++) {
$chars .= chr($i);
}
}
}
parent::__construct($chars, $min, $max, $capture);
}
}
| <?php
namespace vektah\parser_combinator\parser;
class CharRangeParser extends CharParser
{
public function __construct(array $ranges, $min = null, $max = null, $capture = true)
{
$chars = '';
foreach ($ranges as $first => $last) {
// Use non numeric keys as chars directly.
if (!is_string($first)) {
$chars .= $last;
}
for ($i = ord($first); $i <= ord($last); $i++) {
$chars .= chr($i);
}
}
parent::__construct($chars, $min, $max, $capture);
}
}
|
Add const to feature for of loop | const { MIN_ECMA_VERSION } = require('./constants');
const astTypeToFeatures = getAstTypeToFeatures(require('../data/es-features'));
function getAstTypeToFeatures(esFeatures) {
const astTypeToFeatures = {};
for (const feature of esFeatures) {
if (!astTypeToFeatures[feature.astType]) {
astTypeToFeatures[feature.astType] = [];
}
astTypeToFeatures[feature.astType].push(feature);
}
return astTypeToFeatures;
}
function getNodeEcmaVersion(node) {
const features = astTypeToFeatures[node.type];
const matchedEcmaVersions = features
? features
.filter((feature) => (feature.isMatch ? feature.isMatch(node) : true))
.map((feature) => feature.ecmaVersion)
: [];
return Math.max(...matchedEcmaVersions, MIN_ECMA_VERSION);
}
module.exports = getNodeEcmaVersion;
| const { MIN_ECMA_VERSION } = require('./constants');
const astTypeToFeatures = getAstTypeToFeatures(require('../data/es-features'));
function getAstTypeToFeatures(esFeatures) {
const astTypeToFeatures = {};
for (feature of esFeatures) {
if (!astTypeToFeatures[feature.astType]) {
astTypeToFeatures[feature.astType] = [];
}
astTypeToFeatures[feature.astType].push(feature);
}
return astTypeToFeatures;
}
function getNodeEcmaVersion(node) {
const features = astTypeToFeatures[node.type];
const matchedEcmaVersions = features
? features
.filter((feature) => (feature.isMatch ? feature.isMatch(node) : true))
.map((feature) => feature.ecmaVersion)
: [];
return Math.max(...matchedEcmaVersions, MIN_ECMA_VERSION);
}
module.exports = getNodeEcmaVersion;
|
Update Resources translation based on translate.google.com | <?php
return array(
'account' => array(
'profile' => 'Редактировать профиль',
'password' => 'Изменить пароль',
),
'extensions' => array(
'list' => 'Расширения',
'configure' => 'Настройки расширения: :name',
),
'forgot-password' => 'Забыли пароль',
'home' => array(
'list' => 'Главная',
),
'login' => 'Вход',
'logout' => 'Выход',
'resources' => array(
'list' => 'Pесурсы',
),
'settings' => array(
'list' => 'Настройки',
),
'users' => array(
'list' => 'Пользователи',
'create' => 'Добавить пользователя',
'update' => 'Редактировать пользователя',
),
);
| <?php
return array(
'account' => array(
'profile' => 'Редактировать профиль',
'password' => 'Изменить пароль',
),
'extensions' => array(
'list' => 'Расширения',
'configure' => 'Настройки расширения: :name',
),
'forgot-password' => 'Забыли пароль',
'home' => array(
'list' => 'Главная',
),
'login' => 'Вход',
'logout' => 'Выход',
'resources' => array(
'list' => 'Resources',
),
'settings' => array(
'list' => 'Настройки',
),
'users' => array(
'list' => 'Пользователи',
'create' => 'Добавить пользователя',
'update' => 'Редактировать пользователя',
),
);
|
Use 0.18-style schema spec access | const {Schema, DOMParser} = require("prosemirror-model")
const {EditorView} = require("prosemirror-view")
const {EditorState} = require("prosemirror-state")
const {schema} = require("prosemirror-schema-basic")
const {addListNodes} = require("prosemirror-schema-list")
const {addTableNodes} = require("prosemirror-schema-table")
const {exampleSetup} = require("prosemirror-example-setup")
const demoSchema = new Schema({
nodes: addListNodes(addTableNodes(schema.spec.nodes, "block+", "block"), "paragraph block*", "block"),
marks: schema.spec.marks
})
let state = EditorState.create({doc: DOMParser.fromSchema(demoSchema).parse(document.querySelector("#content")),
plugins: exampleSetup({schema: demoSchema})})
let view = window.view = new EditorView(document.querySelector(".full"), {state})
| const {Schema, DOMParser} = require("prosemirror-model")
const {EditorView} = require("prosemirror-view")
const {EditorState} = require("prosemirror-state")
const {schema} = require("prosemirror-schema-basic")
const {addListNodes} = require("prosemirror-schema-list")
const {addTableNodes} = require("prosemirror-schema-table")
const {exampleSetup} = require("prosemirror-example-setup")
const demoSchema = new Schema({
nodes: addListNodes(addTableNodes(schema.nodeSpec, "block+", "block"), "paragraph block*", "block"),
marks: schema.markSpec
})
let state = EditorState.create({doc: DOMParser.fromSchema(demoSchema).parse(document.querySelector("#content")),
plugins: exampleSetup({schema: demoSchema})})
let view = window.view = new EditorView(document.querySelector(".full"), {state})
|
Include any files ending in '.install' in package data
This makes sure the new `dpkg-reconfigure-dracut.install` file under resources
gets included as package data. | #!/usr/bin/python3
# SPDX-License-Identifier: LGPL-2.1+
from setuptools import setup, Command, find_packages
class BuildManpage(Command):
description = ('builds the manpage')
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
self.spawn(['pandoc', '-t', 'man', '-s', '-o', 'man/mkosi.1', 'mkosi.md'])
setup(
name="mkosi",
version="13",
description="Build Bespoke OS Images",
url="https://github.com/systemd/mkosi",
maintainer="mkosi contributors",
maintainer_email="systemd-devel@lists.freedesktop.org",
license="LGPLv2+",
python_requires=">=3.7",
packages = find_packages(".", exclude=["tests"]),
package_data = {"": ["*.sh", "*.hook", "*.conf", "*.install"]},
include_package_data = True,
scripts = ["bin/mkosi"],
cmdclass = { "man": BuildManpage },
data_files = [('share/man/man1', ["man/mkosi.1"])],
)
| #!/usr/bin/python3
# SPDX-License-Identifier: LGPL-2.1+
from setuptools import setup, Command, find_packages
class BuildManpage(Command):
description = ('builds the manpage')
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
self.spawn(['pandoc', '-t', 'man', '-s', '-o', 'man/mkosi.1', 'mkosi.md'])
setup(
name="mkosi",
version="13",
description="Build Bespoke OS Images",
url="https://github.com/systemd/mkosi",
maintainer="mkosi contributors",
maintainer_email="systemd-devel@lists.freedesktop.org",
license="LGPLv2+",
python_requires=">=3.7",
packages = find_packages(".", exclude=["tests"]),
package_data = {"": ["*.sh", "*.hook", "*.conf"]},
include_package_data = True,
scripts = ["bin/mkosi"],
cmdclass = { "man": BuildManpage },
data_files = [('share/man/man1', ["man/mkosi.1"])],
)
|
Update test models for new metaclass support. | # -*- coding: utf-8 -*_
from django.db import models
from ..base import ModelTranslationBase
from ..mixins import ModelMixin, ManagerMixin
class FooManager(ManagerMixin, models.Manager):
pass
class BarManager(ManagerMixin, models.Manager):
pass
class FooModel(ModelMixin, models.Model):
title = models.CharField(max_length=255)
excerpt = models.TextField(null=True, blank=True)
body = models.TextField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
objects = FooManager()
class Meta:
linguist = {
'identifier': 'foo',
'fields': ('title', 'excerpt', 'body'),
}
class BarModel(ModelMixin, models.Model):
title = models.CharField(max_length=255, null=True, blank=True)
objects = BarManager()
class Meta:
linguist = {
'identifier': 'bar',
'fields': ('title', ),
}
class BadTranslation(object):
pass
class BadModel(object):
pass
| # -*- coding: utf-8 -*_
from django.db import models
from ..base import ModelTranslationBase
from ..mixins import ModelMixin, ManagerMixin
class FooManager(ManagerMixin, models.Manager):
pass
class BarManager(ManagerMixin, models.Manager):
pass
class FooModel(ModelMixin, models.Model):
title = models.CharField(max_length=255, null=True, blank=True)
excerpt = models.TextField(null=True, blank=True)
body = models.TextField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
objects = FooManager()
class FooTranslation(ModelTranslationBase):
model = FooModel
identifier = 'foo'
fields = ('title', 'excerpt', 'body')
class BarModel(ModelMixin, models.Model):
title = models.CharField(max_length=255, null=True, blank=True)
objects = BarManager()
class BarTranslation(ModelTranslationBase):
model = BarModel
identifier = 'bar'
fields = ('title', )
class BadTranslation(object):
pass
class BadModel(object):
pass
|
Define the log level of the logger instead of the handler. | # -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
from knot import Container
from sqlalchemy import create_engine
from .domain import Db, MeasurementService
def build(app):
c = Container(app.config)
@c.factory(cache=True)
def db(c):
return Db(create_engine(
c['SQLALCHEMY_DATABASE_URI'],
echo=c['SQLALCHEMY_ECHO']
))
@c.factory(cache=True)
def measurement_service(c):
return MeasurementService(c('db').measurement)
@c.factory(cache=True)
def logger(c):
handler = RotatingFileHandler(
c('LOGGER_FILENAME', '{}.log'.format(app.name)),
maxBytes=c('LOGGER_MAX_BYTES', 1024*1024),
backupCount=c('LOGGER_BACKUP_COUNT', 3)
)
handler.setFormatter(logging.Formatter(
c('LOGGER_FORMAT', "%(asctime)s %(levelname)s: %(message)s")
))
app.logger.setLevel(c('LOGGER_LEVEL', logging.INFO))
app.logger.addHandler(handler)
return app.logger
return c
| # -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
from knot import Container
from sqlalchemy import create_engine
from .domain import Db, MeasurementService
def build(app):
c = Container(app.config)
@c.factory(cache=True)
def db(c):
return Db(create_engine(
c['SQLALCHEMY_DATABASE_URI'],
echo=c['SQLALCHEMY_ECHO']
))
@c.factory(cache=True)
def measurement_service(c):
return MeasurementService(c('db').measurement)
@c.factory(cache=True)
def logger(c):
handler = RotatingFileHandler(
c('LOGGER_FILENAME', '{}.log'.format(app.name)),
maxBytes=c('LOGGER_MAX_BYTES', 1024*1024),
backupCount=c('LOGGER_BACKUP_COUNT', 3)
)
handler.setLevel(c('LOGGER_LEVEL', logging.INFO))
handler.setFormatter(logging.Formatter(
c('LOGGER_FORMAT', "%(asctime)s %(levelname)s: %(message)s")
))
app.logger.addHandler(handler)
return app.logger
return c
|
Add spinner to external preview | function applyClickCallbackOnProtocolCards() {
$('.protocol-card').off('click').on('click', function(e) {
$.ajax({
url: $(this).data('show-url'),
type: 'GET',
dataType: 'json',
data: {
protocol_source: $(this).data('protocol-source'),
protocol_id: $(this).data('show-protocol-id')
},
beforeSend: animateSpinner($('.protocol-preview-panel'), true),
success: function(data) {
$('.empty-preview-panel').hide();
$('.full-preview-panel').show();
$('.preview-iframe').contents().find('body').html(data.html);
animateSpinner($('.protocol-preview-panel'), false);
},
error: function(_error) {
// TODO: we should probably show some alert bubble
$('.empty-preview-panel').show();
$('.full-preview-panel').hide();
animateSpinner($('.protocol-preview-panel'), false);
}
});
e.preventDefault();
return false;
});
}
applyClickCallbackOnProtocolCards();
| function applyClickCallbackOnProtocolCards() {
$('.protocol-card').off('click').on('click', function(e) {
$.ajax({
url: $(this).data('show-url'),
type: 'GET',
dataType: 'json',
data: {
protocol_source: $(this).data('protocol-source'),
protocol_id: $(this).data('show-protocol-id')
},
success: function(data) {
$('.empty-preview-panel').hide();
$('.full-preview-panel').show();
$('.preview-iframe').contents().find('body').html(data.html);
},
error: function(_error) {
// TODO: we should probably show some alert bubble
$('.empty-preview-panel').show();
$('.full-preview-panel').hide();
}
});
e.preventDefault();
return false;
});
}
applyClickCallbackOnProtocolCards();
|
Use session instead of cookie for tracking visitor UUID
session ID is only recorded after this layer of middleware, hence the need for a new UUID | import uuid
from django.conf import settings
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
from analytics.models import AnalyticsRecord
from analytics.utils import (
should_ignore,
status_code_invalid,
get_tracking_params,
)
class AnalyticsMiddleware(MiddlewareMixin):
def process_response(self, request, response):
if should_ignore(request) or status_code_invalid(response):
return response
timestamp = timezone.now()
if 'visitor_uuid' not in request.session:
request.session['visitor_uuid'] = uuid.uuid4().hex
visitor_uuid = request.session['visitor_uuid']
params = get_tracking_params(
request, response, timestamp, visitor_uuid)
AnalyticsRecord.objects.create(**params)
return response
| import uuid
from django.conf import settings
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
from analytics.models import AnalyticsRecord
from analytics.utils import (
should_ignore,
status_code_invalid,
get_tracking_params,
)
class AnalyticsMiddleware(MiddlewareMixin):
def process_response(self, request, response):
if should_ignore(request) or status_code_invalid(response):
return response
timestamp = timezone.now()
visitor_uuid = request.COOKIES.get('visitor_uuid', False)
if not visitor_uuid:
response.set_cookie('visitor_uuid', str(uuid.uuid4()))
params = get_tracking_params(
request, response, timestamp, visitor_uuid)
AnalyticsRecord.objects.create(**params)
return response
|
Stop augmenting the error message | var async = require('async')
var RSVP = require('rsvp')
var transformers = require('../transformers')
var Component = require('../component').Component
exports.CompilerCollection = CompilerCollection
CompilerCollection.prototype = Object.create(transformers.Transformer.prototype)
CompilerCollection.prototype.constructor = CompilerCollection
function CompilerCollection () {
this.compilers = []
}
CompilerCollection.prototype.addCompiler = function (compiler) {
this.compilers.push(compiler)
return this
}
CompilerCollection.prototype.transform = RSVP.denodeify(function (srcDir, destDir, callback) {
async.eachSeries(this.compilers, function (compiler, compilerCallback) {
try { // this should go away, or be a domain handler instead
compiler.compile(srcDir, destDir, function (err) {
setImmediate(function () { // async to avoid long stack traces
compilerCallback(err)
})
})
} catch (err) {
compilerCallback(err)
}
}, function (err) {
callback(err)
})
})
exports.Compiler = Compiler
Compiler.prototype = Object.create(Component.prototype)
Compiler.prototype.constructor = Compiler
function Compiler () {}
| var async = require('async')
var RSVP = require('rsvp')
var transformers = require('../transformers')
var Component = require('../component').Component
exports.CompilerCollection = CompilerCollection
CompilerCollection.prototype = Object.create(transformers.Transformer.prototype)
CompilerCollection.prototype.constructor = CompilerCollection
function CompilerCollection () {
this.compilers = []
}
CompilerCollection.prototype.addCompiler = function (compiler) {
this.compilers.push(compiler)
return this
}
CompilerCollection.prototype.transform = RSVP.denodeify(function (srcDir, destDir, callback) {
async.eachSeries(this.compilers, function (compiler, compilerCallback) {
try { // this should go away, or be a domain handler instead
compiler.compile(srcDir, destDir, function (err) {
setImmediate(function () { // async to avoid long stack traces
compilerCallback(err)
})
})
} catch (err) {
err.message = compiler.constructor.name + ': ' + err.message
compilerCallback(err)
}
}, function (err) {
callback(err)
})
})
exports.Compiler = Compiler
Compiler.prototype = Object.create(Component.prototype)
Compiler.prototype.constructor = Compiler
function Compiler () {}
|
Install templates when using pip to install package. | import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-mingus',
version='0.9.7',
description='A django blog engine.',
long_description=read('README.textile'),
author='Kevin Fricovsky',
author_email='kfricovsky@gmail.com',
license='BSD',
url='http://github.com/montylounge/django-mingus/',
keywords = ['blog', 'django',],
packages=[
'mingus',
'mingus.core',
'mingus.core.templatetags',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
zip_safe=False,
include_package_data=True,
)
| import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-mingus',
version='0.9.7',
description='A django blog engine.',
long_description=read('README.textile'),
author='Kevin Fricovsky',
author_email='kfricovsky@gmail.com',
license='BSD',
url='http://github.com/montylounge/django-mingus/',
keywords = ['blog', 'django',],
packages=[
'mingus',
'mingus.core',
'mingus.core.templatetags',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
zip_safe=False,
)
|
Enable cache for all endpoints | /* global angular */
angular
.module('speciesApp')
.factory('SpeciesService', [
'API_BASE_URL',
'$resource',
SpeciesService
])
function SpeciesService (API_BASE_URL, $resource) {
return $resource(
API_BASE_URL,
null,
{
getKingdoms: {
method: 'GET',
isArray: false,
cache: true,
params: {
op: 'getkingdomnames'
}
},
getClasses: {
method: 'GET',
isArray: false,
cache: true,
params: {
op: 'getclassnames'
}
},
getFamilies: {
method: 'GET',
isArray: false,
cache: true,
params: {
op: 'getfamilynames'
}
}
}
)
}
| /* global angular */
angular
.module('speciesApp')
.factory('SpeciesService', [
'API_BASE_URL',
'$resource',
SpeciesService
])
function SpeciesService (API_BASE_URL, $resource) {
return $resource(
API_BASE_URL,
null,
{
getKingdoms: {
method: 'GET',
isArray: false,
params: {
op: 'getkingdomnames'
}
},
getClasses: {
method: 'GET',
isArray: false,
params: {
op: 'getclassnames'
}
},
getFamilies: {
method: 'GET',
isArray: false,
params: {
op: 'getfamilynames'
}
}
}
)
}
|
Remove dependency on setTimeout global. | "use strict";
var reducible = require("reducible/reducible")
var reduce = require("reducible/reduce")
var isReduced = require("reducible/is-reduced")
var end = require("reducible/end")
var setTimeout = require("timers").setTimeout
function delay(source, ms) {
ms = ms || 6 // Minimum 6ms, as on less dispatch order becomes unreliable
return reducible(function reduceDelayed(next, result) {
var timeout = 0
var ended = false
reduce(source, function reduceDelaySource(value) {
setTimeout(function delayed() {
if (!ended) {
timeout = timeout - ms
result = next(value, result)
if (isReduced(result)) {
ended = true
next(end)
}
}
}, timeout = timeout + ms)
return result
})
})
}
module.exports = delay
| "use strict";
var reducible = require("reducible/reducible")
var reduce = require("reducible/reduce")
var isReduced = require("reducible/is-reduced")
var end = require("reducible/end")
function delay(source, ms) {
ms = ms || 6 // Minimum 6ms, as on less dispatch order becomes unreliable
return reducible(function reduceDelayed(next, result) {
var timeout = 0
var ended = false
reduce(source, function reduceDelaySource(value) {
setTimeout(function delayed() {
if (!ended) {
timeout = timeout - ms
result = next(value, result)
if (isReduced(result)) {
ended = true
next(end)
}
}
}, timeout = timeout + ms)
return result
})
})
}
module.exports = delay
|
Clean up database test case imports
Signed-off-by: Aleksi Häkli <44cb6a94c0d20644d531e2be44779b52833cdcd2@iki.fi> | from django.apps.registry import apps
from django.db import connection
from django.db.migrations.autodetector import MigrationAutodetector
from django.db.migrations.executor import MigrationExecutor
from django.db.migrations.state import ProjectState
from django.test import TestCase
from django.utils import translation
class MigrationsCheck(TestCase):
def setUp(self):
self.saved_locale = translation.get_language()
translation.deactivate_all()
def tearDown(self):
if self.saved_locale is not None:
translation.activate(self.saved_locale)
def test_missing_migrations(self):
executor = MigrationExecutor(connection)
autodetector = MigrationAutodetector(
executor.loader.project_state(),
ProjectState.from_apps(apps),
)
changes = autodetector.changes(graph=executor.loader.graph)
self.assertEqual({}, changes)
| from django.test import TestCase
class MigrationsCheck(TestCase):
def setUp(self):
from django.utils import translation
self.saved_locale = translation.get_language()
translation.deactivate_all()
def tearDown(self):
if self.saved_locale is not None:
from django.utils import translation
translation.activate(self.saved_locale)
def test_missing_migrations(self):
from django.db import connection
from django.apps.registry import apps
from django.db.migrations.executor import MigrationExecutor
executor = MigrationExecutor(connection)
from django.db.migrations.autodetector import MigrationAutodetector
from django.db.migrations.state import ProjectState
autodetector = MigrationAutodetector(
executor.loader.project_state(),
ProjectState.from_apps(apps),
)
changes = autodetector.changes(graph=executor.loader.graph)
self.assertEqual({}, changes)
|
Comment out some debugging output. | foam.CLASS({
package: 'foam.build',
name: 'ClassLoaderContext',
exports: [
'aref',
'acreate'
],
methods: [
{
class: 'ContextMethod',
name: 'aref',
async: true,
code: async function(x, id) {
// console.log("aref(" + id + ")");
var cls = x.lookup(id, true);
if ( cls ) return cls;
return await x.classloader.load(id)
}
},
{
class: 'ContextMethod',
name: 'acreate',
async: true,
code: async function(x, id, args) {
// console.log("acreate(" + id + ", " + args);
var cls = x.lookup(id, true);
if ( cls ) {
// console.log("** cls found");
return cls.create(args, x);
}
cls = await x.classloader.load(id);
return cls.create(args, x);
}
}
]
});
| foam.CLASS({
package: 'foam.build',
name: 'ClassLoaderContext',
exports: [
'aref',
'acreate'
],
methods: [
{
class: 'ContextMethod',
name: 'aref',
async: true,
code: async function(x, id) {
console.log("aref(" + id + ")");
var cls = x.lookup(id, true);
if ( cls ) return cls;
return await x.classloader.load(id)
}
},
{
class: 'ContextMethod',
name: 'acreate',
async: true,
code: async function(x, id, args) {
console.log("acreate(" + id + ", " + args);
var cls = x.lookup(id, true);
if ( cls ) {
console.log("** cls found");
return cls.create(args, x);
}
cls = await x.classloader.load(id);
return cls.create(args, x);
}
}
]
});
|
Fix labels once and for all. | <?php
class DownloadStatsPage extends Page {
}
class DownloadStatsPage_Controller extends Page_Controller {
function DownloadStatsChartUrl() {
$downloads = DataObject::get("DownloadPage");
$values = array();
foreach ($downloads as $download) {
$label = explode(" ", $download->Title);
$temp = $label[0];
$values[$temp] = $download->DownloadCount;
}
arsort($values);
$url = "https://chart.googleapis.com/chart?cht=bvs&chd=t:" .
implode(",", array_values($values)); //Chart data
$temp = array_values($values);
$max = $temp[0];
$min = $temp[count($values) - 1];
$url = $url . "&chds=0,$max&chxr=1,$min,$max"; //Chart scale
$url = $url . "&chs=400x200"; //Chart size
$url = $url . "&chxt=x,y&chxl=0:|" .
implode("|", array_keys($values)); //Chart labels
$url = $url . "&chbh=50,15&chxs=0,FFFFFF,13,0,l,FFFFFF|1,FFFFFF,13,0,l,FFFFFF&chf=bg,s,000000&chtt=Download+Count&chts=FFFFFF,13";
return $url;
}
}
?>
| <?php
class DownloadStatsPage extends Page {
}
class DownloadStatsPage_Controller extends Page_Controller {
function DownloadStatsChartUrl() {
$downloads = DataObject::get("DownloadPage");
$values = array();
foreach ($downloads as $download) {
$label = explode(" ", $download->Title);
$temp = $label[0];
print($temp);
$values[$temp] = $download->DownloadCount;
}
rsort($values);
$url = "https://chart.googleapis.com/chart?cht=bvs&chd=t:" .
implode(",", array_values($values)); //Chart data
$temp = array_values($values);
$max = $temp[0];
$min = $temp[count($values) - 1];
$url = $url . "&chds=0,$max&chxr=1,$min,$max"; //Chart scale
$url = $url . "&chs=400x200"; //Chart size
$url = $url . "&chxt=x,y&chxl=0:|" .
implode("|", array_keys($values)); //Chart labels
$url = $url . "&chbh=50,15&chxs=0,FFFFFF,13,0,l,FFFFFF|1,FFFFFF,13,0,l,FFFFFF&chf=bg,s,000000&chtt=Download+Count&chts=FFFFFF,13";
return $url;
}
}
?>
|
Fix difference in URLs in webmention | <?php
use Illuminate\Database\Seeder;
class WebMentionsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$webmention = App\WebMention::create([
'source' => 'https://aaornpk.localhost/reply/1',
'target' => 'https://jonnybarnes.localhost/notes/D',
'commentable_id' => '13',
'commentable_type' => 'App\Note',
'type' => 'in-reply-to',
'mf2' => '{"rels": [], "items": [{"type": ["h-entry"], "properties": {"url": ["https://aaronpk.localhost/reply/1"], "name": ["Hi too"], "author": [{"type": ["h-card"], "value": "Aaron Parecki", "properties": {"url": ["https://aaronpk.localhost"], "name": ["Aaron Parecki"], "photo": ["https://aaronparecki.com/images/profile.jpg"]}}], "content": [{"html": "Hi too", "value": "Hi too"}], "published": ["' . date(DATE_W3C) . '"], "in-reply-to": ["https://aaronpk.loclahost/reply/1", "https://jonnybarnes.uk/notes/D"]}}]}'
]);
}
}
| <?php
use Illuminate\Database\Seeder;
class WebMentionsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$webmention = App\WebMention::create([
'source' => 'https://aaornpk.local/reply/1',
'target' => 'https://jonnybarnes.localhost/notes/D',
'commentable_id' => '13',
'commentable_type' => 'App\Note',
'type' => 'in-reply-to',
'mf2' => '{"rels": [], "items": [{"type": ["h-entry"], "properties": {"url": ["https://aaronpk.localhost/reply/1"], "name": ["Hi too"], "author": [{"type": ["h-card"], "value": "Aaron Parecki", "properties": {"url": ["https://aaronpk.localhost"], "name": ["Aaron Parecki"], "photo": ["https://aaronparecki.com/images/profile.jpg"]}}], "content": [{"html": "Hi too", "value": "Hi too"}], "published": ["' . date(DATE_W3C) . '"], "in-reply-to": ["https://aaronpk.loclahost/reply/1", "https://jonnybarnes.uk/notes/D"]}}]}'
]);
}
}
|
Change requirement from 'adb>1.3.0' to 'adb-homeassistant' | from setuptools import setup
setup(
name='firetv',
version='1.0.6',
description='Communicate with an Amazon Fire TV device via ADB over a network.',
url='https://github.com/happyleavesaoc/python-firetv/',
license='MIT',
author='happyleaves',
author_email='happyleaves.tfr@gmail.com',
packages=['firetv'],
install_requires=['pycryptodome', 'rsa', 'adb-homeassistant'],
extras_require={
'firetv-server': ['Flask>=0.10.1', 'PyYAML>=3.12']
},
entry_points={
'console_scripts': [
'firetv-server = firetv.__main__:main'
]
},
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3'
]
)
| from setuptools import setup
setup(
name='firetv',
version='1.0.6',
description='Communicate with an Amazon Fire TV device via ADB over a network.',
url='https://github.com/happyleavesaoc/python-firetv/',
license='MIT',
author='happyleaves',
author_email='happyleaves.tfr@gmail.com',
packages=['firetv'],
install_requires=['pycryptodome', 'rsa', 'adb>1.3.0'],
extras_require={
'firetv-server': ['Flask>=0.10.1', 'PyYAML>=3.12']
},
entry_points={
'console_scripts': [
'firetv-server = firetv.__main__:main'
]
},
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3'
]
)
|
Add util function to retrieve favicons | (function() {
this.ColorUtil = (function() {
function ColorUtil() {}
ColorUtil.changeLuminance = function(hex, lum) {
// validate hex string
hex = String(hex).replace(/[^0-9a-f]/gi, '');
if (hex.length < 6) {
hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
}
lum = lum || 0;
// convert to decimal and change luminosity
var rgb = "#", c, i;
for (i = 0; i < 3; i++) {
c = parseInt(hex.substr(i*2,2), 16);
c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
rgb += ("00"+c).substr(c.length);
}
;
return rgb;
};
return ColorUtil;
})();
this.Util = (function(){
function Util() {}
Util.getURLHost = function(url) {
var parser = document.createElement("a");
parser.href = url;
return parser.protocol+"//"+parser.hostname;
}
Util.getFaviconURL = function(url) {
return Util.getURLHost(url)+"/favicon.ico";
}
return Util
})();
}).call(this);
| (function() {
this.ColorUtil = (function() {
function ColorUtil() {}
ColorUtil.changeLuminance = function(hex, lum) {
// validate hex string
hex = String(hex).replace(/[^0-9a-f]/gi, '');
if (hex.length < 6) {
hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
}
lum = lum || 0;
// convert to decimal and change luminosity
var rgb = "#", c, i;
for (i = 0; i < 3; i++) {
c = parseInt(hex.substr(i*2,2), 16);
c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
rgb += ("00"+c).substr(c.length);
}
;
return rgb;
};
return ColorUtil;
})();
}).call(this);
|
Fix incorrect line numbers in test failures
Reviewed By: voideanvalue
Differential Revision: D4597677
fbshipit-source-id: 9e10fb7aaee16cd902489cd95cfb04a151da2226 | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
const babel = require('babel-core');
const babelRegisterOnly = require('../packager/babelRegisterOnly');
const createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction');
const path = require('path');
const nodeFiles = RegExp([
'/local-cli/',
'/packager/(?!src/Resolver/polyfills/)',
].join('|'));
const nodeOptions = babelRegisterOnly.config([nodeFiles]);
babelRegisterOnly([]);
// has to be required after setting up babelRegisterOnly
const transformer = require('../packager/transformer.js');
module.exports = {
process(src, file) {
if (nodeFiles.test(file)) { // node specific transforms only
return babel.transform(
src,
Object.assign({filename: file}, nodeOptions)
).code;
}
return transformer.transform(src, file, {inlineRequires: true}).code;
},
getCacheKey: createCacheKeyFunction([
__filename,
path.join(__dirname, '../packager/transformer.js'),
require.resolve('babel-core/package.json'),
]),
};
| /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
const babel = require('babel-core');
const babelRegisterOnly = require('../packager/babelRegisterOnly');
const createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction');
const path = require('path');
const nodeFiles = RegExp([
'/local-cli/',
'/packager/(?!src/Resolver/polyfills/)',
].join('|'));
const nodeOptions = babelRegisterOnly.config([nodeFiles]);
babelRegisterOnly([]);
// has to be required after setting up babelRegisterOnly
const transformer = require('../packager/transformer.js');
module.exports = {
process(src, file) {
// Don't transform node_modules, except react-tools which includes the
// untransformed copy of React
if (file.match(/node_modules\/(?!react-tools\/)/)) {
return src;
} else if (nodeFiles.test(file)) { // node specific transforms only
return babel.transform(
src, Object.assign({filename: file}, nodeOptions)).code;
}
return transformer.transform(src, file, {inlineRequires: true}).code;
},
getCacheKey: createCacheKeyFunction([
__filename,
path.join(__dirname, '../packager/transformer.js'),
require.resolve('babel-core/package.json'),
]),
};
|
Fix alias in query template of georeference-city analysis | 'use strict';
var Node = require('../node');
var debug = require('../../util/debug')('analysis:georeference-country');
var TYPE = 'georeference-country';
var PARAMS = {
source: Node.PARAM.NODE(Node.GEOMETRY.ANY),
country_column: Node.PARAM.STRING()
};
var GeoreferenceCountry = Node.create(TYPE, PARAMS, {
cache: true
});
module.exports = GeoreferenceCountry;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;
GeoreferenceCountry.prototype.sql = function() {
var sql = queryTemplate({
source: this.source.getQuery(),
columns: this.source.getColumns(true).join(', '),
country: this.country_column
});
debug(sql);
return sql;
};
var queryTemplate = Node.template([
'SELECT',
' {{=it.columns}},',
' cdb_dataservices_client.cdb_geocode_admin0_polygon({{=it.country}}) AS the_geom',
'FROM ({{=it.source}}) AS _camshaft_georeference_city_analysis'
].join('\n'));
| 'use strict';
var Node = require('../node');
var debug = require('../../util/debug')('analysis:georeference-country');
var TYPE = 'georeference-country';
var PARAMS = {
source: Node.PARAM.NODE(Node.GEOMETRY.ANY),
country_column: Node.PARAM.STRING()
};
var GeoreferenceCountry = Node.create(TYPE, PARAMS, {
cache: true
});
module.exports = GeoreferenceCountry;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;
GeoreferenceCountry.prototype.sql = function() {
var sql = queryTemplate({
source: this.source.getQuery(),
columns: this.source.getColumns(true).join(', '),
country: this.country_column
});
debug(sql);
return sql;
};
var queryTemplate = Node.template([
'SELECT',
' {{=it.columns}},',
' cdb_dataservices_client.cdb_geocode_admin0_polygon({{=it.country}}) AS the_geom',
'FROM ({{=it.source}}) AS _camshaft_georeference_admin_region_analysis'
].join('\n'));
|
Fix grammar of the sentence for welcome page. | package org.wildfly.jaxrs;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
/**
* Created by Muhammad on 11/11/2015.
*/
// This class is located at "/helloworld"
@Path("/helloworld")
public class HelloWorldResource {
// These method will process HTTP GET requests
// The Java method will produce content identified by the MIME Media
/**
* Method to return text/plain request
* @return
*/
@GET
@Produces("application/json")
public String getJsonMessage() {
// return some cliched textual content
return "{\"info\": \"Welcome to the demo of Wildfly, Java EE7 and AngularJS. This message is " +
"served using REST API and consumed by AngularJS.\"}";
}
}
| package org.wildfly.jaxrs;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
/**
* Created by Muhammad on 11/11/2015.
*/
// This class is located at "/helloworld"
@Path("/helloworld")
public class HelloWorldResource {
// These method will process HTTP GET requests
// The Java method will produce content identified by the MIME Media
/**
* Method to return text/plain request
* @return
*/
@GET
@Produces("application/json")
public String getJsonMessage() {
// return some cliched textual content
return "{\"info\": \"Welcome to the demo of Wildfly, Java EE7 and AngularJS. This message is retrieved" +
"serve using REST API and consume by AngularJS.\"}";
}
}
|
Add Unit Test For precision=0 | import roundNumber from 'dummy/utils/round-number';
import { module, test } from 'qunit';
module('Unit | Utility | round number');
test('it rounds a number to two decimal places by default', function(assert) {
let result = roundNumber(123.123);
assert.equal(result, 123.12);
});
test('it rounds a number to a configurable number of decimal places', function(assert) {
let result = roundNumber(123.123123, 1);
assert.equal(result, 123.1);
});
test('it rounds a number to a whole number if precision is 0', function(assert) {
let result = roundNumber(123.123123, 0);
assert.equal(result, 123);
});
test('it returns undefined when nothing provided', function(assert) {
let result = roundNumber();
assert.equal(result, undefined);
});
test('it parses a String number', function(assert) {
let result = roundNumber('34.3333');
assert.equal(result, 34.33);
});
test('it returns undefined when provided a string that is not a number', function(assert) {
let result = roundNumber('boogers');
assert.equal(result, undefined);
});
| import roundNumber from 'dummy/utils/round-number';
import { module, test } from 'qunit';
module('Unit | Utility | round number');
test('it rounds a number to two decimal places by default', function(assert) {
let result = roundNumber(123.123);
assert.equal(result, 123.12);
});
test('it rounds a number to a configurable number of decimal places', function(assert) {
let result = roundNumber(123.123123, 1);
assert.equal(result, 123.1);
});
test('it returns undefined when nothing provided', function(assert) {
let result = roundNumber();
assert.equal(result, undefined);
});
test('it parses a String number', function(assert) {
let result = roundNumber('34.3333');
assert.equal(result, 34.33);
});
test('it returns undefined when provided a string that is not a number', function(assert) {
let result = roundNumber('boogers');
assert.equal(result, undefined);
});
|
Change comparison to be non-strict. | from datetime import date
from base import Calendar
from date import InvalidDate
from main import JulianCalendar
class JulianToGregorianCalendar(Calendar):
def date(self, year, month, day):
gregorian_date = date(year, month, day)
if gregorian_date < self.first_gregorian_day:
julian_date = JulianCalendar().date(year, month, day)
if not julian_date < self.first_gregorian_day:
raise InvalidDate("This is a 'missing day' when the calendars changed.")
self.bless(julian_date)
return julian_date
return self.from_date(gregorian_date)
def bless(self, date):
date.calendar = self.__class__
class EnglishHistoricalCalendar(JulianToGregorianCalendar):
first_gregorian_day = date(1752, 9, 13)
| from datetime import date
from base import Calendar
from date import InvalidDate
from main import JulianCalendar
class JulianToGregorianCalendar(Calendar):
def date(self, year, month, day):
gregorian_date = date(year, month, day)
if gregorian_date < self.first_gregorian_day:
julian_date = JulianCalendar().date(year, month, day)
if julian_date > self.first_gregorian_day:
raise InvalidDate("This is a 'missing day' when the calendars changed.")
self.bless(julian_date)
return julian_date
return self.from_date(gregorian_date)
def bless(self, date):
date.calendar = self.__class__
class EnglishHistoricalCalendar(JulianToGregorianCalendar):
first_gregorian_day = date(1752, 9, 13)
|
Fix fatal error on getting mailer
Getting mailer from service container caused fatal error (infinite nesting loop) | <?php
/**
* @author Ivan Voskoboynyk
*/
namespace Axis\S1\ServiceContainer;
class ServiceContainer extends \Pimple
{
/**
* Previous service container object
* @var \ArrayAccess
*/
protected $fallback;
/**
* @param $fallback
*/
function __construct($fallback)
{
$this->fallback = $fallback;
}
function offsetGet($id)
{
if ($id == 'mailer' && !parent::offsetExists($id))
{
return $this['context']->getMailer();
}
if (!parent::offsetExists($id) && isset($this->fallback[$id]))
{
return $this->fallback[$id];
}
return parent::offsetGet($id);
}
function offsetExists($id)
{
return parent::offsetExists($id) || isset($this->fallback[$id]);
}
}
| <?php
/**
* @author Ivan Voskoboynyk
*/
namespace Axis\S1\ServiceContainer;
class ServiceContainer extends \Pimple
{
/**
* Previous service container object
* @var \ArrayAccess
*/
protected $fallback;
/**
* @param $fallback
*/
function __construct($fallback)
{
$this->fallback = $fallback;
}
function offsetGet($id)
{
if ($id == 'mailer')
{
return $this['context']->getMailer();
}
if (!parent::offsetExists($id) && isset($this->fallback[$id]))
{
return $this->fallback[$id];
}
return parent::offsetGet($id);
}
function offsetExists($id)
{
return parent::offsetExists($id) || isset($this->fallback[$id]);
}
}
|
Set canvas width on start if fullscreen | var SQ = SQ || {};
SQ.Screen = function Screen (canvas, settings) {
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this.settings = settings;
if (settings.fullScreen) {
window.addEventListener("resize", this.resizeHandler.bind(this));
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
};
SQ.Screen.prototype.drawLayer = function drawLayer (startX, startY, layerdata, layerdatawidth, tileWidth, tileHeight, tiles, targetCtx) {
if (!targetCtx) {
targetCtx = this.ctx;
}
var maxX = Math.floor((startX + targetCtx.width) / tileWidth),
maxY = Math.floor((startY + targetCtx.height) / tileHeight);
for (var x = Math.floor(startX / tileWidth); x < maxX; x++) {
for (var y = Math.floor(startY / tileHeight); y < maxY; y++) {
var tileNumber = Math.min(x, 0) + Math.min(y, 0) * layerdatawidth;
targetCtx.drawImage(tiles[layerdata[tileNumber]], startX + x * tileWidth, startY + y * tileHeight);
}
}
};
SQ.Screen.prototype.resizeHandler = function resizeHandler () {
if (this.settings.fullScreen) {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
}; | var SQ = SQ || {};
SQ.Screen = function Screen (canvas, settings) {
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this.settings = settings;
if (settings.fullScreen) {
window.addEventListener("resize", this.resizeHandler.bind(this));
}
};
SQ.Screen.prototype.drawLayer = function drawLayer (startX, startY, layerdata, layerdatawidth, tileWidth, tileHeight, tiles, targetCtx) {
if (!targetCtx) {
targetCtx = this.ctx;
}
var maxX = Math.floor((startX + targetCtx.width) / tileWidth),
maxY = Math.floor((startY + targetCtx.height) / tileHeight);
for (var x = Math.floor(startX / tileWidth); x < maxX; x++) {
for (var y = Math.floor(startY / tileHeight); y < maxY; y++) {
var tileNumber = Math.min(x, 0) + Math.min(y, 0) * layerdatawidth;
targetCtx.drawImage(tiles[layerdata[tileNumber]], startX + x * tileWidth, startY + y * tileHeight);
}
}
};
SQ.Screen.prototype.resizeHandler = function resizeHandler () {
if (this.settings.fullScreen) {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
}; |
Fix warning related to deserialization | package fortiss.gui.listeners.button;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import fortiss.gui.LoadingScreen;
import fortiss.gui.listeners.helper.FileManager;
import fortiss.simulation.Simulation;
public class AcceptListener extends MouseAdapter {
public static Simulation sim;
public static LoadingScreen loadingScreen = new LoadingScreen();
private Thread simt;
/**
* Initializes the simulation. Creates a descriptor file for every building and
* a configuration file for the simulation parameters, disposes the interactive
* simulator window.
*/
@Override
public void mouseClicked(MouseEvent e) {
FileManager fm = new FileManager();
fm.writeMemapModel();
fm.writeBuildingDescriptorFiles();
fm.writeParameterConfigFile(); // Should be called after writeDescriptorFiles()
sim = new Simulation();
simt = new Thread(sim);
simt.start();
}
}
| package fortiss.gui.listeners.button;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import fortiss.gui.Designer;
import fortiss.gui.LoadingScreen;
import fortiss.gui.listeners.helper.FileManager;
import fortiss.simulation.Simulation;
public class AcceptListener extends MouseAdapter {
public static Simulation sim;
public static LoadingScreen loadingScreen = new LoadingScreen();
private Thread simt;
/**
* Initializes the simulation. Creates a descriptor file for every building and
* a configuration file for the simulation parameters, disposes the interactive
* simulator window.
*/
@Override
public void mouseClicked(MouseEvent e) {
FileManager fm = new FileManager();
fm.writeMemapModel();
fm.writeBuildingDescriptorFiles();
fm.writeParameterConfigFile(); // Should be called after writeDescriptorFiles()
sim = new Simulation();
simt = new Thread(sim);
simt.start();
Designer.frame.dispose();
}
}
|
Revert "added GFK for group"
This reverts commit 957e11ef62823a29472eeec4dade65ae01bbea70. | from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import post_save
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
class ProfileBase(models.Model):
user = models.ForeignKey(User, unique=True, verbose_name=_("user"))
class Meta:
verbose_name = _("profile")
verbose_name_plural = _("profiles")
abstract = True
def __unicode__(self):
return self.user.username
def get_absolute_url(self, group=None):
# @@@ make group-aware
return reverse("profile_detail", kwargs={"username": self.user.username})
| from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import post_save
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class ProfileBase(models.Model):
user = models.ForeignKey(User, unique=True, verbose_name=_("user"))
group_content_type = models.ForeignKey(ContentType, null=True, blank=True)
group_object_id = models.PositiveIntegerField(null=True, blank=True)
group = generic.GenericForeignKey("group_content_type", "group_object_id")
class Meta:
verbose_name = _("profile")
verbose_name_plural = _("profiles")
abstract = True
def __unicode__(self):
return self.user.username
def get_absolute_url(self, group=None):
# @@@ make group-aware
return reverse("profile_detail", kwargs={"username": self.user.username})
|
Change license from Proprietary to AGPLv3 | from setuptools import setup, find_packages
INSTALL_REQUIRES = [
'BTrees',
'zope.component',
'zodbpickle',
'ZODB',
'zope.index',
'repoze.catalog',
'lz4-cffi',
'zc.zlibstorage',
'pycryptodome',
'click',
'flask-cors',
'flask',
'requests',
'jsonpickle',
'pyelliptic',
'ecdsa']
setup(
name="zerodb",
version="0.96.4",
description="End-to-end encrypted database",
author="ZeroDB Inc.",
author_email="michael@zerodb.io",
license="AGPLv3",
url="http://zerodb.io",
packages=find_packages(),
install_requires=INSTALL_REQUIRES,
)
| from setuptools import setup, find_packages
INSTALL_REQUIRES = [
'BTrees',
'zope.component',
'zodbpickle',
'ZODB',
'zope.index',
'repoze.catalog',
'lz4-cffi',
'zc.zlibstorage',
'pycryptodome',
'click',
'flask-cors',
'flask',
'requests',
'jsonpickle',
'pyelliptic',
'ecdsa']
setup(
name="zerodb",
version="0.96.4",
description="End-to-end encrypted database",
author="ZeroDB Inc.",
author_email="michael@zerodb.io",
license="Proprietary",
url="http://zerodb.io",
packages=find_packages(),
install_requires=INSTALL_REQUIRES,
)
|
Test fewer dts, only test implicit methods.
The timesteps used here are not valid for explicit methods. | import os
import csv
from collections import deque
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
schemes = ['implicit-euler', 'bdf2', 'crank-nicolson', 'dirk']
scheme_errors = {}
# Generate list of dts
dt = 1.0
dts = []
for i in range(0,5):
dts.append(dt)
dt = dt / 2.0
for scheme in schemes:
errors = []
for dt in dts:
command = '../../../moose_test-opt -i high_order_time_integration.i Executioner/dt=' + str(dt) + ' Executioner/scheme=' + scheme
os.system(command)
with open('high_order_time_integration_out.csv', 'r') as csvfile:
csv_data = csv.reader(csvfile, delimiter=',')
# Get the last row second column
error = deque(csv_data, 2)[0][1]
errors.append(error)
scheme_errors[scheme] = errors
for scheme, errors in scheme_errors.iteritems():
plt.plot(dts, errors, label=scheme)
plt.xscale('log')
plt.yscale('log')
plt.title('Time Convergence Study')
plt.xlabel('dt (s)')
plt.ylabel('L2 Error')
plt.legend(loc='upper left')
plt.show()
| import os
import csv
from collections import deque
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
schemes = ['implicit-euler', 'bdf2', 'crank-nicolson', 'dirk', 'explicit-euler', 'rk-2']
scheme_errors = {}
# Generate list of dts
dt = 1.0
dts = []
for i in range(0,10):
dts.append(dt)
dt = dt / 2.0
for scheme in schemes:
errors = []
for dt in dts:
command = '../../../moose_test-opt -i high_order_time_integration.i Executioner/dt=' + str(dt) + ' Executioner/scheme=' + scheme
os.system(command)
with open('high_order_time_integration_out.csv', 'r') as csvfile:
csv_data = csv.reader(csvfile, delimiter=',')
# Get the last row second column
error = deque(csv_data, 2)[0][1]
errors.append(error)
scheme_errors[scheme] = errors
for scheme, errors in scheme_errors.iteritems():
plt.plot(dts, errors, label=scheme)
plt.xscale('log')
plt.yscale('log')
plt.title('Time Convergence Study')
plt.xlabel('dt (s)')
plt.ylabel('L2 Error')
plt.legend(loc='upper left')
plt.show() |
Update relative path with respect to __file__ | import argparse, shutil, os
import ue4util
def install_plugin(project_file, plugin_folder):
project_folder = os.path.dirname(project_file)
install_folder = os.path.join(project_folder, 'Plugins', 'unrealcv')
if os.path.isdir(install_folder):
shutil.rmtree(install_folder) # Complete remove old version, a little dangerous
shutil.copytree(plugin_folder, install_folder)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('plugin_version')
parser.add_argument('project_file')
args = parser.parse_args()
plugin_version = args.plugin_version
project_file = ue4util.get_real_abspath(args.project_file)
cur_dir = os.path.dirname(os.path.abspath(__file__))
plugin_folder = os.path.join(cur_dir, 'built_plugin/%s' % plugin_version)
install_plugin(project_file, plugin_folder)
| import argparse, shutil, os
import ue4util
def install_plugin(project_file, plugin_folder):
project_folder = os.path.dirname(project_file)
install_folder = os.path.join(project_folder, 'Plugins', 'unrealcv')
if os.path.isdir(install_folder):
shutil.rmtree(install_folder) # Complete remove old version, a little dangerous
shutil.copytree(plugin_folder, install_folder)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('plugin_version')
parser.add_argument('project_file')
args = parser.parse_args()
plugin_version = args.plugin_version
project_file = ue4util.get_real_abspath(args.project_file)
plugin_folder = 'built_plugin/%s' % plugin_version
install_plugin(project_file, plugin_folder)
|
Fix conf.get after converting to env variables. | var express = require('express');
var mongoose = require('mongoose');
var cors = require('cors');
var logger = require('morgan');
var bodyParser = require('body-parser');
var conf = require('./lib/config');
var routes = require('./routes/index');
var privateroutes = require('./routes/private');
var app = express();
mongoose.connect(conf.get('MONGO_URL'));
// app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use('/', routes);
app.use('/', privateroutes);
/// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: {}
});
});
module.exports = app; | var express = require('express');
var mongoose = require('mongoose');
var cors = require('cors');
var logger = require('morgan');
var bodyParser = require('body-parser');
var conf = require('./lib/config');
var routes = require('./routes/index');
var privateroutes = require('./routes/private');
var app = express();
mongoose.connect(conf.get('mongo:url'));
// app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use('/', routes);
app.use('/', privateroutes);
/// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: {}
});
});
module.exports = app; |
Remove wrong copy/paste doc description typo | <?php
/**
* Lock
*
* Class for create and handle locks.
*
* @author Ángel Guzmán Maeso <shakaran@gmail.com>
* @since 0.1
*/
class Lock
{
/**
* Create a lock.
*
* @author Ángel Guzmán Maeso <shakaran@gmail.com>
* @param string $lock_filename The name of lock file.
* @return resource A file pointer resource on success, or FALSE on error
*/
public static function create($lock_filename = NULL)
{
$fp = fopen(LOCK_DIRECTORY . '/' . $lock_filename, 'w');
if ($fp && flock($fp, LOCK_EX | LOCK_NB))
{
if (function_exists('posix_getpid'))
{
fwrite($fp, posix_getpid() . PHP_EOL);
}
return $fp;
}
else
{
return FALSE;
}
}
} | <?php
/**
* Lock
*
* Class for create and handle locks.
*
* @author Ángel Guzmán Maeso <shakaran@gmail.com>
* @since 0.1
*/
class Lock
{
/**
* Create a lock.
*
* Additionally fetch the options in plugin hooks.
*
* @author Ángel Guzmán Maeso <shakaran@gmail.com>
* @param string $lock_filename The name of lock file.
* @return resource A file pointer resource on success, or FALSE on error
*/
public static function create($lock_filename = NULL)
{
$fp = fopen(LOCK_DIRECTORY . '/' . $lock_filename, 'w');
if ($fp && flock($fp, LOCK_EX | LOCK_NB))
{
if (function_exists('posix_getpid'))
{
fwrite($fp, posix_getpid() . PHP_EOL);
}
return $fp;
}
else
{
return FALSE;
}
}
} |
Stop opening of new tabs, the pages include links back to admin page | currentSearch = new Mongo.Collection("currentsearch");
Meteor.subscribe('movies');
Meteor.subscribe('tv');
Meteor.subscribe('cpapi');
Session.set('searchType', '');
Router.configure({
notFoundTemplate: "NotFound"
});
Router.route('/', function () {
this.render('home');
});
Router.route('/couchpotato', function () {
this.render('couchpotato');
});
Router.route('/plex', function () {
this.render('plex');
});
Router.route('/sickrage', function () {
this.render('sickrage');
});
Template.body.helpers({
url: function () {
return Meteor.absoluteUrl();
}
});
Houston.menu({
'type': 'link',
'use': '/plex',
'title': 'Plex Auth Setup',
});
Houston.menu({
'type': 'link',
'use': '/couchpotato',
'title': 'CouchPotato Status',
});
Houston.menu({
'type': 'link',
'use': '/sickrage',
'title': 'SickRage Status',
});
Houston.menu({
'type': 'link',
'use': 'http://plexrequests.8bits.ca',
'title': 'Project Site',
'target': '_blank'
}); | currentSearch = new Mongo.Collection("currentsearch");
Meteor.subscribe('movies');
Meteor.subscribe('tv');
Meteor.subscribe('cpapi');
Session.set('searchType', '');
Router.configure({
notFoundTemplate: "NotFound"
});
Router.route('/', function () {
this.render('home');
});
Router.route('/couchpotato', function () {
this.render('couchpotato');
});
Router.route('/plex', function () {
this.render('plex');
});
Router.route('/sickrage', function () {
this.render('sickrage');
});
Template.body.helpers({
url: function () {
return Meteor.absoluteUrl();
}
});
Houston.menu({
'type': 'link',
'use': '/plex',
'title': 'Plex Auth Setup',
'target': '_blank'
});
Houston.menu({
'type': 'link',
'use': '/couchpotato',
'title': 'CouchPotato Status',
'target': '_blank'
});
Houston.menu({
'type': 'link',
'use': '/sickrage',
'title': 'SickRage Status',
'target': '_blank'
});
Houston.menu({
'type': 'link',
'use': 'http://plexrequests.8bits.ca',
'title': 'Project Site',
'target': '_blank'
}); |
Fix signature for ResourceLoader constructor | package com.xtremelabs.robolectric.shadows;
import android.app.Activity;
import android.app.Application;
import android.content.res.Resources;
import com.xtremelabs.robolectric.R;
import com.xtremelabs.robolectric.Robolectric;
import com.xtremelabs.robolectric.WithTestDefaultsRunner;
import com.xtremelabs.robolectric.res.ResourceLoader;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.notNullValue;
import java.io.File;
import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
@RunWith(WithTestDefaultsRunner.class)
public class ResourcesTest {
@Before
public void setUp() throws Exception {
Robolectric.bindDefaultShadowClasses();
Robolectric.application = ShadowApplication.bind(new Application(), new ResourceLoader(R.class, new File("test/res"), new File("test/assets")));
}
@Test(expected = Resources.NotFoundException.class)
public void getStringArray_shouldThrowExceptionIfNotFound() throws Exception {
Robolectric.bindDefaultShadowClasses();
Robolectric.application = ShadowApplication.bind(new Application(), new ResourceLoader(R.class, resourceFile("res"), resourceFile("assets")));
new Activity().getResources().getStringArray(-1);
}
@Test
public void testConfiguration() {
assertThat( new Activity().getResources().getConfiguration(), notNullValue() );
}
}
| package com.xtremelabs.robolectric.shadows;
import android.app.Activity;
import android.app.Application;
import android.content.res.Resources;
import com.xtremelabs.robolectric.R;
import com.xtremelabs.robolectric.Robolectric;
import com.xtremelabs.robolectric.WithTestDefaultsRunner;
import com.xtremelabs.robolectric.res.ResourceLoader;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.notNullValue;
import java.io.File;
import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
@RunWith(WithTestDefaultsRunner.class)
public class ResourcesTest {
@Before
public void setUp() throws Exception {
Robolectric.bindDefaultShadowClasses();
Robolectric.application = ShadowApplication.bind(new Application(), new ResourceLoader(R.class, new File("test/res")));
}
@Test(expected = Resources.NotFoundException.class)
public void getStringArray_shouldThrowExceptionIfNotFound() throws Exception {
Robolectric.bindDefaultShadowClasses();
Robolectric.application = ShadowApplication.bind(new Application(), new ResourceLoader(R.class, resourceFile("res"), resourceFile("assets")));
new Activity().getResources().getStringArray(-1);
}
@Test
public void testConfiguration() {
assertThat( new Activity().getResources().getConfiguration(), notNullValue() );
}
}
|
Fix logged out revision access | import schema from './schema.js';
import { createCollection, getDefaultResolvers /*, getDefaultMutations */} from 'meteor/vulcan:core';
import { extractVersionsFromSemver } from '../../editor/utils'
/**
* @summary Telescope Messages namespace
* @namespace Reports
*/
const Revisions = createCollection({
collectionName: 'Revisions',
typeName: 'Revision',
schema,
resolvers: getDefaultResolvers('Revisions'),
// mutations: getDefaultMutations('Revisions'),
});
// Note, since we want to make sure checkAccess is a performant function, we can only check the
// userId of the current revision for ownership. If the userId of the document the revision is on,
// and the revision itself differ (e.g. because an admin has made the edit, or a coauthor), then
// we will hide those revisions unless they are marked as post-1.0.0 releases. This is not ideal, but
// seems acceptable
Revisions.checkAccess = function (user, revision) {
if ((user && user._id) === revision.userId) return true
const { major } = extractVersionsFromSemver(revision.version)
return major > 0
}
export default Revisions;
| import schema from './schema.js';
import { createCollection, getDefaultResolvers /*, getDefaultMutations */} from 'meteor/vulcan:core';
import { extractVersionsFromSemver } from '../../editor/utils'
/**
* @summary Telescope Messages namespace
* @namespace Reports
*/
const Revisions = createCollection({
collectionName: 'Revisions',
typeName: 'Revision',
schema,
resolvers: getDefaultResolvers('Revisions'),
// mutations: getDefaultMutations('Revisions'),
});
// Note, since we want to make sure checkAccess is a performant function, we can only check the
// userId of the current revision for ownership. If the userId of the document the revision is on,
// and the revision itself differ (e.g. because an admin has made the edit, or a coauthor), then
// we will hide those revisions unless they are marked as post-1.0.0 releases. This is not ideal, but
// seems acceptable
Revisions.checkAccess = function (user, revision) {
if (user._id === revision.userId) return true
const { major } = extractVersionsFromSemver(revision.version)
return major > 0
}
export default Revisions;
|
Fix generator being passed to the wfile.write method of the HttpHandler instead of string | import os
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from jinja2 import Environment, FileSystemLoader
from jinger.config import get_config
env = None
class Http404(Exception):
pass
class JingerHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
try:
self.wfile.write(get_html(self.path))
except Http404:
self.send_error(404, 'Template not found for path: %s' % self.path)
def get_html(path):
global env
templatepath = os.path.abspath(os.path.join(*tuple([s for s in path.split() if s])))
try:
return env.get_template(templatepath).render()
except IOError:
raise Http404
def startserver(port):
global env
conf = get_config(os.getcwd())
env = Environment(loader=FileSystemLoader(conf['sourcedir']))
try:
server = HTTPServer(('', int(port)), JingerHTTPRequestHandler)
print 'Development server started at 127.0.0.1 on port %s' % port
server.serve_forever()
except KeyboardInterrupt:
print 'Shutting down server'
server.socket.close()
if __name__ == '__main__':
startserver()
| import os
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from jinja2 import Environment, FileSystemLoader
from jinger.config import get_config
env = None
class Http404(Exception):
pass
class JingerHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
try:
self.wfile.write(get_html(self.path))
except Http404:
self.send_error(404, 'Template not found for path: %s' % self.path)
def get_html(path):
global env
templatepath = os.path.abspath(os.path.join(*tuple([s for s in path.split() if s])))
try:
return env.get_template(templatepath).generate()
except IOError:
raise Http404
def startserver(port):
global env
conf = get_config(os.getcwd())
env = Environment(loader=FileSystemLoader(conf['sourcedir']))
try:
server = HTTPServer(('', int(port)), JingerHTTPRequestHandler)
print 'Development server started at 127.0.0.1 on port %s' % port
server.serve_forever()
except KeyboardInterrupt:
print 'Shutting down server'
server.socket.close()
if __name__ == '__main__':
startserver()
|
Fix two doc comment format | // Package testing define helper / mock for unit testing
//
// Because golang likes return error object instead of exception/panic,
// always handle error return values is a good practise. But sometimes it is
// impossible to got error, such as read from memory buffer, not handler them
// maybe maybe loose error because someday code changes, but handle them needs
// a lot of duplicate codes.
//
// In package testing contains many test helper packages, suffix with `th', to
// handle these never happen errors. Test helper check the error result, if it
// is not nil, using testing.Fatal(err) to log the error object and abort current
// test case execution.
package testing
import (
"time"
)
// TryWait the action until it returns true, call timeout if timeout.
func TryWait(d time.Duration, try func() bool, timeout func()) {
tick := int64(d) / 100
for i := 0; i < 100; i++ {
if try() {
return
}
time.Sleep(time.Duration(tick))
}
timeout()
}
| // Define helper / mock for unit testing
//
// Because golang likes return error object instead of exception/panic,
// always handle error return values is a good practise. But sometimes it is
// impossible to got error, such as read from memory buffer, not handler them
// maybe maybe loose error because someday code changes, but handle them needs
// a lot of duplicate codes.
//
// In package testing contains many test helper packages, suffix with `th', to
// handle these never happen errors. Test helper check the error result, if it
// is not nil, using testing.Fatal(err) to log the error object and abort current
// test case execution.
package testing
import (
"time"
)
// Try the action until it returns true, call timeout if timeout.
func TryWait(d time.Duration, try func() bool, timeout func()) {
tick := int64(d) / 100
for i := 0; i < 100; i++ {
if try() {
return
}
time.Sleep(time.Duration(tick))
}
timeout()
}
|
Use long stack traces in tests. | 'use strict';
//====================================================================
var hashy = require('./');
//--------------------------------------------------------------------
var expect = require('chai').expect;
var Bluebird = require('bluebird');
Bluebird.longStackTraces();
//====================================================================
var data = [
{
value: 'password',
hash: '$2a$10$3F2S0bh8CO8aVzW/tqyjI.iVQnLNea1YIpNSpS8dmJwUVNXP3D4/y',
info: {
algo: hashy.BCRYPT,
algoName: 'bcrypt',
options: {
cost: 10,
},
}
},
];
//====================================================================
describe('hash()', function () {
var hash = hashy.hash;
it('can return a promise', function () {
return hash('test');
});
it('can work with callback', function (done) {
hash('test', done);
});
it('does not creates the same hash twice', function () {
return Bluebird.all([
hash('test'),
hash('test'),
]).spread(function (hash1, hash2) {
expect(hash1).to.not.equal(hash2);
});
});
});
describe('getInfo()', function () {
var getInfo = hashy.getInfo;
it('returns the algorithm and options', function () {
data.forEach(function (datum) {
expect(getInfo(datum.hash)).to.deep.equal(datum.info);
});
});
});
describe('needsRehash()', function () {
var needsRehash = hashy.needsRehash;
// TODO
});
| 'use strict';
//====================================================================
var hashy = require('./');
//--------------------------------------------------------------------
var expect = require('chai').expect;
var Bluebird = require('bluebird');
//====================================================================
var data = [
{
value: 'password',
hash: '$2a$10$3F2S0bh8CO8aVzW/tqyjI.iVQnLNea1YIpNSpS8dmJwUVNXP3D4/y',
info: {
algo: hashy.BCRYPT,
algoName: 'bcrypt',
options: {
cost: 10,
},
}
},
];
//====================================================================
describe('hash()', function () {
var hash = hashy.hash;
it('can return a promise', function () {
return hash('test');
});
it('can work with callback', function (done) {
hash('test', done);
});
it('does not creates the same hash twice', function () {
return Bluebird.all([
hash('test'),
hash('test'),
]).spread(function (hash1, hash2) {
expect(hash1).to.not.equal(hash2);
});
});
});
describe('getInfo()', function () {
var getInfo = hashy.getInfo;
it('returns the algorithm and options', function () {
data.forEach(function (datum) {
expect(getInfo(datum.hash)).to.deep.equal(datum.info);
});
});
});
describe('needsRehash()', function () {
var needsRehash = hashy.needsRehash;
// TODO
});
|
Add CAS methods to Null memcache
This prevents breaking ownCloud completely when memcache is not enabled
and the locking code is triggered | <?php
/**
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin McCorkell <rmccorkell@karoshi.org.uk>
*
* @copyright Copyright (c) 2015, ownCloud, Inc.
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Memcache;
class Null extends Cache {
public function get($key) {
return null;
}
public function set($key, $value, $ttl = 0) {
return true;
}
public function hasKey($key) {
return false;
}
public function remove($key) {
return true;
}
public function inc($key) {
return true;
}
public function dec($key) {
return true;
}
public function cas($key, $old, $new) {
return true;
}
public function clear($prefix = '') {
return true;
}
static public function isAvailable() {
return true;
}
}
| <?php
/**
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin McCorkell <rmccorkell@karoshi.org.uk>
*
* @copyright Copyright (c) 2015, ownCloud, Inc.
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Memcache;
class Null extends Cache {
public function get($key) {
return null;
}
public function set($key, $value, $ttl = 0) {
return true;
}
public function hasKey($key) {
return false;
}
public function remove($key) {
return true;
}
public function clear($prefix = '') {
return true;
}
static public function isAvailable() {
return true;
}
}
|
Fix for contrast stylesheet public path | /* eslint-disable no-underscore-dangle */
import last from 'lodash/last';
/**
* Change the Scope UI theme from normal to high-contrast.
* This will inject a stylesheet into <head> and override the styles.
*
* A window-level variable is written to the .html page during the build process that contains
* the filename (and content hash) needed to download the file.
*/
function getFilename(href) {
return last(href.split('/'));
}
export function loadTheme(theme = 'normal') {
if (window.__WEAVE_SCOPE_THEMES) {
// Load the pre-built stylesheet.
const stylesheet = window.__WEAVE_SCOPE_THEMES[theme];
const head = document.querySelector('head');
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = stylesheet;
link.onload = () => {
// Remove the old stylesheet to prevent weird overlapping styling issues
const oldTheme = theme === 'normal' ? 'contrast' : 'normal';
const links = document.querySelectorAll('head link');
for (let i = 0; i < links.length; i += 1) {
const l = links[i];
if (getFilename(l.href) === getFilename(window.__WEAVE_SCOPE_THEMES[oldTheme])) {
head.removeChild(l);
break;
}
}
};
head.appendChild(link);
}
}
| /* eslint-disable no-underscore-dangle */
import last from 'lodash/last';
/**
* Change the Scope UI theme from normal to high-contrast.
* This will inject a stylesheet into <head> and override the styles.
*
* A window-level variable is written to the .html page during the build process that contains
* the filename (and content hash) needed to download the file.
*/
function getFilename(href) {
return last(href.split('/'));
}
export function loadTheme(theme = 'normal') {
if (window.__WEAVE_SCOPE_THEMES) {
// Load the pre-built stylesheet.
const stylesheet = window.__WEAVE_SCOPE_THEMES[theme];
const head = document.querySelector('head');
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = `${window.__WEAVE_SCOPE_THEMES.publicPath}${stylesheet}`;
link.onload = () => {
// Remove the old stylesheet to prevent weird overlapping styling issues
const oldTheme = theme === 'normal' ? 'contrast' : 'normal';
const links = document.querySelectorAll('head link');
for (let i = 0; i < links.length; i += 1) {
const l = links[i];
if (getFilename(l.href) === getFilename(window.__WEAVE_SCOPE_THEMES[oldTheme])) {
head.removeChild(l);
break;
}
}
};
head.appendChild(link);
}
}
|
Change plugin order of execution | // --------------------
// Sequelize extra
// --------------------
// modules
var Sequelize = require('sequelize'),
sequelizeDefiner = require('sequelize-definer'),
sequelizeVirtualFields = require('sequelize-virtual-fields'),
sequelizeHierarchy = require('sequelize-hierarchy'),
Utils = Sequelize.Utils,
_ = Utils._;
// imports
var utils = require('./utils'),
dataTypes = require('./dataTypes'),
getValues = require('./getValues');
// exports
module.exports = Sequelize;
// load plugins
sequelizeDefiner(Sequelize);
sequelizeVirtualFields(Sequelize);
sequelizeHierarchy(Sequelize);
// additional data types
_.extend(Sequelize, dataTypes);
// add getValues methods
Sequelize.getValues = getValues.getValuesSequelize;
Sequelize.Instance.prototype.getValues = getValues.getValuesInstance;
Sequelize.getValuesDedup = getValues.getValuesDedupSequelize;
Sequelize.Instance.prototype.getValuesDedup = getValues.getValuesDedupInstance;
| // --------------------
// Sequelize extra
// --------------------
// modules
var Sequelize = require('sequelize'),
sequelizeDefiner = require('sequelize-definer'),
sequelizeHierarchy = require('sequelize-hierarchy'),
sequelizeVirtualFields = require('sequelize-virtual-fields'),
Utils = Sequelize.Utils,
_ = Utils._;
// imports
var utils = require('./utils'),
dataTypes = require('./dataTypes'),
getValues = require('./getValues');
// exports
module.exports = Sequelize;
// load plugins
sequelizeDefiner(Sequelize);
sequelizeHierarchy(Sequelize);
sequelizeVirtualFields(Sequelize);
// additional data types
_.extend(Sequelize, dataTypes);
// add getValues methods
Sequelize.getValues = getValues.getValuesSequelize;
Sequelize.Instance.prototype.getValues = getValues.getValuesInstance;
Sequelize.getValuesDedup = getValues.getValuesDedupSequelize;
Sequelize.Instance.prototype.getValuesDedup = getValues.getValuesDedupInstance;
|
Move promise handler into the factory. | 'use strict';
angular.module('fivefifteenApp')
.controller('MainCtrl', function ($scope, $routeParams, Data, Steps) {
// Simple Data service to persist form values.
$scope.data = Data;
$scope.path = $routeParams.stepName;
$scope.steps = Steps.data;
})
// scope data is not persistent across views so we use a simple service.
.factory('Data', function () {
// This variable holds all of the text used on the site.
return {};
})
.factory('Steps', function($firebase) {
var url = new Firebase("https://fivefifteen.firebaseio.com/steps"),
ref = $firebase(url),
factory = { "data": {} };
ref.$on('loaded', function(values) {
// If we get values, store it both in the scope and Steps.
if (typeof values !== "undefined") {
angular.extend(factory.data, values);
}
});
return factory;
});
| 'use strict';
angular.module('fivefifteenApp')
.controller('MainCtrl', function ($scope, $routeParams, Data, Steps) {
// Simple Data service to persist form values.
$scope.data = Data;
$scope.path = $routeParams.stepName;
$scope.steps = Steps.data;
Steps.promise.$on('loaded', function(values) {
// If we get values, store it both in the scope and Steps.
if (typeof values !== "undefined") {
angular.extend(Steps.data, values);
}
});
})
// scope data is not persistent across views so we use a simple service.
.factory('Data', function () {
// This variable holds all of the text used on the site.
return {};
})
.factory('Steps', function($firebase) {
var url = new Firebase("https://fivefifteen.firebaseio.com/steps"),
ref = $firebase(url);
return {
"promise": ref,
"data": {}
};
});
|
Comment out test assertions to allow travis build to pass to examine logs after | <?php
namespace SimplyTestable\WorkerBundle\Tests\Command;
use SimplyTestable\WorkerBundle\Tests\Command\ConsoleCommandBaseTestCase;
class WorkerActivateCommandTest extends ConsoleCommandBaseTestCase {
public function testSuccessfulActivateWorker() {
$this->setupDatabase();
$response = $this->runConsole('simplytestable:worker:activate', array(
$this->getFixturesDataPath(__FUNCTION__) . '/HttpResponses' => true
));
//$this->assertEquals(self::CONSOLE_COMMAND_SUCCESS, $response);
}
public function test404FailureActivateWorker() {
$this->setupDatabase();
$response = $this->runConsole('simplytestable:worker:activate', array(
'/invalid-fixtures-path-forces-mock-http-client-to-respond-with-404' => true
));
//$this->assertEquals(self::CONSOLE_COMMAND_FAILURE, $response);
}
}
| <?php
namespace SimplyTestable\WorkerBundle\Tests\Command;
use SimplyTestable\WorkerBundle\Tests\Command\ConsoleCommandBaseTestCase;
class WorkerActivateCommandTest extends ConsoleCommandBaseTestCase {
public function testSuccessfulActivateWorker() {
$this->setupDatabase();
$response = $this->runConsole('simplytestable:worker:activate', array(
$this->getFixturesDataPath(__FUNCTION__) . '/HttpResponses' => true
));
$this->assertEquals(self::CONSOLE_COMMAND_SUCCESS, $response);
}
public function test404FailureActivateWorker() {
$this->setupDatabase();
$response = $this->runConsole('simplytestable:worker:activate', array(
'/invalid-fixtures-path-forces-mock-http-client-to-respond-with-404' => true
));
$this->assertEquals(self::CONSOLE_COMMAND_FAILURE, $response);
}
}
|
Add method to add custom texture | package info.u_team.u_team_core.util;
import static net.minecraft.client.renderer.model.ModelBakery.*;
import java.util.*;
import com.google.common.collect.*;
import net.minecraft.block.*;
import net.minecraft.client.renderer.model.RenderMaterial;
import net.minecraft.state.StateContainer;
import net.minecraft.util.ResourceLocation;
public class ModelUtil {
static {
if (STATE_CONTAINER_OVERRIDES instanceof ImmutableMap) {
final Map<ResourceLocation, StateContainer<Block, BlockState>> mutableMap = new HashMap<>();
STATE_CONTAINER_OVERRIDES.forEach(mutableMap::put);
STATE_CONTAINER_OVERRIDES = mutableMap;
}
}
public static void addCustomStateContainer(ResourceLocation location, StateContainer<Block, BlockState> container) {
STATE_CONTAINER_OVERRIDES.put(location, container);
}
public static void addTexture(RenderMaterial material) {
LOCATIONS_BUILTIN_TEXTURES.add(material);
}
public static class EmptyStateContainer extends StateContainer<Block, BlockState> {
public EmptyStateContainer(Block block) {
super(Block::getDefaultState, block, BlockState::new, new HashMap<>());
}
@Override
public ImmutableList<BlockState> getValidStates() {
return getOwner().getStateContainer().getValidStates();
}
}
}
| package info.u_team.u_team_core.util;
import static net.minecraft.client.renderer.model.ModelBakery.STATE_CONTAINER_OVERRIDES;
import java.util.*;
import com.google.common.collect.*;
import net.minecraft.block.*;
import net.minecraft.state.StateContainer;
import net.minecraft.util.ResourceLocation;
public class ModelUtil {
static {
if (STATE_CONTAINER_OVERRIDES instanceof ImmutableMap) {
final Map<ResourceLocation, StateContainer<Block, BlockState>> mutableMap = new HashMap<>();
STATE_CONTAINER_OVERRIDES.forEach(mutableMap::put);
STATE_CONTAINER_OVERRIDES = mutableMap;
}
}
public static void addCustomStateContainer(ResourceLocation location, StateContainer<Block, BlockState> container) {
STATE_CONTAINER_OVERRIDES.put(location, container);
}
public static class EmptyStateContainer extends StateContainer<Block, BlockState> {
public EmptyStateContainer(Block block) {
super(Block::getDefaultState, block, BlockState::new, new HashMap<>());
}
@Override
public ImmutableList<BlockState> getValidStates() {
return getOwner().getStateContainer().getValidStates();
}
}
}
|
Return false in case one of the values is null | <?php
/**
* Copyright (c) 2014 Lukas Reschke <lukas@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace OC\Security;
class StringUtils {
/**
* Compares whether two strings are equal. To prevent guessing of the string
* length this is done by comparing two hashes against each other and afterwards
* a comparison of the real string to prevent against the unlikely chance of
* collisions.
*
* Be aware that this function may leak whether the string to compare have a different
* length.
*
* @param string $expected The expected value
* @param string $input The input to compare against
* @return bool True if the two strings are equal, otherwise false.
*/
public static function equals($expected, $input) {
if(!is_string($expected) || !is_string($input)) {
return false;
}
if(function_exists('hash_equals')) {
return hash_equals($expected, $input);
}
$randomString = \OC::$server->getSecureRandom()->getLowStrengthGenerator()->generate(10);
if(hash('sha512', $expected.$randomString) === hash('sha512', $input.$randomString)) {
if($expected === $input) {
return true;
}
}
return false;
}
} | <?php
/**
* Copyright (c) 2014 Lukas Reschke <lukas@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace OC\Security;
class StringUtils {
/**
* Compares whether two strings are equal. To prevent guessing of the string
* length this is done by comparing two hashes against each other and afterwards
* a comparison of the real string to prevent against the unlikely chance of
* collisions.
*
* Be aware that this function may leak whether the string to compare have a different
* length.
*
* @param string $expected The expected value
* @param string $input The input to compare against
* @return bool True if the two strings are equal, otherwise false.
*/
public static function equals($expected, $input) {
if(function_exists('hash_equals')) {
return hash_equals($expected, $input);
}
$randomString = \OC::$server->getSecureRandom()->getLowStrengthGenerator()->generate(10);
if(hash('sha512', $expected.$randomString) === hash('sha512', $input.$randomString)) {
if($expected === $input) {
return true;
}
}
return false;
}
} |
Fix broken link to ragged tensor guide
PiperOrigin-RevId: 368443422
Change-Id: I69818413b7ed8cf2f372580878860a469b9735a8 | # Copyright 2018 The TensorFlow 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.
# ==============================================================================
"""Ragged Tensors.
This package defines ops for manipulating ragged tensors (`tf.RaggedTensor`),
which are tensors with non-uniform shapes. In particular, each `RaggedTensor`
has one or more *ragged dimensions*, which are dimensions whose slices may have
different lengths. For example, the inner (column) dimension of
`rt=[[3, 1, 4, 1], [], [5, 9, 2], [6], []]` is ragged, since the column slices
(`rt[0, :]`, ..., `rt[4, :]`) have different lengths. For a more detailed
description of ragged tensors, see the `tf.RaggedTensor` class documentation
and the [Ragged Tensor Guide](/guide/ragged_tensor).
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| # Copyright 2018 The TensorFlow 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.
# ==============================================================================
"""Ragged Tensors.
This package defines ops for manipulating ragged tensors (`tf.RaggedTensor`),
which are tensors with non-uniform shapes. In particular, each `RaggedTensor`
has one or more *ragged dimensions*, which are dimensions whose slices may have
different lengths. For example, the inner (column) dimension of
`rt=[[3, 1, 4, 1], [], [5, 9, 2], [6], []]` is ragged, since the column slices
(`rt[0, :]`, ..., `rt[4, :]`) have different lengths. For a more detailed
description of ragged tensors, see the `tf.RaggedTensor` class documentation
and the [Ragged Tensor Guide](/guide/ragged_tensors).
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
|
Add a rule for decimal numbers.
To be used in AlbumEdit.
Refs #78. | export function mandatory(comp) {
return v => !!v || comp.$t('validation.mandatory')
}
function regexMatch(comp, regex, key) {
return v => {
if (!v) {
return true
}
return !!String(v).match(regex) || comp.$t(key)
}
}
export function email(comp) {
// Not really the right regex but it's sufficient
return regexMatch(comp, /^[^@]+@[^@]+$/, 'validation.email')
}
export function integer(comp) {
// Note that this rule only works partially because browsers will return an empty value for
// number fields. But that's the best we can do while keeping up/down arrows.
return regexMatch(comp, /^[0-9]*$/, 'validation.integer')
}
export function number(comp) {
// Note that this rule only works partially because browsers will return an empty value for
// number fields. But that's the best we can do while keeping up/down arrows.
return regexMatch(comp, /^([0-9]*|[0-9]+\.[0-9]+)$/, 'validation.number')
}
export function phone(comp) {
return regexMatch(comp, /^\+?[0-9() /-]+$/, 'validation.phone')
}
export function url(comp) {
return regexMatch(comp, /^https?:\/\/.*$/, 'validation.url')
}
| export function mandatory(comp) {
return v => !!v || comp.$t('validation.mandatory')
}
function regexMatch(comp, regex, key) {
return v => {
if (!v) {
return true
}
return !!String(v).match(regex) || comp.$t(key)
}
}
export function email(comp) {
// Not really the right regex but it's sufficient
return regexMatch(comp, /^[^@]+@[^@]+$/, 'validation.email')
}
export function integer(comp) {
// Note that this rule only works partially because browsers will return an empty value for
// number fields. But that's the best we can do while keeping up/down arrows.
return regexMatch(comp, /^[0-9]*$/, 'validation.integer')
}
export function phone(comp) {
return regexMatch(comp, /^\+?[0-9() /-]+$/, 'validation.phone')
}
export function url(comp) {
return regexMatch(comp, /^https?:\/\/.*$/, 'validation.url')
}
|
Update winston to handle uncaught exceptions | const _ = require('lodash');
const { Logger, transports: { Console } } = require('winston');
module.exports = function wrappedDebug(module) {
const logger = new Logger({
level: 'info',
transports: [
new (Console)({
json: true,
stringify: true,
handleExceptions: true,
}),
],
});
[
'error',
'warn',
'info',
'verbose',
'debug',
'silly',
].forEach((method) => {
const originalMethod = logger[method];
logger[method] = function logMethod(message, meta = {}) {
const newMeta = _.defaultsDeep({}, meta, {
ctx: {
app: 'amion-scraper',
module,
},
});
return originalMethod(message, newMeta);
};
});
return logger.info.bind(logger);
};
| const _ = require('lodash');
const { Logger, transports: { Console } } = require('winston');
module.exports = function wrappedDebug(module) {
const logger = new Logger({
level: 'info',
transports: [
new (Console)({
json: true,
stringify: true,
}),
],
});
[
'error',
'warn',
'info',
'verbose',
'debug',
'silly',
].forEach((method) => {
const originalMethod = logger[method];
logger[method] = function logMethod(message, meta = {}) {
const newMeta = _.defaultsDeep({}, meta, {
ctx: {
app: 'amion-scraper',
module,
},
});
return originalMethod(message, newMeta);
};
});
return logger.info.bind(logger);
};
|
Fix check that decides when SSO screen is rendered | import { Map } from 'immutable';
import LastLoginScreen from './last_login_screen';
import LoadingScreen from '../loading_screen';
import { ui, findConnection } from '../index';
export function renderSSOScreens(m) {
if (!ui.rememberLastLogin(m)) return null;
// TODO: loading pin check belongs here?
if (m.getIn(["sso", "syncStatus"]) != "ok" || m.get("isLoadingPanePinned")) {
return new LoadingScreen();
}
const { name, strategy } = lastUsedConnection(m);
const skipped = m.getIn(["sso", "skipped"], false);
return !skipped && findConnection(m, strategy, name)
? new LastLoginScreen()
: null;
}
export function lastUsedConnection(m) {
// { name, strategy }
return m.getIn(["sso", "lastUsedConnection"], Map()).toJS();
}
export function lastUsedUsername(m) {
return m.getIn(["sso", "lastUsedUsername"], "");
}
export function skipSSOLogin(m) {
return m.setIn(["sso", "skipped"], true);
}
| import { Map } from 'immutable';
import LastLoginScreen from './last_login_screen';
import LoadingScreen from '../loading_screen';
import { findConnection } from '../index';
export function renderSSOScreens(m) {
// TODO: client and pinned checks don't belong here
if (!m.has("sso") || !m.has("client") || m.get("isLoadingPanePinned")) {
return new LoadingScreen();
}
const { name, strategy } = lastUsedConnection(m);
const skipped = m.getIn(["sso", "skipped"], false);
return !skipped && findConnection(m, strategy, name)
? new LastLoginScreen()
: null;
}
export function lastUsedConnection(m) {
// { name, strategy }
return m.getIn(["sso", "lastUsedConnection"], Map()).toJS();
}
export function lastUsedUsername(m) {
return m.getIn(["sso", "lastUsedUsername"], "");
}
export function skipSSOLogin(m) {
return m.setIn(["sso", "skipped"], true);
}
|
Remove controller, just keys ! | /*! Konami v1.0.1 | (c) 2013 Antoine FRITEAU | antoinfriteau.fr/licenses
*/
(function( $ ) {
"use strict";
$.fn.konami = function( options ) {
var opts, konamiCode, keys;
var opts = $.extend({}, $.fn.konami.defaults, options); // extends options
return this.each(function() {
konamiCode = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
keys = [];
$( window ).keyup(function( evt ) {
keys.push( evt.keyCode ? evt.keyCode : evt.which );
if( keys.toString().indexOf( konamiCode ) >= 0 ) {
opts.reveal();
keys = [];
}
});
});
};
$.fn.konami.defaults = {
reveal: null
};
}(jQuery)) | /*! Konami v1.0.1 | (c) 2013 Antoine FRITEAU | antoinfriteau.fr/licenses
*/
(function( $ ) {
"use strict";
$.fn.konami = function( options ) {
var opts, konamiCode, controllerCode;
var opts = $.extend({}, $.fn.konami.defaults, options); // extends options
return this.each(function() {
konamiCode = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
controllerCode = [];
$( window ).keyup(function( evt ) {
controllerCode.push( evt.keyCode ? evt.keyCode : evt.which );
if( controllerCode.toString().indexOf( konamiCode ) >= 0 ) {
opts.reveal();
controllerCode = [];
}
});
});
};
$.fn.konami.defaults = {
reveal: null
};
}(jQuery)) |
Remove unused set*(Collection) methods on models | <?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.
*/
namespace Sylius\Component\Attribute\Model;
use Doctrine\Common\Collections\Collection;
/**
* Interface implemented by object which can be characterized
* using the attributes.
*
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface AttributeSubjectInterface
{
/**
* @return Collection|AttributeValueInterface[]
*/
public function getAttributes();
/**
* @param AttributeValueInterface $attribute
*/
public function addAttribute(AttributeValueInterface $attribute);
/**
* @param AttributeValueInterface $attribute
*/
public function removeAttribute(AttributeValueInterface $attribute);
/**
* @param AttributeValueInterface $attribute
*
* @return bool
*/
public function hasAttribute(AttributeValueInterface $attribute);
/**
* @param string $attributeCode
*
* @return bool
*/
public function hasAttributeByCode($attributeCode);
/**
* @param string $attributeCode
*
* @return AttributeValueInterface
*/
public function getAttributeByCode($attributeCode);
}
| <?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.
*/
namespace Sylius\Component\Attribute\Model;
use Doctrine\Common\Collections\Collection;
/**
* Interface implemented by object which can be characterized
* using the attributes.
*
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface AttributeSubjectInterface
{
/**
* @return Collection|AttributeValueInterface[]
*/
public function getAttributes();
/**
* @param Collection $attributes
*/
public function setAttributes(Collection $attributes);
/**
* @param AttributeValueInterface $attribute
*/
public function addAttribute(AttributeValueInterface $attribute);
/**
* @param AttributeValueInterface $attribute
*/
public function removeAttribute(AttributeValueInterface $attribute);
/**
* @param AttributeValueInterface $attribute
*
* @return bool
*/
public function hasAttribute(AttributeValueInterface $attribute);
/**
* @param string $attributeCode
*
* @return bool
*/
public function hasAttributeByCode($attributeCode);
/**
* @param string $attributeCode
*
* @return AttributeValueInterface
*/
public function getAttributeByCode($attributeCode);
}
|
Fix char to int convesion | package com.vrachieru.cnp4j;
import static java.lang.Character.getNumericValue;
public class CnpUtil {
public static final int CNP_LENGTH = 13;
public static final int[] WEIGHTS = new int[]{2, 7, 9, 1, 4, 6, 3, 5, 8, 2, 7, 9};
public static int calculateCheckDigit(String cnp) {
int sum = calculateSum(cnp);
int checkDigit = sum % 11;
return (checkDigit == 10) ? 1 : checkDigit;
}
public static int calculateSum(String cnp) {
int sum = 0;
for (int i = 0; i < CNP_LENGTH - 1; i++) {
sum += getNumericValue(cnp.charAt(i)) * WEIGHTS[i];
}
return sum;
}
}
| package com.vrachieru.cnp4j;
public class CnpUtil {
public static final int CNP_LENGTH = 13;
public static final int[] WEIGHTS = new int[]{2, 7, 9, 1, 4, 6, 3, 5, 8, 2, 7, 9};
public static int calculateCheckDigit(String cnp) {
int sum = calculateSum(cnp);
int checkDigit = sum % 11;
return (checkDigit == 10) ? 1 : checkDigit;
}
public static int calculateSum(String cnp) {
int sum = 0;
for (int i = 0; i < CNP_LENGTH - 1; i++) {
sum += Integer.valueOf(cnp.charAt(i)) * WEIGHTS[i];
}
return sum;
}
}
|
Enable tests for Safari 9 | var argv = require('yargs').argv;
module.exports = {
registerHooks: function(context) {
var saucelabsPlatforms = [
// 'macOS 10.12/iphone@10.3',
// 'macOS 10.12/ipad@10.3',
'Windows 10/microsoftedge@15',
'Windows 10/internet explorer@11',
'macOS 10.12/safari@11.0',
'macOS 9.3.2/iphone@9.3'
];
var cronPlatforms = [
'Windows 10/chrome@59',
'Windows 10/firefox@54'
];
if (argv.env === 'saucelabs') {
context.options.plugins.sauce.browsers = saucelabsPlatforms;
} else if (argv.env === 'saucelabs-cron') {
context.options.plugins.sauce.browsers = cronPlatforms;
}
}
};
| var argv = require('yargs').argv;
module.exports = {
registerHooks: function(context) {
var saucelabsPlatforms = [
// 'macOS 10.12/iphone@10.3',
// 'macOS 10.12/ipad@10.3',
'Windows 10/microsoftedge@15',
'Windows 10/internet explorer@11',
'macOS 10.12/safari@11.0'
];
var cronPlatforms = [
'Windows 10/chrome@59',
'Windows 10/firefox@54'
];
if (argv.env === 'saucelabs') {
context.options.plugins.sauce.browsers = saucelabsPlatforms;
} else if (argv.env === 'saucelabs-cron') {
context.options.plugins.sauce.browsers = cronPlatforms;
}
}
};
|
Use var named "rpc" and not "a" | #!/srv/python/venv/bin/ipython -i
import bqueryd
import os
import sys
import logging
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')])
redis_url=config.get('Main', 'redis_url')
if __name__ == '__main__':
if '-v' in sys.argv:
loglevel = logging.DEBUG
else:
loglevel = logging.INFO
if 'controller' in sys.argv:
bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'worker' in sys.argv:
bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go()
else:
if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'):
rpc = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel)
else:
rpc = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel)
sys.stderr.write('Run this script with python -i , and then you will have a variable named "rpc" as a connection.\n')
| #!/srv/python/venv/bin/ipython -i
import bqueryd
import os
import sys
import logging
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')])
redis_url=config.get('Main', 'redis_url')
if __name__ == '__main__':
if '-v' in sys.argv:
loglevel = logging.DEBUG
else:
loglevel = logging.INFO
if 'controller' in sys.argv:
bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'worker' in sys.argv:
bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go()
else:
if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'):
a = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel)
else:
a = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel)
sys.stderr.write('Run this script with python -i , and then you will have a variable named "a" as a connection.\n')
|
MAINT: Fix invalid parameter types used in `Dtype` | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from cupy.cuda import Device as _Device
__all__ = [
"Array",
"Device",
"Dtype",
"SupportsDLPack",
"SupportsBufferProtocol",
"PyCapsule",
]
import sys
from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING
from . import Array
from numpy import (
dtype,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
)
# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
NestedSequence = Sequence[Sequence[Any]]
Device = _Device
if TYPE_CHECKING or sys.version_info >= (3, 9):
Dtype = dtype[Union[
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
]]
else:
Dtype = dtype
SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any
| """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from cupy.cuda import Device as _Device
__all__ = [
"Array",
"Device",
"Dtype",
"SupportsDLPack",
"SupportsBufferProtocol",
"PyCapsule",
]
from typing import Any, Literal, Sequence, Type, Union
from . import (
Array,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
)
# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
NestedSequence = Sequence[Sequence[Any]]
Device = _Device
Dtype = Type[
Union[[int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64]]
]
SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any
|
Fix issue checking date when creating new item | /**
* Controller to bring functionality for the modal.
*
* @author Claire Wilgar
*/
/**
* Module export of controller function.
*
* @ngInject
* @param {angular.Service} $scope
* @param {angular.Service} $mdDialog
* @param {service} ApiService
* @param {var} item
*/
module.exports = function($scope, $mdDialog, ApiService, item) {
var self = this;
self.item = item;
if (!angular.isUndefined(self.item) && self.item != null) {
console.log(self.item.available);
self.item.available = new Date(self.item.available);
}
self.hide = function() {
$mdDialog.hide();
};
self.cancel = function() {
$mdDialog.cancel();
};
self.submitForm = function(data) {
ApiService.submitForm(data)
.then(function() {
$mdDialog.hide(data);
}, function(response) {
$mdDialog.cancel(response);
});
};
};
| /**
* Controller to bring functionality for the modal.
*
* @author Claire Wilgar
*/
/**
* Module export of controller function.
*
* @ngInject
* @param {angular.Service} $scope
* @param {angular.Service} $mdDialog
* @param {service} ApiService
* @param {var} item
*/
module.exports = function($scope, $mdDialog, ApiService, item) {
var self = this;
self.item = item;
if (!angular.isUndefined(self.item.available)) {
console.log(self.item.available);
self.item.available = new Date(self.item.available);
}
self.hide = function() {
$mdDialog.hide();
};
self.cancel = function() {
$mdDialog.cancel();
};
self.submitForm = function(data) {
ApiService.submitForm(data)
.then(function() {
$mdDialog.hide(data);
}, function(response) {
$mdDialog.cancel(response);
});
};
};
|
Correct for older Python3 version errors | import numpy as np
import pandas as pd
from transform import transform
# Load the questions
questions = pd.read_csv('questions.csv')
# Initialise the position of the user at the origin
pos = np.zeros(3)
input_text = 'Enter response from -2 (strongly disagree) to +2 (strongly agree): '
# Using a C-style loop over questions without apology
for i in range(0, questions.shape[0]):
# Check the question satisfies a basic sanity check
norm = np.linalg.norm(questions.iloc[i, 1:])
if norm > 2.:
print('# WARNING: Very influential question.')
elif norm < 0.5:
print('# WARNING: Very uninfluential question.')
# Print the question
print('\nQuestion {k}/{n}:\n'.format(k=i+1, n=questions.shape[0]))
print(questions.iloc[i, 0] + '\n')
# Get the user's response
response = None # Placeholder value
while response is None or response < -2. or response > 2.:
response = float(input(input_text))
# Increment the user's position
pos += response*questions.iloc[i, 1:].values
# Apply some scaling to the position based on how far it was possible
# to move in each dimension
print(pos)
pos = transform(pos, questions)[0]
print('Your position in 3D is ' + str(pos) + '.')
| import numpy as np
import pandas as pd
from transform import transform
# Load the questions
questions = pd.read_csv('questions.csv')
# Initialise the position of the user at the origin
pos = np.zeros(3)
input_text = 'Enter response from -2 (strongly disagree) to +2 (strongly agree): '
# Using a C-style loop over questions without apology
for i in range(0, questions.shape[0]):
# Check the question satisfies a basic sanity check
norm = np.linalg.norm(questions.iloc[i, 1:])
if norm > 2.:
print('# WARNING: Very influential question.')
elif norm < 0.5:
print('# WARNING: Very uninfluential question.')
# Print the question
print('\nQuestion {k}/{n}:\n'.format(k=i+1, n=questions.shape[0]))
print(questions.iloc[i, 0] + '\n')
# Get the user's response
response = None # Placeholder value
while response < -2. or response > 2.:
response = input(input_text)
# Increment the user's position
pos += response*questions.iloc[i, 1:].values
# Apply some scaling to the position based on how far it was possible
# to move in each dimension
print(pos)
pos = transform(pos, questions)[0]
print('Your position in 3D is ' + str(pos) + '.')
|
FIX calling loadJuno in place of handleKernel on kernel, session creation | function load_ipython_extension() {
var extensionLoaded = false;
function loadScript( host, name ) {
var script = document.createElement( 'script' );
script.src = name
? host + `/juno/${name}.js`
: host;
document.head.appendChild( script );
return script;
}
function loadJuno( host ) {
if ( extensionLoaded ) { return; }
var reqReact = window.requirejs.config({
paths: {
'react': host + '/juno/react',
'react-dom': host + '/juno/react-dom'
}
});
reqReact([ 'react', 'react-dom' ], () => {
reqReact([ host + '/juno/vendor.js'], () => {
reqReact([ host + '/juno/nbextension.js'], () => {});
});
});
}
requirejs( [
"base/js/namespace",
"base/js/events"
], function( Jupyter, Events ) {
// On new kernel session create new comm managers
if ( Jupyter.notebook && Jupyter.notebook.kernel ) {
loadJuno( '//' + window.location.host )
}
Events.on( 'kernel_created.Kernel kernel_created.Session', ( event, data ) => {
loadJuno( '//' + window.location.host );
});
});
}
module.exports = {
load_ipython_extension: load_ipython_extension
};
| function load_ipython_extension() {
var extensionLoaded = false;
function loadScript( host, name ) {
var script = document.createElement( 'script' );
script.src = name
? host + `/juno/${name}.js`
: host;
document.head.appendChild( script );
return script;
}
function loadJuno( host ) {
if ( extensionLoaded ) { return; }
var reqReact = window.requirejs.config({
paths: {
'react': host + '/juno/react',
'react-dom': host + '/juno/react-dom'
}
});
reqReact([ 'react', 'react-dom' ], () => {
reqReact([ host + '/juno/vendor.js'], () => {
reqReact([ host + '/juno/nbextension.js'], () => {});
});
});
}
requirejs( [
"base/js/namespace",
"base/js/events"
], function( Jupyter, Events ) {
// On new kernel session create new comm managers
if ( Jupyter.notebook && Jupyter.notebook.kernel ) {
loadJuno( '//' + window.location.host )
}
Events.on( 'kernel_created.Kernel kernel_created.Session', ( event, data ) => {
handleKernel( data.kernel );
});
});
}
module.exports = {
load_ipython_extension: load_ipython_extension
};
|
Mark 'TIME_WINDOW' field as deprecated | /* *\
** SICU Stress Measurement System **
** Project P04 | C380 Team A **
** EBME 380: Biomedical Engineering Design Experience **
** Case Western Reserve University **
** 2016 Fall Semester **
\* */
package edu.cwru.sicu_sms;
/**
* This class is dedicated to storing various constants that might otherwise clutter other source files in this package.
*
* @since December 3, 2016
* @author Ted Frohlich <ttf10@case.edu>
* @author Abby Walker <amw138@case.edu>
*/
public class Constants {
@Deprecated
public static final int TIME_WINDOW = 10;
}
| /* *\
** SICU Stress Measurement System **
** Project P04 | C380 Team A **
** EBME 380: Biomedical Engineering Design Experience **
** Case Western Reserve University **
** 2016 Fall Semester **
\* */
package edu.cwru.sicu_sms;
/**
* This class is dedicated to storing various constants that might otherwise clutter other source files in this package.
*
* @since December 3, 2016
* @author Ted Frohlich <ttf10@case.edu>
* @author Abby Walker <amw138@case.edu>
*/
public class Constants {
public static final int TIME_WINDOW = 10;
}
|
Add options for connecting with Fleet | /**
* @package admiral
* @author Andrew Munsell <andrew@wizardapps.net>
* @copyright 2015 WizardApps
*/
var nconf = require('nconf')
.argv({
't': {
describe: 'Tunnel to use to connect to Fleet.',
alias: 'tunnel',
default: null
},
'tunnel-username': {
describe: 'Username to use to connect to Fleet through an SSH tunnel.',
default: 'core'
},
'h': {
describe: 'Host for Etcd',
alias: 'host',
default: '127.0.0.1'
},
'p': {
describe: 'Port for Etcd',
alias: 'port',
default: 4001
},
'ns': {
describe: 'Root namespace for storing configuration.',
alias: 'namespace',
default: '/admiral'
}
});
exports = module.exports = function() {
return nconf;
};
exports['@singleton'] = true; | /**
* @package admiral
* @author Andrew Munsell <andrew@wizardapps.net>
* @copyright 2015 WizardApps
*/
var nconf = require('nconf')
.argv({
'h': {
describe: 'Host for Etcd',
alias: 'host',
default: '127.0.0.1'
},
'p': {
describe: 'Port for Etcd',
alias: 'port',
default: 4001
},
'ns': {
describe: 'Root namespace for storing configuration.',
alias: 'namespace',
default: '/admiral'
}
});
exports = module.exports = function() {
return nconf;
};
exports['@singleton'] = true; |
Remove sqlite3 (part of the standard library) from the list of requirements. | from setuptools import setup
setup(
name = 'PyFVCOM',
packages = ['PyFVCOM'],
version = '1.3.4',
description = ("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."),
author = 'Pierre Cazenave',
author_email = 'pica@pml.ac.uk',
url = 'https://gitlab.ecosystem-modelling.pml.ac.uk/fvcom/PyFVCOM',
download_url = 'http://gitlab.em.pml.ac.uk/fvcom/PyFVCOM/repository/archive.tar.gz?ref=1.2.1',
keywords = ['fvcom', 'unstructured grid', 'mesh'],
license = 'MIT',
platforms = 'any',
install_requires = ['pyshp', 'jdcal', 'scipy', 'numpy', 'matplotlib', 'netCDF4', 'lxml', 'matplotlib'],
classifiers = []
)
| from setuptools import setup
setup(
name = 'PyFVCOM',
packages = ['PyFVCOM'],
version = '1.3.4',
description = ("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."),
author = 'Pierre Cazenave',
author_email = 'pica@pml.ac.uk',
url = 'https://gitlab.ecosystem-modelling.pml.ac.uk/fvcom/PyFVCOM',
download_url = 'http://gitlab.em.pml.ac.uk/fvcom/PyFVCOM/repository/archive.tar.gz?ref=1.2.1',
keywords = ['fvcom', 'unstructured grid', 'mesh'],
license = 'MIT',
platforms = 'any',
install_requires = ['pyshp', 'jdcal', 'scipy', 'numpy', 'matplotlib', 'netCDF4', 'lxml', 'sqlite3', 'matplotlib'],
classifiers = []
)
|
Bump version, allow newer lxml | from setuptools import setup, find_packages
import os
setup(
name="cpgintegrate",
version="0.2.17",
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.18.4',
'pandas>=0.23.0',
'xlrd',
'sqlalchemy>=1.0',
'beautifulsoup4',
'lxml<5.0',
'numpy',
'scipy',
],
extras_require={'dev': [
'pytest>=3.2.2',
'apache-airflow>=1.10.0',
],
'win_auto': [
'pywinauto',
'patool',
],
},
data_files=[
(os.path.join(os.environ.get('AIRFLOW_HOME', 'airflow'), 'plugins'),
['cpgintegrate/airflow/cpg_airflow_plugin.py'])
],
)
| from setuptools import setup, find_packages
import os
setup(
name="cpgintegrate",
version="0.2.17-SNAPSHOT",
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.18.4',
'pandas>=0.23.0',
'xlrd',
'sqlalchemy>=1.0',
'beautifulsoup4',
'lxml<4.0',
'numpy',
'scipy',
],
extras_require={'dev': [
'pytest>=3.2.2',
'apache-airflow>=1.10.0',
],
'win_auto': [
'pywinauto',
'patool',
],
},
data_files=[
(os.path.join(os.environ.get('AIRFLOW_HOME', 'airflow'), 'plugins'),
['cpgintegrate/airflow/cpg_airflow_plugin.py'])
],
)
|
Update test requirements to Attest >=0.5.3, pylint. | # -*- coding: utf8 -*-
from setuptools import setup, find_packages
setup(
name='django-revisionfield',
version='0.2.3.dev',
description = 'An model field that auto increments every time the model is'
' saved',
author='Bradley Ayers',
author_email='bradley.ayers@gmail.com',
license='Simplified BSD',
url='https://github.com/bradleyayers/django-revisionfield/',
packages=find_packages(),
install_requires=['Django >=1.2'],
tests_require=['Django >=1.2', 'Attest >=0.5.3', 'django-attest >=0.2.2',
'unittest-xml-reporting', 'pylint'],
test_loader='tests:loader',
test_suite='tests.everything',
classifiers = [
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| # -*- coding: utf8 -*-
from setuptools import setup, find_packages
setup(
name='django-revisionfield',
version='0.2.2',
description = 'An model field that auto increments every time the model is'
' saved',
author='Bradley Ayers',
author_email='bradley.ayers@gmail.com',
license='Simplified BSD',
url='https://github.com/bradleyayers/django-revisionfield/',
packages=find_packages(),
install_requires=['Django >=1.2'],
tests_require=['Django >=1.2', 'Attest >=0.4', 'django-attest >=0.2.2',
'unittest-xml-reporting'],
test_loader='tests:loader',
test_suite='tests.everything',
classifiers = [
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Add Google Maps API key | <script src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="//maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyDtkPdwkkhmFXLNp9Z4k8JnaLh_yXmSzQ4&libraries=geometry"></script>
<script src="/wp-content/themes/quis/js/quis.js"></script>
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1524236-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
| <script src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=geometry"></script>
<script src="/wp-content/themes/quis/js/quis.js"></script>
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1524236-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
|
Update getAttributes() override to keep up with the PR for Symfony Routing. | <?php
namespace Symfony\Cmf\Component\Routing\NestedMatcher;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\UrlMatcher as SymfonyUrlMatcher;
use Symfony\Component\HttpFoundation\Request;
/**
* Extended UrlMatcher to provide an additional interface and enhanced features.
*
* @author Crell
*/
class UrlMatcher extends SymfonyUrlMatcher implements FinalMatcherInterface
{
/**
* {@inheritdoc}
*/
public function finalMatch(RouteCollection $collection, Request $request)
{
$this->routes = $collection;
$this->match($request->getPathInfo());
}
/**
* {@inheritdoc}
*/
protected function getAttributes(Route $route, $name, $attributes)
{
$attributes['_name'] = $name;
$attributes['_route'] = $route;
return $this->mergeDefaults($attributes, $route->getDefaults());
}
}
| <?php
namespace Symfony\Cmf\Component\Routing\NestedMatcher;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\UrlMatcher as SymfonyUrlMatcher;
use Symfony\Component\HttpFoundation\Request;
/**
* Extended UrlMatcher to provide an additional interface and enhanced features.
*
* @author Crell
*/
class UrlMatcher extends SymfonyUrlMatcher implements FinalMatcherInterface
{
/**
* {@inheritdoc}
*/
public function finalMatch(RouteCollection $collection, Request $request)
{
$this->routes = $collection;
$this->match($request->getPathInfo());
}
/**
* {@inheritdoc}
*/
protected function getAttributes(Route $route)
{
$args = func_get_args();
array_shift($args);
// TODO: where does the $name come from?
$args[] = array('_name' => $name, '_route' => $route);
return $this->mergeDefaults(call_user_func_array('array_replace', $args), $route->getDefaults());
}
}
|
Use config for default paths. | var gulp = require('gulp'),
Elixir = require('laravel-elixir'),
livereload = require('gulp-livereload'),
config = Elixir.config;
Elixir.extend('livereload', function (src) {
defaultSrc = [
config.appPath + '/**/*',
config.publicPath + '/**/*',
'resources/views/**/*'
];
src = src || defaultSrc;
gulp.on('task_start', function (e) {
if (e.task === 'watch') {
gulp.watch(src)
.on('change', function (event) {
livereload.changed(event.path);
});
livereload.listen();
}
});
});
| var gulp = require('gulp'),
Elixir = require('laravel-elixir'),
livereload = require('gulp-livereload'),
config = Elixir.config;
Elixir.extend('livereload', function (src) {
defaultSrc = [
'app/**/*',
'public/**/*',
'resources/views/**/*'
];
src = src || defaultSrc;
gulp.on('task_start', function (e) {
if (e.task === 'watch') {
gulp.watch(src)
.on('change', function (event) {
livereload.changed(event.path);
});
livereload.listen();
}
});
});
|
Fix feature detection bug on Node v0.10 | 'use strict';
// MODULES //
var tape = require( 'tape' );
var detect = require( './../lib' );
// VARIABLES //
var hasSymbols = ( typeof Symbol === 'function' );
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.equal( typeof detect, 'function', 'main export is a function' );
t.end();
});
tape( 'feature detection result is a boolean', function test( t ) {
t.equal( typeof detect(), 'boolean', 'detection result is a boolean' );
t.end();
});
tape( 'if `Symbols` are supported, detection result is `true`', function test( t ) {
if ( hasSymbols ) {
t.equal( detect(), true, 'detection result is `true`' );
} else {
t.equal( detect(), false, 'detection result is `false`' );
}
t.end();
});
tape( 'the function guards against a `Symbol` global variable which does not produce `symbols`', function test( t ) {
var tmp;
if ( hasSymbols ) {
tmp = Symbol;
Symbol = {};
} else {
global.Symbol = {};
}
t.equal( detect(), false, 'detection result is `false`' );
if ( hasSymbols ) {
Symbol = tmp;
}
t.end();
});
| 'use strict';
// MODULES //
var tape = require( 'tape' );
var detect = require( './../lib' );
// VARIABLES //
var hasSymbols = ( typeof Symbol !== 'undefined' );
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.equal( typeof detect, 'function', 'main export is a function' );
t.end();
});
tape( 'feature detection result is a boolean', function test( t ) {
t.equal( typeof detect(), 'boolean', 'detection result is a boolean' );
t.end();
});
tape( 'if `Symbols` are supported, detection result is `true`', function test( t ) {
if ( hasSymbols ) {
t.equal( detect(), true, 'detection result is `true`' );
} else {
t.equal( detect(), false, 'detection result is `false`' );
}
t.end();
});
tape( 'the function guards against a `Symbol` global variable which does not produce `symbols`', function test( t ) {
var tmp;
if ( hasSymbols ) {
tmp = Symbol;
Symbol = {};
} else {
global.Symbol = {};
}
t.equal( detect(), false, 'detection result is `false`' );
if ( hasSymbols ) {
Symbol = tmp;
}
t.end();
});
|
Update sourcemap setting in rollup | import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import postcss from 'rollup-plugin-postcss';
import uglify from 'rollup-plugin-uglify';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
import pkg from './package.json';
const transformStyles = postcss({
extract: 'dist/aos.css',
plugins: [autoprefixer, cssnano]
});
const input = 'src/js/aos.js';
export default [
{
input,
output: {
file: pkg.browser,
name: 'AOS',
format: 'umd',
sourcemap: process.env.NODE_ENV === 'dev'
},
plugins: [
transformStyles,
resolve(),
commonjs(),
babel({
exclude: ['node_modules/**']
}),
uglify()
]
},
{
input,
external: Object.keys(pkg.dependencies),
output: [
{ file: pkg.main, format: 'cjs' },
{ file: pkg.module, format: 'es' }
],
plugins: [
transformStyles,
babel({
exclude: ['node_modules/**']
})
]
}
];
| import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import postcss from 'rollup-plugin-postcss';
import uglify from 'rollup-plugin-uglify';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
import pkg from './package.json';
const transformStyles = postcss({
extract: 'dist/aos.css',
plugins: [autoprefixer, cssnano]
});
const input = 'src/js/aos.js';
export default [
{
input,
output: {
file: pkg.browser,
name: 'AOS',
format: 'umd'
},
sourceMap: process.env.NODE_ENV === 'dev',
plugins: [
transformStyles,
resolve(),
commonjs(),
babel({
exclude: ['node_modules/**']
}),
uglify()
]
},
{
input,
external: Object.keys(pkg.dependencies),
output: [
{ file: pkg.main, format: 'cjs' },
{ file: pkg.module, format: 'es' }
],
plugins: [
transformStyles,
babel({
exclude: ['node_modules/**']
})
]
}
];
|
Add trivikr as one of the maintainers | import React from 'react';
import styles from './Footer.scss';
import Link from '../Link';
export default function Footer({addConferenceUrl, togglePast, showPast}) {
return (
<footer className={styles.Footer}>
<p className={styles.FooterLinks}>
<Link url={addConferenceUrl} external>
Add a conference
</Link>
<Link onClick={togglePast}>
{showPast ? 'Hide past conferences' : 'See past conferences'}
</Link>
</p>
<p>
Maintained by {Twitter('katyaprigara')}, {Twitter('nimz_co')} and {Twitter('trivikram')}
</p>
</footer>
);
}
function Twitter(handle) {
return (
<Link url={`https://twitter.com/@${handle}`} external>
@{handle}
</Link>
);
}
| import React from 'react';
import styles from './Footer.scss';
import Link from '../Link';
export default function Footer({addConferenceUrl, togglePast, showPast}) {
return (
<footer className={styles.Footer}>
<p className={styles.FooterLinks}>
<Link url={addConferenceUrl} external>
Add a conference
</Link>
<Link onClick={togglePast}>
{showPast ? 'Hide past conferences' : 'See past conferences'}
</Link>
</p>
<p>
Maintained by {Twitter('katyaprigara')} and {Twitter('nimz_co')}
</p>
</footer>
);
}
function Twitter(handle) {
return (
<Link url={`https://twitter.com/@${handle}`} external>
@{handle}
</Link>
);
}
|
Fix unequipping backpack not closing GUI | package net.mcft.copy.betterstorage.inventory;
import net.mcft.copy.betterstorage.item.ItemBackpack;
import net.mcft.copy.betterstorage.utils.DirectionUtils;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
public class InventoryBackpackEquipped extends InventoryWrapper {
public final EntityPlayer player;
public final EntityLiving carrier;
public InventoryBackpackEquipped(EntityPlayer player, EntityLiving carrier) {
super(ItemBackpack.getBackpackItems(carrier).contents);
this.player = player;
this.carrier = carrier;
}
@Override
public boolean isUseableByPlayer(EntityPlayer player) {
boolean carriesBackpack = (ItemBackpack.getBackpackItems(carrier).contents == allContents[0]);
double distance = player.getDistanceToEntity(carrier);
double direction = DirectionUtils.angleDifference(carrier.renderYawOffset + 90.0F,
DirectionUtils.angleBetween(carrier, player));
return (carrier.isEntityAlive() && carriesBackpack &&
(distance < 1.5) && (Math.abs(direction) > 135));
}
}
| package net.mcft.copy.betterstorage.inventory;
import net.mcft.copy.betterstorage.item.ItemBackpack;
import net.mcft.copy.betterstorage.utils.DirectionUtils;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
public class InventoryBackpackEquipped extends InventoryWrapper {
public final EntityPlayer player;
public final EntityLiving carrier;
public InventoryBackpackEquipped(EntityPlayer player, EntityLiving carrier) {
super(ItemBackpack.getBackpackItems(carrier).contents);
this.player = player;
this.carrier = carrier;
}
@Override
public boolean isUseableByPlayer(EntityPlayer player) {
if (!carrier.isEntityAlive() || player.getDistanceToEntity(carrier) > 1.5) return false;
double direction = DirectionUtils.angleBetween(carrier, player);
direction = DirectionUtils.angleDifference(carrier.renderYawOffset + 90.0F, direction);
return (Math.abs(direction) > 135);
}
}
|
Fix Access BaseController Methods via url | <?php
/**
* This file is part of the CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use CodeIgniter\Exceptions\PageNotFoundException;
/**
* System URI Routing
*
* This file contains any routing to system tools, such as command-line
* tools for migrations, etc.
*
* It is called by Config\Routes, and has the $routes RouteCollection
* already loaded up and ready for us to use.
*/
// Prevent access to BaseController
$routes->add('BaseController(:any)', function () {
throw PageNotFoundException::forPageNotFound();
});
// Prevent access to initController method
$routes->add('(:any)/initController', function () {
throw PageNotFoundException::forPageNotFound();
});
// Migrations
$routes->cli('migrations/(:segment)/(:segment)', '\CodeIgniter\Commands\MigrationsCommand::$1/$2');
$routes->cli('migrations/(:segment)', '\CodeIgniter\Commands\MigrationsCommand::$1');
$routes->cli('migrations', '\CodeIgniter\Commands\MigrationsCommand::index');
// CLI Catchall - uses a _remap to call Commands
$routes->cli('ci(:any)', '\CodeIgniter\CLI\CommandRunner::index/$1');
| <?php
/**
* This file is part of the CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use CodeIgniter\Exceptions\PageNotFoundException;
/**
* System URI Routing
*
* This file contains any routing to system tools, such as command-line
* tools for migrations, etc.
*
* It is called by Config\Routes, and has the $routes RouteCollection
* already loaded up and ready for us to use.
*/
// Prevent access to BaseController
$routes->add('basecontroller(:any)', function () {
throw PageNotFoundException::forPageNotFound();
});
// Migrations
$routes->cli('migrations/(:segment)/(:segment)', '\CodeIgniter\Commands\MigrationsCommand::$1/$2');
$routes->cli('migrations/(:segment)', '\CodeIgniter\Commands\MigrationsCommand::$1');
$routes->cli('migrations', '\CodeIgniter\Commands\MigrationsCommand::index');
// CLI Catchall - uses a _remap to call Commands
$routes->cli('ci(:any)', '\CodeIgniter\CLI\CommandRunner::index/$1');
// Prevent access to initController method
$routes->add('(:any)/initController', function () {
throw PageNotFoundException::forPageNotFound();
});
|
Change source naming in the raw action
To be consistent with the filesystem deploy action, change the source
identifier from rootdir to filesystem. In general the intended jargon is
that the "filesystem" is the filesystem being created by the tool
(by unpacking a tarball or debootstrap or deploying an ostree or
whatever)
Signed-off-by: Sjoerd Simons <1371fd10dd05a897e5b55dc6ae4fbafa1f84c6ec@collabora.co.uk> | package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"strconv"
)
type RawAction struct {
BaseAction `yaml:",inline"`
Offset string
Source string
Path string
}
func (raw *RawAction) Verify(context *YaibContext) error {
if raw.Source != "filesystem" {
return errors.New("Only suppport sourcing from filesystem")
}
return nil
}
func (raw *RawAction) Run(context *YaibContext) error {
raw.LogStart()
s := path.Join(context.rootdir, raw.Path)
content, err := ioutil.ReadFile(s)
if err != nil {
return fmt.Errorf("Failed to read %s", s)
}
target, err := os.OpenFile(context.image, os.O_WRONLY, 0)
if err != nil {
return fmt.Errorf("Failed to open image file %v", err)
}
offset, err := strconv.ParseInt(raw.Offset, 0, 64)
if err != nil {
return fmt.Errorf("Couldn't parse offset %v", err)
}
bytes, err := target.WriteAt(content, offset)
if bytes != len(content) {
return errors.New("Couldn't write complete data")
}
return nil
}
| package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"strconv"
)
type RawAction struct {
BaseAction `yaml:",inline"`
Offset string
Source string
Path string
}
func (raw *RawAction) Verify(context *YaibContext) error {
if raw.Source != "rootdir" {
return errors.New("Only suppport sourcing from filesystem")
}
return nil
}
func (raw *RawAction) Run(context *YaibContext) error {
raw.LogStart()
s := path.Join(context.rootdir, raw.Path)
content, err := ioutil.ReadFile(s)
if err != nil {
return fmt.Errorf("Failed to read %s", s)
}
target, err := os.OpenFile(context.image, os.O_WRONLY, 0)
if err != nil {
return fmt.Errorf("Failed to open image file %v", err)
}
offset, err := strconv.ParseInt(raw.Offset, 0, 64)
if err != nil {
return fmt.Errorf("Couldn't parse offset %v", err)
}
bytes, err := target.WriteAt(content, offset)
if bytes != len(content) {
return errors.New("Couldn't write complete data")
}
return nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.