text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Update test to work with new monitors. | import theanets
import util
class TestTrainer(util.MNIST):
def setUp(self):
super(TestTrainer, self).setUp()
self.exp = theanets.Experiment(
theanets.Autoencoder,
layers=(self.DIGIT_SIZE, 10, self.DIGIT_SIZE))
def assert_progress(self, algo, **kwargs):
trainer = self.exp.itertrain(self.images, optimize=algo, **kwargs)
t0, v0 = next(trainer)
t1, v1 = next(trainer)
t2, v2 = next(trainer)
assert t2['loss'] < t0['loss']
def test_sgd(self):
self.assert_progress('sgd', learning_rate=1e-4)
def test_nag(self):
self.assert_progress('nag', learning_rate=1e-4)
def test_rprop(self):
self.assert_progress('rprop', learning_rate=1e-4)
def test_rmsprop(self):
self.assert_progress('rmsprop', learning_rate=1e-4)
def test_adadelta(self):
self.assert_progress('adadelta', learning_rate=1e-4)
def test_cg(self):
self.assert_progress('cg')
def test_layerwise(self):
self.exp = theanets.Experiment(
theanets.Autoencoder,
layers=(self.DIGIT_SIZE, 10, 10, self.DIGIT_SIZE))
self.assert_progress('layerwise')
| import theanets
import util
class TestTrainer(util.MNIST):
def setUp(self):
super(TestTrainer, self).setUp()
self.exp = theanets.Experiment(
theanets.Autoencoder,
layers=(self.DIGIT_SIZE, 10, self.DIGIT_SIZE))
def assert_progress(self, algo, **kwargs):
trainer = self.exp.itertrain(self.images, optimize=algo, **kwargs)
costs0 = next(trainer)
costs1 = next(trainer)
costs2 = next(trainer)
assert costs2['loss'] < costs0['loss']
def test_sgd(self):
self.assert_progress('sgd', learning_rate=1e-4)
def test_nag(self):
self.assert_progress('nag', learning_rate=1e-4)
def test_rprop(self):
self.assert_progress('rprop', learning_rate=1e-4)
def test_rmsprop(self):
self.assert_progress('rmsprop', learning_rate=1e-4)
def test_adadelta(self):
self.assert_progress('adadelta', learning_rate=1e-4)
def test_cg(self):
self.assert_progress('cg')
def test_layerwise(self):
self.exp = theanets.Experiment(
theanets.Autoencoder,
layers=(self.DIGIT_SIZE, 10, 10, self.DIGIT_SIZE))
self.assert_progress('layerwise')
|
Update proxima nova font locations.
Summary: The locations of Proxima nova have changed since this was
written, this updates it to the correct location.
Test plan:
- Not actually sure if this is used, but it sure looks better!
Auditors: michelle | /**
* Executed in the browser.
*
* This just ensures that the proxima nova font is loaded, which apparently
* doesn't happen in the dev pages sometimes.
*/
module.exports = function() {
var newStyle = document.createElement('style');
newStyle.appendChild(document.createTextNode(
"@font-face {" +
" font-family: 'Proxima Nova';" +
" src: url('https://www.kastatic.org/fonts/Proxima-Nova-Regular.woff') format('woff');" +
" font-weight: normal;" +
" font-style: normal;" +
"}" +
"" +
"@font-face {" +
" font-family: 'Proxima Nova';" +
" src: url('https://www.kastatic.org/fonts/Proxima-Nova-Semibold.woff') format('woff');" +
" font-weight: bold;" +
" font-style: normal;" +
"}" +
"" +
"@font-face {" +
" font-family: 'Proxima Nova Bold';" +
" src: url('https://www.kastatic.org/fonts/Proxima-Nova-Semibold.woff') format('woff');" +
" font-weight: normal;" +
" font-style: normal;" +
"}" +
"body {" +
" font-family: 'Proxima Nova';" +
"}"));
document.head.appendChild(newStyle);
};
| /**
* Executed in the browser.
*
* This just ensures that the proxima nova font is loaded, which apparently
* doesn't happen in the dev pages sometimes.
*/
module.exports = function() {
var newStyle = document.createElement('style');
newStyle.appendChild(document.createTextNode(
"@font-face {" +
" font-family: 'Proxima Nova';" +
" src: url('https://www.kastatic.org/fonts/ProximaNova-Reg-webfont.woff') format('woff');" +
" font-weight: normal;" +
" font-style: normal;" +
"}" +
"" +
"@font-face {" +
" font-family: 'Proxima Nova';" +
" src: url('https://www.kastatic.org/fonts/ProximaNova-Bold-webfont.woff') format('woff');" +
" font-weight: bold;" +
" font-style: normal;" +
"}" +
"" +
"@font-face {" +
" font-family: 'Proxima Nova Bold';" +
" src: url('https://www.kastatic.org/fonts/ProximaNova-Bold-webfont.woff') format('woff');" +
" font-weight: normal;" +
" font-style: normal;" +
"}" +
"body {" +
" font-family: 'Proxima Nova';" +
"}"));
document.head.appendChild(newStyle);
};
|
Write correct titles for opening plots | #!/usr/bin/python
import sys
def parse_opening_list(filename):
with open(filename) as f:
open_count = dict()
openings = []
for line in (raw.strip() for raw in f):
open_count.setdefault(line, 0)
open_count[line] += 1
openings.append(line)
top10 = list(reversed(sorted(open_count.keys(),
key=lambda x: open_count[x])[-10:]))
movsum_window = 1000
last_window = openings[-movsum_window:]
top10_rate = list(reversed(sorted(open_count.keys(),
key=lambda x : last_window.count(x))[-10:]))
for data in [[top10, '_top_opening_data.txt'], [top10_rate, '_top_opening_rate_data.txt']]:
with open(filename + data[1] , 'w') as out:
out.write(','.join(data[0]) + '\n')
for opening in openings:
marker = ['1' if x == opening else '0' for x in data[0]]
out.write(','.join(marker) + '\n')
if __name__ == '__main__':
parse_opening_list(sys.argv[1])
| #!/usr/bin/python
import sys
def parse_opening_list(filename):
with open(filename) as f:
open_count = dict()
openings = []
for line in (raw.strip() for raw in f):
open_count.setdefault(line, 0)
open_count[line] += 1
openings.append(line)
top10 = list(reversed(sorted(open_count.keys(),
key=lambda x: open_count[x])[-10:]))
movsum_window = 1000
last_window = openings[-movsum_window:]
top10_rate = list(reversed(sorted(open_count.keys(),
key=lambda x : last_window.count(x))[-10:]))
for data in [[top10, '_top_opening_data.txt'], [top10_rate, '_top_opening_rate_data.txt']]:
with open(filename + data[1] , 'w') as out:
out.write(','.join(top10) + '\n')
for opening in openings:
marker = ['1' if x == opening else '0' for x in data[0]]
out.write(','.join(marker) + '\n')
if __name__ == '__main__':
parse_opening_list(sys.argv[1])
|
Use address when there is no location | import React, { PropTypes, Component } from 'react';
import { IMAGES_ROOT } from '../constants/Constants';
import shouldPureComponentUpdate from 'react-pure-render/function';
import selectn from 'selectn';
export default class User extends Component {
static propTypes = {
user: PropTypes.object.isRequired
};
shouldComponentUpdate = shouldPureComponentUpdate;
render() {
const { user, profile } = this.props;
let imgSrc = user.picture ? `${IMAGES_ROOT}media/cache/user_avatar_180x180/user/images/${user.picture}` : `${IMAGES_ROOT}media/cache/user_avatar_180x180/bundles/qnoowweb/images/user-no-img.jpg`;
return (
<div className="User">
<div className="content-block user-block">
<div className="user-image">
<img src={imgSrc} />
</div>
<div className="user-data">
<div className="user-username title">
{user.username}
</div>
<div className="user-location">
{/** TODO: For some reason, profile is different for different renders. This is a temporal fix */}
<span className="icon-marker"></span> {selectn('Location', profile) || selectn('location.locality', profile) || selectn('location.address', profile) || ''}
</div>
</div>
</div>
</div>
);
}
}
| import React, { PropTypes, Component } from 'react';
import { IMAGES_ROOT } from '../constants/Constants';
import shouldPureComponentUpdate from 'react-pure-render/function';
import selectn from 'selectn';
export default class User extends Component {
static propTypes = {
user: PropTypes.object.isRequired
};
shouldComponentUpdate = shouldPureComponentUpdate;
render() {
const { user, profile } = this.props;
let imgSrc = user.picture ? `${IMAGES_ROOT}media/cache/user_avatar_180x180/user/images/${user.picture}` : `${IMAGES_ROOT}media/cache/user_avatar_180x180/bundles/qnoowweb/images/user-no-img.jpg`;
return (
<div className="User">
<div className="content-block user-block">
<div className="user-image">
<img src={imgSrc} />
</div>
<div className="user-data">
<div className="user-username title">
{user.username}
</div>
<div className="user-location">
{/** TODO: For some reason, profile is different for different renders. This is a temporal fix */}
<span className="icon-marker"></span> {selectn('Location', profile) || selectn('location.locality', profile) || ''}
</div>
</div>
</div>
</div>
);
}
}
|
Fix "legacy mode" trying to install scripts when there are none.
--HG--
branch : setuptools
extra : convert_revision : svn%3A6015fed2-1504-0410-9fe1-9d1591cc4771/sandbox/trunk/setuptools%4041777 | from distutils.command.install_scripts import install_scripts \
as _install_scripts
from easy_install import get_script_args
from pkg_resources import Distribution, PathMetadata, ensure_directory
import os
from distutils import log
class install_scripts(_install_scripts):
"""Do normal script install, plus any egg_info wrapper scripts"""
def run(self):
self.run_command("egg_info")
if self.distribution.scripts:
_install_scripts.run(self) # run first to set up self.outfiles
else:
self.outfiles = []
ei_cmd = self.get_finalized_command("egg_info")
dist = Distribution(
ei_cmd.egg_base, PathMetadata(ei_cmd.egg_base, ei_cmd.egg_info),
ei_cmd.egg_name, ei_cmd.egg_version,
)
for args in get_script_args(dist):
self.write_script(*args)
def write_script(self, script_name, contents, mode="t", *ignored):
"""Write an executable file to the scripts directory"""
log.info("Installing %s script to %s", script_name, self.install_dir)
target = os.path.join(self.install_dir, script_name)
self.outfiles.append(target)
if not self.dry_run:
ensure_directory(target)
f = open(target,"w"+mode)
f.write(contents)
f.close()
try:
os.chmod(target,0755)
except (AttributeError, os.error):
pass
| from distutils.command.install_scripts import install_scripts \
as _install_scripts
from easy_install import get_script_args
from pkg_resources import Distribution, PathMetadata, ensure_directory
import os
from distutils import log
class install_scripts(_install_scripts):
"""Do normal script install, plus any egg_info wrapper scripts"""
def run(self):
self.run_command("egg_info")
_install_scripts.run(self) # run first to set up self.outfiles
ei_cmd = self.get_finalized_command("egg_info")
dist = Distribution(
ei_cmd.egg_base, PathMetadata(ei_cmd.egg_base, ei_cmd.egg_info),
ei_cmd.egg_name, ei_cmd.egg_version,
)
for args in get_script_args(dist):
self.write_script(*args)
def write_script(self, script_name, contents, mode="t", *ignored):
"""Write an executable file to the scripts directory"""
log.info("Installing %s script to %s", script_name, self.install_dir)
target = os.path.join(self.install_dir, script_name)
self.outfiles.append(target)
if not self.dry_run:
ensure_directory(target)
f = open(target,"w"+mode)
f.write(contents)
f.close()
try:
os.chmod(target,0755)
except (AttributeError, os.error):
pass
|
Load the properties from via the correct Class otherwise it is not in the class loader
git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@2010 b4e469a2-07ce-4b26-9273-4d7d95a670c7 | package org.helioviewer.jhv.plugins.swek.sources.hek;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Gives access to the HEK source properties
*
* @author Bram Bourgoignie ([email protected])
*
*/
public class HEKSourceProperties {
private static HEKSourceProperties singletonInstance;
/** The HEK source properties */
private final Properties hekSourceProperties;
/**
* Private default constructor.
*/
private HEKSourceProperties() {
hekSourceProperties = new Properties();
loadProperties();
}
/**
* Gets the singleton instance of the HEK source properties
*
* @return the HEK source properties
*/
public static HEKSourceProperties getSingletonInstance() {
if (singletonInstance == null) {
singletonInstance = new HEKSourceProperties();
}
return singletonInstance;
}
/**
* Gets the HEK source properties.
*
* @return the hek source properties
*/
public Properties getHEKSourceProperties() {
return hekSourceProperties;
}
/**
* Loads the overall hek source settings.
*/
private void loadProperties() {
InputStream defaultPropStream = HEKSourceProperties.class.getResourceAsStream("/heksource.properties");
try {
hekSourceProperties.load(defaultPropStream);
} catch (IOException ex) {
System.out.println("Could not load the hek settings." + ex);
}
}
}
| package org.helioviewer.jhv.plugins.swek.sources.hek;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.helioviewer.jhv.plugins.swek.SWEKPlugin;
/**
* Gives access to the HEK source properties
*
* @author Bram Bourgoignie ([email protected])
*
*/
public class HEKSourceProperties {
private static HEKSourceProperties singletonInstance;
/** The HEK source properties */
private final Properties hekSourceProperties;
/**
* Private default constructor.
*/
private HEKSourceProperties() {
this.hekSourceProperties = new Properties();
loadProperties();
}
/**
* Gets the singleton instance of the HEK source properties
*
* @return the HEK source properties
*/
public static HEKSourceProperties getSingletonInstance() {
if (singletonInstance == null) {
singletonInstance = new HEKSourceProperties();
}
return singletonInstance;
}
/**
* Gets the HEK source properties.
*
* @return the hek source properties
*/
public Properties getHEKSourceProperties() {
return this.hekSourceProperties;
}
/**
* Loads the overall hek source settings.
*/
private void loadProperties() {
InputStream defaultPropStream = SWEKPlugin.class.getResourceAsStream("/heksource.properties");
try {
this.hekSourceProperties.load(defaultPropStream);
} catch (IOException ex) {
System.out.println("Could not load the hek settings." + ex);
}
}
}
|
Add export log + permissions | package nuclibook.routes;
import nuclibook.constants.P;
import nuclibook.entity_utils.ActionLogger;
import nuclibook.entity_utils.ExportUtils;
import nuclibook.entity_utils.PatientUtils;
import nuclibook.entity_utils.SecurityUtils;
import nuclibook.models.Patient;
import nuclibook.server.HtmlRenderer;
import spark.Request;
import spark.Response;
import java.util.List;
public class ExportRoute extends DefaultRoute {
@Override
public Object handle(Request request, Response response) throws Exception {
// necessary prelim routine
prepareToHandle();
String[] fileSplit = request.params(":file:").split("\\.", 2);
String table = fileSplit[0];
String type = "";
try {
type = fileSplit[1];
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
String exportData = null;
if (table.equals("patients")) {
if (SecurityUtils.requirePermission(P.EXPORT_PATIENTS, response)) {
if (type.equals("csv")) {
exportData = ExportUtils.exportCSV(Patient.class);
}
ActionLogger.logAction(ActionLogger.EXPORT_PATIENTS, 0);
} else {
ActionLogger.logAction(ActionLogger.ATTEMPT_EXPORT_PATIENTS, 0, "Failed as user does not have permissions for this action");
}
}
if (exportData != null) {
response.header("Content-Disposition", "attachment");
}
return exportData;
}
}
| package nuclibook.routes;
import nuclibook.constants.P;
import nuclibook.entity_utils.ExportUtils;
import nuclibook.entity_utils.PatientUtils;
import nuclibook.entity_utils.SecurityUtils;
import nuclibook.models.Patient;
import nuclibook.server.HtmlRenderer;
import spark.Request;
import spark.Response;
import java.util.List;
public class ExportRoute extends DefaultRoute {
@Override
public Object handle(Request request, Response response) throws Exception {
// necessary prelim routine
prepareToHandle();
String[] fileSplit = request.params(":file:").split("\\.", 2);
String table = fileSplit[0];
String type = "";
try {
type = fileSplit[1];
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
String exportData = null;
if (table.equals("patients")) {
if (SecurityUtils.requirePermission(P.VIEW_PATIENT_LIST, response)) {
if (type.equals("csv")) {
exportData = ExportUtils.exportCSV(Patient.class);
}
}
}
if (exportData != null) {
response.header("Content-Disposition", "attachment");
}
return exportData;
}
}
|
:construction: Load all bugs on mount
We can load all bugs on mount, but this could mean unnecessary requests
From a test 76 requests | ~21KB transferred | Finish: ~30s | import React, { Component } from 'react';
import FilterContainer from './Filter/FilterContainer';
import BugContainer from './Bugs/BugContainer';
import Store from '../Store';
import { FilterOptions } from '../Constants';
class App extends Component {
constructor() {
super()
this.state = {
filterOptions: [],
isLoading: false,
bugs: []
}
}
componentDidMount() {
// NOTE: This will trigger all Bugs to be loaded let's test this
Store.loadBugsByFilterOptions(Object.keys(FilterOptions))
}
onFilterChange(filterOptions) {
this.setState({
filterOptions: filterOptions,
isLoading: true
}, () =>
Store.loadBugsByFilterOptions(filterOptions)
.then(bugs => {
if (filterOptions.every(option => this.state.filterOptions.includes(option))) {
this.setState({
isLoading: false,
bugs: bugs
})
}
return bugs
}))
}
render() {
const appIcon = this.state.isLoading ? 'fa fa-spinner fa-pulse fa-fw' : 'fa fa-bug fa-fw'
return (
<div className="app">
<div className="app-title">
<i className={`app-title-icon ${appIcon}`}/>
<span className="app-title-text">Moz Bugs!</span>
</div>
<div className="app-container">
<FilterContainer onChange={this.onFilterChange.bind(this)}/>
<BugContainer bugs={this.state.bugs}/>
</div>
</div>
);
}
}
export default App;
| import React, { Component } from 'react';
import FilterContainer from './Filter/FilterContainer';
import BugContainer from './Bugs/BugContainer';
import Store from '../Store';
class App extends Component {
constructor() {
super()
this.state = {
filterOptions: [],
isLoading: false,
bugs: []
}
}
onFilterChange(filterOptions) {
this.setState({
filterOptions: filterOptions,
isLoading: true
}, () =>
Store.loadBugsByFilterOptions(filterOptions)
.then(bugs => {
if (filterOptions.every(option => this.state.filterOptions.includes(option))) {
this.setState({
isLoading: false,
bugs: bugs
})
}
return bugs
}))
}
render() {
const appIcon = this.state.isLoading ? 'fa fa-spinner fa-pulse fa-fw' : 'fa fa-bug fa-fw'
return (
<div className="app">
<div className="app-title">
<i className={`app-title-icon ${appIcon}`}/>
<span className="app-title-text">Moz Bugs!</span>
</div>
<div className="app-container">
<FilterContainer onChange={this.onFilterChange.bind(this)}/>
<BugContainer bugs={this.state.bugs}/>
</div>
</div>
);
}
}
export default App;
|
Check for duplicates on saving of each element, instead of entry only | <?php
namespace Craft;
class IncrementPlugin extends BasePlugin
{
public function getName()
{
return Craft::t('Increment');
}
public function getVersion()
{
return '0.2';
}
public function getDeveloper()
{
return 'Bob Olde Hampsink';
}
public function getDeveloperUrl()
{
return 'http://www.itmundi.nl';
}
public function init()
{
// Check increment fields to make sure no duplicate values are inserted
craft()->on('elements.beforeSaveElement', function (Event $event) {
// Check if this is a new element
$isNewElement = $event->params['isNewElement'];
// Get element
$element = $event->params['element'];
// Exisiting elements don't change, so no need to check
if ($isNewElement) {
// Get element fields
$fields = $element->getFieldLayout()->getFields();
// Loop through element fields
foreach ($fields as $field) {
// Get field model
$field = $field->getField();
// Check if this field is an Increment field
if ($field->type == $this->getClassHandle()) {
// Re-calculate max value
$max = craft()->db->createCommand()->select('MAX(`field_'.$field->handle.'`)')->from('content')->queryScalar();
// Get current value
$currentValue = $element->{$field->handle};
// Current value should by higher than max, otherwise a duplicate element could be created
if ($currentValue <= $max) {
$element->setContentFromPost(array($field->handle => ($max + 1)));
}
}
}
}
});
}
}
| <?php
namespace Craft;
class IncrementPlugin extends BasePlugin
{
public function getName()
{
return Craft::t('Increment');
}
public function getVersion()
{
return '0.2';
}
public function getDeveloper()
{
return 'Bob Olde Hampsink';
}
public function getDeveloperUrl()
{
return 'http://www.itmundi.nl';
}
public function init()
{
// check increment fields to make sure no duplicate values are inserted
craft()->on('entries.beforeSaveEntry', function (Event $event) {
$isNewEntry = $event->params['isNewEntry'];
$entry = $event->params['entry'];
// exisiting entries don't change, so no need to check
if ($isNewEntry) {
$fields = $entry->getFieldLayout()->getFields();
foreach ($fields as $field) {
if ($field->getField()->type == 'Increment') {
$handle = $field->getField()->handle;
$max = craft()->db->createCommand()->select('MAX(`field_'.$handle.'`)')->from('content')->queryScalar();
$currentValue = $entry[$handle];
// current value should by higher than max, otherwise a duplicate entry could be created
if ($currentValue <= $max) {
$entry->setContentFromPost(array($handle => $max + 1));
}
}
}
}
});
}
}
|
Modify existing Programs migration to account for help_text change
Prevents makemigrations from creating a new migration for the programs app. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('programs', '0002_programsapiconfig_cache_ttl'),
]
operations = [
migrations.AddField(
model_name='programsapiconfig',
name='authoring_app_css_path',
field=models.CharField(
max_length=255,
help_text='This value is required in order to enable the Studio authoring interface.',
verbose_name="Path to authoring app's CSS",
blank=True
),
),
migrations.AddField(
model_name='programsapiconfig',
name='authoring_app_js_path',
field=models.CharField(
max_length=255,
help_text='This value is required in order to enable the Studio authoring interface.',
verbose_name="Path to authoring app's JS",
blank=True
),
),
migrations.AddField(
model_name='programsapiconfig',
name='enable_studio_tab',
field=models.BooleanField(default=False, verbose_name='Enable Studio Authoring Interface'),
),
migrations.AlterField(
model_name='programsapiconfig',
name='enable_student_dashboard',
field=models.BooleanField(default=False, verbose_name='Enable Student Dashboard Displays'),
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('programs', '0002_programsapiconfig_cache_ttl'),
]
operations = [
migrations.AddField(
model_name='programsapiconfig',
name='authoring_app_css_path',
field=models.CharField(max_length=255, verbose_name="Path to authoring app's CSS", blank=True),
),
migrations.AddField(
model_name='programsapiconfig',
name='authoring_app_js_path',
field=models.CharField(max_length=255, verbose_name="Path to authoring app's JS", blank=True),
),
migrations.AddField(
model_name='programsapiconfig',
name='enable_studio_tab',
field=models.BooleanField(default=False, verbose_name='Enable Studio Authoring Interface'),
),
migrations.AlterField(
model_name='programsapiconfig',
name='enable_student_dashboard',
field=models.BooleanField(default=False, verbose_name='Enable Student Dashboard Displays'),
),
]
|
Use short format when displaying dates on user record | import React from "react";
import moment from "moment";
class Record extends React.Component {
render() {
const {record} = this.props;
return (
<dl className="dl-horizontal">
<dt className="text-muted">Id</dt>
<dd>{record.id}</dd>
<dt className="text-muted">First Name</dt>
<dd>{record.first_name}</dd>
<dt className="text-muted">Last Name</dt>
<dd>{record.last_name}</dd>
<dt className="text-muted">Email</dt>
<dd><a href={`mailto:${record.email}`}>{record.email}</a></dd>
<dt className="text-muted">Date Joined</dt>
<dd>{moment(record.date_joined).format('ddd. MMM. Do YYYY, h:mm A')}</dd>
<dt className="text-muted">Last Login</dt>
<dd>{moment(record.last_login).format('ddd. MMM. Do YYYY, h:mm A')}</dd>
</dl>
);
}
}
export default Record;
| import React from "react";
import moment from "moment";
class Record extends React.Component {
render() {
const {record} = this.props;
return (
<dl className="dl-horizontal">
<dt className="text-muted">Id</dt>
<dd>{record.id}</dd>
<dt className="text-muted">First Name</dt>
<dd>{record.first_name}</dd>
<dt className="text-muted">Last Name</dt>
<dd>{record.last_name}</dd>
<dt className="text-muted">Email</dt>
<dd><a href={`mailto:${record.email}`}>{record.email}</a></dd>
<dt className="text-muted">Date Joined</dt>
<dd>{moment(record.date_joined).format('dddd MMMM Do YYYY, h:mm A')}</dd>
<dt className="text-muted">Last Login</dt>
<dd>{moment(record.last_login).format('dddd MMMM Do YYYY, h:mm A')}</dd>
</dl>
);
}
}
export default Record;
|
Make the template and env yaml parsing more consistent
in the environment_format.py use the same yaml_loader
Partial-bug: #1242155
Change-Id: I66b08415d450bd4758af648eaff0f20dd934a9cc | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from heat.common.template_format import yaml
from heat.common.template_format import yaml_loader
SECTIONS = (PARAMETERS, RESOURCE_REGISTRY) = \
('parameters', 'resource_registry')
def parse(env_str):
'''
Takes a string and returns a dict containing the parsed structure.
This includes determination of whether the string is using the
JSON or YAML format.
'''
try:
env = yaml.load(env_str, Loader=yaml_loader)
except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e:
raise ValueError(e)
else:
if env is None:
env = {}
for param in env:
if param not in SECTIONS:
raise ValueError(_('environment has wrong section "%s"') % param)
return env
def default_for_missing(env):
'''
Checks a parsed environment for missing sections.
'''
for param in SECTIONS:
if param not in env:
env[param] = {}
| # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from heat.common.template_format import yaml
SECTIONS = (PARAMETERS, RESOURCE_REGISTRY) = \
('parameters', 'resource_registry')
def parse(env_str):
'''
Takes a string and returns a dict containing the parsed structure.
This includes determination of whether the string is using the
JSON or YAML format.
'''
try:
env = yaml.safe_load(env_str)
except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e:
raise ValueError(e)
else:
if env is None:
env = {}
for param in env:
if param not in SECTIONS:
raise ValueError(_('environment has wrong section "%s"') % param)
return env
def default_for_missing(env):
'''
Checks a parsed environment for missing sections.
'''
for param in SECTIONS:
if param not in env:
env[param] = {}
|
Revert "Hopefully fixed the double request issues"
This reverts commit 23a6d2219ac9057e87b0e4a2088d79f2d17fbbab. | Checklist.Router = Ember.Router.extend({
location: 'hash',
root: Ember.Route.extend({
home: Ember.Route.extend({
route: '/',
connectOutlets: function(router, event) {
router.get('applicationController')
.connectOutlet({
viewClass: Checklist.MainView,
controller: router.get('taxonConceptController'),
context: Checklist.store.find(
Checklist.Index, router.get('filtersController').toParams()
)
});
}
}),
search: Ember.Route.extend({
route: '/search/:params',
connectOutlets: function(router, event) {
params = Checklist.Helpers.deparam(event.params);
router.get('filtersController').fromParams(params);
router.get('applicationController')
.connectOutlet({
viewClass: Checklist.MainView,
controller: router.get('taxonConceptController'),
context: Checklist.store.find(
Checklist.Index, router.get('filtersController').toParams()
)
});
}
}),
doAbout: function(router, event) {
router.transitionTo('about');
},
about: Ember.Route.extend({
route: '/about',
connectOutlets: function(router, event) {
router.get('applicationController').connectOutlet({viewClass: Checklist.AboutView});
}
})
})
});
| Checklist.Router = Ember.Router.extend({
location: 'hash',
root: Ember.Route.extend({
home: Ember.Route.extend({
route: '/',
connectOutlets: function(router, event) {
router.get('applicationController')
.connectOutlet({
viewClass: Checklist.MainView,
controller: router.get('taxonConceptController'),
context: Checklist.store.find(
Checklist.Index, router.get('filtersController').toParams()
)
});
}
}),
search: Ember.Route.extend({
route: '/search/:params',
connectOutlets: function(router, event) {
params = Checklist.Helpers.deparam(event.params);
router.get('applicationController')
.connectOutlet({
viewClass: Checklist.MainView,
controller: router.get('taxonConceptController'),
context: Checklist.store.find(
Checklist.Index, params
)
});
}
}),
doAbout: function(router, event) {
router.transitionTo('about');
},
about: Ember.Route.extend({
route: '/about',
connectOutlets: function(router, event) {
router.get('applicationController').connectOutlet({viewClass: Checklist.AboutView});
}
})
})
});
|
Add regex to strip html tags from question excerpt when rendering. | package io.github.vcuswimlab.stackintheflow.view;
import io.github.vcuswimlab.stackintheflow.model.Question;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
/**
* Created by batman on 11/16/16.
*/
public class QuestionRenderer extends JLabel implements ListCellRenderer<Question> {
private static final int EXCERPT_LENGTH = 80;
public QuestionRenderer() {
setOpaque(true);
}
@Override
public Component getListCellRendererComponent(JList<? extends Question> list, Question question, int index, boolean
isSelected, boolean cellHasFocus) {
String title = question.getTitle();
if(isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
TitledBorder focusBorder = new TitledBorder(LineBorder.createGrayLineBorder(),
title);
setText(generateExcerpt(question, EXCERPT_LENGTH));
setBorder(focusBorder);
return this;
}
//TODO: Maybe move this into the question object itself?
private String generateExcerpt(Question question, int maxLength) {
//TODO: Probably want a more advanced excerpt generation system later. This works for now, however.
String body = question.getBody().replaceAll("<.*?>", "");
if(body.length() <= maxLength) {
return body;
}
return body.substring(0, maxLength-3) + "...";
}
}
| package io.github.vcuswimlab.stackintheflow.view;
import io.github.vcuswimlab.stackintheflow.model.Question;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
/**
* Created by batman on 11/16/16.
*/
public class QuestionRenderer extends JLabel implements ListCellRenderer<Question> {
private static final int EXCERPT_LENGTH = 80;
public QuestionRenderer() {
setOpaque(true);
}
@Override
public Component getListCellRendererComponent(JList<? extends Question> list, Question question, int index, boolean
isSelected, boolean cellHasFocus) {
String title = question.getTitle();
if(isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
TitledBorder focusBorder = new TitledBorder(LineBorder.createGrayLineBorder(),
title);
setText(generateExcerpt(question, EXCERPT_LENGTH));
setBorder(focusBorder);
return this;
}
//TODO: Maybe move this into the question object itself?
private String generateExcerpt(Question question, int maxLength) {
//TODO: Probably want a more advanced excerpt generation system later. This works for now, however.
String body = question.getBody();
if(body.length() <= maxLength) {
return body;
}
return body.substring(0, maxLength-3) + "...";
}
}
|
Exclude the `flow-typed` directory by default | 'use strict';
var path = require('path');
var DEFAULT_EXCLUDE_PATTERN = "^(node_modules|bower_components|\\.imdone|target|build|dist|logs|flow-typed)[\\/\\\\]?|\\.(git|svn|hg|npmignore)|\\~$|\\.(jpg|png|gif|swp|ttf|otf)$";
var CONFIG_DIR = ".imdone";
module.exports = {
ASYNC_LIMIT: 512,
CONFIG_DIR: CONFIG_DIR,
CONFIG_FILE: path.join(CONFIG_DIR,"config.json"),
IGNORE_FILE: '.imdoneignore',
DEFAULT_FILE_PATTERN: "^(readme\\.md|home\\.md|readme\\.\w+|home\\.\w+)$",
DEFAULT_EXCLUDE_PATTERN: DEFAULT_EXCLUDE_PATTERN,
DEFAULT_CONFIG: {
exclude: [DEFAULT_EXCLUDE_PATTERN],
watcher: true,
keepEmptyPriority: false,
code: {
include_lists:[
"TODO", "DOING", "DONE", "PLANNING", "FIXME", "ARCHIVE", "HACK", "CHANGED", "XXX", "IDEA", "NOTE", "REVIEW"
]
},
lists: [],
marked : {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
smartLists: true,
langPrefix: 'language-' }
},
ERRORS: {
NOT_A_FILE: "file must be of type File",
CALLBACK_REQUIRED: "Last paramter must be a callback function",
NO_CONTENT: "File has no content"
}
};
| 'use strict';
var path = require('path');
var DEFAULT_EXCLUDE_PATTERN = "^(node_modules|bower_components|\\.imdone|target|build|dist|logs)[\\/\\\\]?|\\.(git|svn|hg|npmignore)|\\~$|\\.(jpg|png|gif|swp|ttf|otf)$";
var CONFIG_DIR = ".imdone";
module.exports = {
ASYNC_LIMIT: 512,
CONFIG_DIR: CONFIG_DIR,
CONFIG_FILE: path.join(CONFIG_DIR,"config.json"),
IGNORE_FILE: '.imdoneignore',
DEFAULT_FILE_PATTERN: "^(readme\\.md|home\\.md|readme\\.\w+|home\\.\w+)$",
DEFAULT_EXCLUDE_PATTERN: DEFAULT_EXCLUDE_PATTERN,
DEFAULT_CONFIG: {
exclude: [DEFAULT_EXCLUDE_PATTERN],
watcher: true,
keepEmptyPriority: false,
code: {
include_lists:[
"TODO", "DOING", "DONE", "PLANNING", "FIXME", "ARCHIVE", "HACK", "CHANGED", "XXX", "IDEA", "NOTE", "REVIEW"
]
},
lists: [],
marked : {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
smartLists: true,
langPrefix: 'language-' }
},
ERRORS: {
NOT_A_FILE: "file must be of type File",
CALLBACK_REQUIRED: "Last paramter must be a callback function",
NO_CONTENT: "File has no content"
}
};
|
Change raccordeon class adding behabior. Misunderstood. | (function($) {
$.fn.rtabs = function(options) {
var settings = $.extend({
'threshold' : '481',
'placehold' : 'top' //top, bottom, left, right
}, options);
this.find('.rtabsNavItem').click(function() {
$(this).siblings('.active').removeClass('active');
$(this).parent().parent().find('.rtabsPanel').removeClass('active');
$(this).addClass('active');
$($(this).find('a').attr('href')).addClass('active');
});
if (this.find('.rtabsNavItem.active').length <= 0) {
this.find('.rtabsNavItem:first').click();
} else {
this.find('.rtabsNavItem.active').click();
}
var myself = this;
Response.action( function () {
if (Response.band(settings.threshold)) {// Display is wider than threshold
$(myself).find('.rtabsPanel').each(function(){
$(myself).find('.rtabsNav').after($(this));
});
$(myself).removeClass('raccordeon');
} else {
$(myself).find('.rtabsNavItem').each(function(){
var myid = $(this).find('a').attr('href');
$(this).append($(myid));
});
$(myself).addClass('raccordeon');
}
});
return this;
};
})(jQuery);
| (function($) {
$.fn.rtabs = function(options) {
var settings = $.extend({
'threshold' : '481',
'placehold' : 'top' //top, bottom, left, right
}, options);
this.find('.rtabsNavItem').click(function() {
$(this).siblings('.active').removeClass('active');
$(this).parent().parent().find('.rtabsPanel').removeClass('active');
$(this).addClass('active');
$($(this).find('a').attr('href')).addClass('active');
});
if (this.find('.rtabsNavItem.active').length <= 0) {
this.find('.rtabsNavItem:first').click();
} else {
this.find('.rtabsNavItem.active').click();
}
var myself = this;
Response.action( function () {
if (Response.band(settings.threshold)) {// Display is under threshold
$(myself).find('.rtabsPanel').each(function(){
$(myself).find('.rtabsNav').after($(this));
});
$(myself).addClass('raccordeon');
} else {
$(myself).find('.rtabsNavItem').each(function(){
var myid = $(this).find('a').attr('href');
$(this).append($(myid));
});
$(myself).removeClass('raccordeon');
}
});
return this;
};
})(jQuery);
|
Make discretionary filter hide sold discretionary teams | <?php
namespace Tickets\DB;
class TicketDefaultFilter extends \Data\Filter
{
function __construct($email, $discretionary=false)
{
$this->children[] = new \Data\FilterClause();
$this->children[0]->var1 = 'email';
$this->children[0]->var2 = "'$email'";
$this->children[0]->op = '=';
$this->children[] = 'and';
$clause = new \Data\FilterClause();
if($discretionary === false)
{
$clause->var1 = 'sold';
$clause->var2 = '1';
$clause->op = '=';
}
else
{
$clause->var1 = 'discretionary';
$clause->var2 = '1';
$clause->op = '=';
$this->children[] = $clause;
$this->children[] = 'and';
$clause = new \Data\FilterClause();
$clause->var1 = 'sold';
$clause->var2 = '0';
$clause->op = '=';
}
$this->children[] = $clause;
$this->children[] = 'and';
$clause = new \Data\FilterClause();
$clause->var1 = 'used';
$clause->var2 = '0';
$clause->op = '=';
$this->children[] = $clause;
$this->children[] = 'and';
$clause = new \Data\FilterClause();
$clause->var1 = 'year';
$clause->var2 = TicketSystemSettings::getInstance()['year'];
$clause->op = '=';
$this->children[] = $clause;
}
}
?>
| <?php
namespace Tickets\DB;
class TicketDefaultFilter extends \Data\Filter
{
function __construct($email, $discretionary=false)
{
$this->children[] = new \Data\FilterClause();
$this->children[0]->var1 = 'email';
$this->children[0]->var2 = "'$email'";
$this->children[0]->op = '=';
$this->children[] = 'and';
$this->children[] = new \Data\FilterClause();
$this->children[2]->var1 = 'discretionary';
if($discretionary === false)
{
$this->children[2]->var2 = '0';
}
else
{
$this->children[2]->var2 = '1';
}
$this->children[2]->op = '=';
$this->children[] = 'and';
$this->children[] = new \Data\FilterClause();
$this->children[4]->var1 = 'used';
$this->children[4]->var2 = '0';
$this->children[4]->op = '=';
$this->children[] = 'and';
$this->children[] = new \Data\FilterClause();
$this->children[6]->var1 = 'year';
$this->children[6]->var2 = TicketSystemSettings::getInstance()['year'];
$this->children[6]->op = '=';
}
}
?>
|
Fix loop limits, add per layer options in test mapconfig Factory | function getVectorMapConfig(opts) {
return {
buffersize: {
mvt: 1
},
layers: _generateLayers(opts),
};
}
function _generateLayers(opts) {
const numberOfLayers = opts.numberOfLayers || 1;
const layers = [];
for (let index = 0; index < numberOfLayers; index++) {
const layerOptions = (opts.layerOptions || {})[index] || {};
layers.push(_generateLayerConfig(layerOptions));
}
return layers;
}
function _generateLayerConfig(opts) {
return {
type: 'mapnik',
options: {
sql: `
SELECT
(DATE '2018-06-01' + x) as date,
x as cartodb_id,
st_makepoint(x * 10, x * 10) as the_geom,
st_makepoint(x * 10, x * 10) as the_geom_webmercator
FROM
generate_series(0, 1) x`,
aggregation: {
columns: {},
dimensions: {
date: 'date'
},
placement: 'centroid',
resolution: 1,
threshold: 1
},
dates_as_numbers: opts.dates_as_numbers,
metadata: {
geometryType: true,
columnStats: {
topCategories: 32768,
includeNulls: true
},
sample: {
num_rows: 1000,
include_columns: [
'date'
]
}
}
}
};
}
module.exports = { getVectorMapConfig }; | function getVectorMapConfig(opts) {
return {
buffersize: {
mvt: 1
},
layers: _generateLayers(opts),
};
}
function _generateLayers(opts) {
const numberOfLayers = opts.numberOfLayers || 1;
const layers = [];
for (let index = 0; index <= numberOfLayers; index++) {
layers.push(_generateLayerConfig(opts));
}
return layers;
}
function _generateLayerConfig(opts) {
return {
type: 'mapnik',
options: {
sql: `
SELECT
(DATE '2018-06-01' + x) as date,
x as cartodb_id,
st_makepoint(x * 10, x * 10) as the_geom,
st_makepoint(x * 10, x * 10) as the_geom_webmercator
FROM
generate_series(0, 1) x`,
aggregation: {
columns: {},
dimensions: {
date: 'date'
},
placement: 'centroid',
resolution: 1,
threshold: 1
},
dates_as_numbers: opts.dates_as_numbers,
metadata: {
geometryType: true,
columnStats: {
topCategories: 32768,
includeNulls: true
},
sample: {
num_rows: 1000,
include_columns: [
'date'
]
}
}
}
};
}
module.exports = { getVectorMapConfig }; |
Implement sluggable manager in utils bundle. | <?php
/**
* @author Igor Nikolaev <[email protected]>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\ContentBundle\Slug;
use Darvin\Utils\Sluggable\SlugHandlerInterface;
use Doctrine\ORM\EntityManager;
/**
* Unique slug handler
*/
class UniqueSlugHandler implements SlugHandlerInterface
{
/**
* {@inheritdoc}
*/
public function handle(&$slug, &$suffix, EntityManager $em)
{
$similarSlugs = $this->getSlugMapItemRepository($em)->getSimilarSlugs($slug);
if (empty($similarSlugs) || !in_array($slug, $similarSlugs)) {
return;
}
$originalSlug = $slug;
$index = 0;
do {
$index++;
$slug = $originalSlug.'-'.$index;
} while (in_array($slug, $similarSlugs));
$suffix.='-'.$index;
}
/**
* @param \Doctrine\ORM\EntityManager $em Entity manager
*
* @return \Darvin\ContentBundle\Repository\SlugMapItemRepository
*/
private function getSlugMapItemRepository(EntityManager $em)
{
return $em->getRepository('DarvinContentBundle:SlugMapItem');
}
}
| <?php
/**
* @author Igor Nikolaev <[email protected]>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\ContentBundle\Slug;
use Darvin\Utils\Slug\SlugHandlerInterface;
use Doctrine\ORM\EntityManager;
/**
* Unique slug handler
*/
class UniqueSlugHandler implements SlugHandlerInterface
{
/**
* {@inheritdoc}
*/
public function handle(&$slug, &$suffix, EntityManager $em)
{
$similarSlugs = $this->getSlugMapItemRepository($em)->getSimilarSlugs($slug);
if (empty($similarSlugs) || !in_array($slug, $similarSlugs)) {
return;
}
$originalSlug = $slug;
$index = 0;
do {
$index++;
$slug = $originalSlug.'-'.$index;
} while (in_array($slug, $similarSlugs));
$suffix.='-'.$index;
}
/**
* @param \Doctrine\ORM\EntityManager $em Entity manager
*
* @return \Darvin\ContentBundle\Repository\SlugMapItemRepository
*/
private function getSlugMapItemRepository(EntityManager $em)
{
return $em->getRepository('DarvinContentBundle:SlugMapItem');
}
}
|
Change import so it works | """A custom ILAMB confrontation for net ecosystem productivity (nep)."""
import os
import numpy as np
from ILAMB.Confrontation import Confrontation
from ILAMB.Variable import Variable
from ILAMB.ilamblib import MakeComparable
class ConfNEP(Confrontation):
"""Confront ``nep`` model outputs with ``nee`` observations.
Net ecosystem productivity (``nep``) is a CMIP5 standard output
provided by the MsTMIP models, and is the inverse of net ecosystem
exchange (``nee``), for which benchmark datasets are provided in
ILAMB.
"""
def __init__(self, **keywords):
super(ConfNEP, self).__init__(**keywords)
def stageData(self, m):
obs = Variable(filename=self.source,
variable_name=self.variable)
self._checkRegions(obs)
obs.data *= -1.0 # Reverse sign of benchmark data.
mod = m.extractTimeSeries(self.variable,
alt_vars=self.alternate_vars)
mod.data *= -1.0 # Reverse sign of modified model outputs.
obs, mod = MakeComparable(obs, mod, clip_ref=True,
logstring="[%s][%s]" %
(self.longname, m.name))
return obs, mod
| """A custom ILAMB confrontation for net ecosystem productivity (nep)."""
import os
import numpy as np
from ILAMB.Confrontation import Confrontation
from ILAMB.Variable import Variable
import ilamblib as il
class ConfNEP(Confrontation):
"""Confront ``nep`` model outputs with ``nee`` observations.
Net ecosystem productivity (``nep``) is a CMIP5 standard output
provided by the MsTMIP models, and is the inverse of net ecosystem
exchange (``nee``), for which benchmark datasets are provided in
ILAMB.
"""
def __init__(self, **keywords):
super(ConfNEP, self).__init__(**keywords)
def stageData(self, m):
obs = Variable(filename=self.source,
variable_name=self.variable)
self._checkRegions(obs)
obs.data *= -1.0 # Reverse sign of benchmark data.
mod = m.extractTimeSeries(self.variable,
alt_vars=self.alternate_vars)
mod.data *= -1.0 # Reverse sign of modified model outputs.
obs, mod = il.MakeComparable(obs, mod, clip_ref=True,
logstring="[%s][%s]" %
(self.longname, m.name))
return obs, mod
|
Add option for no ajax | /*
FormAjaxifier
@author Jeevan@blacklizard
*/
(function ($) {
$.fn.FormAjaxifier = function (options) {
var settings = $.extend({
beforeSend: function (self) {},
success: function (self, data, textStatus, jqXHR) {},
error: function (self, jqXHR, textStatus, errorThrown) {},
complete: function (self, jqXHR, textStatus) {},
global: false
}, options);
return this.each(function () {
if (!$(this).hasClass('no-ajax')) {
return $(this).submit(function (event) {
var self = $(this);
$.ajax({
method: self.attr('method'),
url: self.attr('action'),
data: self.serialize(),
global: settings.global,
beforeSend: function () {
settings.beforeSend(self);
},
success: function (data, textStatus, jqXHR) {
settings.success(self, data, textStatus, jqXHR);
},
error: function (jqXHR, textStatus, errorThrown) {
settings.error(self, jqXHR, textStatus, errorThrown);
},
complete: function (jqXHR, textStatus) {
settings.complete(self, jqXHR, textStatus);
}
});
event.preventDefault();
event.stopImmediatePropagation();
});
}
});
}
}(jQuery));
| /*
FormAjaxifier
@author Jeevan@blacklizard
*/
(function ($) {
$.fn.FormAjaxifier = function (options) {
var settings = $.extend({
beforeSend: function (self) {},
success: function (self, data, textStatus, jqXHR) {},
error: function (self, jqXHR, textStatus, errorThrown) {},
complete: function (self, jqXHR, textStatus) {},
global: false
}, options);
return this.each(function () {
return $(this).submit(function (event) {
var self = $(this);
$.ajax({
method: self.attr('method'),
url: self.attr('action'),
data: self.serialize(),
global: settings.global,
beforeSend: function () {
settings.beforeSend(self);
},
success: function (data, textStatus, jqXHR) {
settings.success(self, data, textStatus, jqXHR);
},
error: function (jqXHR, textStatus, errorThrown) {
settings.error(self, jqXHR, textStatus, errorThrown);
},
complete: function (jqXHR, textStatus) {
settings.complete(self, jqXHR, textStatus);
}
});
event.preventDefault();
event.stopImmediatePropagation();
});
});
}
}(jQuery)); |
Add methods to remove vertices | package io.sigpipe.sing.graph;
public class GraphMetrics implements Cloneable {
private long vertices;
private long leaves;
public GraphMetrics() {
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
GraphMetrics that = (GraphMetrics) obj;
return this.vertices == that.vertices
&& this.leaves == that.leaves;
}
public GraphMetrics(int vertices, int leaves) {
this.vertices = vertices;
this.leaves = leaves;
}
public void setVertexCount(long vertices) {
this.vertices = vertices;
}
public void setLeafCount(long leaves) {
this.leaves = leaves;
}
public void addVertex() {
this.vertices++;
}
public void addVertices(long vertices) {
this.vertices += vertices;
}
public void addLeaf() {
this.leaves++;
}
public void addLeaves(long leaves) {
this.leaves += leaves;
}
public void removeVertex() {
this.vertices--;
}
public void removeVertices(long vertices) {
this.vertices -= vertices;
}
public long getVertexCount() {
return this.vertices;
}
public long getLeafCount() {
return this.leaves;
}
public String toString() {
return "V: " + this.vertices + ", L: " + this.leaves;
}
}
| package io.sigpipe.sing.graph;
public class GraphMetrics implements Cloneable {
private long vertices;
private long leaves;
public GraphMetrics() {
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
GraphMetrics that = (GraphMetrics) obj;
return this.vertices == that.vertices
&& this.leaves == that.leaves;
}
public GraphMetrics(int vertices, int leaves) {
this.vertices = vertices;
this.leaves = leaves;
}
public void setVertexCount(long vertices) {
this.vertices = vertices;
}
public void setLeafCount(long leaves) {
this.leaves = leaves;
}
public void addVertex() {
this.vertices++;
}
public void addVertices(long vertices) {
this.vertices += vertices;
}
public void addLeaf() {
this.leaves++;
}
public void addLeaves(long leaves) {
this.leaves += leaves;
}
public long getVertexCount() {
return this.vertices;
}
public long getLeafCount() {
return this.leaves;
}
public String toString() {
return "V: " + this.vertices + ", L: " + this.leaves;
}
}
|
Allow to specify a database when running a query | from fabric.api import sudo, hide
from braid import package
from pipes import quote
def install():
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
def _runQuery(query, database=None):
with hide('running', 'output'):
database = '--dbname={}'.format(database) if database else ''
return sudo('psql --no-align --no-readline --no-password --quiet '
'--tuples-only {} -c {}'.format(database, quote(query)),
user='postgres', pty=False, combine_stderr=False)
def _dbExists(name):
res = _runQuery("select count(*) from pg_database "
"where datname = '{}';".format(name))
return res == '1'
def _userExists(name):
res = _runQuery("select count(*) from pg_user "
"where usename = '{}';".format(name))
return res == '1'
def createUser(name):
if not _userExists(name):
sudo('createuser -D -R -S {}'.format(name), user='postgres', pty=False)
def createDb(name, owner):
if not _dbExists(name):
sudo('createdb -O {} {}'.format(owner, name), user='postgres',
pty=False)
def grantRead(user, database):
"""
Grant read permissions to C{user} to all tables in C{database}.
"""
def grantReadWrite(user, database):
"""
Grant read and write permissions to C{user} to all tables in C{database}.
"""
| from fabric.api import sudo, hide
from braid import package
from pipes import quote
def install():
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
def _runQuery(query):
with hide('running', 'output'):
return sudo('psql --no-align --no-readline --no-password --quiet '
'--tuples-only -c {}'.format(quote(query)),
user='postgres', pty=False, combine_stderr=False)
def _dbExists(name):
res = _runQuery("select count(*) from pg_database "
"where datname = '{}';".format(name))
return res == '1'
def _userExists(name):
res = _runQuery("select count(*) from pg_user "
"where usename = '{}';".format(name))
return res == '1'
def createUser(name):
if not _userExists(name):
sudo('createuser -D -R -S {}'.format(name), user='postgres', pty=False)
def createDb(name, owner):
if not _dbExists(name):
sudo('createdb -O {} {}'.format(owner, name), user='postgres',
pty=False)
def grantRead(user, database):
"""
Grant read permissions to C{user} to all tables in C{database}.
"""
def grantReadWrite(user, database):
"""
Grant read and write permissions to C{user} to all tables in C{database}.
"""
|
Improve link to api docs. | import './SearchBoxHelp.css';
import React, { Component } from 'react';
import MaterialIcon from 'shared/components/icon/MaterialIcon';
import Tooltip from 'shared/components/tooltip/Tooltip';
export default class SearchBoxHelp extends Component {
shouldComponentUpdate() {
return false;
}
render() {
const overlay = (
<div>
<p>You may use search qualifiers in any combination.</p>
<ul>
<li><code>author:sindresorhus</code> Show or filter results by author</li>
<li><code>maintainer:sindresorhus</code> Show or filter results by maintainer</li>
<li><code>keywords:gulpplugin</code> Show or filter results by keywords</li>
<li><code>not:deprecated</code> Exclude packages that are deprecated, unstable or insecure</li>
</ul>
<p>For the complete list of qualifiers, please read the <a href="https://api-docs.npms.io/#api-search-query" target="_blank">Search API documentation</a>.</p>
</div>
);
return (
<Tooltip overlayClassName="search-box-help-component-tooltip" placement="bottom" overlay={ overlay }>
<div className="search-box-help-component">
<MaterialIcon id="help_outline" className="help" />
</div>
</Tooltip>
);
}
}
| import './SearchBoxHelp.css';
import React, { Component } from 'react';
import MaterialIcon from 'shared/components/icon/MaterialIcon';
import Tooltip from 'shared/components/tooltip/Tooltip';
export default class SearchBoxHelp extends Component {
shouldComponentUpdate() {
return false;
}
render() {
const overlay = (
<div>
<p>You may use search qualifiers in any combination.</p>
<ul>
<li><code>author:sindresorhus</code> Show or filter results by author</li>
<li><code>maintainer:sindresorhus</code> Show or filter results by maintainer</li>
<li><code>keywords:gulpplugin</code> Show or filter results by keywords</li>
<li><code>not:deprecated</code> Exclude packages that are deprecated, unstable or insecure</li>
</ul>
<p>For the complete list of qualifiers, please read the Search API <a href="https://api-docs.npms.io" target="_blank">documentation</a>.</p>
</div>
);
return (
<Tooltip overlayClassName="search-box-help-component-tooltip" placement="bottom" overlay={ overlay }>
<div className="search-box-help-component">
<MaterialIcon id="help_outline" className="help" />
</div>
</Tooltip>
);
}
}
|
Test fix due to interface change | <?php
namespace mxdiModuleTest\Annotation;
use mxdiModule\Annotation\Inject;
use mxdiModuleTest\TestCase;
use Zend\ServiceManager\ServiceLocatorInterface;
class InjectTest extends TestCase
{
public function testIsNotInvokableByDefault()
{
$this->assertFalse((new Inject())->invokable);
}
public function testGetValueWithServiceLocator()
{
$inject = new Inject();
$inject->value = 'serviceName';
$inject->invokable = false;
$service = new \stdClass();
/** @var ServiceLocatorInterface|\PHPUnit_Framework_MockObject_MockObject $sm */
$sm = $this->getMockBuilder(ServiceLocatorInterface::class)
->setMethods(['get'])
->getMockForAbstractClass();
$sm->expects($this->once())
->method('get')
->with($this->equalTo($inject->value))
->will($this->returnValue($service));
$this->assertSame($service, $inject->getValue($sm));
}
public function testGetValueBypassesServiceManagerWithInvokable()
{
$inject = new Inject();
$inject->value = self::class;
$inject->invokable = true;
/** @var ServiceLocatorInterface|\PHPUnit_Framework_MockObject_MockObject $sm */
$sm = $this->getMockBuilder(ServiceLocatorInterface::class)
->setMethods(['get'])
->getMockForAbstractClass();
$sm->expects($this->never())
->method('get');
$this->assertInstanceOf(self::class, $inject->getValue($sm));
}
}
| <?php
namespace mxdiModuleTest\Annotation;
use mxdiModule\Annotation\Exception\CannotGetValue;
use mxdiModule\Annotation\Inject;
use mxdiModuleTest\TestCase;
use Zend\ServiceManager\ServiceLocatorInterface;
class InjectTest extends TestCase
{
public function testIsNotInvokableByDefault()
{
$this->assertFalse((new Inject())->invokable);
}
public function testGetValueWithServiceLocator()
{
$inject = new Inject();
$inject->value = 'serviceName';
$inject->invokable = false;
$service = new \stdClass();
$sm = $this->getMockBuilder(ServiceLocatorInterface::class)
->setMethods(['get'])
->getMockForAbstractClass();
$sm->expects($this->once())
->method('get')
->with($this->equalTo($inject->value))
->will($this->returnValue($service));
$this->assertSame($service, $inject->getValue($sm));
}
public function testGetValueBypassesServiceManagerWithInvokable()
{
$inject = new Inject();
$inject->value = self::class;
$inject->invokable = true;
$this->assertInstanceOf(self::class, $inject->getValue());
}
public function testGetValueThrowsExceptionOnMissingSMWhenRequired()
{
$inject = new Inject();
$this->setExpectedException(CannotGetValue::class);
$inject->getValue();
}
}
|
Use more widely the new Check class | <?php
namespace Isbn;
class Validation {
public static function isbn($isbn)
{
if (Check::is13($isbn))
return Validation::isbn13($isbn);
if (Check::is10($isbn))
return Validation::isbn10($isbn);
return false;
}
public static function isbn10($isbn)
{
if (strlen($isbn) != 10)
return false;
$check = 0;
for ($i = 0; $i < 10; $i++)
if ($isbn[$i] == "X")
$check += 10 * intval(10 - $i);
else
$check += intval($isbn[$i]) * intval(10 - $i);
return $check % 11 == 0;
}
public static function isbn13($isbn)
{
if (strlen($isbn) != 13)
return false;
$check = 0;
for ($i = 0; $i < 13; $i+=2)
$check += substr($isbn, $i, 1);
for ($i = 1; $i < 12; $i+=2)
$check += 3 * substr($isbn, $i, 1);
return $check % 10 == 0;
}
}
| <?php
namespace Isbn;
class Validation {
public static function isbn($isbn)
{
if (strlen($isbn) == 13)
return Validation::isbn13($isbn);
if (strlen($isbn) == 10)
return Validation::isbn10($isbn);
return false;
}
public static function isbn10($isbn)
{
if (strlen($isbn) != 10)
return false;
$check = 0;
for ($i = 0; $i < 10; $i++)
if ($isbn[$i] == "X")
$check += 10 * intval(10 - $i);
else
$check += intval($isbn[$i]) * intval(10 - $i);
return $check % 11 == 0;
}
public static function isbn13($isbn)
{
if (strlen($isbn) != 13)
return false;
$check = 0;
for ($i = 0; $i < 13; $i+=2)
$check += substr($isbn, $i, 1);
for ($i = 1; $i < 12; $i+=2)
$check += 3 * substr($isbn, $i, 1);
return $check % 10 == 0;
}
}
|
Revert "Trap focus to the menu when open"
This reverts commit ed195f52702a7eead162d9f10e6e898de0fe9029.
Trapping focus was preventing the menu from being closeable | // JavaScript Document
// Scripts written by __gulp_init__author_name @ __gulp_init__author_company
import SuperSlide from "superslide.js";
// get the elements
const CONTENT = document.getElementById("page-container");
const SLIDER = document.getElementById("mobile-menu");
const TOGGLE = document.querySelector("[data-toggle=mobile-menu]");
// verify that the elements exist
if (CONTENT !== null && SLIDER !== null && TOGGLE !== null) {
// initialize the menu
const MOBILE_MENU = new SuperSlide({
allowContentInteraction: false,
animation: "slideLeft",
closeOnBlur: true,
content: document.getElementById("page-container"),
duration: 0.25,
slideContent: false,
slider: document.getElementById("mobile-menu"),
onOpen: () => {
SLIDER.setAttribute("aria-hidden", false);
},
onClose: () => {
SLIDER.setAttribute("aria-hidden", true);
},
});
// open the menu when clicking on the toggle
TOGGLE.addEventListener("click", (e) => {
e.preventDefault();
console.log(MOBILE_MENU.isOpen());
if (!MOBILE_MENU.isOpen()) {
MOBILE_MENU.open();
} else {
MOBILE_MENU.close();
}
});
}
| // JavaScript Document
// Scripts written by __gulp_init__author_name @ __gulp_init__author_company
import SuperSlide from "superslide.js";
import focusTrap from "focus-trap";
// get the elements
const CONTENT = document.getElementById("page-container");
const SLIDER = document.getElementById("mobile-menu");
const TOGGLE = document.querySelector("[data-toggle=mobile-menu]");
const FOCUS_TRAP = focusTrap("#mobile-menu");
// verify that the elements exist
if (CONTENT !== null && SLIDER !== null && TOGGLE !== null) {
// initialize the menu
const MOBILE_MENU = new SuperSlide({
allowContentInteraction: false,
animation: "slideLeft",
closeOnBlur: true,
content: document.getElementById("page-container"),
duration: 0.25,
slideContent: false,
slider: document.getElementById("mobile-menu"),
onOpen: () => {
SLIDER.setAttribute("aria-hidden", false);
FOCUS_TRAP.activate();
},
onClose: () => {
SLIDER.setAttribute("aria-hidden", true);
FOCUS_TRAP.deactivate();
},
});
// open the menu when clicking on the toggle
TOGGLE.addEventListener("click", (e) => {
e.preventDefault();
console.log(MOBILE_MENU.isOpen());
if (!MOBILE_MENU.isOpen()) {
MOBILE_MENU.open();
} else {
MOBILE_MENU.close();
}
});
}
|
Allow the toolbox to be installed in Python 3.7 | from setuptools import setup
REPO_URL = 'http://github.com/okfn-brasil/serenata-toolbox'
with open('README.rst') as fobj:
long_description = fobj.read()
setup(
author='Serenata de Amor',
author_email='[email protected]',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
zip_safe=False,
install_requires=[
'aiofiles',
'aiohttp',
'beautifulsoup4>=4.4',
'lxml>=3.6',
'pandas>=0.18',
'python-decouple>=3.1',
'tqdm'
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description=long_description,
name='serenata-toolbox',
packages=[
'serenata_toolbox',
'serenata_toolbox.federal_senate',
'serenata_toolbox.chamber_of_deputies',
'serenata_toolbox.datasets'
],
scripts=['serenata_toolbox/serenata-toolbox'],
url=REPO_URL,
python_requires='>=3.6',
version='15.1.5',
)
| from setuptools import setup
REPO_URL = 'http://github.com/okfn-brasil/serenata-toolbox'
with open('README.rst') as fobj:
long_description = fobj.read()
setup(
author='Serenata de Amor',
author_email='[email protected]',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.6',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
zip_safe=False,
install_requires=[
'aiofiles',
'aiohttp',
'beautifulsoup4>=4.4',
'lxml>=3.6',
'pandas>=0.18',
'python-decouple>=3.1',
'tqdm'
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description=long_description,
name='serenata-toolbox',
packages=[
'serenata_toolbox',
'serenata_toolbox.federal_senate',
'serenata_toolbox.chamber_of_deputies',
'serenata_toolbox.datasets'
],
scripts=['serenata_toolbox/serenata-toolbox'],
url=REPO_URL,
python_requires='>=3.6',
version='15.1.4',
)
|
Use source maps and uglify | import webpack from "webpack";
import path from "path";
const plugins = [
new webpack.HotModuleReplacementPlugin()
];
if (process.env.NODE_ENV === "production") {
plugins.push(new webpack.optimize.UglifyJsPlugin());
}
export default {
devtool: "source-map",
entry: [
"webpack-dev-server/client?http://localhost:3000",
"webpack/hot/only-dev-server",
"./src/index"
],
output: {
path: path.join(__dirname, "dist"),
publicPath: "/dist/",
filename: "bundle.min.js",
sourceMapFilename: "bundle.min.js.map"
},
plugins,
module: {
preLoaders: [
{
test: /\.js$/,
loader: "eslint-loader",
exclude: /node_modules/
}
],
loaders: [
{
test: /\.js$/,
loaders: [ "react-hot", "babel" ],
exclude: /node_modules/
},
{
test: /\.json$/,
loader: "json",
exclude: /node_modules/
}
]
}
};
| import webpack from "webpack";
import path from "path";
export default {
devtool: "eval",
entry: [
"webpack-dev-server/client?http://localhost:3000",
"webpack/hot/only-dev-server",
"./src/index"
],
output: {
path: path.join(__dirname, "dist"),
filename: "bundle.min.js",
publicPath: "/dist/"
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
preLoaders: [
{
test: /\.js$/,
loader: "eslint-loader",
exclude: /node_modules/
}
],
loaders: [
{
test: /\.js$/,
loaders: [ "react-hot", "babel" ],
exclude: /node_modules/
},
{
test: /\.json$/,
loaders: [ "json" ],
exclude: /node_modules/
}
]
}
};
|
Fix bug in DateUtilities test suite. | 'use strict';
describe("Date Utilities", function() {
describe("Function 'roundToFollowingHalfHour'", function() {
it("Before half hours", function() {
var date = new Date();
date.setMinutes(0);
var hoursBefore = date.getHours();
for(var i = 0; i < 30; i++) {
var currentDate = new Date(date);
currentDate.setMinutes(i);
DateUtilities.roundToFollowingHalfHour(currentDate);
expect(currentDate.getHours()).toBe(hoursBefore);
}
});
it("Exactly half hours", function() {
var date = new Date();
date.setMinutes(30);
var hoursBefore = date.getHours();
for(var i = 0; i < 24; i++) {
var currentDate = new Date(date);
currentDate.setHours(currentDate.getHours() + i);
DateUtilities.roundToFollowingHalfHour(currentDate);
expect(currentDate.getHours()).toBe((hoursBefore + i) % 24);
}
});
it("After half hours", function() {
var date = new Date();
date.setMinutes(31);
var hoursBefore = date.getHours();
for(var i = 0; i < 30; i++) {
var currentDate = new Date(date);
currentDate.setMinutes(date.getMinutes() + i);
DateUtilities.roundToFollowingHalfHour(currentDate);
expect(currentDate.getHours()).toBe((hoursBefore + 1) % 24);
}
});
});
});
| 'use strict';
describe("Date Utilities", function() {
describe("Function 'roundToFollowingHalfHour'", function() {
it("Before half hours", function() {
var date = new Date();
date.setMinutes(0);
var hoursBefore = date.getHours();
for(var i = 0; i < 30; i++) {
var currentDate = new Date(date);
currentDate.setMinutes(i);
DateUtilities.roundToFollowingHalfHour(currentDate);
expect(currentDate.getHours()).toBe(hoursBefore);
}
});
it("Exactly half hours", function() {
var date = new Date();
date.setMinutes(30);
var hoursBefore = date.getHours();
for(var i = 0; i < 24; i++) {
var currentDate = new Date(date);
currentDate.setHours(currentDate.getHours() + i);
DateUtilities.roundToFollowingHalfHour(currentDate);
expect(currentDate.getHours()).toBe((hoursBefore + i) % 24);
}
});
it("After half hours", function() {
var date = new Date();
date.setMinutes(31);
var hoursBefore = date.getHours();
for(var i = 0; i < 30; i++) {
var currentDate = new Date(date);
currentDate.setMinutes(date.getMinutes() + i);
DateUtilities.roundToFollowingHalfHour(currentDate);
expect(currentDate.getHours()).toBe(hoursBefore + 1);
}
});
});
});
|
Split dependencies out in webpack to reduce bundle size | const path = require("path");
module.exports = {
entry: path.resolve(__dirname, "./source/index.js"),
externals: {
argon2: "argon2",
buttercup: "buttercup",
kdbxweb: "kdbxweb"
},
module: {
rules : [
{
test: /\.(js|esm)$/,
use: {
loader: "babel-loader",
options: {
"presets": [
["@babel/preset-env", {
"corejs": 3,
"useBuiltIns": "entry",
"targets": {
"node": "6"
}
}]
],
"plugins": [
["@babel/plugin-proposal-object-rest-spread", {
"useBuiltIns": true
}]
]
}
}
}
]
},
output: {
filename: "buttercup-importer.js",
libraryTarget: "commonjs2",
path: path.resolve(__dirname, "./dist")
},
target: "node"
};
| const path = require("path");
module.exports = {
entry: path.resolve(__dirname, "./source/index.js"),
externals: {
buttercup: "buttercup"
},
module: {
rules : [
{
test: /\.(js|esm)$/,
use: {
loader: "babel-loader",
options: {
"presets": [
["@babel/preset-env", {
"corejs": 3,
"useBuiltIns": "entry",
"targets": {
"node": "6"
}
}]
],
"plugins": [
["@babel/plugin-proposal-object-rest-spread", {
"useBuiltIns": true
}]
]
}
}
}
]
},
output: {
filename: "buttercup-importer.js",
libraryTarget: "commonjs2",
path: path.resolve(__dirname, "./dist")
},
target: "node"
};
|
Remove return statements from assert methods | import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
def assertRequest(self, method="GET", url="", status_code=200,
contains=None, **kwargs):
"""
Asserts requests on a given endpoint
"""
if contains is None:
cotains = []
if method is "GET":
request = requests.get
elif method is "POST":
request = requests.post
elif method is "PUT":
request = requests.put
elif method is "DELETE":
request = requests.delete
response = request(url, **kwargs)
self.assertEqual(response.status_code, status_code)
if contains:
for item in contains:
self.assertIn(item, response.content)
def assertGet(self, *args, **kwargs):
"""
Asserts GET requests on a URL
"""
self.assertRequest("GET", *args, **kwargs)
def assertPost(self, *args, **kwargs):
"""
Asserts POST requests on a URL
"""
self.assertRequest("POST", *args, **kwargs)
def assertPut(self, *args, **kwargs):
"""
Asserts PUT requests on a URL
"""
self.assertRequest("PUT", *args, **kwargs)
def assertDelete(self, *args, **kwargs):
"""
Asserts DELETE requests on a URL
"""
self.assertRequest("DELETE", *args, **kwargs)
| import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
def assertRequest(self, method="GET", url="", status_code=200,
contains=None, **kwargs):
"""
Asserts requests on a given endpoint
"""
if contains is None:
cotains = []
if method is "GET":
request = requests.get
elif method is "POST":
request = requests.post
elif method is "PUT":
request = requests.put
elif method is "DELETE":
request = requests.delete
response = request(url, **kwargs)
self.assertEqual(response.status_code, status_code)
if contains:
for item in contains:
self.assertIn(item, response.content)
def assertGet(self, *args, **kwargs):
"""
Asserts GET requests on a URL
"""
return self.assertRequest("GET", *args, **kwargs)
def assertPost(self, *args, **kwargs):
"""
Asserts POST requests on a URL
"""
return self.assertRequest("POST", *args, **kwargs)
def assertPut(self, *args, **kwargs):
"""
Asserts PUT requests on a URL
"""
return self.assertRequest("PUT", *args, **kwargs)
def assertDelete(self, *args, **kwargs):
"""
Asserts DELETE requests on a URL
"""
return self.assertRequest("DELETE", *args, **kwargs)
|
Clone git repos if they do not exist. | """
Version control management tools.
"""
import abc
import brigit
from docutils import nodes
from docutils.parsers.rst import directives
from .tool import Tool, Directive
class VCS(Tool):
"""Abstract class for VCS tools."""
__metaclass__ = abc.ABCMeta
def __init__(self, path, branch, url=None):
self.path = path
self.branch = branch
self.url = url
super(VCS, self).__init__()
@abc.abstractmethod
def log(self, number=10):
"""List of :class:`Commit` items."""
raise NotImplementedError
class Git(VCS):
"""Git tool."""
def __init__(self, path, branch='master', url=None):
super(Git, self).__init__(path, branch, url)
self._repository = brigit.Git(path, remote=self.url)
def log(self, number=10):
commits = "%s~%i..%s" % (self.branch, number, self.branch)
return self._repository.pretty_log(commits)
def update(self):
self._repository.fetch()
class Log(Directive):
"""List logs as a definition list."""
option_spec = {'number': directives.nonnegative_int}
def run(self):
children = []
for item in self.tool.log():
children.append(nodes.term(text=item['hash']))
children.append(
nodes.definition('', nodes.paragraph(text=item['message'])))
definition_list = nodes.definition_list('', *children)
return [definition_list]
| """
Version control management tools.
"""
import abc
import brigit
from docutils import nodes
from docutils.parsers.rst import directives
from .tool import Tool, Directive
class VCS(Tool):
"""Abstract class for VCS tools."""
__metaclass__ = abc.ABCMeta
def __init__(self, path, branch, url=None):
self.path = path
self.branch = branch
super(VCS, self).__init__()
@abc.abstractmethod
def log(self, number=10):
"""List of :class:`Commit` items."""
raise NotImplementedError
class Git(VCS):
"""Git tool."""
def __init__(self, path, branch='master', url=None):
self._repository = brigit.Git(path)
super(Git, self).__init__(path, branch)
def log(self, number=10):
commits = "%s~%i..%s" % (self.branch, number, self.branch)
return self._repository.pretty_log(commits)
def update(self):
self._repository.fetch()
class Log(Directive):
"""List logs as a definition list."""
option_spec = {'number': directives.nonnegative_int}
def run(self):
children = []
for item in self.tool.log():
children.append(nodes.term(text=item['hash']))
children.append(
nodes.definition('', nodes.paragraph(text=item['message'])))
definition_list = nodes.definition_list('', *children)
return [definition_list]
|
Change match all query syntax | '''
Biothings Query Component Common Tests
'''
import os
from nose.core import main
from biothings.tests import BiothingsTestCase
class QueryTests(BiothingsTestCase):
''' Test against server specified in environment variable BT_HOST
and BT_API or MyGene.info production server V3 by default '''
__test__ = True
host = os.getenv("BT_HOST", "http://mygene.info")
api = os.getenv("BT_API", "/v3")
def test_01(self):
''' KWARGS CTRL Format Json '''
self.query(q='__all__', size='1')
def test_02(self):
''' KWARGS CTRL Format Yaml '''
res = self.request('query?q=__all__&size=1&format=yaml').text
assert res.startswith('max_score:')
def test_03(self):
''' KWARGS CTRL Format Html '''
res = self.request('query?q=__all__&size=1&format=html').text
assert '<html>' in res
def test_04(self):
''' KWARGS CTRL Format Msgpack '''
res = self.request('query?q=__all__&size=1&format=msgpack').content
self.msgpack_ok(res)
if __name__ == '__main__':
main(defaultTest='__main__.QueryTests', argv=['', '-v'])
| '''
Biothings Query Component Common Tests
'''
import os
from nose.core import main
from biothings.tests import BiothingsTestCase
class QueryTests(BiothingsTestCase):
''' Test against server specified in environment variable BT_HOST
and BT_API or MyGene.info production server V3 by default '''
__test__ = True
host = os.getenv("BT_HOST", "http://mygene.info")
api = os.getenv("BT_API", "/v3")
def test_01(self):
''' KWARGS CTRL Format Json '''
self.query(q='*', size='1')
def test_02(self):
''' KWARGS CTRL Format Yaml '''
res = self.request('query?q=*&size=1&out_format=yaml').text
assert res.startswith('max_score:')
def test_03(self):
''' KWARGS CTRL Format Html '''
res = self.request('query?q=*&size=1&out_format=html').text
assert '<html>' in res
def test_04(self):
''' KWARGS CTRL Format Msgpack '''
res = self.request('query?q=*&size=1&out_format=msgpack').content
self.msgpack_ok(res)
if __name__ == '__main__':
main(defaultTest='__main__.QueryTests', argv=['', '-v'])
|
Change vendor script view to not be strictly couple to a user.
For public views, we will not have a user. | var cdb = require('cartodb.js-v3');
module.exports = cdb.core.View.extend({
initialize: function () {
this.config = this.options.config;
this.assetsVersion = this.options.assetsVersion;
this.user = this.options.user;
this.template = cdb.templates.getTemplate('common/views/vendor_scripts');
},
render: function () {
this.$el.html(
this.template({
assetsVersion: this.assetsVersion,
googleAnalyticsDomain: this.config.google_analytics_domain,
googleAnalyticsMemberType: this.user && this.user.get('account_type').toUpperCase(),
googleAnalyticsUa: this.config.google_analytics_ua,
hubspotEnabled: !!this.config.hubspot_enabled,
hubspotIds: this.config.hubspot_ids,
hubspotToken: this.config.hubspot_token,
intercomAppId: this.config.intercom_app_id,
intercomEnabled: this.user && !!this.user.featureEnabled('intercom'),
trackjsAppKey: this.config.trackjs_app_key,
trackjsCustomer: this.config.trackjs_customer,
trackjsEnabled: !!this.config.trackjs_enabled,
fullstoryEnabled: !!this.config.fullstory_enabled,
fullstoryOrg: this.config.fullstoryOrg,
userEmail: this.user && this.user.get('email'),
userName: this.user && this.user.get('username')
})
);
return this;
}
});
| var cdb = require('cartodb.js-v3');
module.exports = cdb.core.View.extend({
initialize: function () {
this.config = this.options.config;
this.assetsVersion = this.options.assetsVersion;
this.user = this.options.user;
this.template = cdb.templates.getTemplate('common/views/vendor_scripts');
},
render: function () {
this.$el.html(
this.template({
assetsVersion: this.assetsVersion,
googleAnalyticsDomain: this.config.google_analytics_domain,
googleAnalyticsMemberType: this.user.get('account_type').toUpperCase(),
googleAnalyticsUa: this.config.google_analytics_ua,
hubspotEnabled: !!this.config.hubspot_enabled,
hubspotIds: this.config.hubspot_ids,
hubspotToken: this.config.hubspot_token,
intercomAppId: this.config.intercom_app_id,
intercomEnabled: !!this.user.featureEnabled('intercom'),
trackjsAppKey: this.config.trackjs_app_key,
trackjsCustomer: this.config.trackjs_customer,
trackjsEnabled: !!this.config.trackjs_enabled,
fullstoryEnabled: !!this.config.fullstory_enabled,
fullstoryOrg: this.config.fullstoryOrg,
userEmail: this.user.get('email'),
userName: this.user.get('username')
})
);
return this;
}
});
|
Add \n\n even when only concat'ing and not compressing JS assets | "use strict";
var util = require('util'),
path = require('path'),
jsParser = require('uglify-js').parser,
compressor = require('uglify-js').uglify,
Asset = require('../Asset'),
JSAsset = function(settings) {
settings.compressor = settings.compressor || 'uglify';
this.init(settings);
var self = this;
this.on('variantPostRenderFile', function(variant, file, cb) {
var basename = path.basename(file),
contents = variant.getRenderCache(file);
if (!Asset.COMPRESS) {
variant.setRenderCache(file, contents + "\n\n");
return cb();
}
self.compress(file, contents, function(err, data) {
// errors are already signaled by the compressor
variant.setRenderCache(file, "/* " + basename + " */\n" + data + "\n\n");
cb();
});
});
};
util.inherits(JSAsset, Asset);
Asset.registerCompressor('uglify', function(filepath, data, cb) {
try {
var ast = compressor.ast_squeeze(compressor.ast_mangle(jsParser.parse(data)));
cb(null, ';' + compressor.gen_code(ast));
} catch (ex) {
console.error('ERROR: Uglify compressor error in ' + filepath);
console.error(ex);
// only show the error in the logs...don't stop serving because of this
cb(null, data);
}
});
JSAsset.configure = function(opts) {
Asset.configure(opts);
};
module.exports = JSAsset;
| "use strict";
var util = require('util'),
path = require('path'),
jsParser = require('uglify-js').parser,
compressor = require('uglify-js').uglify,
Asset = require('../Asset'),
JSAsset = function(settings) {
settings.compressor = settings.compressor || 'uglify';
this.init(settings);
var self = this;
this.on('variantPostRenderFile', function(variant, file, cb) {
if (!Asset.COMPRESS) return cb();
var basename = path.basename(file);
self.compress(file, variant.getRenderCache(file), function(err, data) {
// errors are already signaled by the compressor
variant.setRenderCache(file, "/* " + basename + " */\n" + data + "\n\n");
cb();
});
});
};
util.inherits(JSAsset, Asset);
Asset.registerCompressor('uglify', function(filepath, data, cb) {
try {
var ast = compressor.ast_squeeze(compressor.ast_mangle(jsParser.parse(data)));
cb(null, ';' + compressor.gen_code(ast));
} catch (ex) {
console.error('ERROR: Uglify compressor error in ' + filepath);
console.error(ex);
// only show the error in the logs...don't stop serving because of this
cb(null, data);
}
});
JSAsset.configure = function(opts) {
Asset.configure(opts);
};
module.exports = JSAsset;
|
Add a build task to grunt. | module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jasmine: {
geojson_to_gmaps: {
src: 'geojson-to-gmaps.js',
options: {
specs: 'spec/*Spec.js',
helpers: 'spec/*Helper.js',
vendor: 'vendor/*.js'
}
}
},
jshint: {
all: ['Gruntfile.js', 'src/**/*.js', 'spec/**/*.js']
},
uglify: {
my_target: {
files: {
'geojson-to-gmaps.min.js': ['geojson-to-gmaps.js']
}
}
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
// Default task(s).
grunt.registerTask('default', ['jasmine']);
grunt.registerTask('build', 'Build a release', ['jasmine', 'uglify']);
};
| module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jasmine: {
geojson_to_gmaps: {
src: 'geojson-to-gmaps.js',
options: {
specs: 'spec/*Spec.js',
helpers: 'spec/*Helper.js',
vendor: 'vendor/*.js'
}
}
},
jshint: {
all: ['Gruntfile.js', 'src/**/*.js', 'spec/**/*.js']
},
uglify: {
my_target: {
files: {
'geojson-to-gmaps.min.js': ['geojson-to-gmaps.js']
}
}
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
// Default task(s).
grunt.registerTask('default', ['jasmine']);
};
|
Align centrally contact avatar in chat window. | /*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.customcontrols;
import java.awt.*;
import javax.swing.*;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.util.*;
/**
* A custom label, used to show contact images in a frame, where appropriate.
*
* @author Yana Stamcheva
*/
public class ContactPhotoLabel extends JLabel
{
private Image photoFrameImage
= ImageLoader.getImage(ImageLoader.USER_PHOTO_FRAME);
private ImageIcon labelIcon;
/**
* Creates a ContactPhotoLabel by specifying the width and the height of the
* label. These are used to paint the frame in the correct bounds.
*
* @param width the width of the label.
* @param height the height of the label.
*/
public ContactPhotoLabel(int width, int height)
{
this.labelIcon
= ImageUtils.scaleIconWithinBounds( photoFrameImage,
width,
height);
this.setAlignmentX(CENTER_ALIGNMENT);
this.setAlignmentY(CENTER_ALIGNMENT);
}
/**
* Overrides {@link JComponent#paintComponent(Graphics)}.
*/
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(labelIcon.getImage(), 0, 0, null);
}
}
| /*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.customcontrols;
import java.awt.*;
import javax.swing.*;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.util.*;
/**
* A custom label, used to show contact images in a frame, where appropriate.
*
* @author Yana Stamcheva
*/
public class ContactPhotoLabel extends JLabel
{
private Image photoFrameImage
= ImageLoader.getImage(ImageLoader.USER_PHOTO_FRAME);
private ImageIcon labelIcon;
/**
* Creates a ContactPhotoLabel by specifying the width and the height of the
* label. These are used to paint the frame in the correct bounds.
*
* @param width the width of the label.
* @param height the height of the label.
*/
public ContactPhotoLabel(int width, int height)
{
this.labelIcon
= ImageUtils.scaleIconWithinBounds( photoFrameImage,
width,
height);
}
/**
* Overrides {@link JComponent#paintComponent(Graphics)}.
*/
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(labelIcon.getImage(), 0, 0, null);
}
}
|
Fix typo in named group regex | from django.conf.urls import url
from .views import Dashboard
class Router(object):
def __init__(self):
self.registry = []
def register(self, widget, basename, **parameters):
""" Register a widget, URL basename and any optional URL parameters.
Parameters are passed as keyword arguments, i.e.
>>> router.register(MyWidget, 'mywidget', my_parameter="[A-Z0-9]+")
This would be the equivalent of manually adding the following to urlpatterns:
>>> url(r"^widgets/mywidget/(P<my_parameter>[A-Z0-9]+)/?", MyWidget.as_view(), "widget_mywidget")
"""
self.registry.append((widget, basename, parameters))
def get_urls(self):
urlpatterns = [
url(r'^$', Dashboard.as_view(), name='dashboard'),
]
for widget, basename, parameters in self.registry:
urlpatterns += [
url(r'/'.join((
r'^widgets/{}'.format(basename),
r'/'.join((r'(?P<{}>{})'.format(parameter, regex)
for parameter, regex in parameters.items())),
)),
widget.as_view(),
name='widget_{}'.format(basename)),
]
return urlpatterns
@property
def urls(self):
return self.get_urls()
router = Router()
| from django.conf.urls import url
from .views import Dashboard
class Router(object):
def __init__(self):
self.registry = []
def register(self, widget, basename, **parameters):
""" Register a widget, URL basename and any optional URL parameters.
Parameters are passed as keyword arguments, i.e.
>>> router.register(MyWidget, 'mywidget', my_parameter="[A-Z0-9]+")
This would be the equivalent of manually adding the following to urlpatterns:
>>> url(r"^widgets/mywidget/(P<my_parameter>[A-Z0-9]+)/?", MyWidget.as_view(), "widget_mywidget")
"""
self.registry.append((widget, basename, parameters))
def get_urls(self):
urlpatterns = [
url(r'^$', Dashboard.as_view(), name='dashboard'),
]
for widget, basename, parameters in self.registry:
urlpatterns += [
url(r'/'.join((
r'^widgets/{}'.format(basename),
r'/'.join((r'(P<{}>{})'.format(parameter, regex)
for parameter, regex in parameters.items())),
)),
widget.as_view(),
name='widget_{}'.format(basename)),
]
return urlpatterns
@property
def urls(self):
return self.get_urls()
router = Router()
|
Add possitive user login test | <?php
require_once('Autoload.php');
class SQLAuthTest extends PHPUnit_Framework_TestCase
{
public function testSQLAuthenticator()
{
$GLOBALS['FLIPSIDE_SETTINGS_LOC'] = './tests/travis/helpers';
if(!isset(FlipsideSettings::$dataset['auth']))
{
$params = array('dsn'=>'mysql:host=localhost;dbname=auth', 'host'=>'localhost', 'user'=>'root', 'pass'=>'');
FlipsideSettings::$dataset['auth'] = array('type'=>'SQLDataSet', 'params'=>$params);
}
$dataSet = \DataSetFactory::getDataSetByName('auth');
$dataSet->raw_query('CREATE TABLE tbluser (uid VARCHAR(255), pass VARCHAR(255));');
$params = array('current'=>true, 'pending'=>false, 'supplement'=>false, 'current_data_set'=>'auth');
$auth = new \Auth\SQLAuthenticator($params);
$this->assertFalse($auth->login('test', 'test'));
$dataSet->raw_query('INSERT INTO tbluser (\'test\', \'$2a$10$KSQ0GxWYv9nUS.TmNSLYnOo/33maFdXhgQ9qU.fLsMSNwtMnwl3FS\');');
$res = $auth->login('test', 'test');
$this->assertNotFalse($res);
}
}
/* vim: set tabstop=4 shiftwidth=4 expandtab: */
?>
| <?php
require_once('Autoload.php');
class SQLAuthTest extends PHPUnit_Framework_TestCase
{
public function testSQLAuthenticator()
{
$GLOBALS['FLIPSIDE_SETTINGS_LOC'] = './tests/travis/helpers';
if(!isset(FlipsideSettings::$dataset['auth']))
{
$params = array('dsn'=>'mysql:host=localhost;dbname=auth', 'host'=>'localhost', 'user'=>'root', 'pass'=>'');
FlipsideSettings::$dataset['auth'] = array('type'=>'SQLDataSet', 'params'=>$params);
}
$dataSet = \DataSetFactory::getDataSetByName('auth');
$dataSet->raw_query('CREATE TABLE tbluser (uid VARCHAR(255), pass VARCHAR(255));');
$params = array('current'=>true, 'pending'=>false, 'supplement'=>false, 'current_data_set'=>'auth');
$auth = new \Auth\SQLAuthenticator($params);
$this->assertFalse($auth->login('test', 'test'));
$dataSet->raw_query('INSERT INTO tbluser (\'test\', \'$2a$04$B5RseAQlJOuAwZzYtSeLY.sehGtBPTlkZUuh2sv9vCwXzAAI7ribO\');');
$res = $auth->login('test', 'test');
$this->assertNotFalse($res);
}
}
/* vim: set tabstop=4 shiftwidth=4 expandtab: */
?>
|
Fix home page.
When there are no game, it still show a random entry. | var express = require('express');
var router = express.Router();
var GameModel = require('../models/game');
var model = require('../models');
const _ = require('underscore');
/* GET home page. */
router.get('/', function(req, res, next) {
let gameParam = {
order: [
['id', 'desc']
],
include: [
{
model: model.Guide,
attributes: [
[model.sequelize.fn('COUNT', 'Guide.id'), 'Count']
]
}
],
limit: 5
};
let guideParam = {
order: [
['id', 'desc']
],
include: [
{
model: model.Game,
attributes: ['name', 'url']
},
{
model: model.User,
attributes: ['name']
}
],
limit: 5
};
Promise
.all([model.Game.findAll(gameParam), model.Guide.findAll(guideParam)])
.then(values => {
let [games, guides] = values;
games = games
.filter(game => game.id)
.map(g => {
return _.extend({
guideCount: g.Guides.length > 0 ? g.Guides[0].dataValues.Count : 0
}, g.dataValues);
});
res.render('home', {
games: games,
guides: guides
});
}).catch(err => next(err));
});
router.get('/tag/:tag', function(req, res, next) {
res.render('index', { title: 'tag' });
});
module.exports = router;
| var express = require('express');
var router = express.Router();
var GameModel = require('../models/game');
var model = require('../models');
const _ = require('underscore');
/* GET home page. */
router.get('/', function(req, res, next) {
let gameParam = {
order: [
['id', 'desc']
],
include: [
{
model: model.Guide,
attributes: [
[model.sequelize.fn('COUNT', 'Guide.id'), 'Count']
]
}
],
limit: 5
};
let guideParam = {
order: [
['id', 'desc']
],
include: [
{
model: model.Game,
attributes: ['name', 'url']
},
{
model: model.User,
attributes: ['name']
}
],
limit: 5
};
Promise
.all([model.Game.findAll(gameParam), model.Guide.findAll(guideParam)])
.then(values => {
let [games, guides] = values;
console.info(guides[0]);
games = games.map(g => {
return _.extend({
guideCount: g.Guides.length > 0 ? g.Guides[0].dataValues.Count : 0
}, g.dataValues);
});
res.render('home', {
games: games,
guides: guides
});
}).catch(err => next(err));
});
router.get('/tag/:tag', function(req, res, next) {
res.render('index', { title: 'tag' });
});
module.exports = router;
|
Fix texture style adapter float parsing | package org.yggard.brokkgui.style.adapter;
import org.yggard.brokkgui.paint.Texture;
public class TextureStyleAdapter implements IStyleAdapter<Texture>
{
@Override
public Texture decode(String style)
{
if (!style.startsWith("url("))
return null;
String[] splitted = style.replace("url(", "").replace(")", "").split(",");
switch (splitted.length)
{
case 1:
return new Texture(splitted[0].replace("\"", "").trim());
case 3:
return new Texture(splitted[0].replace("\"", "").trim(), Float.parseFloat(splitted[1].trim()),
Float.parseFloat(splitted[2].trim()));
case 5:
return new Texture(splitted[0].replace("\"", "").trim(), Float.parseFloat(splitted[1].trim()),
Float.parseFloat(splitted[2].trim()), Float.parseFloat(splitted[3].trim()),
Float.parseFloat(splitted[4].trim()));
default:
return null;
}
}
}
| package org.yggard.brokkgui.style.adapter;
import org.yggard.brokkgui.paint.Texture;
public class TextureStyleAdapter implements IStyleAdapter<Texture>
{
@Override
public Texture decode(String style)
{
if (!style.startsWith("url("))
return null;
String[] splitted = style.replace("url(", "").replace(")", "").split(",");
switch (splitted.length)
{
case 1:
return new Texture(splitted[0].replace("\"", "").trim());
case 3:
return new Texture(splitted[0].replace("\"", "").trim(), Integer.parseInt(splitted[1].trim()),
Integer.parseInt(splitted[2].trim()));
case 5:
return new Texture(splitted[0].replace("\"", "").trim(), Integer.parseInt(splitted[1].trim()),
Integer.parseInt(splitted[2].trim()), Integer.parseInt(splitted[3].trim()),
Integer.parseInt(splitted[4].trim()));
default:
return null;
}
}
}
|
Revert "Refresh all views when invoking move action"
This reverts commit 76b1802295a934f3bdf20d09fea7f705b2189425. | package com.yuyakaido.android.cardstackview.internal;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import com.yuyakaido.android.cardstackview.CardStackLayoutManager;
public class CardStackDataObserver extends RecyclerView.AdapterDataObserver {
private final RecyclerView recyclerView;
public CardStackDataObserver(RecyclerView recyclerView) {
this.recyclerView = recyclerView;
}
@Override
public void onChanged() {
CardStackLayoutManager manager = getCardStackLayoutManager();
manager.setTopPosition(0);
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount) {
// Do nothing
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount, @Nullable Object payload) {
// Do nothing
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
// Do nothing
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
CardStackLayoutManager manager = getCardStackLayoutManager();
if (positionStart == 0) {
manager.setTopPosition(0);
}
manager.removeAllViews();
}
@Override
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
// Do nothing
}
private CardStackLayoutManager getCardStackLayoutManager() {
RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
if (manager instanceof CardStackLayoutManager) {
return (CardStackLayoutManager) manager;
}
throw new IllegalStateException("CardStackView must be set CardStackLayoutManager.");
}
}
| package com.yuyakaido.android.cardstackview.internal;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import com.yuyakaido.android.cardstackview.CardStackLayoutManager;
public class CardStackDataObserver extends RecyclerView.AdapterDataObserver {
private final RecyclerView recyclerView;
public CardStackDataObserver(RecyclerView recyclerView) {
this.recyclerView = recyclerView;
}
@Override
public void onChanged() {
CardStackLayoutManager manager = getCardStackLayoutManager();
manager.setTopPosition(0);
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount) {
// Do nothing
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount, @Nullable Object payload) {
// Do nothing
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
// Do nothing
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
CardStackLayoutManager manager = getCardStackLayoutManager();
if (positionStart == 0) {
manager.setTopPosition(0);
}
manager.removeAllViews();
}
@Override
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
CardStackLayoutManager manager = getCardStackLayoutManager();
manager.removeAllViews();
}
private CardStackLayoutManager getCardStackLayoutManager() {
RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
if (manager instanceof CardStackLayoutManager) {
return (CardStackLayoutManager) manager;
}
throw new IllegalStateException("CardStackView must be set CardStackLayoutManager.");
}
}
|
fix: Move properties fetching before dict | """Notify Slack channel."""
import time
from ..utils import get_properties, get_template, post_slack_message
class SlackNotification:
"""Post slack notification.
Inform users about infrastructure changes to prod* accounts.
"""
def __init__(self, app=None, env=None, prop_path=None):
timestamp = time.strftime("%B %d, %Y %H:%M:%S %Z", time.gmtime())
self.settings = get_properties(prop_path)
short_commit_sha = self.settings['pipeline']['config_commit'][0:11]
self.info = {
'app': app,
'env': env,
'config_commit_short': short_commit_sha,
'timestamp': timestamp,
}
def post_message(self):
"""Send templated message to **#deployments-{env}**."""
message = get_template(
template_file='slack-templates/pipeline-prepare-ran.j2',
info=self.info)
channel = '#deployments-{}'.format(self.info['env'].lower())
post_slack_message(message, channel)
def notify_slack_channel(self):
"""Post message to a defined Slack channel."""
message = get_template(
template_file='slack-templates/pipeline-prepare-ran.j2',
info=self.info)
if self.settings['pipeline']['notifications']['slack']:
post_slack_message(
message, self.settings['pipeline']['notifications']['slack'])
| """Notify Slack channel."""
import time
from ..utils import get_properties, get_template, post_slack_message
class SlackNotification:
"""Post slack notification.
Inform users about infrastructure changes to prod* accounts.
"""
def __init__(self, app=None, env=None, prop_path=None):
timestamp = time.strftime("%B %d, %Y %H:%M:%S %Z", time.gmtime())
self.info = {'app': app,
'env': env,
'properties': prop_path,
'timestamp': timestamp}
self.settings = get_properties(self.info['properties'])
self.info['config_commit_short'] = self.settings['pipeline'][
'config_commit'][0:11]
def post_message(self):
"""Send templated message to **#deployments-{env}**."""
message = get_template(
template_file='slack-templates/pipeline-prepare-ran.j2',
info=self.info)
channel = '#deployments-{}'.format(self.info['env'].lower())
post_slack_message(message, channel)
def notify_slack_channel(self):
"""Post message to a defined Slack channel."""
message = get_template(
template_file='slack-templates/pipeline-prepare-ran.j2',
info=self.info)
if self.settings['pipeline']['notifications']['slack']:
post_slack_message(
message, self.settings['pipeline']['notifications']['slack'])
|
DOC: Change rtfd -> readthedocs in package description | from setuptools import setup
# "import" __version__
for line in open('nbsphinx.py'):
if line.startswith('__version__'):
exec(line)
break
setup(
name='nbsphinx',
version=__version__,
py_modules=['nbsphinx'],
install_requires=[
'docutils',
'jinja2',
'nbconvert',
'traitlets',
'nbformat',
'sphinx>=1.3.2,!=1.5.0',
],
author='Matthias Geier',
author_email='[email protected]',
description='Jupyter Notebook Tools for Sphinx',
long_description=open('README.rst').read(),
license='MIT',
keywords='Sphinx Jupyter notebook'.split(),
url='http://nbsphinx.readthedocs.io/',
platforms='any',
classifiers=[
'Framework :: Sphinx',
'Framework :: Sphinx :: Extension',
'Framework :: Jupyter',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Documentation :: Sphinx',
],
zip_safe=True,
)
| from setuptools import setup
# "import" __version__
for line in open('nbsphinx.py'):
if line.startswith('__version__'):
exec(line)
break
setup(
name='nbsphinx',
version=__version__,
py_modules=['nbsphinx'],
install_requires=[
'docutils',
'jinja2',
'nbconvert',
'traitlets',
'nbformat',
'sphinx>=1.3.2,!=1.5.0',
],
author='Matthias Geier',
author_email='[email protected]',
description='Jupyter Notebook Tools for Sphinx',
long_description=open('README.rst').read(),
license='MIT',
keywords='Sphinx Jupyter notebook'.split(),
url='http://nbsphinx.rtfd.io/',
platforms='any',
classifiers=[
'Framework :: Sphinx',
'Framework :: Sphinx :: Extension',
'Framework :: Jupyter',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Documentation :: Sphinx',
],
zip_safe=True,
)
|
Update to handle in-memory filelike objects | #!/usr/bin/env python
from setuptools import setup
setup(name='imagesize',
version='1.2.0',
description='Getting image size from png/jpeg/jpeg2000/gif file',
long_description='''
It parses image files' header and return image size.
* PNG
* JPEG
* JPEG2000
* GIF
* TIFF (experimental)
* SVG
This is a pure Python library.
''',
author='Yoshiki Shibukawa',
author_email='[email protected]',
url='https://github.com/shibukawa/imagesize_py',
license="MIT",
py_modules=['imagesize'],
test_suite='test',
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
install_requires=['requests',],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Multimedia :: Graphics'
]
)
| #!/usr/bin/env python
from setuptools import setup
setup(name='imagesize',
version='1.2.0',
description='Getting image size from png/jpeg/jpeg2000/gif file',
long_description='''
It parses image files' header and return image size.
* PNG
* JPEG
* JPEG2000
* GIF
* TIFF (experimental)
* SVG
This is a pure Python library.
''',
author='Yoshiki Shibukawa',
author_email='[email protected]',
url='https://github.com/shibukawa/imagesize_py',
license="MIT",
py_modules=['imagesize'],
test_suite='test',
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Multimedia :: Graphics'
]
)
|
Modify sms format in sms receiving event
Sms regex format is changed to support all institutes names. | package in.testpress.testpress.events;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import in.testpress.testpress.authenticator.CodeVerificationActivity.Timer;
public class SmsReceivingEvent extends BroadcastReceiver {
public String code;
private Timer timer;
public SmsReceivingEvent(Timer timer) {
this.timer = timer;
}
@Override
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[0]);
String senderNum = currentMessage.getDisplayOriginatingAddress();
if (senderNum.matches(".*TSTPRS")) { //check whether TSTPRS present in senderAddress
String smsContent = currentMessage.getDisplayMessageBody();
//get the code from smsContent
code = smsContent.replaceAll(".*(?=.*)(?<=Your authorization code is )([^\n]*)(?=.).*", "$1");
timer.cancel();
timer.onFinish();
}
} // bundle is null
} catch (Exception e) {
timer.cancel();
timer.onFinish();
}
}
}
| package in.testpress.testpress.events;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import in.testpress.testpress.R;
import in.testpress.testpress.authenticator.CodeVerificationActivity.Timer;
import in.testpress.testpress.core.Constants;
public class SmsReceivingEvent extends BroadcastReceiver {
public String code;
private Timer timer;
public SmsReceivingEvent(Timer timer) {
this.timer = timer;
}
@Override
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[0]);
String senderNum = currentMessage.getDisplayOriginatingAddress();
if (senderNum.matches(".*TSTPRS")) { //check whether TSTPRS present in senderAddress
String smsContent = currentMessage.getDisplayMessageBody();
//get the code from smsContent
code = smsContent.replaceAll(".*(?<=Thank you for registering at +"+Constants.Http.URL_BASE +"+. Your authorization code is )([^\n]*)(?=.).*", "$1");
timer.cancel();
timer.onFinish();
}
} // bundle is null
} catch (Exception e) {
timer.cancel();
timer.onFinish();
}
}
}
|
Enable markdown on message history | import React from 'react';
import { FormattedRelative } from 'react-intl';
import Body from '../Post/Body';
import Avatar from '../widgets/Avatar';
function Message(props) {
const { model } = props;
const sentAt = model[0].sentAt;
const senderUsername = (model[0].senderUsername || model[0].sentBy);
return (
<li className="Message message">
<div className="container">
<div data-uuid={model[0].uuid}>
<div className="Message__left">
<Avatar sm username={senderUsername} />
</div>
<div className="ml-5">
<div className="media-heading">
<b>{senderUsername}</b>
{' '}
<span className="text-info">
<FormattedRelative value={sentAt} />
</span>
</div>
<p>{model[0].text}</p>
</div>
</div>
</div>
{
model.slice(1).map(({ uuid, text }, i) => (
<div className="container" key={i} data-uuid={uuid}>
<div className="ml-5">
<Body body={text} />
</div>
</div>
))
}
</li>
);
}
export default Message;
| import React from 'react';
import { FormattedRelative } from 'react-intl';
import Avatar from '../widgets/Avatar';
function Message(props) {
const { model } = props;
const sentAt = model[0].sentAt;
const senderUsername = (model[0].senderUsername || model[0].sentBy);
return (
<li className="Message message">
<div className="container">
<div data-uuid={model[0].uuid}>
<div className="Message__left">
<Avatar sm username={senderUsername} />
</div>
<div className="ml-5">
<div className="media-heading">
<b>{senderUsername}</b>
{' '}
<span className="text-info">
<FormattedRelative value={sentAt} />
</span>
</div>
<p>{model[0].text}</p>
</div>
</div>
</div>
{
model.slice(1).map(({ uuid, text }, i) => (
<div className="container" key={i} data-uuid={uuid}>
<div className="ml-5">
<p>{text}</p>
</div>
</div>
))
}
</li>
);
}
export default Message;
|
Add doc link to local footer | <div class="wdn-grid-set wdn-footer-links-local">
<div class="bp960-wdn-col-two-thirds">
<div class="wdn-footer-module">
<span role="heading" class="wdn-footer-heading">About UNL Events</span>
<?php
if ($file = @file_get_contents(\UNL\UCBCN\Util::getWWWRoot() . '/tmp/iim-app-footer.html')) {
echo $file;
} else {
echo file_get_contents('http://iim.unl.edu/iim-app-footer?format=partial');
}
?>
</div>
</div>
<div class="bp960-wdn-col-one-third">
<div class="wdn-footer-module">
<span role="heading" class="wdn-footer-heading">Related Links</span>
<ul class="wdn-related-links-v1">
<li><a href="http://wdn.unl.edu/documentation/unl-events">UNL Events Documentation</a></li>
<li><a href="http://wdn.unl.edu/">Web Developer Network</a></li>
<li><a href="http://iim.unl.edu/">Internet and Interactive Media</a></li>
<li><a href="http://ucomm.unl.edu/">University Communications</a></li>
<li><a href="http://its.unl.edu/">Information Technology Services</a></li>
</ul>
</div>
</div>
</div> | <div class="wdn-grid-set wdn-footer-links-local">
<div class="bp960-wdn-col-two-thirds">
<div class="wdn-footer-module">
<span role="heading" class="wdn-footer-heading">About UNL Events</span>
<?php
if ($file = @file_get_contents(\UNL\UCBCN\Util::getWWWRoot() . '/tmp/iim-app-footer.html')) {
echo $file;
} else {
echo file_get_contents('http://iim.unl.edu/iim-app-footer?format=partial');
}
?>
</div>
</div>
<div class="bp960-wdn-col-one-third">
<div class="wdn-footer-module">
<span role="heading" class="wdn-footer-heading">Related Links</span>
<ul class="wdn-related-links-v1">
<li><a href="http://wdn.unl.edu/">Web Developer Network</a></li>
<li><a href="http://iim.unl.edu/">Internet and Interactive Media</a></li>
<li><a href="http://ucomm.unl.edu/">University Communications</a></li>
<li><a href="http://its.unl.edu/">Information Technology Services</a></li>
</ul>
</div>
</div>
</div> |
Remove click dependent import from the main module.
This leads to import error when textX is installed without CLI support. | # flake8: noqa
from textx.metamodel import metamodel_from_file, metamodel_from_str
from textx.model import get_children_of_type, get_parent_of_type, \
get_model, get_metamodel, get_children, get_location, textx_isinstance
from textx.exceptions import TextXError, TextXSyntaxError, \
TextXSemanticError, TextXRegistrationError
from textx.registration import (LanguageDesc, GeneratorDesc,
register_language, register_generator,
language_descriptions, language_description,
generator_descriptions, generator_description,
clear_language_registrations,
clear_generator_registrations,
languages_for_file,
language_for_file,
metamodel_for_language,
metamodel_for_file,
metamodels_for_file,
generator_for_language_target,
generator, language)
__version__ = "2.3.0.dev0"
| # flake8: noqa
from textx.metamodel import metamodel_from_file, metamodel_from_str
from textx.model import get_children_of_type, get_parent_of_type, \
get_model, get_metamodel, get_children, get_location, textx_isinstance
from textx.exceptions import TextXError, TextXSyntaxError, \
TextXSemanticError, TextXRegistrationError
from textx.generators import get_output_filename, gen_file
from textx.registration import (LanguageDesc, GeneratorDesc,
register_language, register_generator,
language_descriptions, language_description,
generator_descriptions, generator_description,
clear_language_registrations,
clear_generator_registrations,
languages_for_file,
language_for_file,
metamodel_for_language,
metamodel_for_file,
metamodels_for_file,
generator_for_language_target,
generator, language)
__version__ = "2.3.0.dev0"
|
Upgrade deps to latest point releases
- nose 1.3.0 to 1.3.1
- Sphinx 1.2.1 to 1.2.2 | from setuptools import setup
setup(
name='tangled',
version='0.1a7.dev0',
description='Tangled namespace and utilities',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled/tags',
author='Wyatt Baldwin',
author_email='[email protected]',
packages=[
'tangled',
'tangled.scripts',
'tangled.tests',
'tangled.tests.dummy_package',
],
extras_require={
'dev': (
'coverage>=3.7.1',
'nose>=1.3.1',
'pep8>=1.4.6',
'pyflakes>=0.7.3',
'Sphinx>=1.2.2',
'sphinx_rtd_theme>=0.1.5',
)
},
entry_points="""
[console_scripts]
tangled = tangled.__main__:main
[tangled.scripts]
release = tangled.scripts:ReleaseCommand
scaffold = tangled.scripts:ScaffoldCommand
python = tangled.scripts:ShellCommand
test = tangled.scripts:TestCommand
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| from setuptools import setup
setup(
name='tangled',
version='0.1a7.dev0',
description='Tangled namespace and utilities',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled/tags',
author='Wyatt Baldwin',
author_email='[email protected]',
packages=[
'tangled',
'tangled.scripts',
'tangled.tests',
'tangled.tests.dummy_package',
],
extras_require={
'dev': (
'coverage>=3.7.1',
'nose>=1.3.0',
'pep8>=1.4.6',
'pyflakes>=0.7.3',
'Sphinx>=1.2.1',
'sphinx_rtd_theme>=0.1.5',
)
},
entry_points="""
[console_scripts]
tangled = tangled.__main__:main
[tangled.scripts]
release = tangled.scripts:ReleaseCommand
scaffold = tangled.scripts:ScaffoldCommand
python = tangled.scripts:ShellCommand
test = tangled.scripts:TestCommand
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Bump the number for a minor release to fix the mysql migrations issue. | VERSION = (1, 0, 'alpha', 15)
def get_version(join=' ', short=False):
"""
Return the version of this package as a string.
The version number is built from a ``VERSION`` tuple, which should consist
of integers, or trailing version information (such as 'alpha', 'beta' or
'final'). For example:
>>> VERSION = (2, 0, 6)
>>> get_version()
'2.0.6'
>>> VERSION = (1, 0, 'beta', 2)
>>> get_version()
'1.0 beta 2'
Use the ``join`` argument to join the version elements by an alternate
character to the default ``' '``. This is useful when building a distutils
setup module::
from this_package import get_version
setup(
version=get_version(join='-'),
# ...
)
Use the ``short`` argument to get the version number without trailing
version information.
"""
version = []
number = []
remainder = []
for i, bit in enumerate(VERSION):
if isinstance(bit, int):
number.append(str(bit))
else:
remainder = [str(bit) for bit in VERSION[i:]]
break
if number:
version.append('.'.join(number))
if not short:
if remainder == ['alpha', 0]:
version.append('pre-alpha')
elif 'final' not in remainder:
version.extend(remainder)
return join.join(version)
| VERSION = (1, 0, 'alpha', 14)
def get_version(join=' ', short=False):
"""
Return the version of this package as a string.
The version number is built from a ``VERSION`` tuple, which should consist
of integers, or trailing version information (such as 'alpha', 'beta' or
'final'). For example:
>>> VERSION = (2, 0, 6)
>>> get_version()
'2.0.6'
>>> VERSION = (1, 0, 'beta', 2)
>>> get_version()
'1.0 beta 2'
Use the ``join`` argument to join the version elements by an alternate
character to the default ``' '``. This is useful when building a distutils
setup module::
from this_package import get_version
setup(
version=get_version(join='-'),
# ...
)
Use the ``short`` argument to get the version number without trailing
version information.
"""
version = []
number = []
remainder = []
for i, bit in enumerate(VERSION):
if isinstance(bit, int):
number.append(str(bit))
else:
remainder = [str(bit) for bit in VERSION[i:]]
break
if number:
version.append('.'.join(number))
if not short:
if remainder == ['alpha', 0]:
version.append('pre-alpha')
elif 'final' not in remainder:
version.extend(remainder)
return join.join(version)
|
Use get_db_prep_value instead of get_db_prep_save. Closes gh-42 | from django.core.exceptions import ValidationError
from django.db import models
from django.utils import simplejson
class JSONField(models.TextField):
"""Simple JSON field that stores python structures as JSON strings
on database.
"""
__metaclass__ = models.SubfieldBase
def to_python(self, value):
"""
Convert the input JSON value into python structures, raises
django.core.exceptions.ValidationError if the data can't be converted.
"""
if self.blank and not value:
return None
if isinstance(value, basestring):
try:
return simplejson.loads(value)
except Exception, e:
raise ValidationError(str(e))
else:
return value
def validate(self, value, model_instance):
"""Check value is a valid JSON string, raise ValidationError on
error."""
super(JSONField, self).validate(value, model_instance)
try:
return simplejson.loads(value)
except Exception, e:
raise ValidationError(str(e))
def get_db_prep_value(self, value, connection, prepared=False):
"""Convert value to JSON string before save"""
try:
return simplejson.dumps(value)
except Exception, e:
raise ValidationError(str(e))
| from django.core.exceptions import ValidationError
from django.db import models
from django.utils import simplejson
class JSONField(models.TextField):
"""Simple JSON field that stores python structures as JSON strings
on database.
"""
__metaclass__ = models.SubfieldBase
def to_python(self, value):
"""
Convert the input JSON value into python structures, raises
django.core.exceptions.ValidationError if the data can't be converted.
"""
if self.blank and not value:
return None
if isinstance(value, basestring):
try:
return simplejson.loads(value)
except Exception, e:
raise ValidationError(str(e))
else:
return value
def validate(self, value, model_instance):
"""Check value is a valid JSON string, raise ValidationError on
error."""
super(JSONField, self).validate(value, model_instance)
try:
return simplejson.loads(value)
except Exception, e:
raise ValidationError(str(e))
def get_db_prep_save(self, value):
"""Convert value to JSON string before save"""
try:
value = simplejson.dumps(value)
except Exception, e:
raise ValidationError(str(e))
return super(JSONField, self).get_db_prep_save(value)
|
Add cancel call to call buffer | from constants import *
import collections
import uuid
class CallBuffer():
def __init__(self):
self.waiter = None
self.queue = collections.deque(maxlen=CALL_QUEUE_MAX)
self.call_waiters = {}
def wait_for_calls(self, callback):
self.stop_waiter()
calls = []
while True:
try:
calls.append(self.queue.popleft())
except IndexError:
break
if calls:
callback(calls)
return
self.waiter = callback
def cancel_waiter(self):
self.waiter = None
def stop_waiter(self):
if self.waiter:
self.waiter(None)
self.waiter = None
def return_call(self, call_id, response):
callback = self.call_waiters.pop(call_id, None)
if callback:
callback(response)
def create_call(self, command, args, callback=None):
call_id = uuid.uuid4().hex
call = {
'id': call_id,
'command': command,
'args': args,
}
if callback:
self.call_waiters[call_id] = callback
if self.waiter:
self.waiter([call])
self.waiter = None
else:
self.queue.append(call)
return call_id
def cancel_call(self, call_id):
self.call_waiters.pop(call_id, None)
| from constants import *
import collections
import uuid
class CallBuffer():
def __init__(self):
self.waiter = None
self.queue = collections.deque(maxlen=CALL_QUEUE_MAX)
self.call_waiters = {}
def wait_for_calls(self, callback):
self.stop_waiter()
calls = []
while True:
try:
calls.append(self.queue.popleft())
except IndexError:
break
if calls:
callback(calls)
return
self.waiter = callback
def cancel_waiter(self):
self.waiter = None
def stop_waiter(self):
if self.waiter:
self.waiter(None)
self.waiter = None
def return_call(self, id, response):
callback = self.call_waiters.pop(id, None)
if callback:
callback(response)
def create_call(self, command, args, callback=None):
call_id = uuid.uuid4().hex
call = {
'id': call_id,
'command': command,
'args': args,
}
if callback:
self.call_waiters[call_id] = callback
if self.waiter:
self.waiter([call])
self.waiter = None
else:
self.queue.append(call)
|
feat: Add service that returns monthly limit | import Ember from 'ember';
export default Ember.Service.extend({
store: Ember.inject.service(),
currencies: ['AUD', 'CAD', 'CHF', 'EUR', 'GBP', 'JPY', 'NZD', 'RUB', 'USD'],
currencySymbol () {
return this.get('store').findRecord('setting', 'st-setting')
.then(response => response.get('currencySymbol'))
.catch(err => {
if (typeof err === 'undefined') {
return '$';
}
});
},
currentCurrencyName () {
return this.get('store').findRecord('setting', 'st-setting')
.then(response => response.get('currencyName'))
.catch(err => {
if (typeof err === 'undefined') {
return 'USD';
}
});
},
currencyNames (value) {
return this.get('store').findRecord('setting', 'st-setting')
.then(response => {
if (value === 'all') {
return this.get('currencies');
}
return this.get('currencies').filter(item => item !== response.get('currencyName'));
})
.catch(err => {
if (typeof err === 'undefined') {
if (value === 'all') {
return this.get('currencies');
}
return this.get('currencies').filter(item => item !== 'USD');
}
});
},
monthlyExpensesLimit () {
return this.get('store').findRecord('setting', 'st-setting')
.then(response => response.get('monthlyLimit'))
.catch(err => {
if (typeof err === 'undefined') {
return 1000;
}
});
}
});
| import Ember from 'ember';
export default Ember.Service.extend({
store: Ember.inject.service(),
currencies: ['AUD', 'CAD', 'CHF', 'EUR', 'GBP', 'JPY', 'NZD', 'RUB', 'USD'],
currencySymbol () {
return this.get('store').findRecord('setting', 'st-setting')
.then(response => response.get('currencySymbol'))
.catch(err => {
if (typeof err === 'undefined') {
return '$';
}
});
},
currentCurrencyName () {
return this.get('store').findRecord('setting', 'st-setting')
.then(response => response.get('currencyName'))
.catch(err => {
if (typeof err === 'undefined') {
return 'USD';
}
});
},
currencyNames (value) {
return this.get('store').findRecord('setting', 'st-setting')
.then(response => {
if (value === 'all') {
return this.get('currencies');
}
return this.get('currencies').filter(item => item !== response.get('currencyName'));
})
.catch(err => {
if (typeof err === 'undefined') {
if (value === 'all') {
return this.get('currencies');
}
return this.get('currencies').filter(item => item !== 'USD');
}
});
}
});
|
Use zip from future_builtins for Python 2 and 3 compatibility | """Utils for django-sekh"""
from future_builtins import zip
import re
def remove_duplicates(items):
"""
Remove duplicates elements in a list preserving the order.
"""
seen = {}
result = []
for item in items:
item = item.strip()
if not item or item in seen:
continue
seen[item] = True
result.append(item)
return result
def compile_terms(terms):
"""
Compile terms as regular expression,
for better matching.
"""
return [re.compile(re.escape(term), re.I | re.U)
for term in terms]
def list_range(x):
"""
Returns the range of a list.
"""
return max(x) - min(x)
def get_window(positions, indices):
"""
Given a list of lists and an index for each of those lists,
this returns a list of all of the corresponding values for those
lists and their respective index.
"""
return [word_positions[index] for
word_positions, index in
zip(positions, indices)]
def get_min_index(positions, window):
"""
Given a list of lists representing term positions in a corpus,
this returns the index of the min term, or nothing if None left.
"""
for min_index in [window.index(i) for i in sorted(window)]:
if window[min_index] < positions[min_index][-1]:
return min_index
return None
| """Utils for django-sekh"""
import re
from itertools import izip
def remove_duplicates(items):
"""
Remove duplicates elements in a list preserving the order.
"""
seen = {}
result = []
for item in items:
item = item.strip()
if not item or item in seen:
continue
seen[item] = True
result.append(item)
return result
def compile_terms(terms):
"""
Compile terms as regular expression,
for better matching.
"""
return [re.compile(re.escape(term), re.I | re.U)
for term in terms]
def list_range(x):
"""
Returns the range of a list.
"""
return max(x) - min(x)
def get_window(positions, indices):
"""
Given a list of lists and an index for each of those lists,
this returns a list of all of the corresponding values for those
lists and their respective index.
"""
return [word_positions[index] for
word_positions, index in
izip(positions, indices)]
def get_min_index(positions, window):
"""
Given a list of lists representing term positions in a corpus,
this returns the index of the min term, or nothing if None left.
"""
for min_index in [window.index(i) for i in sorted(window)]:
if window[min_index] < positions[min_index][-1]:
return min_index
return None
|
Add path to theme attributes | <?php namespace Pingpong\Themes;
use Illuminate\Filesystem\Filesystem;
use Pingpong\Modules\Json;
use Symfony\Component\Finder\Finder as SymfonyFinder;
class Finder {
/**
* The symfony finder instance.
*
* @var SymfonyFinder
*/
protected $finder;
/**
* The constructor.
*
* @param $finder SymfonyFinder
*/
public function __construct(SymfonyFinder $finder = null)
{
$this->finder = $finder ?: new SymfonyFinder;
}
/**
* Find the specified theme by searching a 'theme.json' file as identifier.
*
* @param string $path
* @param string $filename
* @return array
*/
public function find($path, $filename = 'theme.json')
{
$themes = [];
if(is_dir($path))
{
$found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks();
foreach ($found as $file) $themes[] = new Theme($this->getInfo($file));
}
return $themes;
}
/**
* Get theme info from json file.
*
* @param SplFileInfo $file
* @return array
*/
protected function getInfo($file)
{
$attributes = Json::make($path = $file->getRealPath())->toArray();
$attributes['path'] = dirname($path);
return $attributes;
}
} | <?php namespace Pingpong\Themes;
use Illuminate\Filesystem\Filesystem;
use Pingpong\Modules\Json;
use Symfony\Component\Finder\Finder as SymfonyFinder;
class Finder {
/**
* The symfony finder instance.
*
* @var SymfonyFinder
*/
protected $finder;
/**
* The constructor.
*
* @param $finder SymfonyFinder
*/
public function __construct(SymfonyFinder $finder = null)
{
$this->finder = $finder ?: new SymfonyFinder;
}
/**
* Find the specified theme by searching a 'theme.json' file as identifier.
*
* @param string $path
* @param string $filename
* @return array
*/
public function find($path, $filename = 'theme.json')
{
$themes = [];
if(is_dir($path))
{
$found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks();
foreach ($found as $file) $themes[] = new Theme($this->getInfo($file));
}
return $themes;
}
/**
* Get theme info from json file.
*
* @param SplFileInfo $file
* @return array
*/
protected function getInfo($file)
{
return Json::make($file->getRealPath())->toArray();
}
} |
Add sanitation of provided name, formatting. | module.exports = function (grunt) {
/*
Create template pages and their associated assets
Run from the command line as follows: grunt create --name=$var
*/
var name = grunt.option('name') || null;
grunt.registerTask('create', function () {
var title = name,
filename = name.toUpperCase().split(' ').join('_'),
pagesDirectory = 'app/templates/pages/',
cssDirectory = 'app/assets/styles/pages/',
imagesDirectory = 'app/assets/img/',
javascriptDirectory = 'app/assets/scripts/',
modulePattern = 'var ' + name + ' = (function () {\n\tfunction init () {\n\t}\n\treturn {\n\t\tinit: init\n\t}\n}());\n\n$(function () {\n\t' + name + '.init();\n});',
templateContent = '---\ntitle: ' + title + '\ncssname: ' + filename + '\njsname: ' + filename + '\n---';
// Cursory check that the file doesn't exist
if (grunt.file.exists(pagesDirectory + filename + '.hbs')) {
grunt.fail.warn('Sorry, that page already exists', 1);
}
// Make img directory
grunt.file.mkdir(imagesDirectory + filename);
// create css
grunt.file.write(cssDirectory + filename + '.scss', '#' + filename + ' {\n\n}');
// create js module
grunt.file.write(javascriptDirectory + filename + '.js', modulePattern);
// create page template
grunt.file.write(pagesDirectory + filename + '.hbs', templateContent);
});
}; | module.exports = function (grunt) {
/*
Create template pages and their associated assets
Run from the command line as follows: grunt create --name=$var
*/
var name = grunt.option('name') || null;
grunt.registerTask('create', function() {
var assetsDirectory = 'app/assets/',
pagesDirectory = 'app/templates/pages/',
cssDirectory = 'app/assets/styles/',
imagesDirectory = 'app/assets/img/',
javascriptDirectory = 'app/assets/scripts/',
modulePattern = 'var '+name+' = (function () {\n\tfunction init () {\n\t}\n\treturn {\n\t\tinit: init\n\t}\n}());\n\n$(function () {\n\t'+name+'.init();\n});',
templateContent = '---\ntitle: '+name+'\ncssname: ' + name + '\njsname: ' + name + '\n---';
// Cursory check that the file doesn't exist
if(grunt.file.exists(pagesDirectory+name+'.hbs')) {
grunt.fail.warn('Sorry, that page already exists' ,1);
}
// Make img directory
grunt.file.mkdir(imagesDirectory+name);
// create css
grunt.file.write(cssDirectory+name+'.scss', '#'+name+' {\n\n}');
// create js module
grunt.file.write(javascriptDirectory+name+'.js', modulePattern)
// create page template
grunt.file.write(pagesDirectory+name+'.hbs', templateContent);
});
}; |
Add ship movement to the left in game loop | /**
* game-loop.js
*
* Manages the creation and properties for our game loop object
*/
/**
* Main game loop factory
*
* @returns {object}
*/
var createGameLoop = function() {
var fps = 2;
var lastCycleKeypress = '';
var update = function() {
if (typeof(game.keypress.keyCode) === 'undefined') {
return;
}
console.log(game.keypress);
switch (game.keypress.keyCode) {
case LOWER_CASE_Q_KEY_CODE:
this.end();
break;
case LOWER_CASE_A_KEY_CODE:
ship.updateXPosLeft();
break;
case LOWER_CASE_D_KEY_CODE:
ship.updateXPosRight();
break;
}
lastCycleKeypress = game.keypress.keyCode;
};
var draw = function() {
var svgSpec = 'http://www.w3.org/2000/svg';
var shipEl = document.getElementById('ship');
shipEl.setAttribute('x', ship.xPos);
};
var run = function() {
update();
draw();
};
var end = function() {
clearInterval(gameLoop._intervalId);
};
return {
fps: fps,
lastCycleKeypress: lastCycleKeypress,
update: update,
draw: draw,
end: end,
run: run
};
};
// Create game loop
game.loop = createGameLoop(); | /**
* game-loop.js
*
* Manages the creation and properties for our game loop object
*/
/**
* Main game loop factory
*
* @returns {object}
*/
var createGameLoop = function() {
var fps = 2;
var lastCycleKeypress = '';
var update = function() {
if (typeof(game.keypress.keyCode) === 'undefined') {
return;
}
console.log(game.keypress);
switch (game.keypress.keyCode) {
case LOWER_CASE_Q_KEY_CODE:
this.end();
break;
case LOWER_CASE_D_KEY_CODE:
ship.updateXPosRight();
break;
}
lastCycleKeypress = game.keypress.keyCode;
};
var draw = function() {
var svgSpec = 'http://www.w3.org/2000/svg';
var shipEl = document.getElementById('ship');
shipEl.setAttribute('x', ship.xPos);
};
var run = function() {
update();
draw();
};
var end = function() {
clearInterval(gameLoop._intervalId);
};
return {
fps: fps,
lastCycleKeypress: lastCycleKeypress,
update: update,
draw: draw,
end: end,
run: run
};
};
// Create game loop
game.loop = createGameLoop(); |
Fix para modelo de posicioanmento autal | angular.module('sislegisapp').factory('ReuniaoResource',
function($resource, BACKEND) {
return $resource(BACKEND + '/reuniaos/:ReuniaoId', {
ReuniaoId : '@id'
}, {
'queryAll' : {
method : 'GET',
isArray : true
},
'query' : {
method : 'GET',
isArray : false
},
'buscarReuniaoPorData' : {
url : BACKEND + "/reuniaos/findByData",
method : 'GET',
isArray : true,
transformResponse: function(data){
var jsonParse = JSON.parse(data);
jsonParse.forEach(function(item, index){
if(item.posicionamentoPreliminar==true){
jsonParse[index].posicionamentoAtual.nome = 'Previamente ' + item.posicionamentoAtual.posicionamento.nome;
}
});
return jsonParse;
}
},
'update' : {
method : 'PUT'
}
});
});
| angular.module('sislegisapp').factory('ReuniaoResource',
function($resource, BACKEND) {
return $resource(BACKEND + '/reuniaos/:ReuniaoId', {
ReuniaoId : '@id'
}, {
'queryAll' : {
method : 'GET',
isArray : true
},
'query' : {
method : 'GET',
isArray : false
},
'buscarReuniaoPorData' : {
url : BACKEND + "/reuniaos/findByData",
method : 'GET',
isArray : true,
transformResponse: function(data){
var jsonParse = JSON.parse(data);
jsonParse.forEach(function(item, index){
if(item.posicionamentoPreliminar==true){
jsonParse[index].posicionamento.nome = 'Previamente ' + item.posicionamentoAtual.posicionamento.nome;
}
});
return jsonParse;
}
},
'update' : {
method : 'PUT'
}
});
});
|
Fix imports in plugin manager test to work with nosetests | import socket
import time
from threading import Event
from unittest import TestCase
from honeypot.PluginManager import PluginManager
class TestPluginManager(TestCase):
def test_stop(self):
"""Test connecting to plugin's port, stopping PluginManager."""
class Plugin:
"""Mock plugin, uses random available port."""
def __init__(self):
sock = socket.socket()
sock.bind(('', 0)) # bind to any available port
self._port = sock.getsockname()[1]
sock.close()
self.run_called = Event()
def get_port(self):
return self._port
def run(self, sock, address, session):
self.run_called.set()
plugin = Plugin()
plugin_manager = PluginManager(plugin, lambda: None)
plugin_manager.start()
time.sleep(0.01)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', plugin.get_port()))
sock.close()
time.sleep(0.01)
self.assertTrue(plugin.run_called.is_set())
plugin_manager.stop()
plugin_manager.join()
self.assertFalse(plugin_manager.is_alive())
| import socket
import time
from threading import Event
from unittest import TestCase
from PluginManager import PluginManager
class TestPluginManager(TestCase):
def test_stop(self):
"""Test connecting to plugin's port, stopping PluginManager."""
class Plugin:
"""Mock plugin, uses random available port."""
def __init__(self):
sock = socket.socket()
sock.bind(('', 0)) # bind to any available port
self._port = sock.getsockname()[1]
sock.close()
self.run_called = Event()
def get_port(self):
return self._port
def run(self, sock, address, session):
self.run_called.set()
plugin = Plugin()
plugin_manager = PluginManager(plugin, lambda: None)
plugin_manager.start()
time.sleep(0.01)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', plugin.get_port()))
sock.close()
time.sleep(0.01)
self.assertTrue(plugin.run_called.is_set())
plugin_manager.stop()
plugin_manager.join()
self.assertFalse(plugin_manager.is_alive())
|
Add comment and reformat code | from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class MockRequest(object):
pass
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def setUp(self):
self.site = AdminSite()
self.query_set = User.objects.all()
def test_method_is_avaible(self):
""" Test UserAdmin class has method export_email """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
""" Test method is an custom action for user admin """
self.assertTrue('export_email' in UserAdmin.actions)
def test_action_has_a_short_description(self):
""" Test method has a short description """
self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
def test_action_return_http_response(self):
""" Test method return an HttpResponse """
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(),
queryset=self.query_set)
self.assertIsInstance(response, HttpResponse)
def test_action_return_csv(self):
""" Test method return text/csv as http response content type """
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(),
queryset=self.query_set)
self.assertEqual(response.get('Content-Type'), 'text/csv')
| from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class MockRequest(object):
pass
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def setUp(self):
self.site = AdminSite()
self.query_set = User.objects.all()
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
""" Test method is an custom action for user admin """
self.assertTrue('export_email' in UserAdmin.actions)
def test_action_has_a_short_description(self):
""" Test method has a short description """
self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
def test_action_return_http_response(self):
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(), queryset=self.query_set)
self.assertIsInstance(response, HttpResponse)
def test_action_return_csv(self):
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(), queryset=self.query_set)
self.assertEqual(response.get('Content-Type'), 'text/csv')
|
Add webpack hot reload patch | const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
module.exports = {
entry: [
process.env.NODE_ENV !== 'production' && 'react-hot-loader/patch',
'./client/src/index.js',
],
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js',
},
resolve: {
modules: [
path.resolve('./client/src'),
'node_modules',
],
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
},
],
},
{
test: /\.(eot|svg|ttf|woff|woff2)(\?[a-z0-9=&.]+)?$/,
use: [
{
loader: 'url-loader',
options: {
limit: 10000,
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: 'client/index.html',
}),
new FaviconsWebpackPlugin('./client/favicon.png'),
new webpack.EnvironmentPlugin({
SDF_SENTRY_DSN_BACKEND: '',
SDF_SENTRY_DSN_FRONTEND: '',
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: module => (
module.context && module.context.indexOf('node_modules') !== -1
),
}),
],
};
| const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
module.exports = {
entry: ['./client/src/index.js'],
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js',
},
resolve: {
modules: [
path.resolve('./client/src'),
'node_modules',
],
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
},
],
},
{
test: /\.(eot|svg|ttf|woff|woff2)(\?[a-z0-9=&.]+)?$/,
use: [
{
loader: 'url-loader',
options: {
limit: 10000,
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: 'client/index.html',
}),
new FaviconsWebpackPlugin('./client/favicon.png'),
new webpack.EnvironmentPlugin({
SDF_SENTRY_DSN_BACKEND: '',
SDF_SENTRY_DSN_FRONTEND: '',
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: module => (
module.context && module.context.indexOf('node_modules') !== -1
),
}),
],
};
|
Make getting mailbox case insensitive | <?php
namespace Ddeboer\Imap;
/**
* A connection to an IMAP server that is authenticated for a user
*/
class Connection
{
protected $server;
protected $resource;
protected $mailboxes;
public function __construct($resource, $server)
{
if (!is_resource($resource)) {
throw new \InvalidArgumentException('$resource must be a resource');
}
$this->resource = $resource;
$this->server = $server;
}
/**
* Get a list of mailboxes
*
* @return array
*/
public function getMailboxes()
{
if (null === $this->mailboxes) {
$mailboxes = \imap_getmailboxes($this->resource, $this->server, '*');
foreach ($mailboxes as $mailbox) {
$this->mailboxes[] = str_replace($this->server, '', $mailbox->name);
}
}
return $this->mailboxes;
}
public function getMailbox($name)
{
foreach ($this->getMailboxes() as $mailbox) {
if (strcasecmp($name, $mailbox) === 0) {
if (false === \imap_reopen($this->resource, $this->server . $mailbox)) {
throw new \Exception('Could not open mailbox ' . $mailbox);
}
return new Mailbox($mailbox, $this->resource);
}
}
throw new \InvalidArgumentException('Mailbox ' . $name . ' not found');
}
public function count()
{
return \imap_num_msg($this->resource);
}
} | <?php
namespace Ddeboer\Imap;
/**
* A connection to an IMAP server that is authenticated for a user
*/
class Connection
{
protected $server;
protected $resource;
protected $mailboxes;
public function __construct($resource, $server)
{
if (!is_resource($resource)) {
throw new \InvalidArgumentException('$resource must be a resource');
}
$this->resource = $resource;
$this->server = $server;
}
/**
* Get a list of mailboxes
*
* @return array
*/
public function getMailboxes()
{
if (null === $this->mailboxes) {
$mailboxes = \imap_getmailboxes($this->resource, $this->server, '*');
foreach ($mailboxes as $mailbox) {
$this->mailboxes[] = str_replace($this->server, '', $mailbox->name);
}
}
return $this->mailboxes;
}
public function getMailbox($name)
{
foreach ($this->getMailboxes() as $mailbox) {
if ($name === $mailbox) {
if (false === \imap_reopen($this->resource, $this->server . $mailbox)) {
throw new \Exception('Could not open mailbox ' . $mailbox);
}
return new Mailbox($mailbox, $this->resource);
}
}
throw new \InvalidArgumentException('Mailbox ' . $name . ' not found');
}
public function count()
{
return \imap_num_msg($this->resource);
}
} |
Add docblock and if statements to growl method | <?php
namespace BryanCrowe;
class Growl
{
public function __construct() {}
/**
* Options:
* - title The title
* - subtitle The subtitle
* - sticky Make it sticky. Defaults to false
*
*/
public function growl($message = null, $options = []) {
$args = $this->createCommand();
if (PHP_OS === 'Darwin') {
}
if (PHP_OS === 'Linux') {
}
if (PHP_OS === 'WINNT') {
}
}
public function createCommand()
{
switch (PHP_OS) {
case 'Darwin':
if (exec('which growlnotify')) {
return [
'pkg' => 'growlnotify',
'msg' => '-m',
'sticky' => '--sticky'
];
} else {
return [
'pkg' => 'terminal-notifier',
'msg' => '-message',
'title' => '-title',
'subtitle' => '-subtitle'
];
}
break;
case 'Linux':
if (exec('which growl')) {
return [
'pkg' => 'growl',
'msg' => '-m',
'title' => '-title',
'subtitle' => '-subtitle'
];
} else {
return [
'pkg' => 'notify-send',
'msg' => '',
'sticky' => '-t 0'
];
}
break;
case 'WINNT':
return [
'pkg' => 'growlnotify',
'msg' => '',
'title' => '/t:',
'sticky' => '/s:true'
];
break;
}
}
}
| <?php
namespace BryanCrowe;
class Growl
{
public function __construct() {}
public function growl($message = null, $options = []) {}
public function createCommand()
{
switch (PHP_OS) {
case 'Darwin':
if (exec('which growlnotify')) {
return [
'pkg' => 'growlnotify',
'msg' => '-m',
'sticky' => '--sticky'
];
} else {
return [
'pkg' => 'terminal-notifier',
'msg' => '-message',
'title' => '-title',
'subtitle' => '-subtitle'
];
}
break;
case 'Linux':
if (exec('which growl')) {
return [
'pkg' => 'growl',
'msg' => '-m',
'title' => '-title',
'subtitle' => '-subtitle'
];
} else {
return [
'pkg' => 'notify-send',
'msg' => '',
'sticky' => '-t 0'
];
}
break;
case 'WINNT':
return [
'pkg' => 'growlnotify',
'msg' => '',
'title' => '/t:',
'sticky' => '/s:true'
];
break;
}
}
}
|
Add log file name to command line. | #!/usr/bin/env python3
import sys
_args = sys.argv
if __name__ == "__main__":
if len(_args) == 5:
keys_file = _args[1]
target_file = _args[2]
result_file = _args[3]
log_file = _args[4]
try:
with open(keys_file, 'r') as k:
keys = k.readlines()
keys = [key.strip().split('@')[0] for key in keys]
keys = [key for key in keys if key != '']
with open(target_file, 'r') as t:
target_lines = t.readlines()
log = open(log_file, 'w')
with open(result_file, 'w') as r:
for line in target_lines:
if line.split(':')[0] in keys or line.split(':')[3] != '12':
r.write(line)
else:
log.write(line)
log.close()
except Exception as e:
print(str(e))
sys.exit()
else:
print('./passwd_change.py keys_file.txt passwd_file result_file log_file')
| #!/usr/bin/env python3
import sys
_args = sys.argv
if __name__ == "__main__":
if len(_args) == 4:
keys_file = _args[1]
target_file = _args[2]
result_file = _args[3]
try:
with open(keys_file, 'r') as k:
keys = k.readlines()
keys = [key.strip().split('@')[0] for key in keys]
keys = [key for key in keys if key != '']
with open(target_file, 'r') as t:
target_lines = t.readlines()
log = open('deletel.log', 'w')
with open(result_file, 'w') as r:
for line in target_lines:
if line.split(':')[0] in keys or line.split(':')[3] != '12':
r.write(line)
else:
log.write(line)
log.close()
except Exception as e:
print(str(e))
sys.exit()
else:
print('./passwd_change.py keys_file.txt passwd_file result_file')
|
Fix unittest failure in python 3.x. | import json
import unittest
import sys
if sys.version_info[0] == 2:
from urllib import urlencode
else:
from urllib.parse import urlencode
from pyunio import pyunio
pyunio.use('httpbin')
params_get = {
'params': {
'name': 'James Bond'
}
}
params_body = {
'body': {
'name': 'James Bond'
}
}
class pyuniotTest(unittest.TestCase):
def test_get(self):
response = json.loads(pyunio.get('get', params_get).text)
self.assertEqual(response['args']['name'], 'James Bond')
def test_post(self):
response = json.loads(pyunio.post('post', params_body).text)
self.assertEqual(response['form']['name'],'James Bond')
def test_put(self):
response = json.loads(pyunio.put('put', params_body).text)
self.assertEqual(response['form']['name'], 'James Bond')
def test_delete(self):
response = json.loads(pyunio.delete('delete', params_body).text)
self.assertEqual(response['data'], urlencode({'name':'James Bond'}))
if __name__ == '__main__':
unittest.main()
| import json
import unittest
from pyunio import pyunio
import urllib
pyunio.use('httpbin')
params_get = {
'params': {
'name': 'James Bond'
}
}
params_body = {
'body': {
'name': 'James Bond'
}
}
class pyuniotTest(unittest.TestCase):
def test_get(self):
response = json.loads(pyunio.get('get', params_get).text)
self.assertEqual(response['args']['name'], 'James Bond')
def test_post(self):
response = json.loads(pyunio.post('post', params_body).text)
self.assertEqual(response['form']['name'],'James Bond')
def test_put(self):
response = json.loads(pyunio.put('put', params_body).text)
self.assertEqual(response['form']['name'], 'James Bond')
def test_delete(self):
response = json.loads(pyunio.delete('delete', params_body).text)
self.assertEqual(response['data'], urllib.urlencode({'name':'James Bond'}))
if __name__ == '__main__':
unittest.main()
|
Check that coverage file exists | import os
import re
filename_matcher = re.compile(r'^\+\+\+ b/([\w/\._]+)\s+.+$')
diff_line_matcher = re.compile(r'^@@ -\d+,\d+ \+(\d+),(\d+) @@$')
def report_diffs(diff):
for line in diff:
name_match = filename_matcher.match(line)
if name_match:
filename = name_match.group(1)
continue
diff_line_match = diff_line_matcher.match(line)
if diff_line_match:
start_line = int(diff_line_match.group(1))
number_of_lines = int(diff_line_match.group(2))
if filename.startswith('src') and not is_covered(filename, start_line, number_of_lines):
sys.exit(1)
def is_covered(filename, start_line, number_of_lines):
cover_file_name = filename+',cover'
if not os.path.is_file(cover_file_name):
return False
start_line -= 1
with open(cover_file_name) as annotation:
lines = annotation.readlines()[start_line:start_line+number_of_lines]
for line in lines:
if not line.startswith('>'):
print 'Line not covered %r in file "%s"!!' % (line, filename)
return False
return True
if __name__ == '__main__':
import sys
diff_file = sys.argv[1]
with open(diff_file) as diff:
report_diffs(diff)
print 'All lines covered'
| import re
filename_matcher = re.compile(r'^\+\+\+ b/([\w/\._]+)\s+.+$')
diff_line_matcher = re.compile(r'^@@ -\d+,\d+ \+(\d+),(\d+) @@$')
def report_diffs(diff):
for line in diff:
name_match = filename_matcher.match(line)
if name_match:
filename = name_match.group(1)
continue
diff_line_match = diff_line_matcher.match(line)
if diff_line_match:
start_line = int(diff_line_match.group(1))
number_of_lines = int(diff_line_match.group(2))
if filename.startswith('src') and not is_covered(filename, start_line, number_of_lines):
sys.exit(1)
def is_covered(filename, start_line, number_of_lines):
start_line -= 1
with open(filename+',cover') as annotation:
lines = annotation.readlines()[start_line:start_line+number_of_lines]
for line in lines:
if not line.startswith('>'):
print 'Line not covered %r in file "%s"!!' % (line, filename)
return False
return True
if __name__ == '__main__':
import sys
diff_file = sys.argv[1]
with open(diff_file) as diff:
report_diffs(diff)
print 'All lines covered'
|
Add a message that Jen is the only one to use this | @extends('layouts.master')
@section('main_content')
@include('layouts.header', ['header' => 'Upload a CSV for import'])
<div class="container -padded">
<div class="wrapper">
<div class="container__block -narrow">
<p>For the time being, This feature should only be used by Jen Ng. If you have any questions please reach out to Jen directly or post a message in the #rogue channel in slack</p>
</div>
<div class="container__block -narrow">
<form action={{url('/import')}} method="post" enctype="multipart/form-data">
{{ csrf_field()}}
<div class="form-item">
<label for="upload-file" class="field-label">Upload</label>
<input type="file" name="upload-file" class="form-control">
</div>
<label class="field-label">Type of Import</label>
<div class="form-item">
<label class="option -checkbox">
<input checked type="checkbox" id="importType" value="turbovote" name="importType">
<span class="option__indicator"></span>
<span>Turbovote Import</span>
</label>
</div>
<div class="form-actions -padded">
<input type="submit" class="button" value="Submit CSV">
</div>
</form>
</div>
</div>
</div>
@stop
| @extends('layouts.master')
@section('main_content')
@include('layouts.header', ['header' => 'Upload a CSV for import'])
<div class="container -padded">
<div class="wrapper">
<div class="container__block -narrow">
<form action={{url('/import')}} method="post" enctype="multipart/form-data">
{{ csrf_field()}}
<div class="form-item">
<label for="upload-file" class="field-label">Upload</label>
<input type="file" name="upload-file" class="form-control">
</div>
<label class="field-label">Type of Import</label>
<div class="form-item">
<label class="option -checkbox">
<input checked type="checkbox" id="importType" value="turbovote" name="importType">
<span class="option__indicator"></span>
<span>Turbovote Import</span>
</label>
</div>
<div class="form-actions -padded">
<input type="submit" class="button" value="Submit CSV">
</div>
</form>
</div>
</div>
</div>
@stop
|
Copy indent rule to TS as well | module.exports = {
extends: ["matrix-org", "matrix-org/react-legacy"],
parser: "babel-eslint",
env: {
browser: true,
node: true,
},
globals: {
LANGUAGES_FILE: "readonly",
},
rules: {
// Things we do that break the ideal style
"no-constant-condition": "off",
"prefer-promise-reject-errors": "off",
"no-async-promise-executor": "off",
"quotes": "off",
"indent": "off",
},
overrides: [{
"files": ["src/**/*.{ts,tsx}"],
"extends": ["matrix-org/ts"],
"rules": {
// We're okay being explicit at the moment
"@typescript-eslint/no-empty-interface": "off",
// We disable this while we're transitioning
"@typescript-eslint/no-explicit-any": "off",
// We'd rather not do this but we do
"@typescript-eslint/ban-ts-comment": "off",
"quotes": "off",
"indent": "off",
"no-extra-boolean-cast": "off",
},
}],
};
| module.exports = {
extends: ["matrix-org", "matrix-org/react-legacy"],
parser: "babel-eslint",
env: {
browser: true,
node: true,
},
globals: {
LANGUAGES_FILE: "readonly",
},
rules: {
// Things we do that break the ideal style
"no-constant-condition": "off",
"prefer-promise-reject-errors": "off",
"no-async-promise-executor": "off",
"quotes": "off",
"indent": "off",
},
overrides: [{
"files": ["src/**/*.{ts,tsx}"],
"extends": ["matrix-org/ts"],
"rules": {
// We're okay being explicit at the moment
"@typescript-eslint/no-empty-interface": "off",
// We disable this while we're transitioning
"@typescript-eslint/no-explicit-any": "off",
// We'd rather not do this but we do
"@typescript-eslint/ban-ts-comment": "off",
"quotes": "off",
"no-extra-boolean-cast": "off",
},
}],
};
|
Add logging to Twitch emotes module | from io import BytesIO
import logging
import requests
from discord.ext import commands
from discord.ext.commands import Bot
TWITCH_EMOTES_API = 'https://twitchemotes.com/api_cache/v2/global.json'
logger = logging.getLogger(__name__)
class TwitchEmotes:
def __init__(self, bot: Bot):
self.bot = bot
r = requests.get(TWITCH_EMOTES_API)
emote_data = r.json()
emote_template = emote_data['template']['small']
emote_ids = {name: info['image_id'] for name, info in
emote_data['emotes'].items()}
emote_cache = {}
logger.info('Got %d emotes from Twitchemotes.com API' % len(emote_ids))
logger.info('Using template: %s' % emote_template)
@bot.listen('on_message')
async def respond(message):
if message.author == bot.user:
return
text = message.content
if text in emote_ids:
if text not in emote_cache:
url = emote_template.replace('{image_id}',
str(emote_ids[text]))
logger.info('Fetching emote %s from %s' % (text, url))
emote_img = requests.get(url).content
emote_cache[text] = emote_img
data = BytesIO(emote_cache[text])
filename = '%s.png' % text
await bot.send_file(message.channel, data, filename=filename)
def setup(bot: Bot):
bot.add_cog(TwitchEmotes(bot))
| from io import BytesIO
import requests
from discord.ext import commands
from discord.ext.commands import Bot
TWITCH_EMOTES_API = 'https://twitchemotes.com/api_cache/v2/global.json'
class TwitchEmotes:
def __init__(self, bot: Bot):
self.bot = bot
r = requests.get(TWITCH_EMOTES_API)
emote_data = r.json()
emote_template = emote_data['template']['small']
emote_ids = {name: info['image_id'] for name, info in
emote_data['emotes'].items()}
emote_cache = {}
@bot.listen('on_message')
async def respond(message):
if message.author == bot.user:
return
text = message.content
if text in emote_ids:
if text not in emote_cache:
url = emote_template.replace('{image_id}',
str(emote_ids[text]))
emote_img = requests.get(url).content
emote_cache[text] = emote_img
data = BytesIO(emote_cache[text])
filename = '%s.png' % text
await bot.send_file(message.channel, data, filename=filename)
def setup(bot: Bot):
bot.add_cog(TwitchEmotes(bot))
|
Fix card rendering in dash | import React, { Component } from 'react';
import Registry from '../utils/Registry';
import BaseComponent from './BaseComponent';
import Card from './Card';
import { pick } from 'lodash';
/**
* @@TODO Currently in practice this only handles regions
* MOST OF THIS LOGIC IS REPRODUCE IN THE Region Component
* We should refactor so this is not the case
*/
export default class Dashboard extends BaseComponent {
render() {
let markup;
console.log('DASH RENDER', this);
let routeParams = pick(this.props, ['history', 'location', 'params', 'route', 'routeParams', 'routes']);
// We wrap the whole dashboard in the route so we that we get paramater info in the els
// @@TODO this needs to be repeated in Region because of our dumb scheme
return (
<div className="container">
<h1 className="dashboard-title">{this.props.title}</h1>
{this.props.components.map((element, key) => {
let props = Object.assign(this.props.components[key], {globalData: this.state.data}, routeParams);
let output;
if (props.cardStyle) {
output =
<Card key={key} {...element}>
{React.createElement(Registry.get(element.type), Object.assign(this.props.components[key], props))}
</Card>
} else {
output =
React.createElement(Registry.get(element.type), Object.assign(this.props.components[key], props))
}
return output;
})}
</div>
);
}
}
| import React, { Component } from 'react';
import Registry from '../utils/Registry';
import BaseComponent from './BaseComponent';
import Card from './Card';
import { pick } from 'lodash';
/**
* @@TODO Currently in practice this only handles regions
* MOST OF THIS LOGIC IS REPRODUCE IN THE Region Component
* We should refactor so this is not the case
*/
export default class Dashboard extends BaseComponent {
render() {
let markup;
console.log('DASH RENDER', this);
let routeParams = pick(this.props, ['history', 'location', 'params', 'route', 'routeParams', 'routes']);
// We wrap the whole dashboard in the route so we that we get paramater info in the els
// @@TODO this needs to be repeated in Region because of our dumb scheme
return (
<div className="container">
<h1 className="dashboard-title">{this.props.title}</h1>
{this.props.components.map((element, key) => {
let props = Object.assign(this.props.components[key], {globalData: this.state.data}, routeParams);
let output;
if (props.cardType !== 'undefined') {
output =
<Card key={key} {...element}>
{React.createElement(Registry.get(element.type), Object.assign(this.props.components[key], props))}
</Card>
} else {
output =
React.createElement(Registry.get(element.type), Object.assign(this.props.components[key], props))
}
return output;
})}
</div>
);
}
}
|
Add offline support for swagger generation | 'use strict';
module.exports = function(grunt) {
grunt.registerMultiTask('swagger', 'Generate Source from Swagger files', function(){
var fs = require('fs');
var request = require('request');
var done = this.async();
var options = this.options();
var url = this.data.url;
var dest = options.dest;
var failIfOffline = options.failIfOffline;
grunt.file.mkdir(dest);
var count = options.apis.length;
grunt.log.writeln('Using api: ' + url);
options.apis.forEach(function(api){
var swagger = fs.readFileSync(api.swagger);
request({
uri: url + '/angular.jq',
qs: { module: api.module, service: api.service, 'new-module': api.newModule },
headers: { 'Content-Type': 'text/json; utf-8' },
body: swagger
}, function(error, response, body){
if(response === undefined) {
if(failIfOffline) {
grunt.fail.fatal('Couldn\'t connect to server');
} else {
grunt.log.writeln('Skipped ' + dest + '/' + api.service + '.js');
count--;
if(count === 0) {
done();
}
return;
}
}
if(response.statusCode !== 200) {
grunt.fail.fatal('Server replied: ' + response.statusCode);
}
fs.writeFileSync(dest + '/' + api.service + '.js', body);
grunt.log.writeln(dest + '/' + api.service + '.js written (' + api.module + '.' + api.service + ')');
count--;
if(count === 0) {
done();
}
});
});
});
};
| 'use strict';
module.exports = function(grunt) {
grunt.registerMultiTask('swagger', 'Generate Source from Swagger files', function(){
var fs = require('fs');
var request = require('request');
var done = this.async();
var options = this.options();
var url = this.data.url;
var dest = options.dest;
grunt.file.mkdir(dest);
var count = options.apis.length;
grunt.log.writeln('Using api: ' + url);
options.apis.forEach(function(api){
var swagger = fs.readFileSync(api.swagger);
request({
uri: url + '/angular.jq',
qs: { module: api.module, service: api.service, 'new-module': api.newModule },
headers: { 'Content-Type': 'text/json; utf-8' },
body: swagger
}, function(error, response, body){
if(response === undefined) {
grunt.fail.fatal('Couldn\'t connect to server');
}
if(response.statusCode !== 200) {
grunt.fail.fatal('Server replied: ' + response.statusCode);
}
fs.writeFileSync(dest + '/' + api.service + '.js', body);
grunt.log.writeln(dest + '/' + api.service + '.js written (' + api.module + '.' + api.service + ')');
count--;
if(count === 0) {
done();
}
});
});
});
};
|
Use context manager for file opening/reading. | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
setup(
name='binaryornot',
version='0.4.0',
description=(
'Ultra-lightweight pure Python package to check '
'if a file is binary or text.'
),
long_description=readme + '\n\n' + history,
author='Audrey Roy Greenfeld',
author_email='[email protected]',
url='https://github.com/audreyr/binaryornot',
packages=[
'binaryornot',
],
package_dir={'binaryornot': 'binaryornot'},
include_package_data=True,
install_requires=[
'chardet>=2.0.0',
],
license="BSD",
zip_safe=False,
keywords='binaryornot',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
test_suite='tests',
)
| #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
setup(
name='binaryornot',
version='0.4.0',
description=(
'Ultra-lightweight pure Python package to check '
'if a file is binary or text.'
),
long_description=readme + '\n\n' + history,
author='Audrey Roy Greenfeld',
author_email='[email protected]',
url='https://github.com/audreyr/binaryornot',
packages=[
'binaryornot',
],
package_dir={'binaryornot': 'binaryornot'},
include_package_data=True,
install_requires=[
'chardet>=2.0.0',
],
license="BSD",
zip_safe=False,
keywords='binaryornot',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
test_suite='tests',
)
|
Add typehints for ServiceRegistryInterface::all() calls | <?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\Shipping\Resolver;
use Sylius\Component\Registry\PrioritizedServiceRegistryInterface;
use Sylius\Component\Shipping\Model\ShippingSubjectInterface;
/**
* @author Mateusz Zalewski <[email protected]>
*/
class CompositeMethodsResolver implements MethodsResolverInterface
{
/**
* @var PrioritizedServiceRegistryInterface
*/
private $resolversRegistry;
/**
* @param PrioritizedServiceRegistryInterface $resolversRegistry
*/
public function __construct(PrioritizedServiceRegistryInterface $resolversRegistry)
{
$this->resolversRegistry = $resolversRegistry;
}
/**
* {@inheritdoc}
*/
public function getSupportedMethods(ShippingSubjectInterface $shippingSubject)
{
/** @var MethodsResolverInterface $resolver */
foreach ($this->resolversRegistry->all() as $resolver) {
if ($resolver->supports($shippingSubject)) {
return $resolver->getSupportedMethods($shippingSubject);
}
}
return [];
}
/**
* {@inheritdoc}
*/
public function supports(ShippingSubjectInterface $subject)
{
/** @var MethodsResolverInterface $resolver */
foreach ($this->resolversRegistry->all() as $resolver) {
if ($resolver->supports($subject)) {
return true;
}
}
return false;
}
}
| <?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\Shipping\Resolver;
use Sylius\Component\Registry\PrioritizedServiceRegistryInterface;
use Sylius\Component\Shipping\Model\ShippingSubjectInterface;
/**
* @author Mateusz Zalewski <[email protected]>
*/
class CompositeMethodsResolver implements MethodsResolverInterface
{
/**
* @var PrioritizedServiceRegistryInterface
*/
private $resolversRegistry;
/**
* @param PrioritizedServiceRegistryInterface $resolversRegistry
*/
public function __construct(PrioritizedServiceRegistryInterface $resolversRegistry)
{
$this->resolversRegistry = $resolversRegistry;
}
/**
* {@inheritdoc}
*/
public function getSupportedMethods(ShippingSubjectInterface $shippingSubject)
{
foreach ($this->resolversRegistry->all() as $resolver) {
if ($resolver->supports($shippingSubject)) {
return $resolver->getSupportedMethods($shippingSubject);
}
}
return [];
}
/**
* {@inheritdoc}
*/
public function supports(ShippingSubjectInterface $subject)
{
foreach ($this->resolversRegistry->all() as $resolver) {
if ($resolver->supports($subject)) {
return true;
}
}
return false;
}
}
|
Prepare with vespenen gas count too | from functools import partial
from .data import ActionResult
class BotAI(object):
def _prepare_start(self, client, game_info, game_data):
self._client = client
self._game_info = game_info
self._game_data = game_data
self.do = partial(self._client.actions, game_data=game_data)
@property
def game_info(self):
return self._game_info
@property
def enemy_start_locations(self):
return self._game_info.start_locations
async def can_place(self, building, position):
ability_id = self._game_data.find_ability_by_name(f"Build {building}").id
r = await self._client.query_building_placement(ability_id, [position])
return r[0] == ActionResult.Success
async def select_placement(self, building, positions):
ability_id = self._game_data.find_ability_by_name(f"Build {building}").id
r = await self._client.query_building_placement(ability_id, positions)
print(r)
exit("!!!!")
def _prepare_step(self, state):
self.units = state.units.owned
self.minerals = state.common.minerals
self.vespene = state.common.vespene
def on_start(self):
pass
async def on_step(self, do, state, game_loop):
raise NotImplementedError
| from functools import partial
from .data import ActionResult
class BotAI(object):
def _prepare_start(self, client, game_info, game_data):
self._client = client
self._game_info = game_info
self._game_data = game_data
self.do = partial(self._client.actions, game_data=game_data)
@property
def game_info(self):
return self._game_info
@property
def enemy_start_locations(self):
return self._game_info.start_locations
async def can_place(self, building, position):
ability_id = self._game_data.find_ability_by_name(f"Build {building}").id
r = await self._client.query_building_placement(ability_id, [position])
return r[0] == ActionResult.Success
async def select_placement(self, building, positions):
ability_id = self._game_data.find_ability_by_name(f"Build {building}").id
r = await self._client.query_building_placement(ability_id, positions)
print(r)
exit("!!!!")
def _prepare_step(self, state):
self.units = state.units.owned
self.minerals = state.common.minerals
self.vespnene = state.common.vespene
def on_start(self):
pass
async def on_step(self, do, state, game_loop):
raise NotImplementedError
|
Return the written value of DMA register. | package eu.rekawek.coffeegb.memory;
import eu.rekawek.coffeegb.AddressSpace;
import eu.rekawek.coffeegb.cpu.SpeedMode;
public class Dma implements AddressSpace {
private final AddressSpace addressSpace;
private final AddressSpace oam;
private final SpeedMode speedMode;
private boolean transferInProgress;
private boolean restarted;
private int from;
private int ticks;
private int regValue = 0xff;
public Dma(AddressSpace addressSpace, AddressSpace oam, SpeedMode speedMode) {
this.addressSpace = addressSpace;
this.speedMode = speedMode;
this.oam = oam;
}
@Override
public boolean accepts(int address) {
return address == 0xff46;
}
public void tick() {
if (transferInProgress) {
if (++ticks >= 648 / speedMode.getSpeedMode()) {
transferInProgress = false;
restarted = false;
ticks = 0;
for (int i = 0; i < 0xa0; i++) {
oam.setByte(0xfe00 + i, addressSpace.getByte(from + i));
}
}
}
}
@Override
public void setByte(int address, int value) {
from = value * 0x100;
restarted = isOamBlocked();
ticks = 0;
transferInProgress = true;
regValue = value;
}
@Override
public int getByte(int address) {
return regValue;
}
public boolean isOamBlocked() {
return restarted || (transferInProgress && ticks >= 5);
}
} | package eu.rekawek.coffeegb.memory;
import eu.rekawek.coffeegb.AddressSpace;
import eu.rekawek.coffeegb.cpu.SpeedMode;
public class Dma implements AddressSpace {
private final AddressSpace addressSpace;
private final AddressSpace oam;
private final SpeedMode speedMode;
private boolean transferInProgress;
private boolean restarted;
private int from;
private int ticks;
public Dma(AddressSpace addressSpace, AddressSpace oam, SpeedMode speedMode) {
this.addressSpace = addressSpace;
this.speedMode = speedMode;
this.oam = oam;
}
@Override
public boolean accepts(int address) {
return address == 0xff46;
}
public void tick() {
if (transferInProgress) {
if (++ticks >= 648 / speedMode.getSpeedMode()) {
transferInProgress = false;
restarted = false;
ticks = 0;
for (int i = 0; i < 0xa0; i++) {
oam.setByte(0xfe00 + i, addressSpace.getByte(from + i));
}
}
}
}
@Override
public void setByte(int address, int value) {
from = value * 0x100;
restarted = isOamBlocked();
ticks = 0;
transferInProgress = true;
}
@Override
public int getByte(int address) {
return 0;
}
public boolean isOamBlocked() {
return restarted || (transferInProgress && ticks >= 5);
}
} |
Support making available to exec cmd on sub dir | import os
import sys
from commands.apply_config import ApplyConfigCommand
from commands.compile import CompileCommand
from commands.init import InitCommand
from commands.setup import SetupCommand
from commands.update_deps import UpdateDepsCommand
from lib.config import Config
from lib.error import GoogkitError
CONFIG = 'googkit.cfg'
COMMANDS_DICT = {
'apply-config': [ApplyConfigCommand, UpdateDepsCommand],
'compile': [CompileCommand],
'init': [InitCommand],
'setup': [SetupCommand, UpdateDepsCommand],
'update-deps': [UpdateDepsCommand]}
def print_help():
print('Usage: googkit command')
print('')
print('Available subcommands:')
for name in sorted(COMMANDS_DICT.keys()):
print(' ' + name)
if __name__ == '__main__':
if len(sys.argv) != 2:
print_help()
sys.exit()
subcommand_classes = COMMANDS_DICT.get(sys.argv[1])
if subcommand_classes is None:
print_help()
sys.exit()
config = Config()
try:
while os.path.exists(os.path.relpath(CONFIG)):
before = os.getcwd()
os.chdir('..')
# Break if current dir is root.
if before == os.getcwd():
break
config.load(CONFIG)
except IOError:
config = None
try:
for klass in subcommand_classes:
subcommand = klass(config)
subcommand.run()
except GoogkitError, e:
sys.exit('[ERROR] ' + str(e))
| import os
import sys
from commands.apply_config import ApplyConfigCommand
from commands.compile import CompileCommand
from commands.init import InitCommand
from commands.setup import SetupCommand
from commands.update_deps import UpdateDepsCommand
from lib.config import Config
from lib.error import GoogkitError
CONFIG = 'googkit.cfg'
COMMANDS_DICT = {
'apply-config': [ApplyConfigCommand, UpdateDepsCommand],
'compile': [CompileCommand],
'init': [InitCommand],
'setup': [SetupCommand, UpdateDepsCommand],
'update-deps': [UpdateDepsCommand]}
def print_help():
print('Usage: googkit command')
print('')
print('Available subcommands:')
for name in sorted(COMMANDS_DICT.keys()):
print(' ' + name)
if __name__ == '__main__':
if len(sys.argv) != 2:
print_help()
sys.exit()
subcommand_classes = COMMANDS_DICT.get(sys.argv[1])
if subcommand_classes is None:
print_help()
sys.exit()
config = Config()
try:
config.load(CONFIG)
except IOError:
config = None
try:
for klass in subcommand_classes:
subcommand = klass(config)
subcommand.run()
except GoogkitError, e:
sys.exit('[ERROR] ' + str(e))
|
Add missing '&' to area query in Aliss | module.exports = {
getDetails:function(id,callback){
callback({});
},
query:function(qo,callback){
var query=qo.query,area=qo.area;
let path = "/api/v2/search/?q="+encodeURIComponent(query);
if(area){
path += `&latitude=${area.lat}&longitude=${area.lon}&distance=${area.distance}`;
}
https.get({
path:path,
hostname:"www.aliss.org",
method:"GET",
headers:{
'Accept':'application/json'
}
},function(res){
console.log('Status '+res.statusCode);
console.log('Headers '+JSON.stringify(res.headers));
let data='';
res.on('data',function(chunk){
data+=chunk;
});
res.on('end',function(){
try{
callback(JSON.parse(data));
}
catch(err){
console.error('ALISS error: '+err);
}
});
});
}
};
| module.exports = {
getDetails:function(id,callback){
callback({});
},
query:function(qo,callback){
var query=qo.query,area=qo.area;
let path = "/api/v2/search/?q="+encodeURIComponent(query);
if(area){
path += `latitude=${area.lat}&longitude=${area.lon}&distance=${area.distance}`;
}
https.get({
path:path,
hostname:"www.aliss.org",
method:"GET",
headers:{
'Accept':'application/json'
}
},function(res){
console.log('Status '+res.statusCode);
console.log('Headers '+JSON.stringify(res.headers));
let data='';
res.on('data',function(chunk){
data+=chunk;
});
res.on('end',function(){
try{
callback(JSON.parse(data));
}
catch(err){
console.error('ALISS error: '+err);
}
});
});
}
};
|
Reset search on connection error | 'use strict';
angular
.module('flyNg.server', ['services', 'ngCookies'])
.controller('ServerController', ['$scope', '$rootScope', '$location', '$cookies', '$log', 'management', function ($scope, $rootScope, $location, $cookies, $log, management) {
$scope.management = management;
var KEY = 'server-url';
if (!angular.isUndefined($cookies[KEY])) {
var url = decodeURI($cookies[KEY]);
}
if (angular.isUndefined(url)) {
management.server = {"url": "localhost"};
} else {
management.server = {"url": url};
}
loadServerData();
$scope.updateServerUrl = function() {
$cookies[KEY] = encodeURI(management.server.url);
loadServerData();
};
function loadServerData() {
management.load([]).then(
function(response) {
var serverState = response.result['server-state'];
if (serverState == 'reload-required') {
management.server.state = 'running';
} else {
management.server.state = serverState;
}
return management.list([], "subsystem");
}).then(
function (data) {
management.resources = data.result;
},function() {
management.server.state = 'not connected';
$location.path('/');
$location.search('name', null);
}
);
}
}]);
| 'use strict';
angular
.module('flyNg.server', ['services', 'ngCookies'])
.controller('ServerController', ['$scope', '$rootScope', '$location', '$cookies', '$log', 'management', function ($scope, $rootScope, $location, $cookies, $log, management) {
$scope.management = management;
var KEY = 'server-url';
if (!angular.isUndefined($cookies[KEY])) {
var url = decodeURI($cookies[KEY]);
}
if (angular.isUndefined(url)) {
management.server = {"url": "localhost"};
} else {
management.server = {"url": url};
}
loadServerData();
$scope.updateServerUrl = function() {
$cookies[KEY] = encodeURI(management.server.url);
loadServerData();
};
function loadServerData() {
management.load([]).then(
function(response) {
var serverState = response.result['server-state'];
if (serverState == 'reload-required') {
management.server.state = 'running';
} else {
management.server.state = serverState;
}
return management.list([], "subsystem");
}).then(
function (data) {
management.resources = data.result;
},function() {
management.server.state = 'not connected';
$location.path('/');
}
);
}
}]);
|
Make image required on Job submit form. | from datetimewidget.widgets import DateTimeWidget
from django.forms import ModelForm
from form_utils.widgets import ImageWidget
from ..models import Job
job_field_labels = {
'image': 'Image (10Mb Limit)',
'url': 'URL'
}
job_help_texts = {
'url': 'Provide a full url, e.g., "http://www.example.com/page.html"'
}
field_widgets = {
'image': ImageWidget(attrs={'required': 'required'})
}
class JobSubmitForm(ModelForm):
class Meta:
model = Job
fields = ['title',
'url',
'organization',
'image']
labels = job_field_labels
help_texts = job_help_texts
widgets = field_widgets
class JobUpdateForm(ModelForm):
class Meta:
model = Job
fields = ['title',
'url',
'organization',
'image',
'approved',
'include_in_newsletter',
'pub_date']
widgets = {
'pub_date': DateTimeWidget(usel10n=True, bootstrap_version=3),
'image': ImageWidget(),
}
labels = job_field_labels
help_texts = job_help_texts
| from datetimewidget.widgets import DateTimeWidget
from django.forms import ModelForm
from form_utils.widgets import ImageWidget
from ..models import Job
job_field_labels = {
'image': 'Image (10Mb Limit)',
'url': 'URL'
}
job_help_texts = {
'url': 'Provide a full url, e.g., "http://www.example.com/page.html"'
}
class JobSubmitForm(ModelForm):
class Meta:
model = Job
fields = ['title',
'url',
'organization',
'image']
labels = {
}
labels = job_field_labels
help_texts = job_help_texts
class JobUpdateForm(ModelForm):
class Meta:
model = Job
fields = ['title',
'url',
'organization',
'image',
'approved',
'include_in_newsletter',
'pub_date']
widgets = {
'pub_date': DateTimeWidget(usel10n=True, bootstrap_version=3),
'image': ImageWidget(),
}
labels = job_field_labels
help_texts = job_help_texts
|
Make sure the input value is kept up-to-date ... | (function($) {
jQuery.fn.lineeditor = function (options, callback) {
return this.each(function () {
var el = this;
var $el = $(this);
if ( el.nodeName.toLowerCase() != 'textarea' ) { return; }
var hidden = $('<input type="hidden"/>').attr('id', el.id);
var container = $('<div class="lineeditor"></div>');
var val = $el.val();
hidden.val(val);
container.append(hidden);
container.append($('<a href="#add-line">Add Line</a>').click(addLine));
$.each(val.split("\n"),function(){
addLine(this);
});
$el.replaceWith(container);
function addLine(value) {
value = ( value.target ? value.preventDefault() && '' : value );
var node = $('<input type="text"/>').val(value?value.toString():'');
var delete_node = $('<a href="#delete" class="delete">Delete</a>').click(removeLine);
container.find('a:last').before(node, delete_node);
processValues();
}
function removeLine(ev) {
ev.preventDefault();
$(this).prev().remove();
$(this).remove();
processValues();
}
function processValues() {
var val = '';
container.find('input[type=text]').each(function(){
val += $(this).val() + "\n";
})
hidden.val(val);
}
})
}
})(jQuery); | (function($) {
jQuery.fn.lineeditor = function (options, callback) {
return this.each(function () {
var el = this;
var $el = $(this);
if ( el.nodeName.toLowerCase() != 'textarea' ) { return; }
var hidden = $('<input type="hidden"/>').attr('id', el.id);
var container = $('<div class="lineeditor"></div>');
var val = $el.val();
hidden.val(val);
container.append(hidden);
container.append($('<a href="#add-line">Add Line</a>').click(addLine));
$.each(val.split("\n"),function(){
addLine(this);
});
$el.replaceWith(container);
function addLine(value) {
value = ( value.target ? value.preventDefault() && '' : value );
var node = $('<input type="text"/>').val(value?value.toString():'');
var delete_node = $('<a href="#delete" class="delete">Delete</a>').click(removeLine);
container.find('a:last').before(node, delete_node);
}
function removeLine(ev) {
ev.preventDefault();
$(this).prev().remove();
$(this).remove();
}
})
}
})(jQuery); |
Resolve an issue when null is in an array | (function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.deepmerge = factory();
}
}(this, function () {
return function deepmerge(target, src) {
var array = Array.isArray(src);
var dst = array && [] || {};
if (array) {
target = target || [];
dst = dst.concat(target);
src.forEach(function(e, i) {
if (typeof dst[i] === 'undefined') {
dst[i] = e;
} else if (typeof e === 'object' && e !== null) {
dst[i] = deepmerge(target[i], e);
} else {
if (target.indexOf(e) === -1) {
dst.push(e);
}
}
});
} else {
if (target && typeof target === 'object') {
Object.keys(target).forEach(function (key) {
dst[key] = target[key];
})
}
Object.keys(src).forEach(function (key) {
if (typeof src[key] !== 'object' || !src[key]) {
dst[key] = src[key];
}
else {
if (!target[key]) {
dst[key] = src[key];
} else {
dst[key] = deepmerge(target[key], src[key]);
}
}
});
}
return dst;
}
}));
| (function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.deepmerge = factory();
}
}(this, function () {
return function deepmerge(target, src) {
var array = Array.isArray(src);
var dst = array && [] || {};
if (array) {
target = target || [];
dst = dst.concat(target);
src.forEach(function(e, i) {
if (typeof dst[i] === 'undefined') {
dst[i] = e;
} else if (typeof e === 'object') {
dst[i] = deepmerge(target[i], e);
} else {
if (target.indexOf(e) === -1) {
dst.push(e);
}
}
});
} else {
if (target && typeof target === 'object') {
Object.keys(target).forEach(function (key) {
dst[key] = target[key];
})
}
Object.keys(src).forEach(function (key) {
if (typeof src[key] !== 'object' || !src[key]) {
dst[key] = src[key];
}
else {
if (!target[key]) {
dst[key] = src[key];
} else {
dst[key] = deepmerge(target[key], src[key]);
}
}
});
}
return dst;
}
}));
|
Fix exception when paiement is not binded to user anymore | <?php
namespace App\Classes;
use App\Models\Payment;
use Illuminate\Encryption\Encrypter;
use Config;
/**
* EtuPay helper
*/
class EtuPay
{
/*
* Decrypt and do action according to crypted payload content send by a callback
* @param $payload crypted payload given by a callback from EtuPay
* @return Payment object
*/
public static function readCallback($payload)
{
$crypt = new Encrypter(base64_decode(Config::get('services.etupay.key')), 'AES-256-CBC');
$payload = json_decode($crypt->decrypt($payload));
if ($payload && is_numeric($payload->service_data)) {
$paymentId = $payload->service_data;
$payment = Payment::findOrFail($paymentId);
switch ($payload->step) {
case 'INITIALISED':
$payment->state = 'returned';
break;
case 'PAID':
case 'AUTHORISATION':
$payment->state = 'paid';
break;
case 'REFUSED':
case 'CANCELED':
$payment->state = 'refused';
break;
case 'REFUNDED':
$payment->state = 'refunded';
break;
}
$payment->informations = ['transaction_id' => $payload->transaction_id];
$payment->save();
if ($payment->user) {
$payment->user->updateWei();
}
return $payment;
}
return null;
}
}
| <?php
namespace App\Classes;
use App\Models\Payment;
use Illuminate\Encryption\Encrypter;
use Config;
/**
* EtuPay helper
*/
class EtuPay
{
/*
* Decrypt and do action according to crypted payload content send by a callback
* @param $payload crypted payload given by a callback from EtuPay
* @return Payment object
*/
public static function readCallback($payload)
{
$crypt = new Encrypter(base64_decode(Config::get('services.etupay.key')), 'AES-256-CBC');
$payload = json_decode($crypt->decrypt($payload));
if ($payload && is_numeric($payload->service_data)) {
$paymentId = $payload->service_data;
$payment = Payment::findOrFail($paymentId);
switch ($payload->step) {
case 'INITIALISED':
$payment->state = 'returned';
break;
case 'PAID':
case 'AUTHORISATION':
$payment->state = 'paid';
break;
case 'REFUSED':
case 'CANCELED':
$payment->state = 'refused';
break;
case 'REFUNDED':
$payment->state = 'refunded';
break;
}
$payment->informations = ['transaction_id' => $payload->transaction_id];
$payment->save();
$payment->user->updateWei();
return $payment;
}
return null;
}
}
|
Allow for the pickers to be used in custom dashboards
The current setup for nupickers does not allow it to exist outside of the current page context. All that needs to happen is a value needs to be passed for the currentId and parentId if editorstate is null. |
angular.module('umbraco.resources')
.factory('nuPickers.Shared.DataSource.DataSourceResource',
['$http', 'editorState',
function ($http, editorState) {
return {
getEditorDataItems: function (model, typeahead) {
var parentId = 0;
var currentId = 0;
if (editorState.current) {
currentId = editorState.current.id;
parentId = editorState.current.parentId;
}
// returns [{"key":"","label":""},{"key":"","label":""}...]
return $http({
method: 'POST',
url: 'backoffice/nuPickers/' + model.config.dataSource.apiController + '/GetEditorDataItems',
params: {
'currentId': currentId,
'parentId': parentId,
'propertyAlias': model.alias
},
data: {
'config': model.config,
'typeahead': typeahead
}
});
}
};
}
]);
|
angular.module('umbraco.resources')
.factory('nuPickers.Shared.DataSource.DataSourceResource',
['$http', 'editorState',
function ($http, editorState) {
return {
getEditorDataItems: function (model, typeahead) {
// returns [{"key":"","label":""},{"key":"","label":""}...]
return $http({
method: 'POST',
url: 'backoffice/nuPickers/' + model.config.dataSource.apiController + '/GetEditorDataItems',
params: {
'currentId': editorState.current.id,
'parentId': editorState.current.parentId,
'propertyAlias': model.alias
},
data: {
'config': model.config,
'typeahead': typeahead
}
});
}
};
}
]); |
Add s3cmd to the list of requirements. | from setuptools import setup, find_packages
version = open('VERSION').read().strip()
setup(
name="btw-backup",
version=version,
packages=find_packages(),
entry_points={
'console_scripts': [
'btw-backup = btw_backup.__main__:main'
],
},
author="Louis-Dominique Dubeau",
author_email="[email protected]",
description="Backup script for BTW.",
license="MPL 2.0",
keywords=["backup"],
url="https://github.com/mangalam-research/btw-backup",
install_requires=[
'pytimeparse>=1.1.4,<=2',
'pyhash>=0.6.2,<1',
'pyee>=1.0.2,<2',
'awscli>=1.10.21,<2',
's3cmd<3',
],
tests_require=[
'psycopg2>=2.5.2,<3'
],
test_suite='nose.collector',
setup_requires=['nose>=1.3.0'],
data_files=[
('.', ['LICENSE', 'VERSION'])
],
# use_2to3=True,
classifiers=[
"Programming Language :: Python :: 2.7",
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"Operating System :: POSIX",
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)"],
)
| from setuptools import setup, find_packages
version = open('VERSION').read().strip()
setup(
name="btw-backup",
version=version,
packages=find_packages(),
entry_points={
'console_scripts': [
'btw-backup = btw_backup.__main__:main'
],
},
author="Louis-Dominique Dubeau",
author_email="[email protected]",
description="Backup script for BTW.",
license="MPL 2.0",
keywords=["backup"],
url="https://github.com/mangalam-research/btw-backup",
install_requires=[
'pytimeparse>=1.1.4,<=2',
'pyhash>=0.6.2,<1',
'pyee>=1.0.2,<2',
'awscli>=1.10.21,<2'
],
tests_require = [
'psycopg2>=2.5.2,<3'
],
test_suite= 'nose.collector',
setup_requires=['nose>=1.3.0'],
data_files=[
('.', ['LICENSE', 'VERSION'])
],
# use_2to3=True,
classifiers=[
"Programming Language :: Python :: 2.7",
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"Operating System :: POSIX",
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)"],
)
|
Fix multiple modal example not showing up | import React, { PureComponent } from 'react';
import { action } from '@storybook/addon-actions';
import Button from '@ichef/gypcrete/src/Button';
import Modal from '@ichef/gypcrete/src/Modal';
import ModalHeader from './ModalHeader';
export default class ClosableModalExample extends PureComponent {
state ={
modalOpen: true
};
handleModalOpen = () => {
this.setState({ modalOpen: true });
}
handleModalClose = () => {
action('cancel')();
this.setState({ modalOpen: false });
}
render() {
const { children } = this.props;
const { modalOpen } = this.state;
const header = (
<ModalHeader
onCancel={this.handleModalClose} />
);
if (!modalOpen) {
return (
<div>
<Button
solid
color="blue"
onClick={this.handleModalOpen}
style={{ display: 'inline-block' }}
>
Open Modal
</Button>
</div>
);
}
return (
<Modal
header={header}
onClose={this.handleModalClose}
>
Modal content
{children}
</Modal>
);
}
}
export const MulitpleClosableModalExample = (props) => {
const { depth, modalProp } = props;
if (depth === 0) {
return false;
}
return (
<ClosableModalExample {...modalProp}>
<div>{depth}</div>
<MulitpleClosableModalExample depth={depth - 1} />
</ClosableModalExample>
);
};
| import React, { PureComponent } from 'react';
import { action } from '@storybook/addon-actions';
import Button from '@ichef/gypcrete/src/Button';
import Modal from '@ichef/gypcrete/src/Modal';
import ModalHeader from './ModalHeader';
export default class ClosableModalExample extends PureComponent {
state ={
modalOpen: true
};
handleModalOpen = () => {
this.setState({ modalOpen: true });
}
handleModalClose = () => {
action('cancel')();
this.setState({ modalOpen: false });
}
render() {
const { modalOpen } = this.state;
const header = (
<ModalHeader
onCancel={this.handleModalClose} />
);
if (!modalOpen) {
return (
<div>
<Button
solid
color="blue"
onClick={this.handleModalOpen}
style={{ display: 'inline-block' }}
>
Open Modal
</Button>
</div>
);
}
return (
<Modal
header={header}
onClose={this.handleModalClose}
>
Modal content
</Modal>
);
}
}
export const MulitpleClosableModalExample = (props) => {
const { depth, modalProp } = props;
if (depth === 0) {
return false;
}
return (
<ClosableModalExample {...modalProp}>
<div>{depth}</div>
<MulitpleClosableModalExample depth={depth - 1} />
</ClosableModalExample>
);
};
|
Drop unnecessary reference to popped elements to allow finalization through GC (XSTR-264).
git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@649 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e | package com.thoughtworks.xstream.core.util;
public final class FastStack {
private Object[] stack;
private int pointer;
public FastStack(int initialCapacity) {
stack = new Object[initialCapacity];
}
public Object push(Object value) {
if (pointer + 1 >= stack.length) {
resizeStack(stack.length * 2);
}
stack[pointer++] = value;
return value;
}
public void popSilently() {
stack[--pointer] = null;
}
public Object pop() {
final Object result = stack[--pointer];
stack[pointer] = null;
return result;
}
public Object peek() {
return pointer == 0 ? null : stack[pointer - 1];
}
public int size() {
return pointer;
}
public boolean hasStuff() {
return pointer > 0;
}
public Object get(int i) {
return stack[i];
}
private void resizeStack(int newCapacity) {
Object[] newStack = new Object[newCapacity];
System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity));
stack = newStack;
}
public String toString() {
StringBuffer result = new StringBuffer("[");
for (int i = 0; i < pointer; i++) {
if (i > 0) {
result.append(", ");
}
result.append(stack[i]);
}
result.append(']');
return result.toString();
}
}
| package com.thoughtworks.xstream.core.util;
public final class FastStack {
private Object[] stack;
private int pointer;
public FastStack(int initialCapacity) {
stack = new Object[initialCapacity];
}
public Object push(Object value) {
if (pointer + 1 >= stack.length) {
resizeStack(stack.length * 2);
}
stack[pointer++] = value;
return value;
}
public void popSilently() {
pointer--;
}
public Object pop() {
return stack[--pointer];
}
public Object peek() {
return pointer == 0 ? null : stack[pointer - 1];
}
public int size() {
return pointer;
}
public boolean hasStuff() {
return pointer > 0;
}
public Object get(int i) {
return stack[i];
}
private void resizeStack(int newCapacity) {
Object[] newStack = new Object[newCapacity];
System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity));
stack = newStack;
}
public String toString() {
StringBuffer result = new StringBuffer("[");
for (int i = 0; i < pointer; i++) {
if (i > 0) {
result.append(", ");
}
result.append(stack[i]);
}
result.append(']');
return result.toString();
}
}
|
Fix send message delayed when the message has conflict | package info.izumin.android.bletia;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import org.jdeferred.Promise;
import info.izumin.android.bletia.action.Action;
import info.izumin.android.bletia.wrapper.BluetoothGattWrapper;
/**
* Created by izumin on 9/14/15.
*/
public class BleMessageThread extends Handler {
private static final int DELAY_MILLIS = 10;
private final HandlerThread mHandlerThread;
private final BluetoothGattWrapper mGattWrapper;
private final BleActionStore mActionStore;
public BleMessageThread(HandlerThread handlerThread, BluetoothGattWrapper gattWrapper, BleActionStore actionStore) {
super(handlerThread.getLooper());
mHandlerThread = handlerThread;
mGattWrapper = gattWrapper;
mActionStore = actionStore;
}
public void stop() {
mHandlerThread.quitSafely();
}
public <T> Promise<T, BletiaException, Object> execute(Action<T> action) {
mActionStore.enqueue(action);
dispatchMessage(action.obtainMessage());
return action.getDeferred().promise();
}
@Override
public void handleMessage(Message msg) {
Action.Type type = Action.Type.valueOf(msg.what);
if (mActionStore.isRunning(type)) {
Message delayed = obtainMessage();
delayed.copyFrom(msg);
sendMessageDelayed(delayed, DELAY_MILLIS);
} else {
mActionStore.execute(type, mGattWrapper);
}
}
}
| package info.izumin.android.bletia;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import org.jdeferred.Promise;
import info.izumin.android.bletia.action.Action;
import info.izumin.android.bletia.wrapper.BluetoothGattWrapper;
/**
* Created by izumin on 9/14/15.
*/
public class BleMessageThread extends Handler {
private static final int DELAY_MILLIS = 10;
private final HandlerThread mHandlerThread;
private final BluetoothGattWrapper mGattWrapper;
private final BleActionStore mActionStore;
public BleMessageThread(HandlerThread handlerThread, BluetoothGattWrapper gattWrapper, BleActionStore actionStore) {
super(handlerThread.getLooper());
mHandlerThread = handlerThread;
mGattWrapper = gattWrapper;
mActionStore = actionStore;
}
public void stop() {
mHandlerThread.quitSafely();
}
public <T> Promise<T, BletiaException, Object> execute(Action<T> action) {
mActionStore.enqueue(action);
dispatchMessage(action.obtainMessage());
return action.getDeferred().promise();
}
@Override
public void handleMessage(Message msg) {
Action.Type type = Action.Type.valueOf(msg.what);
if (mActionStore.isRunning(type)) {
sendMessageDelayed(msg, DELAY_MILLIS);
} else {
mActionStore.execute(type, mGattWrapper);
}
}
}
|
Fix JSHint error in dashboard | 'use strict';
var angular = require('angular');
var directives = require('../scripts/modules').directives;
angular.module(directives.name).directive('dashboardWidget', function () {
return {
restrict: 'E',
template: '<outpatient-visualization options="options" height="height" width="width"></outpatient-visualization>',
scope: {
options: '=',
sizeX: '=',
sizeY: '='
},
compile: function () {
return {
// TODO Improve selector to get dashboard widget?
pre: function (scope, element) {
scope.$watchCollection('[sizeX, sizeY]', function () {
//TODO Adjust for margins, etc...
var lis = angular.element('li.dashboard-widget');
angular.forEach(lis, function (value) {
if (value.contains(element[0])) {
var parent = angular.element(value);
var height = parent.height();
var width = parent.width();
scope.options.height = scope.height = height - 30;//parent.height();// - 80;// - 20 - 80;
scope.options.width = scope.width = width - 30;//parent.width();// - 100;// - 20;
parent.find('.panel').css({
width: width,
height: height
})
.find('.panel-body').css({
width: width,
height: height - 50
});
}
});
});
}
};
}
};
});
| 'use strict';
var angular = require('angular');
var directives = require('../scripts/modules').directives;
angular.module(directives.name).directive('dashboardWidget', function () {
return {
restrict: 'E',
template: '<outpatient-visualization options="options" height="height" width="width"></outpatient-visualization>',
scope: {
options: '=',
sizeX: '=',
sizeY: '='
},
compile: function () {
return {
// TODO Improve selector to get dashboard widget?
pre: function (scope, element) {
scope.$watchCollection('[sizeX, sizeY]', function () {
//TODO Adjust for margins, etc...
var lis = angular.element('li.dashboard-widget');
angular.forEach(lis, function (value, key) {
if (value.contains(element[0])) {
var parent = angular.element(value);
var height = parent.height();
var width = parent.width();
scope.options.height = scope.height = height - 30;//parent.height();// - 80;// - 20 - 80;
scope.options.width = scope.width = width - 30;//parent.width();// - 100;// - 20;
parent.find('.panel').css({
width: width,
height: height
})
.find('.panel-body').css({
width: width,
height: height - 50
});
}
});
});
}
};
}
};
});
|
Add SITE_ID to test settings since contrib.sites is in INSTALLED_APPS. | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
| #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
Remove dependency on the future lib. | import django_rq
from ievv_opensource.ievv_batchframework.models import BatchOperation
from ievv_opensource.ievv_batchframework import batchregistry
import logging
class BatchActionGroupTask(object):
abstract = True
def run_actiongroup(self, actiongroup_name, batchoperation_id, **kwargs):
try:
batchoperation = BatchOperation.objects\
.get(id=batchoperation_id, status=BatchOperation.STATUS_UNPROCESSED)
except BatchOperation.DoesNotExist:
logging.warning('BatchOperation with id={} does not exist, or is already running.')
return
else:
batchoperation.mark_as_running()
registry = batchregistry.Registry.get_instance()
full_kwargs = {
'started_by': batchoperation.started_by,
'context_object': batchoperation.context_object,
}
full_kwargs.update(kwargs)
actiongroupresult = registry.get_actiongroup(actiongroup_name)\
.run_blocking(**full_kwargs)
batchoperation.finish(failed=actiongroupresult.failed,
output_data=actiongroupresult.to_dict())
@django_rq.job('default')
def default(**kwargs):
BatchActionGroupTask().run_actiongroup(**kwargs)
@django_rq.job('highpriority')
def highpriority(**kwargs):
BatchActionGroupTask().run_actiongroup(**kwargs)
| from __future__ import absolute_import
import django_rq
from ievv_opensource.ievv_batchframework.models import BatchOperation
from ievv_opensource.ievv_batchframework import batchregistry
import logging
class BatchActionGroupTask(object):
abstract = True
def run_actiongroup(self, actiongroup_name, batchoperation_id, **kwargs):
try:
batchoperation = BatchOperation.objects\
.get(id=batchoperation_id, status=BatchOperation.STATUS_UNPROCESSED)
except BatchOperation.DoesNotExist:
logging.warning('BatchOperation with id={} does not exist, or is already running.')
return
else:
batchoperation.mark_as_running()
registry = batchregistry.Registry.get_instance()
full_kwargs = {
'started_by': batchoperation.started_by,
'context_object': batchoperation.context_object,
}
full_kwargs.update(kwargs)
actiongroupresult = registry.get_actiongroup(actiongroup_name)\
.run_blocking(**full_kwargs)
batchoperation.finish(failed=actiongroupresult.failed,
output_data=actiongroupresult.to_dict())
@django_rq.job('default')
def default(**kwargs):
BatchActionGroupTask().run_actiongroup(**kwargs)
@django_rq.job('highpriority')
def highpriority(**kwargs):
BatchActionGroupTask().run_actiongroup(**kwargs)
|
Clean up spacing + use document ready | jQuery.fn.extend({
coverVid: function(width, height) {
$(document).ready(sizeVideo);
$(window).resize(sizeVideo);
var $this = this;
function sizeVideo() {
// Get parent element height and width
var parentHeight = $this.parent().height();
var parentWidth = $this.parent().width();
// Get native video width and height
var nativeWidth = width;
var nativeHeight = height;
// Get the scale factors
var heightScaleFactor = parentHeight / nativeHeight;
var widthScaleFactor = parentWidth / nativeWidth;
// Set necessary styles to position video "center center"
$this.css({
'position': 'absolute',
'top': '50%',
'left': '50%',
'-webkit-transform': 'translate(-50%, -50%)',
'-moz-transform': 'translate(-50%, -50%)',
'-ms-transform': 'translate(-50%, -50%)',
'-o-transform': 'translate(-50%, -50%)',
'transform': 'translate(-50%, -50%)',
});
// Set overflow hidden on parent element
$this.parent().css('overflow', 'hidden');
// Based on highest scale factor set width and height
if(widthScaleFactor > heightScaleFactor) {
$this.css({
'height': 'auto',
'width': parentWidth
});
} else {
$this.css({
'height': parentHeight,
'width': 'auto'
});
}
}
}
});
| jQuery.fn.extend({
coverVid: function(width, height) {
var $this = this;
$(window).on('resize load', function(){
// Get parent element height and width
var parentHeight = $this.parent().height();
var parentWidth = $this.parent().width();
// Get native video width and height
var nativeWidth = width;
var nativeHeight = height;
// Get the scale factors
var heightScaleFactor = parentHeight / nativeHeight;
var widthScaleFactor = parentWidth / nativeWidth;
// Set necessary styles to position video "center center"
$this.css({
'position': 'absolute',
'top': '50%',
'left': '50%',
'-webkit-transform': 'translate(-50%, -50%)',
'-moz-transform': 'translate(-50%, -50%)',
'-ms-transform': 'translate(-50%, -50%)',
'-o-transform': 'translate(-50%, -50%)',
'transform': 'translate(-50%, -50%)',
});
// Set overflow hidden on parent element
$this.parent().css('overflow', 'hidden');
// Based on highest scale factor set width and height
if(widthScaleFactor > heightScaleFactor) {
$this.css({
'height': 'auto',
'width': parentWidth
});
} else {
$this.css({
'height': parentHeight,
'width': 'auto'
});
}
});
}
}); |
Remove only test from button | import {expect} from 'chai'
import {describeComponent} from 'ember-mocha'
import {beforeEach, afterEach, it, describe} from 'mocha'
describeComponent(
'frost-button',
'FrostButtonComponent',
{
unit: true
},
function () {
let component
beforeEach(function () {
component = this.subject()
})
it('includes className frost-button', function () {
expect(component.classNames).to.include('frost-button')
})
describe('._getOnClickHandler()', function () {
beforeEach(function () {
component.attrs = {}
})
afterEach(function () {
component.attrs = null
})
it('returns handler when onClick attribute is a function', function () {
component.attrs.onClick = function () {}
expect(component._getOnClickHandler()).to.be.a('function')
})
it('returns handler when onClick attribute is an mutable cell object', function () {
component.attrs.onClick = {
value: function () {}
}
expect(component._getOnClickHandler()).to.be.a('function')
})
it('doesn\'t return handler when onClick is empty', function () {
component.attrs.onClick = undefined
expect(component._getOnClickHandler()).to.be.an('undefined')
})
it('doesn\'t return handler when onClick is empty object', function () {
component.attrs.onClick = {}
expect(component._getOnClickHandler()).to.be.an('undefined')
})
})
}
)
| import {expect} from 'chai'
import {describeComponent} from 'ember-mocha'
import {beforeEach, afterEach, it, describe} from 'mocha'
describeComponent.only(
'frost-button',
'FrostButtonComponent',
{
unit: true
},
function () {
let component
beforeEach(function () {
component = this.subject()
})
it('includes className frost-button', function () {
expect(component.classNames).to.include('frost-button')
})
describe('._getOnClickHandler()', function () {
beforeEach(function () {
component.attrs = {}
})
afterEach(function () {
component.attrs = null
})
it('returns handler when onClick attribute is a function', function () {
component.attrs.onClick = function () {}
expect(component._getOnClickHandler()).to.be.a('function')
})
it('returns handler when onClick attribute is an mutable cell object', function () {
component.attrs.onClick = {
value: function () {}
}
expect(component._getOnClickHandler()).to.be.a('function')
})
it('doesn\'t return handler when onClick is empty', function () {
component.attrs.onClick = undefined
expect(component._getOnClickHandler()).to.be.an('undefined')
})
it('doesn\'t return handler when onClick is empty object', function () {
component.attrs.onClick = {}
expect(component._getOnClickHandler()).to.be.an('undefined')
})
})
}
)
|
Add comment about SScursor and nextset. | from pymysql.tests import base
from pymysql import util
try:
import unittest2 as unittest
except ImportError:
import unittest
class TestNextset(base.PyMySQLTestCase):
def setUp(self):
super(TestNextset, self).setUp()
self.con = self.connections[0]
def test_nextset(self):
cur = self.con.cursor()
cur.execute("SELECT 1; SELECT 2;")
self.assertEqual([(1,)], list(cur))
r = cur.nextset()
self.assertTrue(r)
self.assertEqual([(2,)], list(cur))
self.assertIsNone(cur.nextset())
def test_skip_nextset(self):
cur = self.con.cursor()
cur.execute("SELECT 1; SELECT 2;")
self.assertEqual([(1,)], list(cur))
cur.execute("SELECT 42")
self.assertEqual([(42,)], list(cur))
@unittest.expectedFailure
def test_multi_cursor(self):
cur1 = self.con.cursor()
cur2 = self.con.cursor()
cur1.execute("SELECT 1; SELECT 2;")
cur2.execute("SELECT 42")
self.assertEqual([(1,)], list(cur1))
self.assertEqual([(42,)], list(cur2))
r = cur1.nextset()
self.assertTrue(r)
self.assertEqual([(2,)], list(cur1))
self.assertIsNone(cur1.nextset())
#TODO: How about SSCursor and nextset?
# It's very hard to implement correctly...
| from pymysql.tests import base
from pymysql import util
try:
import unittest2 as unittest
except ImportError:
import unittest
class TestNextset(base.PyMySQLTestCase):
def setUp(self):
super(TestNextset, self).setUp()
self.con = self.connections[0]
def test_nextset(self):
cur = self.con.cursor()
cur.execute("SELECT 1; SELECT 2;")
self.assertEqual([(1,)], list(cur))
r = cur.nextset()
self.assertTrue(r)
self.assertEqual([(2,)], list(cur))
self.assertIsNone(cur.nextset())
def test_skip_nextset(self):
cur = self.con.cursor()
cur.execute("SELECT 1; SELECT 2;")
self.assertEqual([(1,)], list(cur))
cur.execute("SELECT 42")
self.assertEqual([(42,)], list(cur))
@unittest.expectedFailure
def test_multi_cursor(self):
cur1 = self.con.cursor()
cur2 = self.con.cursor()
cur1.execute("SELECT 1; SELECT 2;")
cur2.execute("SELECT 42")
self.assertEqual([(1,)], list(cur1))
self.assertEqual([(42,)], list(cur2))
r = cur1.nextset()
self.assertTrue(r)
self.assertEqual([(2,)], list(cur1))
self.assertIsNone(cur1.nextset())
|
ZON-4007: Declare dependency (belongs to commit:6791185) | from setuptools import setup, find_packages
setup(
name='zeit.push',
version='1.21.0.dev0',
author='gocept, Zeit Online',
author_email='[email protected]',
url='http://www.zeit.de/',
description="Sending push notifications through various providers",
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
zip_safe=False,
license='BSD',
namespace_packages=['zeit'],
install_requires=[
'fb',
'gocept.testing',
'grokcore.component',
'mock',
'pytz',
'requests',
'setuptools',
'tweepy',
'urbanairship >= 1.0',
'zc.sourcefactory',
'zeit.cms >= 2.102.0.dev0',
'zeit.content.article',
'zeit.content.image',
'zeit.content.text',
'zeit.objectlog',
'zope.app.appsetup',
'zope.component',
'zope.formlib',
'zope.interface',
'zope.schema',
],
entry_points={
'console_scripts': [
'facebook-access-token = zeit.push.facebook:create_access_token',
'ua-payload-doc = zeit.push.urbanairship:print_payload_documentation',
],
'fanstatic.libraries': [
'zeit_push=zeit.push.browser.resources:lib',
],
},
)
| from setuptools import setup, find_packages
setup(
name='zeit.push',
version='1.21.0.dev0',
author='gocept, Zeit Online',
author_email='[email protected]',
url='http://www.zeit.de/',
description="Sending push notifications through various providers",
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
zip_safe=False,
license='BSD',
namespace_packages=['zeit'],
install_requires=[
'fb',
'gocept.testing',
'grokcore.component',
'mock',
'pytz',
'requests',
'setuptools',
'tweepy',
'urbanairship >= 1.0',
'zc.sourcefactory',
'zeit.cms >= 2.102.0.dev0',
'zeit.content.article',
'zeit.content.image',
'zeit.objectlog',
'zope.app.appsetup',
'zope.component',
'zope.formlib',
'zope.interface',
'zope.schema',
],
entry_points={
'console_scripts': [
'facebook-access-token = zeit.push.facebook:create_access_token',
'ua-payload-doc = zeit.push.urbanairship:print_payload_documentation',
],
'fanstatic.libraries': [
'zeit_push=zeit.push.browser.resources:lib',
],
},
)
|
Update tile culling to factor in the new scale | var CullTiles = function (layer, camera, outputArray)
{
if (outputArray === undefined) { outputArray = []; }
outputArray.length = 0;
var tilemapLayer = layer.tilemapLayer;
var mapData = layer.data;
var mapWidth = layer.width;
var mapHeight = layer.height;
var left = (camera.scrollX * tilemapLayer.scrollFactorX) - tilemapLayer.x;
var top = (camera.scrollY * tilemapLayer.scrollFactorY) - tilemapLayer.y;
var tileWidth = layer.tileWidth * tilemapLayer.scaleX;
var tileHeight = layer.tileHeight * tilemapLayer.scaleY;
for (var row = 0; row < mapHeight; ++row)
{
for (var col = 0; col < mapWidth; ++col)
{
var tile = mapData[row][col];
if (tile === null || (tile.index <= 0 && tilemapLayer.skipIndexZero)) { continue; }
var tileX = tile.x * tileWidth - left;
var tileY = tile.y * tileHeight - top;
var cullW = camera.width + tileWidth;
var cullH = camera.height + tileHeight;
if (tile.visible &&
tileX > -tileWidth && tileY > -tileHeight &&
tileX < cullW && tileY < cullH)
{
outputArray.push(tile);
}
}
}
return outputArray;
};
module.exports = CullTiles;
| var CullTiles = function (layer, camera, outputArray)
{
if (outputArray === undefined) { outputArray = []; }
outputArray.length = 0;
var tilemapLayer = layer.tilemapLayer;
var mapData = layer.data;
var mapWidth = layer.width;
var mapHeight = layer.height;
var left = (camera.scrollX * tilemapLayer.scrollFactorX) - tilemapLayer.x;
var top = (camera.scrollY * tilemapLayer.scrollFactorY) - tilemapLayer.y;
for (var row = 0; row < mapHeight; ++row)
{
for (var col = 0; col < mapWidth; ++col)
{
var tile = mapData[row][col];
if (tile === null || (tile.index <= 0 && tilemapLayer.skipIndexZero)) { continue; }
var tileX = tile.worldX - left;
var tileY = tile.worldY - top;
var cullW = camera.width + tile.width;
var cullH = camera.height + tile.height;
if (tile.visible &&
tileX > -tile.width && tileY > -tile.height &&
tileX < cullW && tileY < cullH)
{
outputArray.push(tile);
}
}
}
return outputArray;
};
module.exports = CullTiles;
|
Fix require to use new mauth package | var mAuthMint = require("mauth").mAuthMint;
module.exports = function(options) {
return function getMacaroonUserSecret(req, res, next) {
if(typeof options.collection !== "undefined" && options.collection !== ""){
var userId = "";
if(req.method == "GET" || req.method == "DELETE"){
userId = req.query.userId;
}
else{
userId = req.body.userId;
}
if(typeof userId !== "undefined" && userId !== ""){
var collection = req.db.collection(options.collection);
collection.findOne({userId: userId})
.then(function(user){
if(user !== null){
console.log("Setting macaroonUserSecret for user: " + user.userId);
var macaroonSecret = mAuthMint.calculateMacaroonSecret(user.macaroonSecret);
req.macaroonSecret = macaroonSecret;
}
else{
console.log("Setting macaroonUserSecret to null for user");
req.macaroonUserSecret = null;
}
next();
}).catch(function (error) {
console.log("Promise rejected:");
console.log(error);
res.sendStatus("401");
});
}
else{
console.log("userId not found. Setting macaroonUserSecret to null: " + userId);
req.macaroonUserSecret = null;
next();
}
}
else{
var error = new Error("Error configuring getMacaroonUserSecret")
console.log(error);
res.sendStatus("401");
}
};
}; | var MacaroonAuthUtils = require("../utils/macaroon_auth.js");
module.exports = function(options) {
return function getMacaroonUserSecret(req, res, next) {
if(typeof options.collection !== "undefined" && options.collection !== ""){
var userId = "";
if(req.method == "GET" || req.method == "DELETE"){
userId = req.query.userId;
}
else{
userId = req.body.userId;
}
if(typeof userId !== "undefined" && userId !== ""){
var collection = req.db.collection(options.collection);
collection.findOne({userId: userId})
.then(function(user){
if(user !== null){
console.log("Setting macaroonUserSecret for user: " + user.userId);
var macaroonSecret = MacaroonAuthUtils.calculateMacaroonSecret(user.macaroonSecret);
req.macaroonSecret = macaroonSecret;
}
else{
console.log("Setting macaroonUserSecret to null for user");
req.macaroonUserSecret = null;
}
next();
}).catch(function (error) {
console.log("Promise rejected:");
console.log(error);
res.sendStatus("401");
});
}
else{
console.log("userId not found. Setting macaroonUserSecret to null: " + userId);
req.macaroonUserSecret = null;
next();
}
}
else{
var error = new Error("Error configuring getMacaroonUserSecret")
console.log(error);
res.sendStatus("401");
}
};
}; |
Remove unneeded nav checks for forward/back buttons. | browser.on("init", function () {
"use strict";
// Show the refresh button
this.showRefresh = () => {
this.stopButton.classList.remove("stopButton");
this.stopButton.classList.add("refreshButton");
this.stopButton.title = "Refresh the page";
};
// Show the stop button
this.showStop = () => {
this.stopButton.classList.add("stopButton");
this.stopButton.classList.remove("refreshButton");
this.stopButton.title = "Stop loading";
};
// Listen for the stop/refresh button to stop navigation/refresh the page
this.stopButton.addEventListener("click", () => {
if (this.loading) {
this.webview.stop();
this.showProgressRing(false);
this.showRefresh();
}
else {
this.webview.refresh();
}
});
// Update the navigation state
this.updateNavState = () => {
this.backButton.disabled = !this.webview.canGoBack;
this.forwardButton.disabled = !this.webview.canGoForward;
};
// Listen for the back button to navigate backwards
this.backButton.addEventListener("click", () => this.webview.goBack());
// Listen for the forward button to navigate forwards
this.forwardButton.addEventListener("click", () => this.webview.goForward());
});
| browser.on("init", function () {
"use strict";
// Show the refresh button
this.showRefresh = () => {
this.stopButton.classList.remove("stopButton");
this.stopButton.classList.add("refreshButton");
this.stopButton.title = "Refresh the page";
};
// Show the stop button
this.showStop = () => {
this.stopButton.classList.add("stopButton");
this.stopButton.classList.remove("refreshButton");
this.stopButton.title = "Stop loading";
};
// Listen for the stop/refresh button to stop navigation/refresh the page
this.stopButton.addEventListener("click", () => {
if (this.loading) {
this.webview.stop();
this.showProgressRing(false);
this.showRefresh();
}
else {
this.webview.refresh();
}
});
// Update the navigation state
this.updateNavState = () => {
this.backButton.disabled = !this.webview.canGoBack;
this.forwardButton.disabled = !this.webview.canGoForward;
};
// Listen for the back button to navigate backwards
this.backButton.addEventListener("click", () => {
if (this.webview.canGoBack) {
this.webview.goBack();
}
});
// Listen for the forward button to navigate forwards
this.forwardButton.addEventListener("click", () => {
if (this.webview.canGoForward) {
this.webview.goForward();
}
});
});
|
Save creatorId as well for geometries
This is to keep track of the creator, even when the provenance
is not the user.
Signed-off-by: Patrick Avery <[email protected]> | from bson.objectid import ObjectId
from girder.models.model_base import AccessControlledModel
from girder.constants import AccessType
from .molecule import Molecule as MoleculeModel
class Geometry(AccessControlledModel):
def __init__(self):
super(Geometry, self).__init__()
def initialize(self):
self.name = 'geometry'
self.ensureIndex('moleculeId')
self.exposeFields(level=AccessType.READ, fields=(
'_id', 'moleculeId', 'cjson', 'provenanceType', 'provenanceId'))
def validate(self, doc):
# If we have a moleculeId ensure it is valid.
if 'moleculeId' in doc:
mol = MoleculeModel().load(doc['moleculeId'], force=True)
doc['moleculeId'] = mol['_id']
return doc
def create(self, user, moleculeId, cjson, provenanceType=None,
provenanceId=None, public=False):
geometry = {
'moleculeId': moleculeId,
'cjson': cjson,
'creatorId': user['_id']
}
if provenanceType is not None:
geometry['provenanceType'] = provenanceType
if provenanceId is not None:
geometry['provenanceId'] = provenanceId
self.setUserAccess(geometry, user=user, level=AccessType.ADMIN)
if public:
self.setPublic(geometry, True)
return self.save(geometry)
def find_geometries(self, moleculeId, user=None):
query = {
'moleculeId': ObjectId(moleculeId)
}
return self.findWithPermissions(query, user=user)
| from bson.objectid import ObjectId
from girder.models.model_base import AccessControlledModel
from girder.constants import AccessType
from .molecule import Molecule as MoleculeModel
class Geometry(AccessControlledModel):
def __init__(self):
super(Geometry, self).__init__()
def initialize(self):
self.name = 'geometry'
self.ensureIndex('moleculeId')
self.exposeFields(level=AccessType.READ, fields=(
'_id', 'moleculeId', 'cjson', 'provenanceType', 'provenanceId'))
def validate(self, doc):
# If we have a moleculeId ensure it is valid.
if 'moleculeId' in doc:
mol = MoleculeModel().load(doc['moleculeId'], force=True)
doc['moleculeId'] = mol['_id']
return doc
def create(self, user, moleculeId, cjson, provenanceType=None,
provenanceId=None, public=False):
geometry = {
'moleculeId': moleculeId,
'cjson': cjson
}
if provenanceType is not None:
geometry['provenanceType'] = provenanceType
if provenanceId is not None:
geometry['provenanceId'] = provenanceId
self.setUserAccess(geometry, user=user, level=AccessType.ADMIN)
if public:
self.setPublic(geometry, True)
return self.save(geometry)
def find_geometries(self, moleculeId, user=None):
query = {
'moleculeId': ObjectId(moleculeId)
}
return self.findWithPermissions(query, user=user)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.