text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Normalize usernames properly to prevent clashes from guest accounts
Guest accounts can have non berkeley.edu emails, and might
get access to a berkeley.edu user's home directory. This
will prevent that. | from traitlets import List, Unicode
from oauthenticator.generic import GenericOAuthenticator
from tornado import gen
canvas_site = 'https://ucberkeley.test.instructure.com/'
class CanvasAuthenticator(GenericOAuthenticator):
allowed_email_domains = List(
[],
config=True,
help="""
List of domains whose users are authorized to log in.
This relies on the primary email id set in canvas for the user
"""
)
canvas_url = Unicode(
'',
config=True,
help="""
URL to canvas installation to use for authentication.
Must have a trailing slash
"""
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.canvas_url:
raise ValueError('c.CanvasAuthenticator.canvas_url must be set')
# canvas_url must have a trailing slash
if self.canvas_url[-1] != '/':
raise ValueError('c.CanvasAuthenticator.canvas_url must have a trailing slash')
self.token_url = f'{self.canvas_url}login/oauth2/token'
self.userdata_url = f'{self.canvas_url}api/v1/users/self/profile'
self.extra_params = {
'client_id': self.client_id,
'client_secret': self.client_secret
}
def normalize_username(self,username):
username = username.lower()
# To make life easier & match usernames with existing users who were
# created with google auth, we want to strip the domain name. If not,
# we use the full email as the official user name
if username.endswith('@berkeley.edu'):
return username.split('@')[0]
return username
| from traitlets import List, Unicode
from oauthenticator.generic import GenericOAuthenticator
from tornado import gen
canvas_site = 'https://ucberkeley.test.instructure.com/'
class CanvasAuthenticator(GenericOAuthenticator):
allowed_email_domains = List(
[],
config=True,
help="""
List of domains whose users are authorized to log in.
This relies on the primary email id set in canvas for the user
"""
)
canvas_url = Unicode(
'',
config=True,
help="""
URL to canvas installation to use for authentication.
Must have a trailing slash
"""
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.canvas_url:
raise ValueError('c.CanvasAuthenticator.canvas_url must be set')
# canvas_url must have a trailing slash
if self.canvas_url[-1] != '/':
raise ValueError('c.CanvasAuthenticator.canvas_url must have a trailing slash')
self.token_url = f'{self.canvas_url}login/oauth2/token'
self.userdata_url = f'{self.canvas_url}api/v1/users/self/profile'
self.extra_params = {
'client_id': self.client_id,
'client_secret': self.client_secret
}
def normalize_username(self,username):
username = username.lower()
# FIXME: allow
username = username.split('@')[0]
return username |
Add new line below each snippet | define([
'text!snippet-collapsible',
'text!snippet-ticks',
'text!snippet-callout',
'text!snippet-add-action',
'text!snippet-video',
'text!snippet-action-item'
], function (
collapsibleSnippet,
ticksSnippet,
calloutSnippet,
addActionSnippet,
videoSnippet,
actionItemSnippet
) {
'use strict';
/**
* This plugin adds each mastalk md snippet
*/
return function (type) {
return function (scribe) {
var commandName = "mastalk_" + type;
var mastalkCommand = new scribe.api.Command('insertHTML');
mastalkCommand.execute = function () {
scribe.insertPlainText(this.getType()[type].trim() + '\n\n');
};
mastalkCommand.getType = function () {
return {
actionItem: actionItemSnippet,
addAction: addActionSnippet,
collapsible: collapsibleSnippet,
callout: calloutSnippet,
ticks: ticksSnippet,
video: videoSnippet
};
};
mastalkCommand.queryState = function () {
return true;
};
mastalkCommand.queryEnabled = function () {
return true;
};
scribe.commands[commandName] = mastalkCommand;
};
};
});
| define([
'text!snippet-collapsible',
'text!snippet-ticks',
'text!snippet-callout',
'text!snippet-add-action',
'text!snippet-video',
'text!snippet-action-item'
], function (
collapsibleSnippet,
ticksSnippet,
calloutSnippet,
addActionSnippet,
videoSnippet,
actionItemSnippet
) {
'use strict';
/**
* This plugin adds each mastalk md snippet
*/
return function (type) {
return function (scribe) {
var commandName = "mastalk_" + type;
var mastalkCommand = new scribe.api.Command('insertHTML');
mastalkCommand.execute = function () {
scribe.insertPlainText(this.getType()[type].trim());
};
mastalkCommand.getType = function () {
return {
actionItem: actionItemSnippet,
addAction: addActionSnippet,
collapsible: collapsibleSnippet,
callout: calloutSnippet,
ticks: ticksSnippet,
video: videoSnippet
};
};
mastalkCommand.queryState = function () {
return true;
};
mastalkCommand.queryEnabled = function () {
return true;
};
scribe.commands[commandName] = mastalkCommand;
};
};
});
|
Fix "Python :: 2" being listed twice in pypi classifiers | #!/usr/bin/env python
from setuptools import setup
setup(
name='clize',
version='3.0a2',
description='Command-line argument parsing for Python, without the effort',
license='MIT',
url='https://github.com/epsy/clize',
author='Yann Kaiser',
author_email='[email protected]',
install_requires=['six', 'sigtools >= 0.1b1'],
extras_require={
':python_version in "2.6"': ['ordereddict'],
},
packages=('clize', 'clize.extra'),
test_suite='clize.tests',
keywords=[
'CLI', 'options', 'arguments', 'getopts', 'getopt', 'argparse',
'introspection', 'flags', 'decorator', 'subcommands',
],
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Natural Language :: English",
"Operating System :: OS Independent",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Software Development :: User Interfaces",
],
)
| #!/usr/bin/env python
from setuptools import setup
setup(
name='clize',
version='3.0a2',
description='Command-line argument parsing for Python, without the effort',
license='MIT',
url='https://github.com/epsy/clize',
author='Yann Kaiser',
author_email='[email protected]',
install_requires=['six', 'sigtools >= 0.1b1'],
extras_require={
':python_version in "2.6"': ['ordereddict'],
},
packages=('clize', 'clize.extra'),
test_suite='clize.tests',
keywords=[
'CLI', 'options', 'arguments', 'getopts', 'getopt', 'argparse',
'introspection', 'flags', 'decorator', 'subcommands',
],
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Natural Language :: English",
"Operating System :: OS Independent",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Software Development :: User Interfaces",
],
)
|
Update author email to Spirent support. | import os, sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def main():
setup(
name='stcrestclient',
version= '1.8.3',
author='Andrew Gillis',
author_email='[email protected]',
url='https://github.com/Spirent/py-stcrestclient',
description='stcrestclient: Client modules for STC ReST API',
long_description = 'See https://github.com/Spirent/py-stcrestclient#python-stc-rest-api-client-stcrestclient',
license='http://www.opensource.org/licenses/mit-license.php',
keywords='Spirent TestCenter API',
classifiers=['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Topic :: Software Development :: Libraries',
'Topic :: Utilities',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3'],
packages=['stcrestclient'],
entry_points={
'console_scripts': [
'tccsh = stcrestclient.tccsh:main',
'stcinfo = stcrestclient.systeminfo:main'],
},
install_requires=['requests>=2.7'],
zip_safe=True,
)
if __name__ == '__main__':
main()
| import os, sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def main():
setup(
name='stcrestclient',
version= '1.8.3',
author='Andrew Gillis',
author_email='[email protected]',
url='https://github.com/Spirent/py-stcrestclient',
description='stcrestclient: Client modules for STC ReST API',
long_description = 'See https://github.com/Spirent/py-stcrestclient#python-stc-rest-api-client-stcrestclient',
license='http://www.opensource.org/licenses/mit-license.php',
keywords='Spirent TestCenter API',
classifiers=['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Topic :: Software Development :: Libraries',
'Topic :: Utilities',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3'],
packages=['stcrestclient'],
entry_points={
'console_scripts': [
'tccsh = stcrestclient.tccsh:main',
'stcinfo = stcrestclient.systeminfo:main'],
},
install_requires=['requests>=2.7'],
zip_safe=True,
)
if __name__ == '__main__':
main()
|
Remove grids from templates where not needed | <?php
global $post;
$items = get_field('items', $module->ID);
?>
<div class="box box-panel">
<h4 class="box-title"><?php echo $module->post_title; ?></h4>
<ul>
<?php foreach ($items as $item) : ?>
<?php if ($item['type'] == 'external') : ?>
<li>
<a class="link-item link-item-outbound" href="<?php echo $item['link_external']; ?>" target="_blank"><?php echo $item['title'] ?></a>
</li>
<?php elseif ($item['type'] == 'internal') : ?>
<li>
<a class="link-item" href="<?php echo get_permalink($item['link_internal']->ID); ?>"><?php echo (!empty($item['title'])) ? $item['title'] : $item['link_internal']->post_title; ?>
<?php if ($item['date'] === true) : ?>
<span class="date pull-right text-sm text-dark-gray"><?php echo date('Y-m-d', strtotime($item['link_internal']->post_date)); ?></span>
<?php endif; ?>
</a>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
</div>
| <?php
global $post;
$items = get_field('items', $module->ID);
?>
<div class="grid">
<div class="grid-lg-12">
<div class="box box-panel">
<h4 class="box-title"><?php echo $module->post_title; ?></h4>
<ul>
<?php foreach ($items as $item) : ?>
<?php if ($item['type'] == 'external') : ?>
<li>
<a class="link-item link-item-outbound" href="<?php echo $item['link_external']; ?>" target="_blank"><?php echo $item['title'] ?></a>
</li>
<?php elseif ($item['type'] == 'internal') : ?>
<li>
<a class="link-item" href="<?php echo get_permalink($item['link_internal']->ID); ?>"><?php echo (!empty($item['title'])) ? $item['title'] : $item['link_internal']->post_title; ?>
<?php if ($item['date'] === true) : ?>
<span class="date pull-right text-sm text-dark-gray"><?php echo date('Y-m-d', strtotime($item['link_internal']->post_date)); ?></span>
<?php endif; ?>
</a>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
</div>
</div>
</div>
|
Make Data match the Extension API. | <?php
namespace ComplexPie;
class Data extends Extension
{
protected static $static_ext = array();
public static function add_static_extension($extpoint, $ext, $priority)
{
if ($extpoint === 'get' && !is_callable($ext))
{
throw new \InvalidArgumentException("$ext is not callable");
}
parent::add_static_extension($extpoint, $ext, $priority);
}
public function add_extension($extpoint, $ext, $priority)
{
if ($extpoint === 'get' && !is_callable($ext))
{
throw new \InvalidArgumentException("$ext is not callable");
}
parent::add_extension($extpoint, $ext, $priority);
}
/**
* @todo This should cope with things that return an array and merge them
*/
public function __get($name)
{
foreach ($this->get_extensions('get') as $extension)
{
if (($return = $extension($this->dom, $name)) !== null)
{
return $return;
}
}
if (method_exists($this, "get_$name"))
{
return call_user_func(array($this, "get_$name"));
}
trigger_error('Undefined property: ' . get_class($this) . '::' . $name, E_USER_NOTICE);
return null;
}
}
Data::add_static_extension_point('get');
| <?php
namespace ComplexPie;
class Data extends Extension
{
protected static $static_ext = array();
public static function add_static_extension($extpoint, $ext, $priority)
{
if ($extpoint === 'get' && !is_callable($ext))
{
throw new \InvalidArgumentException("$ext is not callable");
}
parent::add_static_extension($extpoint, $ext, $priority);
}
public function add_extension($extpoint, $ext, $priority)
{
if ($extpoint === 'get' && !is_callable($ext))
{
throw new \InvalidArgumentException("$ext is not callable");
}
parent::add_extension($extpoint, $ext, $priority);
}
/**
* @todo This should cope with things that return an array and merge them
*/
public function __get($name)
{
foreach ($this->get_extensions('get') as $extension => $priority)
{
if (($return = $extension($this->dom, $name)) !== null)
{
return $return;
}
}
if (method_exists($this, "get_$name"))
{
return call_user_func(array($this, "get_$name"));
}
trigger_error('Undefined property: ' . get_class($this) . '::' . $name, E_USER_NOTICE);
return null;
}
}
Data::add_static_extension_point('get');
|
[docs] Fix small coding style issue | import React from 'react';
import {Tabs, Tab} from 'material-ui/Tabs';
const styles = {
headline: {
fontSize: 24,
paddingTop: 16,
marginBottom: 12,
fontWeight: 400,
},
};
export default class TabsExampleControlled extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 'a',
};
}
handleChange = (value) => {
this.setState({
value: value,
});
};
render() {
return (
<Tabs
value={this.state.value}
onChange={this.handleChange}
>
<Tab label="Tab A" value="a">
<div>
<h2 style={styles.headline}>Controllable Tab A</h2>
<p>
Tabs are also controllable if you want to programmatically pass them their values.
This allows for more functionality in Tabs such as not
having any Tab selected or assigning them different values.
</p>
</div>
</Tab>
<Tab label="Tab B" value="b">
<div>
<h2 style={styles.headline}>Controllable Tab B</h2>
<p>
This is another example of a controllable tab. Remember, if you
use controllable Tabs, you need to give all of your tabs values or else
you wont be able to select them.
</p>
</div>
</Tab>
</Tabs>
);
}
}
| import React from 'react';
import {Tabs, Tab} from 'material-ui/Tabs';
const styles = {
headline: {
fontSize: 24,
paddingTop: 16,
marginBottom: 12,
fontWeight: 400,
},
};
export default class TabsExampleControlled extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 'a',
};
}
handleChange = (value) => {
this.setState({
value: value,
});
};
render() {
return (
<Tabs
value={this.state.value}
onChange={this.handleChange}
>
<Tab label="Tab A" value="a" >
<div>
<h2 style={styles.headline}>Controllable Tab A</h2>
<p>
Tabs are also controllable if you want to programmatically pass them their values.
This allows for more functionality in Tabs such as not
having any Tab selected or assigning them different values.
</p>
</div>
</Tab>
<Tab label="Tab B" value="b">
<div>
<h2 style={styles.headline}>Controllable Tab B</h2>
<p>
This is another example of a controllable tab. Remember, if you
use controllable Tabs, you need to give all of your tabs values or else
you wont be able to select them.
</p>
</div>
</Tab>
</Tabs>
);
}
}
|
Remove inspector left over from module tests. |
function runTests(testType, BABYLON, GUI) {
console.log("running tests");
describe(testType + ' tests', function () {
it("should have BABYLON loaded", function () {
assert.isDefined(BABYLON);
})
it("should have GUI loaded", function () {
assert.isDefined(GUI);
})
it("should have BABYLON.GLTF2 loaded", function () {
assert.isDefined(BABYLON.GLTF2);
})
var subject;
/**
* Create a nu engine subject before each test.
*/
beforeEach(function () {
subject = new BABYLON.NullEngine({
renderHeight: 256,
renderWidth: 256,
textureSize: 256,
deterministicLockstep: false,
lockstepMaxSteps: 1
});
});
/**
* This test is more an integration test than a regular unit test but highlights how to rely
* on the BABYLON.NullEngine in order to create complex test cases.
*/
describe('#GLTF', function () {
it('should load BoomBox GLTF', function (done) {
mocha.timeout(10000);
var scene = new BABYLON.Scene(subject);
BABYLON.SceneLoader.Append("/Playground/scenes/BoomBox/", "BoomBox.gltf", scene, function () {
scene.meshes.length.should.be.equal(2);
scene.materials.length.should.be.equal(1);
scene.multiMaterials.length.should.be.equal(0);
done();
});
});
});
});
} |
function runTests(testType, BABYLON, GUI, INSPECTOR) {
console.log("running tests");
describe(testType + ' tests', function () {
it("should have BABYLON loaded", function () {
assert.isDefined(BABYLON);
})
it("should have GUI loaded", function () {
assert.isDefined(GUI);
})
it("should have BABYLON.GLTF2 loaded", function () {
assert.isDefined(BABYLON.GLTF2);
})
var subject;
/**
* Create a nu engine subject before each test.
*/
beforeEach(function () {
subject = new BABYLON.NullEngine({
renderHeight: 256,
renderWidth: 256,
textureSize: 256,
deterministicLockstep: false,
lockstepMaxSteps: 1
});
});
/**
* This test is more an integration test than a regular unit test but highlights how to rely
* on the BABYLON.NullEngine in order to create complex test cases.
*/
describe('#GLTF', function () {
it('should load BoomBox GLTF', function (done) {
mocha.timeout(10000);
var scene = new BABYLON.Scene(subject);
BABYLON.SceneLoader.Append("/Playground/scenes/BoomBox/", "BoomBox.gltf", scene, function () {
scene.meshes.length.should.be.equal(2);
scene.materials.length.should.be.equal(1);
scene.multiMaterials.length.should.be.equal(0);
done();
});
});
});
});
} |
Enable distinct results for calendar preview | import {
DEFAULT_LIMIT,
DEFAULT_OFFSET,
} from './base'
import {
EventBelongsToManyImage,
EventBelongsToPlace,
EventHasManySlots,
} from '../database/associations'
import Event from '../models/event'
export default {
findAll: (req, res, next) => {
const {
limit = DEFAULT_LIMIT,
offset = DEFAULT_OFFSET,
} = req.query
return Event.findAndCountAll({
distinct: true,
include: [
EventBelongsToManyImage,
EventHasManySlots, {
association: EventBelongsToPlace,
required: true,
where: {
isPublic: true,
},
},
],
limit,
offset,
where: {
isPublic: true,
},
order: [
[
EventHasManySlots,
'from',
'ASC',
],
],
})
.then(result => {
res.json({
data: result.rows,
limit: parseInt(limit, 10),
offset: parseInt(offset, 10),
total: result.count,
})
})
.catch(err => next(err))
},
}
| import {
DEFAULT_LIMIT,
DEFAULT_OFFSET,
} from './base'
import {
EventBelongsToManyImage,
EventBelongsToPlace,
EventHasManySlots,
} from '../database/associations'
import Event from '../models/event'
export default {
findAll: (req, res, next) => {
const {
limit = DEFAULT_LIMIT,
offset = DEFAULT_OFFSET,
} = req.query
return Event.findAndCountAll({
include: [
EventBelongsToManyImage,
EventHasManySlots, {
association: EventBelongsToPlace,
required: true,
where: {
isPublic: true,
},
},
],
limit,
offset,
where: {
isPublic: true,
},
order: [
[
EventHasManySlots,
'from',
'ASC',
],
],
})
.then(result => {
res.json({
data: result.rows,
limit: parseInt(limit, 10),
offset: parseInt(offset, 10),
total: result.count,
})
})
.catch(err => next(err))
},
}
|
Use json library instead of eval. | import sys
import caching
import urllib
import urllib2
import re
import json
from pyquery import PyQuery as p
try: cache = caching.get_cache('tnrs')
except: cache = {}
def tnrs_lookup(name, TIMEOUT=10, CACHE=True):
'''
Look up "name" on the TNRS web service. If a most likely standard name can be identified,
returns that name. Returns False if no or ambiguous result.
'''
name = name.replace("'", '').lower()
if name in cache and CACHE:
return cache[name]
url = "http://tnrs.iplantc.org/tnrsm-svc/matchNames?retrieve=best&names=%s"
# lookup canonical plant names on TNRS web service
try:
response = urllib2.urlopen(url % name.replace(' ', '%20'), timeout=TIMEOUT).read()
#response_dict = eval(response, {}, {'true':True, 'false':False, 'null':None})
response_dict = json.loads(response)
sci_name = response_dict['items'][0]['nameScientific']
if sci_name: result = sci_name
else: result = None
except Exception as e:
print e
result = False
# cache results and return
cache[name] = result
if CACHE: caching.save_cache(cache, 'tnrs')
return result
if __name__=='__main__':
if len(sys.argv) > 1: names = sys.argv[1:]
else: names = [raw_input('species name: ')]
for name in names:
print name, '->', tnrs_lookup(name)
| import sys
import caching
import urllib
import urllib2
import re
from pyquery import PyQuery as p
try: cache = caching.get_cache('tnrs')
except: cache = {}
def tnrs_lookup(name, TIMEOUT=10, CACHE=True):
'''
Look up "name" on the TNRS web service. If a most likely standard name can be identified,
returns that name. Returns False if no or ambiguous result.
'''
name = name.replace("'", '').lower()
if name in cache and CACHE:
return cache[name]
url = "http://tnrs.iplantc.org/tnrsm-svc/matchNames?retrieve=best&names=%s"
# lookup canonical plant names on TNRS web service
try:
response = urllib2.urlopen(url % name.replace(' ', '%20'), timeout=TIMEOUT).read()
response_dict = eval(response, {}, {'true':True, 'false':False, 'null':None})
sci_name = response_dict['items'][0]['nameScientific']
if sci_name: result = sci_name
else: result = None
except Exception as e:
print e
result = False
# cache results and return
cache[name] = result
if CACHE: caching.save_cache(cache, 'tnrs')
return result
if __name__=='__main__':
if len(sys.argv) > 1: names = sys.argv[1:]
else: names = [raw_input('species name: ')]
for name in names:
print name, '->', tnrs_lookup(name)
|
Use global settings instead of system settings. | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package info.zamojski.soft.towercollector.utils;
import android.Manifest;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
public class NetworkUtils {
public static String getNetworkType(Context context) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager == null)
return "NO CONNECTIVITY";
NetworkInfo netInfo = manager.getActiveNetworkInfo();
if (netInfo == null)
return "NO ACTIVE NETWORK";
return netInfo.getTypeName().toUpperCase();
}
public static boolean isNetworkAvailable(Context context) {
if (PermissionUtils.hasPermissions(context, Manifest.permission.ACCESS_NETWORK_STATE)) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
return (activeNetworkInfo != null && activeNetworkInfo.isConnected());
}
return true; // assume there's one
}
public static boolean isInAirplaneMode(Context context) {
return Settings.Global.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}
}
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package info.zamojski.soft.towercollector.utils;
import android.Manifest;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
public class NetworkUtils {
public static String getNetworkType(Context context) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager == null)
return "NO CONNECTIVITY";
NetworkInfo netInfo = manager.getActiveNetworkInfo();
if (netInfo == null)
return "NO ACTIVE NETWORK";
return netInfo.getTypeName().toUpperCase();
}
public static boolean isNetworkAvailable(Context context) {
if (PermissionUtils.hasPermissions(context, Manifest.permission.ACCESS_NETWORK_STATE)) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
return (activeNetworkInfo != null && activeNetworkInfo.isConnected());
}
return true; // assume there's one
}
public static boolean isInAirplaneMode(Context context) {
return Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}
}
|
Fix broken unit test which resulted from deprecating KeyboardDirectionMixin defining a public orientation property. | import * as symbols from '../../src/symbols.js';
import KeyboardDirectionMixin from '../../src/KeyboardDirectionMixin.js';
class KeyboardDirectionMixinTest extends KeyboardDirectionMixin(HTMLElement) {
constructor() {
super();
this.state = {};
}
[symbols.goRight]() {
if (super[symbols.goRight]) { super[symbols.goRight](); }
return true;
}
}
customElements.define('keyboard-direction-test', KeyboardDirectionMixinTest);
describe("KeyboardDirectionMixin", () => {
it("maps a Right arrow key to a goRight action", () => {
const fixture = new KeyboardDirectionMixinTest();
const spy = sinon.spy(fixture, symbols.goRight);
const result = fixture[symbols.keydown]({
key: 'ArrowRight'
});
assert(spy.calledOnce);
assert(result);
});
it("ignores a Right arrow key when orientation is vertical", () => {
const fixture = new KeyboardDirectionMixinTest();
Object.assign(fixture.state, {
orientation: 'vertical'
});
const spy = sinon.spy(fixture, symbols.goRight);
const result = fixture[symbols.keydown]({
key: 'ArrowRight'
});
assert(!spy.calledOnce);
assert(!result);
});
it("ignores a Right arrow key if the meta (command) key was pressed", () => {
const fixture = new KeyboardDirectionMixinTest();
const spy = sinon.spy(fixture, symbols.goRight);
const result = fixture[symbols.keydown]({
altKey: true,
key: 'ArrowRight'
});
assert(!spy.calledOnce);
assert(!result);
});
});
| import * as symbols from '../../src/symbols.js';
import KeyboardDirectionMixin from '../../src/KeyboardDirectionMixin.js';
class KeyboardDirectionMixinTest extends KeyboardDirectionMixin(HTMLElement) {
[symbols.goRight]() {
if (super[symbols.goRight]) { super[symbols.goRight](); }
return true;
}
}
customElements.define('keyboard-direction-test', KeyboardDirectionMixinTest);
describe("KeyboardDirectionMixin", () => {
it("maps a Right arrow key to a goRight action", () => {
const fixture = new KeyboardDirectionMixinTest();
const spy = sinon.spy(fixture, symbols.goRight);
const result = fixture[symbols.keydown]({
key: 'ArrowRight'
});
assert(spy.calledOnce);
assert(result);
});
it("ignores a Right arrow key when orientation is vertical", () => {
const fixture = new KeyboardDirectionMixinTest();
fixture.state = {
orientation: 'vertical'
};
const spy = sinon.spy(fixture, symbols.goRight);
const result = fixture[symbols.keydown]({
key: 'ArrowRight'
});
assert(!spy.calledOnce);
assert(!result);
});
it("ignores a Right arrow key if the meta (command) key was pressed", () => {
const fixture = new KeyboardDirectionMixinTest();
const spy = sinon.spy(fixture, symbols.goRight);
const result = fixture[symbols.keydown]({
altKey: true,
key: 'ArrowRight'
});
assert(!spy.calledOnce);
assert(!result);
});
});
|
Change jquery `find` to `querySelectorAll`
Using `querySelectorAll` rather than `querySelector` as input is a list
of radio buttons or checkboxes
Remove global JQuery object as we're no longer using it. | window.GOVUK = window.GOVUK || {}
window.GOVUK.Modules = window.GOVUK.Modules || {};
(function (global, GOVUK) {
'use strict'
GOVUK.Modules.TrackBrexitQaChoices = function () {
this.start = function (element) {
track(element)
}
function track (element) {
element.on('submit', function (event) {
var $checkedOption, eventLabel, options
var $submittedForm = event.target
var $checkedOptions = $submittedForm.querySelectorAll('input:checked')
var questionKey = $submittedForm.data('question-key')
if ($checkedOptions.length) {
$checkedOptions.each(function (index) {
$checkedOption = $(this)
var checkedOptionId = $checkedOption.attr('id')
var checkedOptionLabel = $submittedForm.find('label[for="' + checkedOptionId + '"]').text().trim()
eventLabel = checkedOptionLabel.length
? checkedOptionLabel
: $checkedOption.val()
options = { transport: 'beacon', label: eventLabel }
GOVUK.SearchAnalytics.trackEvent('brexit-checker-qa', questionKey, options)
})
} else {
// Skipped questions
options = { transport: 'beacon', label: 'no choice' }
GOVUK.SearchAnalytics.trackEvent('brexit-checker-qa', questionKey, options)
}
})
}
}
})(window, window.GOVUK)
| window.GOVUK = window.GOVUK || {}
window.GOVUK.Modules = window.GOVUK.Modules || {};
(function (global, GOVUK) {
'use strict'
var $ = global.jQuery
GOVUK.Modules.TrackBrexitQaChoices = function () {
this.start = function (element) {
track(element)
}
function track (element) {
element.on('submit', function (event) {
var $checkedOption, eventLabel, options
var $submittedForm = $(event.target)
var $checkedOptions = $submittedForm.find('input:checked')
var questionKey = $submittedForm.data('question-key')
if ($checkedOptions.length) {
$checkedOptions.each(function (index) {
$checkedOption = $(this)
var checkedOptionId = $checkedOption.attr('id')
var checkedOptionLabel = $submittedForm.find('label[for="' + checkedOptionId + '"]').text().trim()
eventLabel = checkedOptionLabel.length
? checkedOptionLabel
: $checkedOption.val()
options = { transport: 'beacon', label: eventLabel }
GOVUK.SearchAnalytics.trackEvent('brexit-checker-qa', questionKey, options)
})
} else {
// Skipped questions
options = { transport: 'beacon', label: 'no choice' }
GOVUK.SearchAnalytics.trackEvent('brexit-checker-qa', questionKey, options)
}
})
}
}
})(window, window.GOVUK)
|
Stop iteration if callback returned false value | module.exports = {
iterate: iterate
};
var iterableProperties = {
'body': true,
'expression': true,
// if
'test': true,
'consequent': true,
'alternate': true,
'object': true,
//switch
'discriminant': true,
'cases': true,
// return
'argument': true,
'arguments': true,
// try
'block': true,
'guardedHandlers': true,
'handlers': true,
'finalizer': true,
// catch
'handler': true,
// for
'init': true,
'update': true,
// for in
'left': true,
'right': true,
// var
'declarations': true,
// array
'elements': true,
// object
'properties': true,
'key': true,
'value': true,
// new
'callee': true,
// xxx.yyy
'property': true
};
function iterate(node, cb, parentNode, parentCollection) {
if (cb(node, parentNode, parentCollection) === false) {
return;
}
for (var propName in node) {
if (node.hasOwnProperty(propName)) {
if (iterableProperties[propName]) {
var contents = node[propName];
if (typeof contents === 'object') {
if (Array.isArray(contents)) {
for (var i = 0, l = contents.length; i < l; i++) {
iterate(contents[i], cb, node, contents);
}
} else {
iterate(contents, cb, node, [ contents ]);
}
}
}
}
}
}
| module.exports = {
iterate: iterate
};
var iterableProperties = {
'body': true,
'expression': true,
// if
'test': true,
'consequent': true,
'alternate': true,
'object': true,
//switch
'discriminant': true,
'cases': true,
// return
'argument': true,
'arguments': true,
// try
'block': true,
'guardedHandlers': true,
'handlers': true,
'finalizer': true,
// catch
'handler': true,
// for
'init': true,
'update': true,
// for in
'left': true,
'right': true,
// var
'declarations': true,
// array
'elements': true,
// object
'properties': true,
'key': true,
'value': true,
// new
'callee': true,
// xxx.yyy
'property': true
};
function iterate(node, cb, parentNode, parentCollection) {
cb(node, parentNode, parentCollection);
for (var propName in node) {
if (node.hasOwnProperty(propName)) {
if (iterableProperties[propName]) {
var contents = node[propName];
if (typeof contents === 'object') {
if (Array.isArray(contents)) {
for (var i = 0, l = contents.length; i < l; i++) {
iterate(contents[i], cb, node, contents);
}
} else {
iterate(contents, cb, node, [ contents ]);
}
}
}
}
}
}
|
Add space after EC prefix
Co-authored-by: Charles Tapley Hoyt <[email protected]> | # -*- coding: utf-8 -*-
"""Processor for the `Chemical Roles Graph (CRoG)
<https://github.com/chemical-roles/chemical-roles>`_.
"""
from typing import Optional
from ..utils import RemoteProcessor
__all__ = [
'CrogProcessor',
]
CROG_URL = 'https://raw.githubusercontent.com/chemical-roles/' \
'chemical-roles/master/docs/_data/crog.indra.json'
class CrogProcessor(RemoteProcessor):
"""A processor for the Chemical Roles Graph.
Parameters
----------
url :
An optional URL. If none given, defaults to
:data:`indra.sources.crog.processor.CROG_URL`.
"""
def __init__(self, url: Optional[str] = None):
super().__init__(url=url or CROG_URL)
def extract_statements(self):
super().extract_statements()
for stmt in self.statements:
# We remap the source API to crog to align with the belief model
for ev in stmt.evidence:
ev.source_api = 'crog'
# We also change the name of targets whose names are ECCODEs to
# have the EC prefix in their name
for agent in stmt.real_agent_list():
if agent.name == agent.db_refs.get('ECCODE'):
agent.name = 'EC %s' % agent.name
| # -*- coding: utf-8 -*-
"""Processor for the `Chemical Roles Graph (CRoG)
<https://github.com/chemical-roles/chemical-roles>`_.
"""
from typing import Optional
from ..utils import RemoteProcessor
__all__ = [
'CrogProcessor',
]
CROG_URL = 'https://raw.githubusercontent.com/chemical-roles/' \
'chemical-roles/master/docs/_data/crog.indra.json'
class CrogProcessor(RemoteProcessor):
"""A processor for the Chemical Roles Graph.
Parameters
----------
url :
An optional URL. If none given, defaults to
:data:`indra.sources.crog.processor.CROG_URL`.
"""
def __init__(self, url: Optional[str] = None):
super().__init__(url=url or CROG_URL)
def extract_statements(self):
super().extract_statements()
for stmt in self.statements:
# We remap the source API to crog to align with the belief model
for ev in stmt.evidence:
ev.source_api = 'crog'
# We also change the name of targets whose names are ECCODEs to
# have the EC prefix in their name
for agent in stmt.real_agent_list():
if agent.name == agent.db_refs.get('ECCODE'):
agent.name = 'EC%s' % agent.name
|
Fix concurrent modification exception when switching root | package com.reactnativenavigation.events;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public enum EventBus {
instance;
private final List<WeakReference<Subscriber>> subscribers = new ArrayList<>();
public void register(Subscriber subscriber) {
if (isSubscribed(subscriber)) return;
subscribers.add(new WeakReference<>(subscriber));
}
public void unregister(Subscriber subscriber) {
ListIterator<WeakReference<Subscriber>> iterator = subscribers.listIterator();
while (iterator.hasNext()) {
WeakReference<Subscriber> ref = iterator.next();
Subscriber registered = ref.get();
if (registered != null && registered == subscriber) {
iterator.remove();
}
}
}
public void post(Event event) {
for (WeakReference<Subscriber> ref : subscribers) {
Subscriber registered = ref.get();
if (registered != null) {
registered.onEvent(event);
}
}
}
public boolean isSubscribed(Subscriber subscriber) {
for (WeakReference<Subscriber> ref : subscribers) {
Subscriber registered = ref.get();
if (registered != null && registered.equals(subscriber)) {
return true;
}
}
return false;
}
}
| package com.reactnativenavigation.events;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public enum EventBus {
instance;
private final List<WeakReference<Subscriber>> subscribers = new ArrayList<>();
public void register(Subscriber subscriber) {
if (isSubscribed(subscriber)) return;
subscribers.add(new WeakReference<>(subscriber));
}
public void unregister(Subscriber subscriber) {
ListIterator<WeakReference<Subscriber>> iterator = subscribers.listIterator();
while (iterator.hasNext()) {
WeakReference<Subscriber> ref = iterator.next();
Subscriber registered = ref.get();
if (registered != null && registered == subscriber) {
subscribers.remove(ref);
}
}
}
public void post(Event event) {
for (WeakReference<Subscriber> ref : subscribers) {
Subscriber registered = ref.get();
if (registered != null) {
registered.onEvent(event);
}
}
}
public boolean isSubscribed(Subscriber subscriber) {
for (WeakReference<Subscriber> ref : subscribers) {
Subscriber registered = ref.get();
if (registered != null && registered.equals(subscriber)) {
return true;
}
}
return false;
}
}
|
Update double_width_emojis list to improve "rich" printing | from rich.console import Console
from rich.markdown import Markdown
from rich.syntax import Syntax
def process_syntax(code, lang, theme, line_numbers, code_width, word_wrap):
syntax = Syntax(
code,
lang,
theme=theme,
line_numbers=line_numbers,
code_width=code_width,
word_wrap=word_wrap,
)
return syntax
def display_markdown(code):
try:
markdown = Markdown(code)
console = Console()
console.print(markdown) # noqa
return True # Success
except Exception:
return False # Failure
def display_code(code):
try:
console = Console()
console.print(code) # noqa
return True # Success
except Exception:
return False # Failure
def fix_emoji_spacing(code):
try:
# Fix the display width of certain emojis that take up two spaces
double_width_emojis = [
"🗺️", "🖼️", "🗄️", "⏺️", "♻️", "🗂️", "🖥️", "🕹️", "🎞️"
]
for emoji in double_width_emojis:
if emoji in code:
code = code.replace(emoji, emoji + " ")
except Exception:
pass
return code
| from rich.console import Console
from rich.markdown import Markdown
from rich.syntax import Syntax
def process_syntax(code, lang, theme, line_numbers, code_width, word_wrap):
syntax = Syntax(
code,
lang,
theme=theme,
line_numbers=line_numbers,
code_width=code_width,
word_wrap=word_wrap,
)
return syntax
def display_markdown(code):
try:
markdown = Markdown(code)
console = Console()
console.print(markdown) # noqa
return True # Success
except Exception:
return False # Failure
def display_code(code):
try:
console = Console()
console.print(code) # noqa
return True # Success
except Exception:
return False # Failure
def fix_emoji_spacing(code):
try:
# Fix the display width of certain emojis that take up two spaces
double_width_emojis = ["🗺️", "🖼️", "🗄️", "⏺️", "♻️", "🗂️", "🖥️"]
for emoji in double_width_emojis:
if emoji in code:
code = code.replace(emoji, emoji + " ")
except Exception:
pass
return code
|
Fix Evocation Illager animation on 1.12 | package us.myles.ViaVersion.protocols.protocol1_12to1_11_1;
import us.myles.ViaVersion.api.Via;
import us.myles.ViaVersion.api.data.UserConnection;
import us.myles.ViaVersion.api.entities.Entity1_12Types;
import us.myles.ViaVersion.api.minecraft.item.Item;
import us.myles.ViaVersion.api.minecraft.metadata.Metadata;
import java.util.ArrayList;
import java.util.List;
public class MetadataRewriter {
public static void handleMetadata(int entityId, Entity1_12Types.EntityType type, List<Metadata> metadatas, UserConnection connection) {
for (Metadata metadata : new ArrayList<>(metadatas)) {
try {
if (metadata.getValue() instanceof Item) {
// Apply rewrite
BedRewriter.toClientItem((Item) metadata.getValue());
}
// Evocation Illager aggressive property became 13
if (type.is(Entity1_12Types.EntityType.EVOCATION_ILLAGER)) {
if (metadata.getId() == 12) {
metadata.setId(13);
}
}
} catch (Exception e) {
metadatas.remove(metadata);
if (!Via.getConfig().isSuppressMetadataErrors() || Via.getManager().isDebug()) {
Via.getPlatform().getLogger().warning("An error occurred with entity metadata handler");
Via.getPlatform().getLogger().warning("Metadata: " + metadata);
e.printStackTrace();
}
}
}
}
}
| package us.myles.ViaVersion.protocols.protocol1_12to1_11_1;
import us.myles.ViaVersion.api.Via;
import us.myles.ViaVersion.api.data.UserConnection;
import us.myles.ViaVersion.api.entities.Entity1_12Types;
import us.myles.ViaVersion.api.minecraft.item.Item;
import us.myles.ViaVersion.api.minecraft.metadata.Metadata;
import java.util.ArrayList;
import java.util.List;
public class MetadataRewriter {
public static void handleMetadata(int entityId, Entity1_12Types.EntityType type, List<Metadata> metadatas, UserConnection connection) {
for (Metadata metadata : new ArrayList<>(metadatas)) {
try {
if (metadata.getValue() instanceof Item) {
// Apply rewrite
BedRewriter.toClientItem((Item) metadata.getValue());
}
} catch (Exception e) {
metadatas.remove(metadata);
if (!Via.getConfig().isSuppressMetadataErrors() || Via.getManager().isDebug()) {
Via.getPlatform().getLogger().warning("An error occurred with entity metadata handler");
Via.getPlatform().getLogger().warning("Metadata: " + metadata);
e.printStackTrace();
}
}
}
}
}
|
Move the call to the server into a separate thread
So that it does not block the webcore thread | package edu.berkeley.eecs.emission.cordova.comm;
import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import edu.berkeley.eecs.emission.cordova.comm.CommunicationHelper;
import edu.berkeley.eecs.emission.cordova.connectionsettings.ConnectionSettings;
public class CommunicationHelperPlugin extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray data, final CallbackContext callbackContext) throws JSONException {
if (action.equals("pushGetJSON")) {
try {
final Context ctxt = cordova.getActivity();
String relativeURL = data.getString(0);
final JSONObject filledMessage = data.getJSONObject(1);
String commuteTrackerHost = ConnectionSettings.getConnectURL(ctxt);
final String fullURL = commuteTrackerHost + relativeURL;
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
String resultString = CommunicationHelper.pushGetJSON(ctxt, fullURL, filledMessage);
callbackContext.success(new JSONObject(resultString));
} catch (Exception e) {
callbackContext.error("While pushing/getting from server "+e.getMessage());
}
}
});
} catch (Exception e) {
callbackContext.error("While pushing/getting from server "+e.getMessage());
}
return true;
} else {
return false;
}
}
}
| package edu.berkeley.eecs.emission.cordova.comm;
import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import edu.berkeley.eecs.emission.cordova.comm.CommunicationHelper;
import edu.berkeley.eecs.emission.cordova.connectionsettings.ConnectionSettings;
public class CommunicationHelperPlugin extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
if (action.equals("pushGetJSON")) {
try {
Context ctxt = cordova.getActivity();
String relativeURL = data.getString(0);
JSONObject filledMessage = data.getJSONObject(1);
String commuteTrackerHost = ConnectionSettings.getConnectURL(ctxt);
String fullURL = commuteTrackerHost + relativeURL;
String resultString = CommunicationHelper.pushGetJSON(ctxt, fullURL, filledMessage);
callbackContext.success(new JSONObject(resultString));
} catch (Exception e) {
callbackContext.error("While pushing/getting from server "+e.getMessage());
}
return true;
} else {
return false;
}
}
}
|
Remove handling of failed send error | // let messanger = require('./mailer/transport')();
module.exports = function(_db, messanger){
if(!SlickSources[_db]) return {start: () => false};
let _req = {db:SlickSources[_db]},
Mails = Models.Mails(_req),
fetchMails = cb => {
Mails.find({limit:100}, function(e, recs){
if(!e){
cb(recs);
}else{
console.error(e);
}
})
},
start = () => {
fetchMails( dispatch );
},
dispatch = recs => {
let run = function(){
if(recs.length){
sendMail(recs.pop());
}else setTimeout(start,100);
},
sendMail = r => {
r.to = `${r.receiver_name} <${r.receiver_email}>`;
r.message = r.body;
messanger.sendMail(r, function (e, info) {
if (!e) {
Mails.destroy({id:r.id}, function(err, res){
run();
});
}
// else{
// Mails.update({id:r.id, sent:'1'}, function(){
// run();
// });
// }
});
};
run();
};
console.log('Registered Mailer for ', _db);
return {
start:start
}
}; | // let messanger = require('./mailer/transport')();
module.exports = function(_db, messanger){
if(!SlickSources[_db]) return {start: () => false};
let _req = {db:SlickSources[_db]},
Mails = Models.Mails(_req),
fetchMails = cb => {
Mails.find({limit:100,sent:'0'}, function(e, recs){
if(!e){
cb(recs);
}else{
console.error(e);
}
})
},
start = () => {
fetchMails( dispatch );
},
dispatch = recs => {
let run = function(){
if(recs.length){
sendMail(recs.pop());
}else setTimeout(start,100);
},
sendMail = r => {
r.to = `${r.receiver_name} <${r.receiver_email}>`;
r.message = r.body;
messanger.sendMail(r, function (e, info) {
if (!e) {
Mails.destroy({id:r.id}, function(err, res){
run();
});
} else{
Mails.update({id:r.id, sent:'1'}, function(){
run();
});
}
});
};
run();
};
console.log('Registered Mailer for ', _db);
return {
start:start
}
}; |
Fix test to work correctly on windows. | package org.wkh.bateman.trade;
import org.wkh.bateman.trade.Quote;
import org.wkh.bateman.trade.GoogleQuoteFetcher;
import java.io.File;
import java.util.List;
import java.util.Scanner;
import static junit.framework.Assert.assertEquals;
import junit.framework.TestCase;
public class GoogleQuoteFetcherTest extends TestCase {
public GoogleQuoteFetcherTest(String testName) {
super(testName);
}
public void testParseQuotes() throws Exception {
String samplePath = "src/main/resources/sample_response.txt";
Scanner scan = new Scanner(new File(samplePath));
scan.useDelimiter("\\Z");
String sampleResponse = scan.next().replaceAll("\r\n", "\n");
GoogleQuoteFetcher fetcher = new GoogleQuoteFetcher();
List<Quote> quotes = fetcher.parseQuotes(sampleResponse, 60);
Quote firstQuote = quotes.get(0);
assertEquals(firstQuote.getOpen(), 444.05);
assertEquals(firstQuote.getHigh(), 444.19);
assertEquals(firstQuote.getLow(), 443.8);
assertEquals(firstQuote.getClose(), 443.8);
assertEquals(firstQuote.getVolume(), 78179);
assertEquals(firstQuote.getOpenDate().getMillis(), 1362061800000L);
assertEquals(quotes.size(), 5873);
}
}
| package org.wkh.bateman.trade;
import org.wkh.bateman.trade.Quote;
import org.wkh.bateman.trade.GoogleQuoteFetcher;
import java.io.File;
import java.util.List;
import java.util.Scanner;
import static junit.framework.Assert.assertEquals;
import junit.framework.TestCase;
public class GoogleQuoteFetcherTest extends TestCase {
public GoogleQuoteFetcherTest(String testName) {
super(testName);
}
public void testParseQuotes() throws Exception {
String samplePath = "src/main/resources/sample_response.txt";
Scanner scan = new Scanner(new File(samplePath));
scan.useDelimiter("\\Z");
String sampleResponse = scan.next();
GoogleQuoteFetcher fetcher = new GoogleQuoteFetcher();
List<Quote> quotes = fetcher.parseQuotes(sampleResponse, 60);
Quote firstQuote = quotes.get(0);
assertEquals(firstQuote.getOpen(), 444.05);
assertEquals(firstQuote.getHigh(), 444.19);
assertEquals(firstQuote.getLow(), 443.8);
assertEquals(firstQuote.getClose(), 443.8);
assertEquals(firstQuote.getVolume(), 78179);
assertEquals(firstQuote.getOpenDate().getMillis(), 1362061800000L);
assertEquals(quotes.size(), 5873);
}
}
|
Use WebserviceTestCase as parent for listing overview test | <?php
namespace Tests\AppBundle\API\Listing;
use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;
class OverviewTest extends WebserviceTestCase
{
const NICKNAME = 'listingOverviewTestUser';
const USERID = 'listingOverviewTestUser';
const PROVIDER = 'listingOverviewTestUser';
public function testExecute()
{
//Test for overview if user is not logged in
$default_db = $this->default_db;
$session = $this->session;
$overview = $this->webservice->factory('listing', 'overview');
$parameterBag = new ParameterBag(array('dbversion' => $default_db));
$results = $overview->execute($parameterBag, $session);
$expected = array(
"projects" => 0,
"organisms" => 173716,
"trait_entries" => 48916,
"trait_types" => 1
);
$this->assertEquals($expected, $results);
//Test of correct project if the user has only one project
$session->set('user', array(
'nickname' => OverviewTest::NICKNAME,
'id' => OverviewTest::USERID,
'provider' => OverviewTest::PROVIDER,
'token' => 'listingOverviewTestUserToken'
));
$results = $overview->execute($parameterBag, $session);
$expected['projects'] = 1;
$this->assertEquals($expected, $results);
}
} | <?php
namespace Tests\AppBundle\API\Listing;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
class OverviewTest extends WebTestCase
{
const NICKNAME = 'listingOverviewTestUser';
const USERID = 'listingOverviewTestUser';
const PROVIDER = 'listingOverviewTestUser';
public function testExecute()
{
$client = static::createClient();
//Test for overview if user is not logged in
$default_db = $client->getContainer()->getParameter('default_db');
$session = new Session(new MockArraySessionStorage());
$overview = $client->getContainer()->get('app.api.webservice')->factory('listing', 'overview');
$parameterBag = new ParameterBag(array('dbversion' => $default_db));
$results = $overview->execute($parameterBag, $session);
$expected = array(
"projects" => 0,
"organisms" => 173716,
"trait_entries" => 48916,
"trait_types" => 1
);
$this->assertEquals($expected, $results);
//Test of correct project if the user has only one project
$session->set('user', array(
'nickname' => OverviewTest::NICKNAME,
'id' => OverviewTest::USERID,
'provider' => OverviewTest::PROVIDER,
'token' => 'listingOverviewTestUserToken'
));
$results = $overview->execute($parameterBag, $session);
$expected['projects'] = 1;
$this->assertEquals($expected, $results);
}
} |
Fix NPE if no auth info provided | package digital.loom.rhizome.authentication;
import java.util.regex.Pattern;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import com.auth0.jwt.internal.org.apache.commons.lang3.StringUtils;
import com.auth0.spring.security.api.Auth0AuthenticationFilter;
import com.google.common.base.MoreObjects;
public class CookieReadingAuth0AuthenticationFilter extends Auth0AuthenticationFilter {
@Override
protected String getToken( HttpServletRequest httpRequest ) {
String authorizationCookie = null;
Cookie[] cookies = httpRequest.getCookies();
if ( cookies != null ) {
for ( Cookie cookie : httpRequest.getCookies() ) {
if ( StringUtils.equals( cookie.getName(), "authorization" ) ) {
authorizationCookie = cookie.getValue();
break;
}
}
}
final String authorizationInfo = MoreObjects.firstNonNull( httpRequest.getHeader( "authorization" ), authorizationCookie );
if( authorizationInfo == null ) {
return null;
}
final String[] parts = authorizationInfo.split( " " );
if ( parts.length != 2 ) {
// "Unauthorized: Format is Authorization: Bearer [token]"
return null;
}
final String scheme = parts[ 0 ];
final String credentials = parts[ 1 ];
final Pattern pattern = Pattern.compile( "^Bearer$", Pattern.CASE_INSENSITIVE );
return pattern.matcher( scheme ).matches() ? credentials : null;
}
}
| package digital.loom.rhizome.authentication;
import java.util.regex.Pattern;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import com.auth0.jwt.internal.org.apache.commons.lang3.StringUtils;
import com.auth0.spring.security.api.Auth0AuthenticationFilter;
import com.google.common.base.MoreObjects;
public class CookieReadingAuth0AuthenticationFilter extends Auth0AuthenticationFilter {
@Override
protected String getToken( HttpServletRequest httpRequest ) {
String authorizationCookie = null;
Cookie[] cookies = httpRequest.getCookies();
if ( cookies != null ) {
for ( Cookie cookie : httpRequest.getCookies() ) {
if ( StringUtils.equals( cookie.getName(), "authorization" ) ) {
authorizationCookie = cookie.getValue();
break;
}
}
}
final String authorizationHeader = httpRequest.getHeader( "authorization" );
final String[] parts = MoreObjects.firstNonNull( authorizationHeader, authorizationCookie ).split( " " );
if ( parts.length != 2 ) {
// "Unauthorized: Format is Authorization: Bearer [token]"
return null;
}
final String scheme = parts[ 0 ];
final String credentials = parts[ 1 ];
final Pattern pattern = Pattern.compile( "^Bearer$", Pattern.CASE_INSENSITIVE );
return pattern.matcher( scheme ).matches() ? credentials : null;
}
}
|
Set cache buster equal to 0 when there is no affected tables in the mapconfig | 'use strict';
module.exports = function setLastUpdatedTimeToLayergroup () {
return function setLastUpdatedTimeToLayergroupMiddleware (req, res, next) {
const { mapConfigProvider, analysesResults } = res.locals;
const layergroup = res.body;
mapConfigProvider.createAffectedTables((err, affectedTables) => {
if (err) {
return next(err);
}
if (!affectedTables) {
res.locals.cache_buster = 0;
layergroup.layergroupid = `${layergroup.layergroupid}:${res.locals.cache_buster}`;
layergroup.last_updated = new Date(res.locals.cache_buster).toISOString();
return next();
}
var lastUpdateTime = affectedTables.getLastUpdatedAt();
lastUpdateTime = getLastUpdatedTime(analysesResults, lastUpdateTime) || lastUpdateTime;
// last update for layergroup cache buster
layergroup.layergroupid = layergroup.layergroupid + ':' + lastUpdateTime;
layergroup.last_updated = new Date(lastUpdateTime).toISOString();
res.locals.cache_buster = lastUpdateTime;
next();
});
};
};
function getLastUpdatedTime (analysesResults, lastUpdateTime) {
if (!Array.isArray(analysesResults)) {
return lastUpdateTime;
}
return analysesResults.reduce(function (lastUpdateTime, analysis) {
return analysis.getNodes().reduce(function (lastNodeUpdatedAtTime, node) {
var nodeUpdatedAtDate = node.getUpdatedAt();
var nodeUpdatedTimeAt = (nodeUpdatedAtDate && nodeUpdatedAtDate.getTime()) || 0;
return nodeUpdatedTimeAt > lastNodeUpdatedAtTime ? nodeUpdatedTimeAt : lastNodeUpdatedAtTime;
}, lastUpdateTime);
}, lastUpdateTime);
}
| 'use strict';
module.exports = function setLastUpdatedTimeToLayergroup () {
return function setLastUpdatedTimeToLayergroupMiddleware (req, res, next) {
const { mapConfigProvider, analysesResults } = res.locals;
const layergroup = res.body;
mapConfigProvider.createAffectedTables((err, affectedTables) => {
if (err) {
return next(err);
}
if (!affectedTables) {
return next();
}
var lastUpdateTime = affectedTables.getLastUpdatedAt();
lastUpdateTime = getLastUpdatedTime(analysesResults, lastUpdateTime) || lastUpdateTime;
// last update for layergroup cache buster
layergroup.layergroupid = layergroup.layergroupid + ':' + lastUpdateTime;
layergroup.last_updated = new Date(lastUpdateTime).toISOString();
res.locals.cache_buster = lastUpdateTime;
next();
});
};
};
function getLastUpdatedTime (analysesResults, lastUpdateTime) {
if (!Array.isArray(analysesResults)) {
return lastUpdateTime;
}
return analysesResults.reduce(function (lastUpdateTime, analysis) {
return analysis.getNodes().reduce(function (lastNodeUpdatedAtTime, node) {
var nodeUpdatedAtDate = node.getUpdatedAt();
var nodeUpdatedTimeAt = (nodeUpdatedAtDate && nodeUpdatedAtDate.getTime()) || 0;
return nodeUpdatedTimeAt > lastNodeUpdatedAtTime ? nodeUpdatedTimeAt : lastNodeUpdatedAtTime;
}, lastUpdateTime);
}, lastUpdateTime);
}
|
Fix error logging to actually output useful data | import { basename, extname, join, dirname, relative, resolve } from 'path'
import { default as put } from 'output-file-sync'
import { parallel } from 'async'
const keys = Object.keys
export default function createPipeline(pkg, opts, build, progress) {
const
{ onBuild = noop
, onError = noop
} = progress
return (files, callback) => {
parallel(
[].concat(files).map(file => cont => {
const name = basename(file, extname(file))
build(name, file, (error, output) => {
let result = { input: file }
if (error) {
result.error = error
onError(result)
} else {
result.messages = output.messages
result.files = keys(output.files).map(name => {
let path = join(pkg.resolve(opts.lib), dirname(relative(pkg.resolve(opts.src), resolve(file))))
let outfile = join(path, name)
put(outfile, output.files[name])
return outfile
})
onBuild(result)
}
cont(null, result)
})
})
, callback
)
}
}
function noop() {} | import { basename, extname, join, dirname, relative, resolve } from 'path'
import { default as put } from 'output-file-sync'
import { parallel } from 'async'
const keys = Object.keys
export default function createPipeline(pkg, opts, build, progress) {
const
{ onBuild = noop
, onError = noop
} = progress
return (files, callback) => {
parallel(
[].concat(files).map(file => cont => {
const name = basename(file, extname(file))
build(name, file, (error, output) => {
let result = { input: file }
if (error) {
result.error = error
console.log(onError, result)
} else {
result.messages = output.messages
result.files = keys(output.files).map(name => {
let path = join(pkg.resolve(opts.lib), dirname(relative(pkg.resolve(opts.src), resolve(file))))
let outfile = join(path, name)
put(outfile, output.files[name])
return outfile
})
onBuild(result)
}
cont(null, result)
})
})
, callback
)
}
}
function noop() {} |
Add helper to load a single test case. | # -*- encoding: utf-8 -*-
"""Utility routines
"""
import os
import re
from enum import Enum
from contextlib import contextmanager
import unittest
def pyname_join(seq):
return ".".join(seq)
def is_pkgdir(dirpath):
return os.path.isdir(dirpath) \
and os.path.isfile(os.path.join(dirpath, "__init__.py"))
def mod_split(modname):
mo = re.match(r"^(.+)\.(.*)$", modname)
if not mo:
raise ValueError("invalid python path identifier")
return (mo.group(1), mo.group(2))
def is_empty_generator(generator):
try:
next(generator)
except StopIteration:
return True
else:
return False
class AutoEnum(Enum):
def __new__(cls):
value = len(cls.__members__) + 1
obj = object.__new__(cls)
obj._value_ = value
return obj
def mkdir_p(path):
try:
os.makedirs(path)
except FileExistsError:
pass
@contextmanager
def protect_cwd(dirpath=None):
saved_cwd = os.getcwd()
if dirpath is not None:
os.chdir(dirpath)
try:
yield
finally:
os.chdir(saved_cwd)
def safe_getcwd():
try:
return os.getcwd()
except FileNotFoundError:
return None
def load_single_test_case(test_name):
test_suite = list(unittest.defaultTestLoader.loadTestsFromName(test_name))
assert len(test_suite) == 1
return test_suite[0]
| # -*- encoding: utf-8 -*-
"""Utility routines
"""
import os
import re
from enum import Enum
from contextlib import contextmanager
def pyname_join(seq):
return ".".join(seq)
def is_pkgdir(dirpath):
return os.path.isdir(dirpath) \
and os.path.isfile(os.path.join(dirpath, "__init__.py"))
def mod_split(modname):
mo = re.match(r"^(.+)\.(.*)$", modname)
if not mo:
raise ValueError("invalid python path identifier")
return (mo.group(1), mo.group(2))
def is_empty_generator(generator):
try:
next(generator)
except StopIteration:
return True
else:
return False
class AutoEnum(Enum):
def __new__(cls):
value = len(cls.__members__) + 1
obj = object.__new__(cls)
obj._value_ = value
return obj
def mkdir_p(path):
try:
os.makedirs(path)
except FileExistsError:
pass
@contextmanager
def protect_cwd(dirpath=None):
saved_cwd = os.getcwd()
if dirpath is not None:
os.chdir(dirpath)
try:
yield
finally:
os.chdir(saved_cwd)
def safe_getcwd():
try:
return os.getcwd()
except FileNotFoundError:
return None
|
Increase each item of the lVal by rVal when lVal is an array and rVal is a plain value. |
var Operator = require("dice-js/operator");
Operator.define("Addition", {
symbol: "+",
operation: function (lVal, rVal) {
var lValIsArray = Array.isArray(lVal),
rValIsArray = Array.isArray(rVal),
lValIsObj = typeof lVal === "object",
rValIsObj = typeof rVal === "object"
;
if (lValIsArray) {
if (rValIsArray) {
// is this the correct default?
// should we add values from rVal to the corresponding values in lVal?
return lVal.concat(rVal);
}
else if (rValIsObj) {
return [lVal, rVal];
}
else {
return lVal.map(function (val) {
return val + rVal;
});
}
}
else if (lValIsObj) {
if (rValIsArray || !rValIsObj) {
return [lVal, rVal];
}
else {
return Object.keys(rVal).reduce(function (acc, key) {
if (acc[key] !== undefined) {
acc[key] += rVal[key];
}
else {
acc[key] = rVal[key];
}
return acc;
}, Object.keys(lVal).reduce(function (acc, key) {
acc[key] = lVal[key];
return acc;
}, {}));
}
}
else {
return lVal + rVal;
}
},
precedence: 0,
associativity: "left"
});
|
var Operator = require("dice-js/operator");
Operator.define("Addition", {
symbol: "+",
operation: function (lVal, rVal) {
var lValIsArray = Array.isArray(lVal),
rValIsArray = Array.isArray(rVal),
lValIsObj = typeof lVal === "object",
rValIsObj = typeof rVal === "object"
;
if (lValIsArray) {
if (rValIsArray) {
return lVal.concat(rVal);
}
else {
lVal.push(rVal);
}
}
else if (lValIsObj) {
if (rValIsArray || !rValIsObj) {
return [lVal, rVal];
}
else {
return Object.keys(rVal).reduce(function (acc, key) {
if (acc[key] !== undefined) {
acc[key] += rVal[key];
}
else {
acc[key] = rVal[key];
}
return acc;
}, Object.keys(lVal).reduce(function (acc, key) {
acc[key] = lVal[key];
return acc;
}, {}));
}
}
else {
return lVal + rVal;
}
},
precedence: 0,
associativity: "left"
});
|
Fix the raw paths for Gitorious
Gitorious have changed the raw orl paths, making impossible to use a Gitorious
repository.
This patch has been tested in production at
http://reviewboard.chakra-project.org/r/27/diff/#index_header
Reviewed at http://reviews.reviewboard.org/r/3649/diff/#index_header | from django import forms
from django.utils.translation import ugettext_lazy as _
from reviewboard.hostingsvcs.forms import HostingServiceForm
from reviewboard.hostingsvcs.service import HostingService
class GitoriousForm(HostingServiceForm):
gitorious_project_name = forms.CharField(
label=_('Project name'),
max_length=64,
required=True,
widget=forms.TextInput(attrs={'size': '60'}))
gitorious_repo_name = forms.CharField(
label=_('Repository name'),
max_length=64,
required=True,
widget=forms.TextInput(attrs={'size': '60'}))
class Gitorious(HostingService):
name = 'Gitorious'
form = GitoriousForm
supported_scmtools = ['Git']
supports_repositories = True
repository_fields = {
'Git': {
'path': 'git://gitorious.org/%(gitorious_project_name)s/'
'%(gitorious_repo_name)s.git',
'mirror_path': 'https://gitorious.org/'
'%(gitorious_project_name)s/'
'%(gitorious_repo_name)s.git',
'raw_file_url': 'https://gitorious.org/'
'%(gitorious_project_name)s/'
'%(gitorious_repo_name)s/blobs/raw/<revision>'
},
}
| from django import forms
from django.utils.translation import ugettext_lazy as _
from reviewboard.hostingsvcs.forms import HostingServiceForm
from reviewboard.hostingsvcs.service import HostingService
class GitoriousForm(HostingServiceForm):
gitorious_project_name = forms.CharField(
label=_('Project name'),
max_length=64,
required=True,
widget=forms.TextInput(attrs={'size': '60'}))
gitorious_repo_name = forms.CharField(
label=_('Repository name'),
max_length=64,
required=True,
widget=forms.TextInput(attrs={'size': '60'}))
class Gitorious(HostingService):
name = 'Gitorious'
form = GitoriousForm
supported_scmtools = ['Git']
supports_repositories = True
repository_fields = {
'Git': {
'path': 'git://gitorious.org/%(gitorious_project_name)s/'
'%(gitorious_repo_name)s.git',
'mirror_path': 'http://git.gitorious.org/'
'%(gitorious_project_name)s/'
'%(gitorious_repo_name)s.git',
'raw_file_url': 'http://git.gitorious.org/'
'%(gitorious_project_name)s/'
'%(gitorious_repo_name)s/blobs/raw/<revision>'
},
}
|
Use more appropriate status code |
from . import settings
from django.http import HttpResponse
import time
import redis
# Connection pool
POOL = redis.ConnectionPool(**settings.REDIS)
class RatedMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
# Try to determine the realm for this view
try:
realm = view_func._rated_realm
except AttributeError:
try:
realm = settings.REALM_MAP[request.resolver_match.url_name]
except KeyError:
return None
# should we also try the view name?
source = request.META['REMOTE_ADDR']
conf = settings.REALMS.get(realm, {})
# Check against Realm whitelist
if source in conf.get('whitelist', settings.DEFAULT_WHITELIST):
return None
key = 'rated:%s:%s' % (realm, source,)
now = time.time()
client = redis.Redis(connection_pool=POOL)
# Do commands at once for speed
pipe = client.pipeline()
# Add our timestamp to the range
pipe.zadd(key, now, now)
# Update to not expire for another hour
pipe.expireat(key, int(now + conf.get('timeout', settings.DEFAULT_TIMEOUT)))
# Remove old values
pipe.zremrangebyscore(key, '-inf', now - settings.DEFAULT_TIMEOUT)
# Test count
pipe.zcard(key)
size = pipe.execute()[-1]
if size > conf.get('limit', settings.DEFAULT_LIMIT):
return HttpResponse(status=429)
return None
|
from . import settings
from django.http import HttpResponse
import time
import redis
# Connection pool
POOL = redis.ConnectionPool(**settings.REDIS)
class RatedMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
# Try to determine the realm for this view
try:
realm = view_func._rated_realm
except AttributeError:
try:
realm = settings.REALM_MAP[request.resolver_match.url_name]
except KeyError:
return None
# should we also try the view name?
source = request.META['REMOTE_ADDR']
conf = settings.REALMS.get(realm, {})
# Check against Realm whitelist
if source in conf.get('whitelist', settings.DEFAULT_WHITELIST):
return None
key = 'rated:%s:%s' % (realm, source,)
now = time.time()
client = redis.Redis(connection_pool=POOL)
# Do commands at once for speed
pipe = client.pipeline()
# Add our timestamp to the range
pipe.zadd(key, now, now)
# Update to not expire for another hour
pipe.expireat(key, int(now + conf.get('timeout', settings.DEFAULT_TIMEOUT)))
# Remove old values
pipe.zremrangebyscore(key, '-inf', now - settings.DEFAULT_TIMEOUT)
# Test count
pipe.zcard(key)
size = pipe.execute()[-1]
if size > conf.get('limit', settings.DEFAULT_LIMIT):
return HttpResponse(status=501)
return None
|
CRM-82: Apply forms JS validation
- remove constraint from email form type to fix tests | <?php
namespace Oro\Bundle\FlexibleEntityBundle\Form\Type;
use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Form\FormBuilderInterface;
class EmailType extends CollectionItemAbstract
{
const TYPE_CORPORATE = 1;
const TYPE_PERSONAL = 2;
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('id', 'hidden');
$builder->add(
'data',
'email'
);
$builder->add(
'type',
'choice',
array(
'empty_value' => 'Choose email type...',
'empty_data' => null,
'choice_list' => new ChoiceList(
array_keys(self::getTypesArray()),
array_values(self::getTypesArray())
),
'attr' => array ('class' => 'oro-multiselect')
)
);
}
/**
* {@inheritdoc}
*/
public function getTypesArray()
{
return array(
self::TYPE_CORPORATE => 'Сorporate email',
self::TYPE_PERSONAL => 'Personal email'
);
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'oro_flexibleentity_email';
}
}
| <?php
namespace Oro\Bundle\FlexibleEntityBundle\Form\Type;
use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Form\FormBuilderInterface;
class EmailType extends CollectionItemAbstract
{
const TYPE_CORPORATE = 1;
const TYPE_PERSONAL = 2;
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('id', 'hidden');
$builder->add(
'data',
'email',
array(
'constraints' => array(
new Email()
)
)
);
$builder->add(
'type',
'choice',
array(
'empty_value' => 'Choose email type...',
'empty_data' => null,
'choice_list' => new ChoiceList(
array_keys(self::getTypesArray()),
array_values(self::getTypesArray())
),
'attr' => array ('class' => 'oro-multiselect')
)
);
}
/**
* {@inheritdoc}
*/
public function getTypesArray()
{
return array(
self::TYPE_CORPORATE => 'Сorporate email',
self::TYPE_PERSONAL => 'Personal email'
);
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'oro_flexibleentity_email';
}
}
|
Update Icebreath to remove "Loading..." messages. | <?php
namespace PVL\RadioAdapter;
use \Entity\Station;
class IceBreath extends AdapterAbstract
{
/* Process a nowplaying record. */
protected function _process(&$np)
{
$return_raw = $this->getUrl();
if (empty($return_raw))
return false;
$return = @json_decode($return_raw, true);
if (empty($return))
return false;
if (count($return['result']['server_streams']) == 0)
return false;
$stream = $return['result']['server_streams'][0];
$np['meta']['status'] = 'online';
$np['meta']['bitrate'] = $stream['stream_audio_info']['bitrate'];
$np['meta']['format'] = $stream['stream_mime'];
$u_list = (int)$stream['stream_listeners_unique'];
$t_list = (int)$stream['stream_listeners'];
$np['listeners'] = array(
'current' => $this->getListenerCount($u_list, $t_list),
'unique' => $u_list,
'total' => $t_list,
);
$np['current_song'] = array(
'artist' => $stream['stream_nowplaying']['artist'],
'title' => $stream['stream_nowplaying']['song'],
'text' => $stream['stream_nowplaying']['text'],
);
return true;
}
} | <?php
namespace PVL\RadioAdapter;
use \Entity\Station;
class IceBreath extends AdapterAbstract
{
/* Process a nowplaying record. */
protected function _process(&$np)
{
$return_raw = $this->getUrl();
if (empty($return_raw))
return false;
$return = @json_decode($return_raw, true);
if (empty($return))
return false;
$stream = $return['result']['server_streams'][0];
$np['meta']['status'] = 'online';
$np['meta']['bitrate'] = $stream['stream_audio_info']['bitrate'];
$np['meta']['format'] = $stream['stream_mime'];
$u_list = (int)$stream['stream_listeners_unique'];
$t_list = (int)$stream['stream_listeners'];
$np['listeners'] = array(
'current' => $this->getListenerCount($u_list, $t_list),
'unique' => $u_list,
'total' => $t_list,
);
$np['current_song'] = array(
'artist' => $stream['stream_nowplaying']['artist'],
'title' => $stream['stream_nowplaying']['song'],
'text' => $stream['stream_nowplaying']['text'],
);
return true;
}
} |
Add back `localized` function which was accidentally removed | <?php
class Lang extends \Fuel\Core\Lang
{
/**
* @var string default language when language is not specified in URI
*/
public static $default_language;
public static function _init()
{
static::$default_language = \Config::get('language');
parent::_init();
}
/**
* Returns currently active language.
*
* @return string currently active language
*/
public static function get_lang()
{
$language = \Config::get('language');
if ($language == self::$default_language)
{
$lang_segment = \Uri::segment(1);
if (!empty($lang_segment) and $lang_segment != false)
{
$languages = \Config::get('languages');
if (!empty($languages) and array_search($lang_segment, $languages) !== false)
{
$language = $lang_segment;
}
}
}
if (empty($language))
{
$language = self::$fallback[0];
}
return $language;
}
/**
* Create localized URI
*
* @param string $uri URI to localize
* @param string|null $language name of the language with which create URI, null for active language
* @return string localized URI
*/
public static function localized($uri, $language = null)
{
if (empty($language))
{
$language = self::get_lang();
}
if (!empty($language) and $language != self::$default_language)
{
$uri = '/' . $language . $uri;
}
return $uri;
}
}
| <?php
class Lang extends \Fuel\Core\Lang
{
/**
* @var string default language when language is not specified in URI
*/
public static $default_language;
public static function _init()
{
static::$default_language = \Config::get('language');
parent::_init();
}
/**
* Returns currently active language.
*
* @return string currently active language
*/
public static function get_lang()
{
$language = \Config::get('language');
if ($language == self::$default_language)
{
$lang_segment = \Uri::segment(1);
if (!empty($lang_segment) and $lang_segment != false)
{
$languages = \Config::get('languages');
if (!empty($languages) and array_search($lang_segment, $languages) !== false)
{
$language = $lang_segment;
}
}
}
if (empty($language))
{
$language = self::$fallback[0];
}
return $language;
}
}
|
Send flag when success push notifications | # coding=utf-8
import time, os, json
from apns import APNs, Frame, Payload
from push.models import DevelopFileModel, ProductFileModel
from django.conf import settings
PEM_FILE_DIR = settings.BASE_DIR + '/push/files/'
def execute(device_token_lists, notification):
if notification.is_production:
pem_file_name = ProductFileModel.objects.all()[0].production_file_name
apns = APNs(use_sandbox = False, cert_file = PEM_FILE_DIR + pem_file_name, enhanced = True)
else:
pem_file_name = DevelopFileModel.objects.all()[0].development_file_name
apns = APNs(use_sandbox = True, cert_file = PEM_FILE_DIR + pem_file_name, enhanced = True)
token_hex = []
for token in device_token_lists:
token_hex.append(token)
json_data = ''
if notification.json != '':
json_data = json.loads(notification.json)
payload = Payload(alert = notification.message,
sound = notification.sound,
badge = notification.badge,
custom = json_data)
frame = Frame()
identifier = 1
expiry = time.time() + 3600
priority = 10
for token in token_hex:
frame.add_item(token, payload, identifier, expiry, priority)
apns.gateway_server.send_notification_multiple(frame)
notification.is_sent = True
notification.save()
| # coding=utf-8
import time, os, json
from apns import APNs, Frame, Payload
from push.models import DevelopFileModel, ProductFileModel
from django.conf import settings
PEM_FILE_DIR = settings.BASE_DIR + '/push/files/'
def execute(device_token_lists, notification):
if notification.is_production:
pem_file_name = ProductFileModel.objects.all()[0].production_file_name
apns = APNs(use_sandbox = False, cert_file = PEM_FILE_DIR + pem_file_name, enhanced = True)
else:
pem_file_name = DevelopFileModel.objects.all()[0].development_file_name
apns = APNs(use_sandbox = True, cert_file = PEM_FILE_DIR + pem_file_name, enhanced = True)
token_hex = []
for token in device_token_lists:
token_hex.append(token)
json_data = ''
if notification.json != '':
json_data = json.loads(notification.json)
payload = Payload(alert = notification.message,
sound = notification.sound,
badge = notification.badge,
custom = json_data)
frame = Frame()
identifier = 1
expiry = time.time() + 3600
priority = 10
for token in token_hex:
frame.add_item(token, payload, identifier, expiry, priority)
apns.gateway_server.send_notification_multiple(frame)
|
Fix urls of switcher after first switch | <?php
namespace LanguageSwitcher\View\Helper;
use Cake\Core\Configure;
use Cake\Core\InstanceConfigTrait;
use Cake\Routing\Router;
use Cake\Utility\Hash;
use Cake\Utility\Text;
use Cake\View\Helper;
use Cake\View\View;
/**
* LanguageSwitcher helper
*/
class LanguageSwitcherHelper extends Helper
{
use InstanceConfigTrait;
protected $_defaultConfig = [
'availableLanguages' => [
'en_US' => 'en_US'
],
'displayNames' => [
'en_US' => 'English'
],
'imageMapping' => [
'en_US' => 'United-States'
]
];
/**
* Renders language switcher dropdown
*
* @return element
*/
public function renderLanguageSwitcher()
{
return $this->_View->element('LanguageSwitcher.language_switcher', [
'availableLanguages' => $this->config('availableLanguages'),
'displayNames' => $this->config('displayNames'),
'imageMapping' => $this->config('imageMapping')
]);
}
/**
* Merge current GET parameters with the language string
*
* @param string $language Language
* @return string Url
*/
public function getUrl($language)
{
$lang = ['lang' => $language];
$query = Hash::merge($this->request->query, $lang);
$urlArray = Hash::merge($this->request->params['pass'], ['?' => $query]);
return Router::url($urlArray);
}
}
| <?php
namespace LanguageSwitcher\View\Helper;
use Cake\Core\Configure;
use Cake\Core\InstanceConfigTrait;
use Cake\Routing\Router;
use Cake\Utility\Hash;
use Cake\Utility\Text;
use Cake\View\Helper;
use Cake\View\View;
/**
* LanguageSwitcher helper
*/
class LanguageSwitcherHelper extends Helper
{
use InstanceConfigTrait;
protected $_defaultConfig = [
'availableLanguages' => [
'en_US' => 'en_US'
],
'displayNames' => [
'en_US' => 'English'
],
'imageMapping' => [
'en_US' => 'United-States'
]
];
/**
* Renders language switcher dropdown
*
* @return element
*/
public function renderLanguageSwitcher()
{
return $this->_View->element('LanguageSwitcher.language_switcher', [
'availableLanguages' => $this->config('availableLanguages'),
'displayNames' => $this->config('displayNames'),
'imageMapping' => $this->config('imageMapping')
]);
}
/**
* Merge current GET parameters with the language string
*
* @param string $language Language
* @return string Url
*/
public function getUrl($language)
{
$lang = ['lang' => $language];
$query = Hash::merge($lang, $this->request->query);
$urlArray = Hash::merge($this->request->params['pass'], ['?' => $query]);
return Router::url($urlArray);
}
}
|
Make challenges the initial route | import React from 'react'
import { TabNavigator, addNavigationHelpers } from 'react-navigation'
import { connect } from 'react-redux'
import Challenges from './components/Challenges'
import Friends from './components/Friends'
import CameraScreen from './components/CameraScreen'
import PostChallengeScreen from './components/PostChallengeScreen'
import CompleteChallengeScreen from './components/CompleteChallengeScreen'
import LoginScreen from './components/LoginScreen'
export const Navigator = TabNavigator({
Home: {
screen: Friends,
},
Challenges: {
screen: Challenges,
},
CameraScreen: {
screen: CameraScreen,
},
PostChallenge: {
screen: PostChallengeScreen,
},
CompleteChallenge: {
screen: CompleteChallengeScreen
}
}, {
tabBarComponent: () => null,
tabBarPosition: 'bottom',
animationEnabled: true,
swipeEnabled: true,
tabBarOptions: {
activeTintColor: '#e91e63',
},
initialRouteName: 'Challenges',
});
class App extends React.Component {
render () {
const {dispatch, nav} = this.props
if (this.props.user) {
return (
<Navigator
navigation={addNavigationHelpers({
dispatch,
state: nav,
})}
/>
)
} else {
return (
<LoginScreen/>
)
}
}
}
function mapStateToProps (state) {
return {
nav: state.nav,
user: state.user,
}
}
export default connect(
mapStateToProps,
null
)(App) | import React from 'react'
import { TabNavigator, addNavigationHelpers } from 'react-navigation'
import { connect } from 'react-redux'
import Challenges from './components/Challenges'
import Friends from './components/Friends'
import CameraScreen from './components/CameraScreen'
import PostChallengeScreen from './components/PostChallengeScreen'
import CompleteChallengeScreen from './components/CompleteChallengeScreen'
import LoginScreen from './components/LoginScreen'
export const Navigator = TabNavigator({
Home: {
screen: Friends,
},
Challenges: {
screen: Challenges,
},
CameraScreen: {
screen: CameraScreen,
},
PostChallenge: {
screen: PostChallengeScreen,
},
CompleteChallenge: {
screen: CompleteChallengeScreen
}
}, {
tabBarComponent: () => null,
tabBarPosition: 'bottom',
animationEnabled: true,
swipeEnabled: true,
tabBarOptions: {
activeTintColor: '#e91e63',
},
});
class App extends React.Component {
render () {
const {dispatch, nav} = this.props
if (this.props.user) {
return (
<Navigator
navigation={addNavigationHelpers({
dispatch,
state: nav,
})}
/>
)
} else {
return (
<LoginScreen/>
)
}
}
}
function mapStateToProps (state) {
return {
nav: state.nav,
user: state.user,
}
}
export default connect(
mapStateToProps,
null
)(App) |
Fix setPositionVisible on dropdown when in mobile. | var locastyle = locastyle || {};
locastyle.dropdown = (function() {
'use strict';
function init() {
unbind();
bindClickOnTriggers();
bindClickOutsideTriggers();
}
function unbind() {
$("[data-ls-module=dropdown] > a:first-child").off("click.ls");
$("body").off("click.ls");
}
function bindClickOnTriggers() {
$("[data-ls-module=dropdown] > a:first-child").on("click.ls", function(evt) {
evt.preventDefault();
var $target = $($(this).parents("[data-ls-module=dropdown]"));
locastyle.dropdown.toggleDropdown($target);
locastyle.dropdown.closeDropdown($target);
setPositionVisible($target);
evt.stopPropagation();
});
}
function bindClickOutsideTriggers() {
$("body").on("click.ls", function(){
locastyle.dropdown.closeDropdown();
});
}
function toggleDropdown($target) {
$target.toggleClass("ls-active");
locastyle.topbarCurtain.hideCurtains();
}
function closeDropdown(el) {
$("[data-ls-module=dropdown]").not(el).removeClass("ls-active");
}
function setPositionVisible($target){
var $main = $('body');
if($main.get(0).scrollWidth > $main.width()){
$($target).addClass('ls-pos-right')
}
}
return {
init: init,
unbind: unbind,
toggleDropdown: toggleDropdown,
closeDropdown: closeDropdown
}
}());
| var locastyle = locastyle || {};
locastyle.dropdown = (function() {
'use strict';
function init() {
unbind();
bindClickOnTriggers();
bindClickOutsideTriggers();
}
function unbind() {
$("[data-ls-module=dropdown] > a:first-child").off("click.ls");
$("body").off("click.ls");
}
function bindClickOnTriggers() {
$("[data-ls-module=dropdown] > a:first-child").on("click.ls", function(evt) {
evt.preventDefault();
var $target = $($(this).parents("[data-ls-module=dropdown]"));
locastyle.dropdown.toggleDropdown($target);
locastyle.dropdown.closeDropdown($target);
setPositionVisible($target);
evt.stopPropagation();
});
}
function bindClickOutsideTriggers() {
$("body").on("click.ls", function(){
locastyle.dropdown.closeDropdown();
});
}
function toggleDropdown($target) {
$target.toggleClass("ls-active");
locastyle.topbarCurtain.hideCurtains();
}
function closeDropdown(el) {
$("[data-ls-module=dropdown]").not(el).removeClass("ls-active");
}
function setPositionVisible($target){
var $main = $('.ls-main');
if($main.get(0).scrollWidth > $main.width()){
$($target).addClass('ls-pos-right')
}
}
return {
init: init,
unbind: unbind,
toggleDropdown: toggleDropdown,
closeDropdown: closeDropdown
}
}());
|
Use <aside> rather than <div>
So all page content is within landmarks.
Resolves: https://trello.com/c/ZpypHwAa/526-fix-banner-styling | <?php
$showBannerOnNetwork = get_site_option('banner_setting');
$showBannerBySite = get_field('show_banner', 'options');
if ($showBannerOnNetwork == true && ($showBannerBySite == true || $showBannerBySite === null)) {
$bannerTitle = get_site_option('banner_title');
$bannerLinkText = get_site_option('banner_link_text');
$bannerLink = get_site_option('banner_link'); ?>
<aside id="user-satisfaction-survey-container" class="govuk-width-container">
<section id="user-satisfaction-survey" class="visible" aria-hidden="false">
<div class="govuk-grid-row">
<div class="govuk-grid-column-three-quarters">
<p class="govuk-heading-s"><?php echo esc_html($bannerTitle) ?></p>
<p class="govuk-body"><a href="<?php echo esc_url($bannerLink)?>" id="take-survey" target="_blank"><?php echo esc_html($bannerLinkText) ?></a></p>
</div>
<div class="govuk-grid-column-one-quarter">
<p class="govuk-body"><a href="#survey-no-thanks" id="survey-no-thanks" class="govuk-link" role="button" aria-controls="user-satisfaction-survey">No thanks</a></p>
</div>
</div>
</section>
</aside>
<?php
}
?>
| <?php
$showBannerOnNetwork = get_site_option('banner_setting');
$showBannerBySite = get_field('show_banner', 'options');
if ($showBannerOnNetwork == true && ($showBannerBySite == true || $showBannerBySite === null)) {
$bannerTitle = get_site_option('banner_title');
$bannerLinkText = get_site_option('banner_link_text');
$bannerLink = get_site_option('banner_link'); ?>
<div id="user-satisfaction-survey-container" class="govuk-width-container">
<section id="user-satisfaction-survey" class="visible" aria-hidden="false">
<div class="govuk-grid-row">
<div class="govuk-grid-column-three-quarters">
<p class="govuk-heading-s"><?php echo esc_html($bannerTitle) ?></p>
<p class="govuk-body"><a href="<?php echo esc_url($bannerLink)?>" id="take-survey" target="_blank"><?php echo esc_html($bannerLinkText) ?></a></p>
</div>
<div class="govuk-grid-column-one-quarter">
<p class="govuk-body"><a href="#survey-no-thanks" id="survey-no-thanks" class="govuk-link" role="button" aria-controls="user-satisfaction-survey">No thanks</a></p>
</div>
</div>
</section>
</div>
<?php
}
?>
|
Remove "named" parameters when calling ImageSVG in class PDFRendere | <?php
namespace raphiz\passwordcards;
class PDFRenderer
{
public static function render($front, $back)
{
// create new PDF document
$pdf = new \TCPDF(PDF_PAGE_ORIENTATION, 'mm', 'A4', true, 'UTF-8', false);
// set document information
$pdf->SetAuthor('Raphael Zimmermann');
$pdf->SetTitle('Password Card');
$pdf->SetSubject('Password Card');
$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
// add a page
$pdf->AddPage();
// Mark the position to fold...
$pdf->Line(95, 10, 95, 13);
$pdf->Line(95, 72, 95, 75);
// Add the front svg
$pdf->ImageSVG(
$front, // filename
10, // x
15, // y
'85', // width
'55' // height
);
// Add the back svg
$pdf->ImageSVG(
$back, // filename
95, // x
15, // y
'85', // width
'55' // height
);
//Close and output PDF document
return $pdf->Output('generated.pdf', 'S');
}
}
| <?php
namespace raphiz\passwordcards;
class PDFRenderer
{
public static function render($front, $back)
{
// create new PDF document
$pdf = new \TCPDF(PDF_PAGE_ORIENTATION, 'mm', 'A4', true, 'UTF-8', false);
// set document information
$pdf->SetAuthor('Raphael Zimmermann');
$pdf->SetTitle('Password Card');
$pdf->SetSubject('Password Card');
$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
// add a page
$pdf->AddPage();
// Mark the position to fold...
$pdf->Line(95, 10, 95, 13);
$pdf->Line(95, 72, 95, 75);
// Add the front svg
$pdf->ImageSVG(
$file = $front,
$x = 10,
$y = 15,
$w = '85',
$h = '55'
);
// Add the back svg
$pdf->ImageSVG(
$file = $back,
$x = 95,
$y = 15,
$w = '85',
$h = '55'
);
//Close and output PDF document
return $pdf->Output('generated.pdf', 'S');
}
}
|
Apply activity readiness check to map screenshot task (instead of hard-coded delay) | package com.basgeekball.screenshotsnanny.core;
import android.app.Activity;
import android.os.Handler;
import com.basgeekball.screenshotsnanny.activityassistant.ActivityHelper;
import com.basgeekball.screenshotsnanny.helper.Callback;
public class ScreenshotsTask {
public static void perform(final Callback callback, long activityDelay, final long screenshotDelay) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
callback.execute();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Activity activity = ActivityHelper.getCurrentActivity();
ScreenshotsCapturer.execute(activity);
activity.finish();
}
}, screenshotDelay);
}
}, activityDelay);
}
public static void perform(final Class<?> T, final Callback callback, final int mapFragmentId, long activityDelay, final long screenshotDelay) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
callback.execute();
ActivityHelper.doSomethingWhenActivityIsReady(T, new Callback() {
@Override
public void execute() {
Activity activity = ActivityHelper.getCurrentActivity();
ScreenshotsCapturer.executeWithMap(activity, mapFragmentId, true);
}
});
}
}, activityDelay);
}
}
| package com.basgeekball.screenshotsnanny.core;
import android.app.Activity;
import android.os.Handler;
import com.basgeekball.screenshotsnanny.activityassistant.ActivityHelper;
import com.basgeekball.screenshotsnanny.helper.Callback;
public class ScreenshotsTask {
public static void perform(final Callback callback, long activityDelay, final long screenshotDelay) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
callback.execute();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Activity activity = ActivityHelper.getCurrentActivity();
ScreenshotsCapturer.execute(activity);
activity.finish();
}
}, screenshotDelay);
}
}, activityDelay);
}
public static void perform(final Class<?> T, final Callback callback, final int mapFragmentId, long activityDelay, final long screenshotDelay) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
callback.execute();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Activity activity = ActivityHelper.getCurrentActivity();
ScreenshotsCapturer.executeWithMap(activity, mapFragmentId, true);
}
}, 1000);
}
}, activityDelay);
}
}
|
Allow relationship to be null | <?php
/*
* This file is part of JSON-API.
*
* (c) Toby Zerner <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tobscure\JsonApi;
use LogicException;
abstract class AbstractSerializer implements SerializerInterface
{
/**
* The type.
*
* @var string
*/
protected $type;
/**
* {@inheritdoc}
*/
public function getType($model)
{
return $this->type;
}
/**
* {@inheritdoc}
*/
public function getId($model)
{
return $model->id;
}
/**
* {@inheritdoc}
*/
public function getAttributes($model, array $fields = null)
{
return [];
}
/**
* {@inheritdoc}
*
* @throws LogicException
*/
public function getRelationship($model, $name)
{
if (method_exists($this, $name)) {
$relationship = $this->$name($model);
if ($relationship !== null && ! ($relationship instanceof Relationship)) {
throw new LogicException('Relationship method must return null or an instance of '
.Relationship::class);
}
return $relationship;
}
}
}
| <?php
/*
* This file is part of JSON-API.
*
* (c) Toby Zerner <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tobscure\JsonApi;
use LogicException;
abstract class AbstractSerializer implements SerializerInterface
{
/**
* The type.
*
* @var string
*/
protected $type;
/**
* {@inheritdoc}
*/
public function getType($model)
{
return $this->type;
}
/**
* {@inheritdoc}
*/
public function getId($model)
{
return $model->id;
}
/**
* {@inheritdoc}
*/
public function getAttributes($model, array $fields = null)
{
return [];
}
/**
* {@inheritdoc}
*
* @throws LogicException
*/
public function getRelationship($model, $name)
{
if (method_exists($this, $name)) {
$relationship = $this->$name($model);
if (! ($relationship instanceof Relationship)) {
throw new LogicException('Relationship method must return an instance of '
.Relationship::class);
}
return $relationship;
}
}
}
|
Add to extras_require examples section | """setup.py"""
from codecs import open as codecs_open
from setuptools import setup
with codecs_open('README.rst', 'r', 'utf-8') as f:
README = f.read()
with codecs_open('HISTORY.rst', 'r', 'utf-8') as f:
HISTORY = f.read()
setup(
name='jsonrpcserver',
version='3.4.0',
description='Process JSON-RPC requests',
long_description=README + '\n\n' + HISTORY,
author='Beau Barker',
author_email='[email protected]',
url='https://jsonrpcserver.readthedocs.io/',
license='MIT',
packages=['jsonrpcserver'],
package_data={'jsonrpcserver': ['request-schema.json']},
include_package_data=True,
install_requires=['jsonschema', 'six', 'funcsigs'],
extras_require={
'tox': ['tox','pylint'],
'examples': [
'aiohttp',
'aiozmq',
'flask',
'flask-socketio',
'pyzmq',
'tornado',
'websockets',
'werkzeug',
]
},
classifiers=[
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
)
| """setup.py"""
from codecs import open as codecs_open
from setuptools import setup
with codecs_open('README.rst', 'r', 'utf-8') as f:
README = f.read()
with codecs_open('HISTORY.rst', 'r', 'utf-8') as f:
HISTORY = f.read()
setup(
name='jsonrpcserver',
version='3.4.0',
description='Process JSON-RPC requests',
long_description=README + '\n\n' + HISTORY,
author='Beau Barker',
author_email='[email protected]',
url='https://jsonrpcserver.readthedocs.io/',
license='MIT',
packages=['jsonrpcserver'],
package_data={'jsonrpcserver': ['request-schema.json']},
include_package_data=True,
install_requires=['jsonschema', 'six', 'funcsigs'],
extras_require={
'tox': ['tox','pylint'],
'examples': [
'aiohttp',
'flask',
'flask-socketio',
'tornado',
'werkzeug',
'pyzmq'
]
},
classifiers=[
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
)
|
Enable a 'now' property for the PollingDataStream | import logging
from datetime import timedelta
from twisted.internet.task import LoopingCall
from moksha.hub.hub import MokshaHub
log = logging.getLogger('moksha.hub')
class DataStream(object):
""" The parent DataStream class. """
def __init__(self):
self.hub = MokshaHub()
def send_message(self, topic, message):
try:
self.hub.send_message(topic, message)
except Exception, e:
log.error('Cannot send message: %s' % e)
def stop(self):
self.hub.close()
class PollingDataStream(DataStream):
""" A self-polling data stream.
This class represents a data stream that wakes up at a given frequency,
and calls the :meth:`poll` method.
"""
frequency = None # Either a timedelta object, or the number of seconds
now = True
def __init__(self):
super(PollingDataStream, self).__init__()
self.timer = LoopingCall(self.poll)
if isinstance(self.frequency, timedelta):
seconds = self.frequency.seconds + \
(self.frequency.days * 24 * 60 * 60) + \
(self.frequency.microseconds / 1000000.0)
else:
seconds = self.frequency
log.debug("Setting a %s second timers" % seconds)
self.timer.start(seconds, now=self.now)
def poll(self):
raise NotImplementedError
def stop(self):
super(PollingDataStream, self).stop()
self.timer.stop()
| import logging
from datetime import timedelta
from twisted.internet.task import LoopingCall
from moksha.hub.hub import MokshaHub
log = logging.getLogger('moksha.hub')
class DataStream(object):
""" The parent DataStream class. """
def __init__(self):
self.hub = MokshaHub()
def send_message(self, topic, message):
try:
self.hub.send_message(topic, message)
except Exception, e:
log.error('Cannot send message: %s' % e)
def stop(self):
self.hub.close()
class PollingDataStream(DataStream):
""" A self-polling data stream.
This class represents a data stream that wakes up at a given frequency,
and calls the :meth:`poll` method.
"""
frequency = None # Either a timedelta object, or the number of seconds
def __init__(self, now=True):
super(PollingDataStream, self).__init__()
self.timer = LoopingCall(self.poll)
if isinstance(self.frequency, timedelta):
seconds = self.frequency.seconds + \
(self.frequency.days * 24 * 60 * 60) + \
(self.frequency.microseconds / 1000000.0)
else:
seconds = self.frequency
log.debug("Setting a %s second timers" % seconds)
self.timer.start(seconds, now=now)
def poll(self):
raise NotImplementedError
def stop(self):
super(PollingDataStream, self).stop()
self.timer.stop()
|
Use DateTime so that Interval s can be compared easily | package edu.deanza.calendar.models;
import org.joda.time.DateTime;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Sara on 5/28/2016.
*/
public class Event {
protected String name, description, location;
protected DateTime startTime, endTime;
// TODO: implement `categories` field
public Event() {}
public Event(String name, String description, String location, String startTime,
String endTime) {
this.name = name;
this.description = description;
this.location = location;
this.startTime = DateTime.parse(startTime);
this.endTime = DateTime.parse(endTime);
}
public static Event fromJson(JSONObject eventJson) {
Event e = new Event();
try {
e.name = eventJson.getString("name");
e.description = eventJson.getString("description");
e.location = eventJson.getString("location");
e.startTime = DateTime.parse(eventJson.getString("start_time"));
e.endTime = DateTime.parse(eventJson.getString("end_time"));
}
catch (JSONException ex) {
ex.printStackTrace();
return null;
}
return e;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getLocation() {
return location;
}
public DateTime getStartTime() {
return startTime;
}
public DateTime getEndTime() {
return endTime;
}
} | package edu.deanza.calendar.models;
import org.joda.time.LocalTime;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Sara on 5/28/2016.
*/
public class Event {
protected String name, description, location;
protected LocalTime startTime, endTime;
// TODO: implement `categories` field
public Event() {}
public Event(String name, String description, String location, String startTime,
String endTime) {
this.name = name;
this.description = description;
this.location = location;
this.startTime = LocalTime.parse(startTime);
this.endTime = LocalTime.parse(endTime);
}
public static Event fromJson(JSONObject eventJson) {
Event e = new Event();
try {
e.name = eventJson.getString("name");
e.description = eventJson.getString("description");
e.location = eventJson.getString("location");
e.startTime = LocalTime.parse(eventJson.getString("start_time"));
e.endTime = LocalTime.parse(eventJson.getString("end_time"));
}
catch (JSONException ex) {
ex.printStackTrace();
return null;
}
return e;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getLocation() {
return location;
}
public LocalTime getStartTime() {
return startTime;
}
public LocalTime getEndTime() {
return endTime;
}
} |
Fix statistics link visible, in Controller all action has permission `manage` but link visible was `support` | <?php
/**
* HiPanel tickets module
*
* @link https://github.com/hiqdev/hipanel-module-ticket
* @package hipanel-module-ticket
* @license BSD-3-Clause
* @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
*/
namespace hipanel\modules\ticket\menus;
use Yii;
class SidebarMenu extends \hiqdev\yii2\menus\Menu
{
public function items()
{
return [
'tickets' => [
'label' => Yii::t('hipanel:ticket', 'Support'),
'url' => ['/ticket/ticket/index'],
'icon' => 'fa-life-ring',
'items' => [
'tickets' => [
'label' => Yii::t('hipanel:ticket', 'Tickets'),
'url' => ['/ticket/ticket/index'],
'visible' => Yii::$app->user->can('ticket.read'),
],
'templates' => [
'label' => Yii::t('hipanel:ticket', 'Templates'),
'url' => ['/ticket/template/index'],
'visible' => Yii::$app->user->can('support'),
],
'statistics' => [
'label' => Yii::t('hipanel:ticket', 'Tickets statistics'),
'url' => ['/ticket/statistic/index'],
'visible' => Yii::$app->user->can('manage'),
],
],
],
];
}
}
| <?php
/**
* HiPanel tickets module
*
* @link https://github.com/hiqdev/hipanel-module-ticket
* @package hipanel-module-ticket
* @license BSD-3-Clause
* @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
*/
namespace hipanel\modules\ticket\menus;
use Yii;
class SidebarMenu extends \hiqdev\yii2\menus\Menu
{
public function items()
{
return [
'tickets' => [
'label' => Yii::t('hipanel:ticket', 'Support'),
'url' => ['/ticket/ticket/index'],
'icon' => 'fa-life-ring',
'items' => [
'tickets' => [
'label' => Yii::t('hipanel:ticket', 'Tickets'),
'url' => ['/ticket/ticket/index'],
'visible' => Yii::$app->user->can('ticket.read'),
],
'templates' => [
'label' => Yii::t('hipanel:ticket', 'Templates'),
'url' => ['/ticket/template/index'],
'visible' => Yii::$app->user->can('support'),
],
'statistics' => [
'label' => Yii::t('hipanel:ticket', 'Tickets statistics'),
'url' => ['/ticket/statistic/index'],
'visible' => Yii::$app->user->can('support'),
],
],
],
];
}
}
|
Remove reports from navigation in layout view | <!DOCTYPE html>
<html>
<head>
<title>Budget</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito+Sans:400,400i" />
<link rel="stylesheet" href="/style.css" />
</head>
<body>
@if (Auth::check())
<div class="navigation">
<ul>
<li>
<a href="/dashboard">Dashboard</a>
</li>
<li>
<a href="/search">Search</a>
</li>
<li>
<a href="/budgets">Budgets</a>
</li>
<li>
<a href="/earnings">Earnings</a>
</li>
<li>
<a href="/spendings">Spendings</a>
</li>
<li>
<a href="/tags">Tags</a>
</li>
</ul>
<ul>
<li>
<a href="/settings">Settings</a>
</li>
<li>
<a href="/logout">Log out</a>
</li>
</ul>
</div>
@endif
<div class="body">
@yield('body')
</div>
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<title>Budget</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito+Sans:400,400i" />
<link rel="stylesheet" href="/style.css" />
</head>
<body>
@if (Auth::check())
<div class="navigation">
<ul>
<li>
<a href="/dashboard">Dashboard</a>
</li>
<li>
<a href="/search">Search</a>
</li>
<li>
<a href="/reports">Reports</a>
</li>
<li>
<a href="/budgets">Budgets</a>
</li>
<li>
<a href="/earnings">Earnings</a>
</li>
<li>
<a href="/spendings">Spendings</a>
</li>
<li>
<a href="/tags">Tags</a>
</li>
</ul>
<ul>
<li>
<a href="/settings">Settings</a>
</li>
<li>
<a href="/logout">Log out</a>
</li>
</ul>
</div>
@endif
<div class="body">
@yield('body')
</div>
</body>
</html>
|
Revert "Change return type hinting to reference the Proxy class"
This reverts commit 9ea4df8541c682097304bc9b1b42f68307f8d57e. | <?php
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\NullObject\MethodGenerator;
use ProxyManager\Generator\MethodGenerator;
use ProxyManager\ProxyGenerator\Util\Properties;
use ReflectionClass;
use ReflectionProperty;
use Zend\Code\Generator\Exception\InvalidArgumentException;
use function array_map;
use function implode;
/**
* The `staticProxyConstructor` implementation for null object proxies
*
*/
class StaticProxyConstructor extends MethodGenerator
{
/**
* Constructor
*
* @param ReflectionClass $originalClass Reflection of the class to proxy
*
* @throws InvalidArgumentException
*/
public function __construct(ReflectionClass $originalClass)
{
parent::__construct('staticProxyConstructor', [], static::FLAG_PUBLIC | static::FLAG_STATIC);
$nullableProperties = array_map(
function (ReflectionProperty $publicProperty) : string {
return '$instance->' . $publicProperty->getName() . ' = null;';
},
Properties::fromReflectionClass($originalClass)->getPublicProperties()
);
$this->setReturnType($originalClass->getName());
$this->setDocBlock('Constructor for null object initialization');
$this->setBody(
'static $reflection;' . "\n\n"
. '$reflection = $reflection ?? $reflection = new \ReflectionClass(__CLASS__);' . "\n"
. '$instance = $reflection->newInstanceWithoutConstructor();' . "\n\n"
. ($nullableProperties ? implode("\n", $nullableProperties) . "\n\n" : '')
. 'return $instance;'
);
}
}
| <?php
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\NullObject\MethodGenerator;
use ProxyManager\Generator\MethodGenerator;
use ProxyManager\ProxyGenerator\Util\Properties;
use ReflectionClass;
use ReflectionProperty;
use Zend\Code\Generator\Exception\InvalidArgumentException;
use function array_map;
use function implode;
/**
* The `staticProxyConstructor` implementation for null object proxies
*
*/
class StaticProxyConstructor extends MethodGenerator
{
/**
* Constructor
*
* @param ReflectionClass $originalClass Reflection of the class to proxy
*
* @throws InvalidArgumentException
*/
public function __construct(ReflectionClass $originalClass)
{
parent::__construct('staticProxyConstructor', [], static::FLAG_PUBLIC | static::FLAG_STATIC);
$nullableProperties = array_map(
function (ReflectionProperty $publicProperty) : string {
return '$instance->' . $publicProperty->getName() . ' = null;';
},
Properties::fromReflectionClass($originalClass)->getPublicProperties()
);
$this->setReturnType($this->getName());
$this->setDocBlock('Constructor for null object initialization');
$this->setBody(
'static $reflection;' . "\n\n"
. '$reflection = $reflection ?? $reflection = new \ReflectionClass(__CLASS__);' . "\n"
. '$instance = $reflection->newInstanceWithoutConstructor();' . "\n\n"
. ($nullableProperties ? implode("\n", $nullableProperties) . "\n\n" : '')
. 'return $instance;'
);
}
}
|
Fix avatar on other pages.
The styling wasn't being set on the parent container so you ended up
with weird things. | // @flow
import React, {Component} from 'react'
import resolveRoot from '../../desktop/resolve-root'
import {globalColorsDZ2} from '../styles/style-guide'
import type {Props} from './avatar'
const noAvatar = `file:///${resolveRoot('shared/images/icons/[email protected]')}`
export default class Avatar extends Component {
props: Props;
state: {
avatarLoaded: boolean
};
constructor (props: Props) {
super(props)
this.state = {avatarLoaded: false}
}
render () {
const width = this.props.size
const height = this.props.size
return (
<div style={{position: 'relative', width, height, ...this.props.style}}>
<div
style={{...avatarStyle(this.props.size),
backgroundImage: `url('${noAvatar}')`,
backgroundSize: 'cover'
}}/>
<img
src={this.props.url}
style={{...avatarStyle(this.props.size),
display: this.state.avatarLoaded ? 'block' : 'none',
backgroundColor: globalColorsDZ2.white
}}
onLoad={() => this.setState({avatarLoaded: true})}/>
</div>
)
}
}
function avatarStyle (size: number): Object {
return {
width: size,
height: size,
borderRadius: size / 2,
position: 'absolute'
}
}
| // @flow
import React, {Component} from 'react'
import resolveRoot from '../../desktop/resolve-root'
import {globalColorsDZ2} from '../styles/style-guide'
import type {Props} from './avatar'
const noAvatar = `file:///${resolveRoot('shared/images/icons/[email protected]')}`
export default class Avatar extends Component {
props: Props;
state: {
avatarLoaded: boolean
};
constructor (props: Props) {
super(props)
this.state = {avatarLoaded: false}
}
render () {
return (
<div style={{position: 'relative'}}>
<div
style={{...avatarStyle(this.props.size),
backgroundImage: `url('${noAvatar}')`,
backgroundSize: 'cover',
...this.props.style
}}/>
<img
src={this.props.url}
style={{...avatarStyle(this.props.size),
display: this.state.avatarLoaded ? 'block' : 'none',
backgroundColor: globalColorsDZ2.white,
...this.props.style
}}
onLoad={() => this.setState({avatarLoaded: true})}/>
</div>
)
}
}
function avatarStyle (size: number): Object {
return {
width: size,
height: size,
borderRadius: size / 2,
position: 'absolute'
}
}
|
Update marker call for pytest 3.6+ | # -*- coding: utf-8 -*-
import sys
import pytest
class ExpectedException(Exception):
pass
class ExpectedMessage(Exception):
pass
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_call(item):
outcome = yield
raises_marker = item.get_closest_marker('raises')
if raises_marker:
exception = raises_marker.kwargs.get('exception')
exception = exception or Exception
message = raises_marker.kwargs.get('message')
raised_exception = outcome.excinfo[1] if outcome.excinfo else None
traceback = outcome.excinfo[2] if outcome.excinfo else None
if isinstance(raised_exception, exception):
outcome.force_result(None)
if message is not None:
try:
raised_message = str(raised_exception)
if message not in raised_message:
raise ExpectedMessage('"{}" not in "{}"'.format(message, raised_message))
except(ExpectedMessage):
excinfo = sys.exc_info()
if traceback:
outcome.excinfo = excinfo[:2] + (traceback, )
else:
outcome.excinfo = excinfo
else:
try:
raise raised_exception or ExpectedException('Expected exception {}, but it did not raise'.format(exception))
except(ExpectedException):
excinfo = sys.exc_info()
if traceback:
outcome.excinfo = excinfo[:2] + (traceback, )
else:
outcome.excinfo = excinfo
| # -*- coding: utf-8 -*-
import sys
import pytest
class ExpectedException(Exception):
pass
class ExpectedMessage(Exception):
pass
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_call(item):
outcome = yield
raises_marker = item.get_marker('raises')
if raises_marker:
exception = raises_marker.kwargs.get('exception')
exception = exception or Exception
message = raises_marker.kwargs.get('message')
raised_exception = outcome.excinfo[1] if outcome.excinfo else None
traceback = outcome.excinfo[2] if outcome.excinfo else None
if isinstance(raised_exception, exception):
outcome.force_result(None)
if message is not None:
try:
raised_message = str(raised_exception)
if message not in raised_message:
raise ExpectedMessage('"{}" not in "{}"'.format(message, raised_message))
except(ExpectedMessage):
excinfo = sys.exc_info()
if traceback:
outcome.excinfo = excinfo[:2] + (traceback, )
else:
outcome.excinfo = excinfo
else:
try:
raise raised_exception or ExpectedException('Expected exception {}, but it did not raise'.format(exception))
except(ExpectedException):
excinfo = sys.exc_info()
if traceback:
outcome.excinfo = excinfo[:2] + (traceback, )
else:
outcome.excinfo = excinfo
|
Fix autologin for versioned feeds. | /**
* Automatically log in a user with a userId and key, so they can view/upload to a feedsource.
*/
var app = require('application');
module.exports = function () {
var feedSourceId, feedVersionId, userId, key;
// yes, this is in fact four arguments, not five, but the Bootstrap router throws an extra null on the end
if (arguments.length == 5) {
feedSourceId = arguments[0];
feedVersionId = arguments[1];
userId = arguments[2];
key = arguments[3];
}
else if (arguments.length == 4) {
feedSourceId = arguments[0];
feedVersionId = null;
userId = arguments[1];
key = arguments[2];
}
else return;
$.post('/authenticate',
{
userId: userId,
key: key
})
.then(function (data) {
$('#logged-in-user').text(window.Messages('app.account.logged_in_as', data['username']));
$('#logout').removeClass('hidden');
// note: log out is handled in application.js
app.user = data;
window.location.hash = '#feed/' + feedSourceId +
(feedVersionId != null ? '/' + feedVersionId : '');
})
.fail(function () {
// TODO: alert is bad, bad error message, not translatable.
alert('Invalid key');
});
}
| /**
* Automatically log in a user with a userId and key, so they can view/upload to a feedsource.
*/
var app = require('application');
module.exports = function () {
var feedSourceId, feedVersionId, userId, key;
if (arguments.length == 4) {
feedSourceId = arguments[0];
feedVersionId = arguments[1];
userId = arguments[2];
key = arguments[3];
}
else if (arguments.length == 3) {
feedSourceId = arguments[0];
feedVersionId = null;
userId = arguments[1];
key = arguments[3];
}
else return;
$.post('/authenticate',
{
userId: userId,
key: key
})
.then(function (data) {
$('#logged-in-user').text(window.Messages('app.account.logged_in_as', data['username']));
$('#logout').removeClass('hidden');
// note: log out is handled in application.js
app.user = data;
window.location.hash = '#feed/' + feedSourceId +
(feedVersionId != null ? '/' + feedVersionId : '');
})
.fail(function () {
// TODO: alert is bad, bad error message, not translatable.
alert('Invalid key');
});
}
|
Remove empty string from requirements list
When we moved to Python 3 we used this simpler method to read the requirements
file. However we need to remove the empty/Falsey elements from the list.
This fixes the error:
```
Failed building wheel for molo.yourwords
``` | from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('requirements.txt') as req_file:
requires = [req for req in req_file.read().split('\n') if req]
with open('requirements-dev.txt') as req_file:
requires_dev = [req for req in req_file.read().split('\n') if req]
with open('VERSION') as fp:
version = fp.read().strip()
setup(name='molo.yourwords',
version=version,
description=('A Molo module that enables user generated content '
'competitions'),
long_description=readme,
classifiers=[
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.6",
"Framework :: Django",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='Praekelt Foundation',
author_email='[email protected]',
url='http://github.com/praekelt/molo.yourwords',
license='BSD',
keywords='praekelt, mobi, web, django',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
namespace_packages=['molo'],
install_requires=requires,
tests_require=requires_dev,
entry_points={})
| from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('requirements.txt') as req_file:
requires = req_file.read().split('\n')
with open('requirements-dev.txt') as req_file:
requires_dev = req_file.read().split('\n')
with open('VERSION') as fp:
version = fp.read().strip()
setup(name='molo.yourwords',
version=version,
description=('A Molo module that enables user generated content '
'competitions'),
long_description=readme,
classifiers=[
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.6",
"Framework :: Django",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='Praekelt Foundation',
author_email='[email protected]',
url='http://github.com/praekelt/molo.yourwords',
license='BSD',
keywords='praekelt, mobi, web, django',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
namespace_packages=['molo'],
install_requires=requires,
tests_require=requires_dev,
entry_points={})
|
Update autocomplete spec to use <ol> | /*global describe, beforeEach, module, inject, it, spyOn, expect, $, console */
describe('dfAutocompleteDatalist', function() {
'use strict';
var scope, $compile;
beforeEach(module('dataform.directives'));
beforeEach(inject(function(_$rootScope_, _$compile_, _$window_) {
scope = _$rootScope_.$new();
$compile = _$compile_;
}));
describe('compiling this directive', function() {
it('should throw an error if there is no df-list attribute value', function() {
function compile() {
$compile('<input df-autocomplete-datalist>')(scope);
}
expect(compile).toThrow();
});
it('should throw an error if the df-list attribute points to a nonexistent datalist', function() {
function compile() {
$compile('<input df-autocomplete-datalist=foo>')(scope);
}
expect(compile).toThrow();
});
});
});
describe('dfDatalist', function() {
'use strict';
var scope, $compile;
beforeEach(module('dataform.directives'));
beforeEach(inject(function(_$rootScope_, _$compile_, _$window_) {
scope = _$rootScope_.$new();
$compile = _$compile_;
}));
describe('compiling this directive', function() {
it('should not throw an error', function() {
function compile() {
$compile('<ol df-datalist id=foo></ol>')(scope);
}
expect(compile).not.toThrow();
});
});
});
| /*global describe, beforeEach, module, inject, it, spyOn, expect, $, console */
describe('dfAutocompleteDatalist', function() {
'use strict';
var scope, $compile;
beforeEach(module('dataform.directives'));
beforeEach(inject(function(_$rootScope_, _$compile_, _$window_) {
scope = _$rootScope_.$new();
$compile = _$compile_;
}));
describe('compiling this directive', function() {
it('should throw an error if there is no df-list attribute value', function() {
function compile() {
$compile('<input df-autocomplete-datalist>')(scope);
}
expect(compile).toThrow();
});
it('should throw an error if the df-list attribute points to a nonexistent datalist', function() {
function compile() {
$compile('<input df-autocomplete-datalist=foo>')(scope);
}
expect(compile).toThrow();
});
});
});
describe('dfDatalist', function() {
'use strict';
var scope, $compile;
beforeEach(module('dataform.directives'));
beforeEach(inject(function(_$rootScope_, _$compile_, _$window_) {
scope = _$rootScope_.$new();
$compile = _$compile_;
}));
describe('compiling this directive', function() {
it('should not throw an error', function() {
function compile() {
$compile('<datalist df-datalist id=foo></datalist>')(scope);
}
expect(compile).not.toThrow();
});
});
});
|
Allow multiple sorting criteria. Reverse specific to each field | 'use strict';
(
function(angular) {
return angular
.module('ngOrderObjectBy', [])
.filter('orderObjectBy', function() {
return function (items, fields) {
if(!Array.isArray(fields))
{
fields = [fields];
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var filtered = [];
angular.forEach(items, function(item, key) {
item.key = key;
filtered.push(item);
});
function index(obj, i) {
return obj[i];
}
function compare(a, b, field)
{
var reverse = false;
if(field.charAt(0) == "-")
{
field = field.substr(1);
reverse = true;
}
var comparator;
var reducedA = field.split('.').reduce(index, a);
var reducedB = field.split('.').reduce(index, b);
if (isNumeric(reducedA) && isNumeric(reducedB)) {
reducedA = Number(reducedA);
reducedB = Number(reducedB);
}
if (reducedA === reducedB) {
comparator = 0;
} else {
if (reverse) {
comparator = reducedA > reducedB ? -1 : 1;
} else {
comparator = reducedA > reducedB ? 1 : -1;
}
}
return comparator;
}
filtered.sort(function(a, b)
{
var result = 0;
for (var f in fields)
{
result = compare(a, b, fields[f]);
if (result !== 0) break;
}
return result;
});
return filtered;
};
});
}
)(angular);
| 'use strict';
(
function(angular) {
return angular
.module('ngOrderObjectBy', [])
.filter('orderObjectBy', function() {
return function (items, field, reverse) {
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var filtered = [];
angular.forEach(items, function(item, key) {
item.key = key;
filtered.push(item);
});
function index(obj, i) {
return obj[i];
}
filtered.sort(function (a, b) {
var comparator;
var reducedA = field.split('.').reduce(index, a);
var reducedB = field.split('.').reduce(index, b);
if (isNumeric(reducedA) && isNumeric(reducedB)) {
reducedA = Number(reducedA);
reducedB = Number(reducedB);
}
if (reducedA === reducedB) {
comparator = 0;
} else {
comparator = reducedA > reducedB ? 1 : -1;
}
return comparator;
});
if (reverse) {
filtered.reverse();
}
return filtered;
};
});
}
)(angular);
|
Raise NotImplemented if methods aren't overridden | # -*- mode: python; indent-tabs-mode: nil -*-
class Connection(object):
"""Interface for receiver connections.
A receiver connection is something that can send messages (filter requests,
multilateration results) to a particular receiver. A single connection
may handle only a single receiver, or may multiplex multiple receivers.
This is a duck-typed interface, implementations are not required to inherit
this class as long as they provide methods with equivalent signatures.
"""
def request_traffic(self, receiver, icao_set):
"""Request that a receiver starts sending traffic for the given
set of aircraft.
receiver: the handle of the concerned receiver
icao_set: a set of ICAO addresses (as ints) to start sending
"""
raise NotImplementedError
def suppress_traffic(self, receiver, icao_set):
"""Request that a receiver stops sending traffic for the given
set of aircraft.
receiver: the handle of the concerned receiver
icao_set: a set of ICAO addresses (as ints) to stop sending
"""
raise NotImplementedError
def report_mlat_position(self, receiver,
icao, utc, ecef, ecef_cov, nstations):
"""Report a multilaterated position result.
receiver: the handle of the concerned receiver
icao: the ICAO address of the aircraft (as an int)
utc: the approximate validity time of the position
ecef: an (x,y,z) tuple giving the position in ECEF coordinates
ecef_cov: a 3x3 matrix giving the covariance matrix of ecef
nstations: the number of stations that contributed to the result
"""
raise NotImplementedError
| # -*- mode: python; indent-tabs-mode: nil -*-
class Connection(object):
"""Interface for receiver connections.
A receiver connection is something that can send messages (filter requests,
multilateration results) to a particular receiver. A single connection
may handle only a single receiver, or may multiplex multiple receivers.
This is a duck-typed interface, implementations are not required to inherit
this class as long as they provide methods with equivalent signatures.
"""
def request_traffic(self, receiver, icao_set):
"""Request that a receiver starts sending traffic for the given
set of aircraft.
receiver: the handle of the concerned receiver
icao_set: a set of ICAO addresses (as ints) to start sending
"""
pass
def suppress_traffic(self, receiver, icao_set):
"""Request that a receiver stops sending traffic for the given
set of aircraft.
receiver: the handle of the concerned receiver
icao_set: a set of ICAO addresses (as ints) to stop sending
"""
pass
def report_mlat_position(self, receiver,
icao, utc, ecef, ecef_cov, nstations):
"""Report a multilaterated position result.
receiver: the handle of the concerned receiver
icao: the ICAO address of the aircraft (as an int)
utc: the approximate validity time of the position
ecef: an (x,y,z) tuple giving the position in ECEF coordinates
ecef_cov: a 3x3 matrix giving the covariance matrix of ecef
nstations: the number of stations that contributed to the result
"""
pass
|
Update Python/Django: Admin queryset -> get_queryset | from django.contrib import admin
from timepiece.contracts.models import ProjectContract, ContractHour,\
ContractAssignment, HourGroup
class ContractAssignmentInline(admin.TabularInline):
model = ContractAssignment
raw_id_fields = ('user',)
def get_queryset(self, request):
qs = super(ContractAssignmentInline, self).get_queryset(request)
return qs.select_related()
class ContractHourInline(admin.TabularInline):
model = ContractHour
class ProjectContractAdmin(admin.ModelAdmin):
model = ProjectContract
list_display = ('name', 'start_date', 'end_date', 'status',
'contracted_hours', 'pending_hours',
'hours_assigned', 'hours_unassigned',
'hours_worked',
'type')
inlines = (ContractAssignmentInline, ContractHourInline)
list_filter = ('status', 'type')
filter_horizontal = ('projects',)
list_per_page = 20
search_fields = ('name', 'projects__name', 'projects__business__name')
def hours_unassigned(self, obj):
return obj.contracted_hours() - obj.hours_assigned
class HourGroupAdmin(admin.ModelAdmin):
model = HourGroup
list_display = ('name',)
list_filter = ('activities',)
ordering = ('order', 'name')
filter_horizontal = ('activities',)
admin.site.register(ProjectContract, ProjectContractAdmin)
admin.site.register(HourGroup, HourGroupAdmin)
admin.site.register(ContractHour)
| from django.contrib import admin
from timepiece.contracts.models import ProjectContract, ContractHour,\
ContractAssignment, HourGroup
class ContractAssignmentInline(admin.TabularInline):
model = ContractAssignment
raw_id_fields = ('user',)
def queryset(self, request):
qs = super(ContractAssignmentInline, self).queryset(request)
return qs.select_related()
class ContractHourInline(admin.TabularInline):
model = ContractHour
class ProjectContractAdmin(admin.ModelAdmin):
model = ProjectContract
list_display = ('name', 'start_date', 'end_date', 'status',
'contracted_hours', 'pending_hours',
'hours_assigned', 'hours_unassigned',
'hours_worked',
'type')
inlines = (ContractAssignmentInline, ContractHourInline)
list_filter = ('status', 'type')
filter_horizontal = ('projects',)
list_per_page = 20
search_fields = ('name', 'projects__name', 'projects__business__name')
def hours_unassigned(self, obj):
return obj.contracted_hours() - obj.hours_assigned
class HourGroupAdmin(admin.ModelAdmin):
model = HourGroup
list_display = ('name',)
list_filter = ('activities',)
ordering = ('order', 'name')
filter_horizontal = ('activities',)
admin.site.register(ProjectContract, ProjectContractAdmin)
admin.site.register(HourGroup, HourGroupAdmin)
admin.site.register(ContractHour)
|
Use .get methods when retrieving uuid keys | #!/usr/bin/env python
import argparse
from bioblend import galaxy
import json
def main():
"""
This script uses bioblend to import .ga workflow files into a running instance of Galaxy
"""
parser = argparse.ArgumentParser()
parser.add_argument("-w", "--workflow_path", help='Path to workflow file')
parser.add_argument("-g", "--galaxy",
dest="galaxy_url",
help="Target Galaxy instance URL/IP address (required "
"if not defined in the tools list file)",)
parser.add_argument("-a", "--apikey",
dest="api_key",
help="Galaxy admin user API key (required if not "
"defined in the tools list file)",)
args = parser.parse_args()
gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key)
import_uuid = json.load(open(args.workflow_path, 'r')).get('uuid')
existing_uuids = [d.get('latest_workflow_uuid') for d in gi.workflows.get_workflows()]
if import_uuid not in existing_uuids:
gi.workflows.import_workflow_from_local_path(args.workflow_path)
if __name__ == '__main__':
main()
| #!/usr/bin/env python
import argparse
from bioblend import galaxy
import json
def main():
"""
This script uses bioblend to import .ga workflow files into a running instance of Galaxy
"""
parser = argparse.ArgumentParser()
parser.add_argument("-w", "--workflow_path", help='Path to workflow file')
parser.add_argument("-g", "--galaxy",
dest="galaxy_url",
help="Target Galaxy instance URL/IP address (required "
"if not defined in the tools list file)",)
parser.add_argument("-a", "--apikey",
dest="api_key",
help="Galaxy admin user API key (required if not "
"defined in the tools list file)",)
args = parser.parse_args()
gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key)
import_uuid = json.load(open(args.workflow_path, 'r'))['uuid']
existing_uuids = [d['latest_workflow_uuid'] for d in gi.workflows.get_workflows()]
if import_uuid not in existing_uuids:
gi.workflows.import_workflow_from_local_path(args.workflow_path)
if __name__ == '__main__':
main()
|
Set EAV form class name to match EAV model name
(for easier debugging, at least in theory) | from django import forms
from django.core.exceptions import ValidationError
from cyder.base.eav.constants import ATTRIBUTE_TYPES
from cyder.base.eav.models import Attribute
def get_eav_form(eav_model, entity_model):
class EAVForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
if 'instance' in kwargs and kwargs['instance'] is not None:
# This is a bound form with a real instance
if 'initial' not in kwargs:
kwargs['initial'] = dict()
# Set the attribute field to the name, not the pk
kwargs['initial']['attribute'] = \
kwargs['instance'].attribute.name
# Set the attribute_type field to the current attribute's type
kwargs['initial']['attribute_type'] = \
kwargs['instance'].attribute.attribute_type
super(EAVForm, self).__init__(*args, **kwargs)
attribute_type = forms.ChoiceField(
choices=eav_model._meta.get_field('attribute').type_choices)
entity = forms.ModelChoiceField(
queryset=entity_model.objects.all(),
widget=forms.HiddenInput())
class Meta:
model = eav_model
fields = ('entity', 'attribute_type', 'attribute', 'value')
EAVForm.__name__ = eav_model.__name__ + 'Form'
return EAVForm
| from django import forms
from django.core.exceptions import ValidationError
from cyder.base.eav.constants import ATTRIBUTE_TYPES
from cyder.base.eav.models import Attribute
def get_eav_form(eav_model, entity_model):
class EAVForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
if 'instance' in kwargs and kwargs['instance'] is not None:
# This is a bound form with a real instance
if 'initial' not in kwargs:
kwargs['initial'] = dict()
# Set the attribute field to the name, not the pk
kwargs['initial']['attribute'] = \
kwargs['instance'].attribute.name
# Set the attribute_type field to the current attribute's type
kwargs['initial']['attribute_type'] = \
kwargs['instance'].attribute.attribute_type
super(EAVForm, self).__init__(*args, **kwargs)
attribute_type = forms.ChoiceField(
choices=eav_model._meta.get_field('attribute').type_choices)
entity = forms.ModelChoiceField(
queryset=entity_model.objects.all(),
widget=forms.HiddenInput())
class Meta:
model = eav_model
fields = ('entity', 'attribute_type', 'attribute', 'value')
return EAVForm
|
Add specification of output directory from command line | #!/usr/bin/env python
# Grab runs from S3 and do analysis
#
# Daniel Klein, 2015-08-14
import sys
import subprocess
import glob
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('remote_dir', help = 'S3 directory with completed runs')
parser.add_argument('output_dir', help = 'Local destination for output')
parser.add_argument('run_ids', help = 'IDs of runs to analyze',
nargs = '+')
parser.add_argument('--leave', help = 'don\'t delete downloaded files',
action = 'store_true')
args = parser.parse_args()
for run_id in args.run_ids:
print run_id
match_run = '%s_*__completed.json' % run_id
subprocess.call(['aws', 's3', 'sync', args.remote_dir, args.output_dir,
'--exclude', '*',
'--include', match_run])
runs = glob.glob(args.output_dir + match_run)
print runs
run_stems = [run.split('completed')[0] for run in runs]
subprocess.call(['python', 'test.py'] + \
[run_stem + 'load.json' for run_stem in run_stems])
subprocess.call(['mv', 'out.pdf',
'%s/%s_figs.pdf' % (args.output_dir, run_id)])
if not args.leave:
for run in runs:
subprocess.call(['rm', run])
| #!/usr/bin/env python
# Grab runs from S3 and do analysis
#
# Daniel Klein, 2015-08-14
import sys
import subprocess
import glob
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('remote_dir', help = 'S3 directory with completed runs')
parser.add_argument('run_ids', help = 'IDs of runs to analyze',
nargs = '+')
parser.add_argument('--leave', help = 'don\'t delete downloaded files',
action = 'store_true')
args = parser.parse_args()
for run_id in args.run_ids:
print run_id
match_run = '%s_*__completed.json' % run_id
subprocess.call(['aws', 's3', 'sync', args.remote_dir, 'runs/',
'--exclude', '*',
'--include', match_run])
runs = glob.glob('runs/' + match_run)
print runs
run_stems = [run.split('completed')[0] for run in runs]
subprocess.call(['python', 'test.py'] + \
[run_stem + 'load.json' for run_stem in run_stems])
subprocess.call(['mv', 'out.pdf', 'runs/%s_figs.pdf' % run_id])
if not args.leave:
for run in runs:
subprocess.call(['rm', run])
|
Fix missing notifications in Rooms | var Rooms = {
anonymous_room: false,
refresh: function() {
var items = document.querySelectorAll('#rooms_widget ul li:not(.subheader)');
var i = 0;
while(i < items.length)
{
if(items[i].dataset.jid != null) {
items[i].onclick = function(e) {
Chats.refresh();
Chat_ajaxGetRoom(this.dataset.jid);
MovimUtils.removeClassInList('active', items);
MovimUtils.addClass(this, 'active');
}
}
MovimUtils.removeClass(items[i], 'active');
i++;
}
Notification_ajaxGet();
},
/**
* @brief Connect to an anonymous server
* @param The jid to remember
*/
anonymousInit : function() {
MovimWebsocket.register(function()
{
form = document.querySelector('form[name="loginanonymous"]');
form.onsubmit = function(e) {
e.preventDefault();
// We login
LoginAnonymous_ajaxLogin(this.querySelector('input#nick').value);
}
});
},
/**
* @brief Join an anonymous room
* @param The jid to remember
*/
anonymousJoin : function() {
// We display the room
Chat_ajaxGetRoom(Rooms.anonymous_room);
// And finally we join
Rooms_ajaxExit(Rooms.anonymous_room);
Rooms_ajaxJoin(Rooms.anonymous_room);
}
}
MovimWebsocket.attach(function() {
Rooms.anonymousInit();
Rooms_ajaxDisplay();
});
| var Rooms = {
anonymous_room: false,
refresh: function() {
var items = document.querySelectorAll('#rooms_widget ul li:not(.subheader)');
var i = 0;
while(i < items.length)
{
if(items[i].dataset.jid != null) {
items[i].onclick = function(e) {
Chats.refresh();
Chat_ajaxGetRoom(this.dataset.jid);
MovimUtils.removeClassInList('active', items);
MovimUtils.addClass(this, 'active');
}
}
MovimUtils.removeClass(items[i], 'active');
i++;
}
},
/**
* @brief Connect to an anonymous server
* @param The jid to remember
*/
anonymousInit : function() {
MovimWebsocket.register(function()
{
form = document.querySelector('form[name="loginanonymous"]');
form.onsubmit = function(e) {
e.preventDefault();
// We login
LoginAnonymous_ajaxLogin(this.querySelector('input#nick').value);
}
});
},
/**
* @brief Join an anonymous room
* @param The jid to remember
*/
anonymousJoin : function() {
// We display the room
Chat_ajaxGetRoom(Rooms.anonymous_room);
// And finally we join
Rooms_ajaxExit(Rooms.anonymous_room);
Rooms_ajaxJoin(Rooms.anonymous_room);
}
}
MovimWebsocket.attach(function() {
Rooms.refresh();
Rooms.anonymousInit();
Rooms_ajaxDisplay();
});
|
Remove square bracket array syntax for 5.3 compatibility | <?php
namespace spec\PhpSpec\Wrapper\Subject;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use PhpSpec\Formatter\Presenter\PresenterInterface;
class WrappedObjectSpec extends ObjectBehavior
{
function let(PresenterInterface $presenter)
{
$this->beConstructedWith(null, $presenter);
}
function it_instantiates_object_using_classname()
{
$this->callOnWrappedObject('beAnInstanceOf', array('ArrayObject'));
$this->instantiate()->shouldHaveType('ArrayObject');
}
function it_keeps_instantiated_object()
{
$this->callOnWrappedObject('beAnInstanceOf', array('ArrayObject'));
$this->instantiate()->shouldBeEqualTo($this->getInstance());
}
function it_can_be_instantiated_with_a_factory_method()
{
$this->callOnWrappedObject(
'beConstructedThrough',
array(
'\DateTime::createFromFormat',
array('d-m-Y', '01-01-1970')
)
);
$this->instantiate()->shouldHaveType('\DateTime');
}
function it_can_be_instantiated_with_a_factory_method_with_method_name_only()
{
$this->callOnWrappedObject('beAnInstanceOf', array('\DateTime'));
$this->callOnWrappedObject(
'beConstructedThrough',
array(
'createFromFormat',
array('d-m-Y', '01-01-1970')
)
);
$this->instantiate()->shouldHaveType('\DateTime');
}
}
| <?php
namespace spec\PhpSpec\Wrapper\Subject;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use PhpSpec\Formatter\Presenter\PresenterInterface;
class WrappedObjectSpec extends ObjectBehavior
{
function let(PresenterInterface $presenter)
{
$this->beConstructedWith(null, $presenter);
}
function it_instantiates_object_using_classname()
{
$this->callOnWrappedObject('beAnInstanceOf', array('ArrayObject'));
$this->instantiate()->shouldHaveType('ArrayObject');
}
function it_keeps_instantiated_object()
{
$this->callOnWrappedObject('beAnInstanceOf', array('ArrayObject'));
$this->instantiate()->shouldBeEqualTo($this->getInstance());
}
function it_can_be_instantiated_with_a_factory_method()
{
$this->callOnWrappedObject(
'beConstructedThrough',
array(
'\DateTime::createFromFormat',
array('d-m-Y', '01-01-1970')
)
);
$this->instantiate()->shouldHaveType('\DateTime');
}
function it_can_be_instantiated_with_a_factory_method_with_method_name_only()
{
$this->callOnWrappedObject('beAnInstanceOf', ['\DateTime']);
$this->callOnWrappedObject(
'beConstructedThrough',
array(
'createFromFormat',
array('d-m-Y', '01-01-1970')
)
);
$this->instantiate()->shouldHaveType('\DateTime');
}
}
|
Update the send email command to use email manager | <?php
namespace Forex\Bundle\EmailBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class SendEmailCommand extends ContainerAwareCommand
{
protected $manager;
protected $em;
protected function configure()
{
$this
->setName('email:send-email')
->setDescription('Sends an email')
->addArgument('email', InputArgument::REQUIRED, 'The email address to send to')
->addArgument('template', InputArgument::REQUIRED, 'The template')
->addArgument('subject', InputArgument::REQUIRED, 'The subject')
->addArgument('data', InputArgument::OPTIONAL, 'The data for the template (JSON formatted)', '[]')
;
}
protected function initialize(InputInterface $input, OutputInterface $output)
{
$container = $this->getContainer();
$this->em = $container->get('doctrine.orm.default_entity_manager');
$this->manager = $container->get('forex.email_manager');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->manager->sendToEmail(
$input->getArgument('email'),
$input->getArgument('subject'),
$input->getArgument('template'),
json_decode($input->getArgument('data'), true)
);
$this->em->flush();
}
}
| <?php
namespace Forex\Bundle\EmailBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class SendEmailCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('email:send-email')
->setDescription('Sends an email')
->addArgument('email', InputArgument::REQUIRED, 'The email address to send to')
->addArgument('template', InputArgument::REQUIRED, 'The template')
->addArgument('subject', InputArgument::REQUIRED, 'The subject')
->addArgument('data', InputArgument::OPTIONAL, 'The data for the template (JSON formatted)', '[]')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->getContainer()->get('forex.email_sender')
->sendToEmail(
$input->getArgument('email'),
$input->getArgument('subject'),
$input->getArgument('template'),
json_decode($input->getArgument('data'), true)
);
}
}
|
Update GitVersion provider to use Process array | <?php
declare(strict_types=1);
/**
* This file is part of Laravel Zero.
*
* (c) Nuno Maduro <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LaravelZero\Framework\Providers\GitVersion;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Symfony\Component\Process\Process;
/**
* @codeCoverageIgnore
* @internal
*/
final class GitVersionServiceProvider extends ServiceProvider
{
/**
* {@inheritdoc}
*/
public function register(): void
{
$this->app->bind(
'git.version',
function (Application $app) {
$lastRevisionTag = '$(git rev-list --tags --max-count=1)';
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$taskGetLastRevisionTag = ['git', 'rev-list', '--tags', '--max-count=1'];
$process = tap(new Process($taskGetLastRevisionTag, $app->basePath()))->run();
$lastRevisionTag = trim($process->getOutput()) ?: 'unreleased';
if ($lastRevisionTag === 'unreleased') {
return 'unreleased';
}
}
$task = ['git', 'describe', '--tags', $lastRevisionTag];
$process = tap(new Process($task, $app->basePath()))->run();
return trim($process->getOutput()) ?: 'unreleased';
}
);
}
}
| <?php
declare(strict_types=1);
/**
* This file is part of Laravel Zero.
*
* (c) Nuno Maduro <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LaravelZero\Framework\Providers\GitVersion;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Symfony\Component\Process\Process;
/**
* @codeCoverageIgnore
* @internal
*/
final class GitVersionServiceProvider extends ServiceProvider
{
/**
* {@inheritdoc}
*/
public function register(): void
{
$this->app->bind(
'git.version',
function (Application $app) {
$lastRevisionTag = '$(git rev-list --tags --max-count=1)';
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$taskGetLastRevisionTag = 'git rev-list --tags --max-count=1';
$process = tap(new Process($taskGetLastRevisionTag, $app->basePath()))->run();
$lastRevisionTag = trim($process->getOutput()) ?: 'unreleased';
if ($lastRevisionTag === 'unreleased') {
return 'unreleased';
}
}
$task = "git describe --tags $lastRevisionTag";
$process = tap(new Process($task, $app->basePath()))->run();
return trim($process->getOutput()) ?: 'unreleased';
}
);
}
}
|
Add mbstring option to atoum configuration | <?php
namespace jubianchi\PhpSwitch\PHP\Option;
use Symfony\Component\Console\Input\InputOption;
use jubianchi\PhpSwitch\Console\Command\Command;
use jubianchi\PhpSwitch\PHP\Option\Enable;
class AtoumOption extends Option
{
const ARG = 'atoum';
/**
* @param \jubianchi\PhpSwitch\Console\Command\Command $command
*
* @return Option
*/
public function applyArgument(Command $command)
{
if (static::ARG !== null && false === $command->getDefinition()->hasArgument(static::ARG)) {
$command->addOption(
static::ARG,
null,
InputOption::VALUE_NONE,
sprintf('atoum compile options <comment>(%s)</comment>', $this)
);
}
return $this;
}
/**
* @return string
*/
public function __toString()
{
return implode(
' ',
array(
new DisableAllOption(),
new Enable\CLIOption(),
new Enable\PHAROption(),
new Enable\HashOption(),
new Enable\JSONOption(),
new Enable\XMLOption(),
new Enable\SessionOption(),
new Enable\TokenizerOption(),
new Enable\PosixOption(),
new Enable\DOMOption(),
new Enable\MBStringOption()
)
);
}
}
| <?php
namespace jubianchi\PhpSwitch\PHP\Option;
use Symfony\Component\Console\Input\InputOption;
use jubianchi\PhpSwitch\Console\Command\Command;
use jubianchi\PhpSwitch\PHP\Option\Enable;
class AtoumOption extends Option
{
const ARG = 'atoum';
/**
* @param \jubianchi\PhpSwitch\Console\Command\Command $command
*
* @return Option
*/
public function applyArgument(Command $command)
{
if (static::ARG !== null && false === $command->getDefinition()->hasArgument(static::ARG)) {
$command->addOption(
static::ARG,
null,
InputOption::VALUE_NONE,
sprintf('atoum compile options <comment>(%s)</comment>', $this)
);
}
return $this;
}
/**
* @return string
*/
public function __toString()
{
return implode(
' ',
array(
new DisableAllOption(),
new Enable\CLIOption(),
new Enable\PHAROption(),
new Enable\HashOption(),
new Enable\JSONOption(),
new Enable\XMLOption(),
new Enable\SessionOption(),
new Enable\TokenizerOption(),
new Enable\PosixOption(),
new Enable\DOMOption()
)
);
}
}
|
Fix for missing view in design doc
My Cloudant DB that I replicated to Pouch has design docs with no views present (for some reason).
Fixes nolanlawson/pouchdb-find#100. | 'use strict';
var utils = require('../../../utils');
var localUtils = require('../utils');
var massageIndexDef = localUtils.massageIndexDef;
function getIndexes(db) {
// just search through all the design docs and filter in-memory.
// hopefully there aren't that many ddocs.
return db.allDocs({
startkey: '_design/',
endkey: '_design/\uffff',
include_docs: true
}).then(function (allDocsRes) {
var res = {
indexes: [{
ddoc: null,
name: '_all_docs',
type: 'special',
def: {
fields: [{_id: 'asc'}]
}
}]
};
res.indexes = utils.flatten(res.indexes, allDocsRes.rows.filter(function (row) {
return row.doc.language === 'query';
}).map(function (row) {
var viewNames = row.doc.views !== undefined ?
Object.keys(row.doc.views) : [];
return viewNames.map(function (viewName) {
var view = row.doc.views[viewName];
return {
ddoc: row.id,
name: viewName,
type: 'json',
def: massageIndexDef(view.options.def)
};
});
}));
// these are sorted by view name for some reason
res.indexes.sort(function (left, right) {
return utils.compare(left.name, right.name);
});
res.total_rows = res.indexes.length;
return res;
});
}
module.exports = getIndexes;
| 'use strict';
var utils = require('../../../utils');
var localUtils = require('../utils');
var massageIndexDef = localUtils.massageIndexDef;
function getIndexes(db) {
// just search through all the design docs and filter in-memory.
// hopefully there aren't that many ddocs.
return db.allDocs({
startkey: '_design/',
endkey: '_design/\uffff',
include_docs: true
}).then(function (allDocsRes) {
var res = {
indexes: [{
ddoc: null,
name: '_all_docs',
type: 'special',
def: {
fields: [{_id: 'asc'}]
}
}]
};
res.indexes = utils.flatten(res.indexes, allDocsRes.rows.filter(function (row) {
return row.doc.language === 'query';
}).map(function (row) {
var viewNames = Object.keys(row.doc.views);
return viewNames.map(function (viewName) {
var view = row.doc.views[viewName];
return {
ddoc: row.id,
name: viewName,
type: 'json',
def: massageIndexDef(view.options.def)
};
});
}));
// these are sorted by view name for some reason
res.indexes.sort(function (left, right) {
return utils.compare(left.name, right.name);
});
res.total_rows = res.indexes.length;
return res;
});
}
module.exports = getIndexes;
|
Remove no-cover from __str__ method | from canvas_object import CanvasObject
from util import combine_kwargs
class Assignment(CanvasObject):
def __str__(self):
return "{} ({})".format(self.name, self.id)
def delete(self):
"""
Delete this assignment.
:calls: `DELETE /api/v1/courses/:course_id/assignments/:id \
<https://canvas.instructure.com/doc/api/assignments.html#method.assignments.destroy>`_
:rtype: :class:`pycanvas.assignment.Assignment`
"""
response = self._requester.request(
'DELETE',
'courses/%s/assignments/%s' % (self.course_id, self.id),
)
return Assignment(self._requester, response.json())
def edit(self, **kwargs):
"""
Modify this assignment.
:calls: `PUT /api/v1/courses/:course_id/assignments/:id \
<https://canvas.instructure.com/doc/api/assignments.html#method.assignments_api.update>`_
:rtype: :class:`pycanvas.assignment.Assignment`
"""
response = self._requester.request(
'PUT',
'courses/%s/assignments/%s' % (self.course_id, self.id),
**combine_kwargs(**kwargs)
)
if 'name' in response.json():
super(Assignment, self).set_attributes(response.json())
return Assignment(self._requester, response.json())
| from canvas_object import CanvasObject
from util import combine_kwargs
class Assignment(CanvasObject):
def __str__(self): # pragma: no cover
return "{} ({})".format(self.name, self.id)
def delete(self):
"""
Delete this assignment.
:calls: `DELETE /api/v1/courses/:course_id/assignments/:id \
<https://canvas.instructure.com/doc/api/assignments.html#method.assignments.destroy>`_
:rtype: :class:`pycanvas.assignment.Assignment`
"""
response = self._requester.request(
'DELETE',
'courses/%s/assignments/%s' % (self.course_id, self.id),
)
return Assignment(self._requester, response.json())
def edit(self, **kwargs):
"""
Modify this assignment.
:calls: `PUT /api/v1/courses/:course_id/assignments/:id \
<https://canvas.instructure.com/doc/api/assignments.html#method.assignments_api.update>`_
:rtype: :class:`pycanvas.assignment.Assignment`
"""
response = self._requester.request(
'PUT',
'courses/%s/assignments/%s' % (self.course_id, self.id),
**combine_kwargs(**kwargs)
)
if 'name' in response.json():
super(Assignment, self).set_attributes(response.json())
return Assignment(self._requester, response.json())
|
Remove hard coded experiment description. Remove done field and add status field since that is what we get from the backend. | export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: false
};
this.displayState = {
details: {
showTitle: true,
showStatus: true,
showNotes: true,
showFiles: false,
showSamples: false,
currentFilesTab: 0,
currentSamplesTab: 0
},
editTitle: true,
open: false,
maximize: false
};
this.node = null;
}
addStep(step) {
this.steps.push(step);
}
}
export class Experiment {
constructor(name) {
this.name = name;
this.goal = '';
this.description = '';
this.aim = '';
this.status = 'in-progress';
this.steps = [];
}
addStep(title, _type) {
let s = new ExperimentStep(title, _type);
this.steps.push(s);
}
}
| export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: false
};
this.displayState = {
details: {
showTitle: true,
showStatus: true,
showNotes: true,
showFiles: false,
showSamples: false,
currentFilesTab: 0,
currentSamplesTab: 0
},
editTitle: true,
open: false,
maximize: false
};
this.node = null;
}
addStep(step) {
this.steps.push(step);
}
}
export class Experiment {
constructor(name) {
this.name = name;
this.goal = '';
this.description = 'Look at grain size as it relates to hardness';
this.aim = '';
this.done = false;
this.steps = [];
}
addStep(title, _type) {
let s = new ExperimentStep(title, _type);
this.steps.push(s);
}
}
|
Remove suit_dashboard from INSTALLED_APPS causing py35 tests breaking as no models | # -*- coding: utf-8 -*-
"""
Entry point for Django tests.
This script will setup the basic configuration needed by Django.
"""
import sys
from os.path import abspath, dirname, join
try:
from django.conf import settings
from django.test.utils import get_runner
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
ROOT_URLCONF='suit_dashboard.urls',
INSTALLED_APPS=[
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
],
SITE_ID=1,
MIDDLEWARE_CLASSES=()
)
try:
import django
sys.path.append(abspath(join(dirname(__file__), 'src')))
setup = django.setup
except AttributeError:
pass
else:
setup()
except ImportError:
import traceback
traceback.print_exc()
raise ImportError('To fix this error, maybe run '
'`pip install -r requirements/test.txt`')
def run_tests(*test_args):
"""Discover and run tests."""
if not test_args:
test_args = ['tests']
# Run tests
runner = get_runner(settings)
test_runner = runner()
failures = test_runner.run_tests(test_args)
if failures:
sys.exit(bool(failures))
if __name__ == '__main__':
run_tests(*sys.argv[1:])
| # -*- coding: utf-8 -*-
"""
Entry point for Django tests.
This script will setup the basic configuration needed by Django.
"""
import sys
from os.path import abspath, dirname, join
try:
from django.conf import settings
from django.test.utils import get_runner
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
ROOT_URLCONF='suit_dashboard.urls',
INSTALLED_APPS=[
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'suit_dashboard',
],
SITE_ID=1,
MIDDLEWARE_CLASSES=()
)
try:
import django
sys.path.append(abspath(join(dirname(__file__), 'src')))
setup = django.setup
except AttributeError:
pass
else:
setup()
except ImportError:
import traceback
traceback.print_exc()
raise ImportError('To fix this error, maybe run '
'`pip install -r requirements/test.txt`')
def run_tests(*test_args):
"""Discover and run tests."""
if not test_args:
test_args = ['tests']
# Run tests
runner = get_runner(settings)
test_runner = runner()
failures = test_runner.run_tests(test_args)
if failures:
sys.exit(bool(failures))
if __name__ == '__main__':
run_tests(*sys.argv[1:])
|
Set the application object into the controller too. | <?php
namespace App;
class Slim extends \Slim\Slim
{
public function mapRoute($args)
{
$callable = array_pop($args);
if (is_string($callable) && strpos($callable, ':')) {
$callable = $this->createControllerCallable($callable);
}
$args[] = $callable;
return parent::mapRoute($args);
}
protected function createControllerCallable($name)
{
list($controllerName, $actionName) = explode(':', $name);
// Create a callable that will find or create the controller instance
// and then execute the action
$app = $this;
$callable = function () use ($app, $controllerName, $actionName) {
// Try to fetch the controller instance from Slim's container
if ($app->container->has($controllerName)) {
$controller = $app->container->get($controllerName);
} else {
// not in container, assume it can be directly instantiated
$controller = new $controllerName($app);
}
// Set the App, request and response into the controller if we can
if (method_exists($controller, 'setApp')) {
$controller->setApp($app);
}
if (method_exists($controller, 'setRequest')) {
$controller->setRequest($app->request);
}
if (method_exists($controller, 'setResponse')) {
$controller->setResponse($app->response);
}
return call_user_func_array(array($controller, $actionName), func_get_args());
};
return $callable;
}
}
| <?php
namespace App;
class Slim extends \Slim\Slim
{
public function mapRoute($args)
{
$callable = array_pop($args);
if (is_string($callable) && strpos($callable, ':')) {
$callable = $this->createControllerCallable($callable);
}
$args[] = $callable;
return parent::mapRoute($args);
}
protected function createControllerCallable($name)
{
list($controllerName, $actionName) = explode(':', $name);
// Create a callable that will find or create the controller instance
// and then execute the action
$app = $this;
$callable = function () use ($app, $controllerName, $actionName) {
// Try to fetch the controller instance from Slim's container
if ($app->container->has($controllerName)) {
$controller = $app->container->get($controllerName);
} else {
// not in container, assume it can be directly instantiated
$controller = new $controllerName($app);
}
// Set the request and response if we can
if (method_exists($controller, 'setRequest')) {
$controller->setRequest($app->request);
}
if (method_exists($controller, 'setResponse')) {
$controller->setResponse($app->response);
}
return call_user_func_array(array($controller, $actionName), func_get_args());
};
return $callable;
}
}
|
Remove removed id property from storage annotation | package de.espend.idea.laravel;
import com.intellij.openapi.components.*;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.XmlSerializerUtil;
import de.espend.idea.laravel.view.dict.TemplatePath;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* @author Daniel Espendiller <[email protected]>
*/
@State(
name = "LaravelPluginSettings",
storages = {
@Storage(file = StoragePathMacros.PROJECT_FILE),
@Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/laravel-plugin.xml", scheme = StorageScheme.DIRECTORY_BASED)
}
)
public class LaravelSettings implements PersistentStateComponent<LaravelSettings> {
public boolean pluginEnabled = false;
public boolean useAutoPopup = false;
public String routerNamespace;
public String mainLanguage;
@Nullable
public List<TemplatePath> templatePaths = new ArrayList<>();
public boolean dismissEnableNotification = false;
public static LaravelSettings getInstance(Project project) {
return ServiceManager.getService(project, LaravelSettings.class);
}
public String getMainLanguage() {
return !StringUtils.isBlank(mainLanguage) ? mainLanguage : "en";
}
@Nullable
@Override
public LaravelSettings getState() {
return this;
}
@Override
public void loadState(LaravelSettings settings) {
XmlSerializerUtil.copyBean(settings, this);
}
}
| package de.espend.idea.laravel;
import com.intellij.openapi.components.*;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.XmlSerializerUtil;
import de.espend.idea.laravel.view.dict.TemplatePath;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* @author Daniel Espendiller <[email protected]>
*/
@State(
name = "LaravelPluginSettings",
storages = {
@Storage(id = "default", file = StoragePathMacros.PROJECT_FILE),
@Storage(id = "dir", file = StoragePathMacros.PROJECT_CONFIG_DIR + "/laravel-plugin.xml", scheme = StorageScheme.DIRECTORY_BASED)
}
)
public class LaravelSettings implements PersistentStateComponent<LaravelSettings> {
public boolean pluginEnabled = false;
public boolean useAutoPopup = false;
public String routerNamespace;
public String mainLanguage;
@Nullable
public List<TemplatePath> templatePaths = new ArrayList<>();
public boolean dismissEnableNotification = false;
public static LaravelSettings getInstance(Project project) {
return ServiceManager.getService(project, LaravelSettings.class);
}
public String getMainLanguage() {
return !StringUtils.isBlank(mainLanguage) ? mainLanguage : "en";
}
@Nullable
@Override
public LaravelSettings getState() {
return this;
}
@Override
public void loadState(LaravelSettings settings) {
XmlSerializerUtil.copyBean(settings, this);
}
}
|
Remove console.log left from debug | CenterScout.factory('gradeData', ['$http', '$q', function($http, $q) {
var grades = null;
return function() {
var deferred = $q.defer();
if(grades) {
deferred.resolve(grades);
} else {
$http.get('http://localhost:8080/api/grades')
.success(function(gradeData) {
grades = gradeData;
deferred.resolve(grades);
})
.error(function(response) {
deferred.reject(response);
});
}
return deferred.promise;
};
}]);
CenterScout.factory('assignmentData', ['$http', '$q', function($http, $q) {
var assignments = null;
return function() {
var deferred = $q.defer();
if(assignments) {
deferred.resolve(assignments);
} else {
$http.get('http://localhost:8080/api/assignments')
.success(function(assignmentData) {
assignments = assignmentData;
deferred.resolve(assignments);
})
.error(function(response) {
deferred.reject(response);
});
}
return deferred.promise;
};
}]);
| CenterScout.factory('gradeData', ['$http', '$q', function($http, $q) {
var grades = null;
return function() {
var deferred = $q.defer();
console.log(deferred);
if(grades) {
deferred.resolve(grades);
} else {
$http.get('http://localhost:8080/api/grades')
.success(function(gradeData) {
grades = gradeData;
deferred.resolve(grades);
})
.error(function(response) {
deferred.reject(response);
});
}
return deferred.promise;
};
}]);
CenterScout.factory('assignmentData', ['$http', '$q', function($http, $q) {
var assignments = null;
return function() {
var deferred = $q.defer();
if(assignments) {
deferred.resolve(assignments);
} else {
$http.get('http://localhost:8080/api/assignments')
.success(function(assignmentData) {
assignments = assignmentData;
deferred.resolve(assignments);
})
.error(function(response) {
deferred.reject(response);
});
}
return deferred.promise;
};
}]);
|
Add simple test for column expansion | from django.test import SimpleTestCase
from jsonobject.exceptions import BadValueError
from sqlagg import SumWhen
from corehq.apps.userreports.sql import _expand_column
from corehq.apps.userreports.reports.specs import ReportColumn
class TestReportColumn(SimpleTestCase):
def testBadAggregation(self):
with self.assertRaises(BadValueError):
ReportColumn.wrap({
"aggregation": "simple_",
"field": "doc_id",
"type": "field",
})
def testGoodFormat(self):
for format in [
'default',
'percent_of_total',
]:
self.assertEquals(ReportColumn, type(
ReportColumn.wrap({
"aggregation": "simple",
"field": "doc_id",
"format": format,
"type": "field",
})
))
def testBadFormat(self):
with self.assertRaises(BadValueError):
ReportColumn.wrap({
"aggregation": "simple",
"field": "doc_id",
"format": "default_",
"type": "field",
})
class TestExpandReportColumn(SimpleTestCase):
def test_expansion(self):
column = ReportColumn(
type="field",
field="lab_result",
display="Lab Result",
format="default",
aggregation="expand",
description="foo"
)
cols = _expand_column(column, ["positive", "negative"])
self.assertEqual(len(cols), 2)
self.assertEqual(type(cols[0].view), SumWhen)
self.assertEqual(cols[1].view.whens, {'negative':1})
| from django.test import SimpleTestCase
from jsonobject.exceptions import BadValueError
from corehq.apps.userreports.reports.specs import ReportColumn
class TestReportColumn(SimpleTestCase):
def testBadAggregation(self):
with self.assertRaises(BadValueError):
ReportColumn.wrap({
"aggregation": "simple_",
"field": "doc_id",
"type": "field",
})
def testGoodFormat(self):
for format in [
'default',
'percent_of_total',
]:
self.assertEquals(ReportColumn, type(
ReportColumn.wrap({
"aggregation": "simple",
"field": "doc_id",
"format": format,
"type": "field",
})
))
def testBadFormat(self):
with self.assertRaises(BadValueError):
ReportColumn.wrap({
"aggregation": "simple",
"field": "doc_id",
"format": "default_",
"type": "field",
})
|
Fix generator path for service provider | <?php namespace Pingpong\Modules\Commands;
use Illuminate\Support\Str;
use Pingpong\Generators\Stub;
use Pingpong\Modules\Traits\ModuleCommandTrait;
use Symfony\Component\Console\Input\InputArgument;
class GenerateProviderCommand extends GeneratorCommand {
use ModuleCommandTrait;
/**
* The console command name.
*
* @var string
*/
protected $name = 'module:provider';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate a new service provider for the specified module.';
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array('name', InputArgument::REQUIRED, 'The service provider name.'),
array('module', InputArgument::OPTIONAL, 'The name of module will be used.'),
);
}
/**
* @return mixed
*/
protected function getTemplateContents()
{
return new Stub('provider', [
'MODULE' => $this->getModuleName(),
'NAME' => $this->getFileName()
]);
}
/**
* @return mixed
*/
protected function getDestinationFilePath()
{
$path = $this->laravel['modules']->getModulePath($this->getModuleName());
$generatorPath = $this->laravel['modules']->config('paths.generator.provider');
return $path . $generatorPath . '/' . $this->getFileName() . '.php';
}
/**
* @return string
*/
private function getFileName()
{
return Str::studly($this->argument('name'));
}
}
| <?php namespace Pingpong\Modules\Commands;
use Illuminate\Support\Str;
use Pingpong\Generators\Stub;
use Pingpong\Modules\Traits\ModuleCommandTrait;
use Symfony\Component\Console\Input\InputArgument;
class GenerateProviderCommand extends GeneratorCommand {
use ModuleCommandTrait;
/**
* The console command name.
*
* @var string
*/
protected $name = 'module:provider';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate a new service provider for the specified module.';
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array('name', InputArgument::REQUIRED, 'The service provider name.'),
array('module', InputArgument::OPTIONAL, 'The name of module will be used.'),
);
}
/**
* @return mixed
*/
protected function getTemplateContents()
{
return new Stub('provider', [
'MODULE' => $this->getModuleName(),
'NAME' => $this->getFileName()
]);
}
/**
* @return mixed
*/
protected function getDestinationFilePath()
{
$path = $this->laravel['modules']->getModulePath($this->getModuleName());
$generatorPath = $this->laravel['modules']->get('paths.generator.provider');
return $path . $generatorPath . '/' . $this->getFileName() . '.php';
}
/**
* @return string
*/
private function getFileName()
{
return Str::studly($this->argument('name'));
}
}
|
Fix markdown explorer for local links. | markdown_explorer = (function() {
var isLocalHref = function(href) {
return href.indexOf("://") === -1;
};
var isMarkdownHref = function(href) {
return href.indexOf(".md") !== -1;
};
var makeLinksHandleMarkdown = function(element, directory) {
element.find('a').click(function() {
var linkHref = $(this).attr('href');
if (isLocalHref(linkHref) && isMarkdownHref(linkHref)) {
window.location = [location.protocol, '//', location.host, location.pathname].join('') + "?href=" + encodeURIComponent(directory + linkHref);
return false;
}
});
};
var loadFromHref = function(element, href) {
$.get(href, function(data) {
element.html(markdown.toHTML(data));
makeLinksHandleMarkdown(element, getCurrentDirectory(href));
});
};
var getCurrentDirectory = function(href) {
return href.substring(0, href.lastIndexOf("/") + 1);
};
var getQueryParameterHref = function() {
return window.location.href.match(/href=([^&]*)/);
};
return {
getCurrentDirectory: getCurrentDirectory,
getQueryParameterHref: getQueryParameterHref,
loadFromHref: loadFromHref
}
})(); | markdown_explorer = (function() {
var isLocalHref = function(href) {
return href.indexOf("://") === -1;
};
var isMarkdownHref = function(href) {
return href.indexOf(".md") !== -1;
};
var makeLinksHandleMarkdown = function(element, directory) {
element.find('a').click(function() {
var linkHref = $(this).attr('href');
if (isLocalHref(linkHref) && isMarkdownHref(linkHref)) {
window.location = "?href=" + encodeURIComponent(directory + linkHref);
return false;
}
});
};
var loadFromHref = function(element, href) {
$.get(href, function(data) {
element.html(markdown.toHTML(data));
makeLinksHandleMarkdown(element, getCurrentDirectory(href));
});
};
var getCurrentDirectory = function(href) {
return href.substring(0, href.lastIndexOf("/") + 1);
};
var getQueryParameterHref = function() {
return window.location.href.match(/href=([^&]*)/);
};
return {
getCurrentDirectory: getCurrentDirectory,
getQueryParameterHref: getQueryParameterHref,
loadFromHref: loadFromHref
}
})(); |
Add isolate scope to permission directive. | (function () {
'use strict';
/**
* Show/hide elements based on provided permissions/roles
*
* @example
* <div permission only="'USER'"></div>
* <div permission only="['USER','ADMIN']" except="'MANAGER'"></div>
* <div permission except="'MANAGER'"></div>
*/
angular
.module('permission')
.directive('permission', function ($log, Authorization, PermissionMap) {
return {
restrict: 'A',
scope: true,
bindToController: {
only: '=',
except: '='
},
controllerAs: 'permission',
controller: function ($scope, $element) {
var permission = this;
$scope.$watchGroup(['permission.only', 'permission.except'],
function () {
try {
Authorization
.authorize(new PermissionMap({
only: permission.only,
except: permission.except
}), null)
.then(function () {
$element.removeClass('ng-hide');
})
.catch(function () {
$element.addClass('ng-hide');
});
} catch (e) {
$element.addClass('ng-hide');
$log.error(e.message);
}
});
}
};
});
}());
| (function () {
'use strict';
/**
* Show/hide elements based on provided permissions/roles
*
* @example
* <div permission only="'USER'"></div>
* <div permission only="['USER','ADMIN']" except="'MANAGER'"></div>
* <div permission except="'MANAGER'"></div>
*/
angular
.module('permission')
.directive('permission', function ($log, Authorization, PermissionMap) {
return {
restrict: 'A',
bindToController: {
only: '=',
except: '='
},
controllerAs: 'permission',
controller: function ($scope, $element) {
var permission = this;
$scope.$watchGroup(['permission.only', 'permission.except'],
function () {
try {
Authorization
.authorize(new PermissionMap({
only: permission.only,
except: permission.except
}), null)
.then(function () {
$element.removeClass('ng-hide');
})
.catch(function () {
$element.addClass('ng-hide');
});
} catch (e) {
$element.addClass('ng-hide');
$log.error(e.message);
}
});
}
};
});
}());
|
Fix callback erroneously filtered out
The tick from pigpio wraps aroud after xFFFFFFFF,
approximately 1h13. When it wraps the delay was not computed
correctly, causing all following calls to be filtered out. | import functools
def Debounce(threshold=100):
"""
Simple debouncing decorator for apigpio callbacks.
Example:
`@Debouncer()
def my_cb(gpio, level, tick)
print('gpio cb: {} {} {}'.format(gpio, level, tick))
`
The threshold can be given to the decorator as an argument (in millisec).
This decorator can be used both on function and object's methods.
Warning: as the debouncer uses the tick from pigpio, which wraps around
after approximately 1 hour 12 minutes, you could theoretically miss one
call if your callback is called twice with that interval.
"""
threshold *= 1000
max_tick = 0xFFFFFFFF
class _decorated(object):
def __init__(self, pigpio_cb):
self._fn = pigpio_cb
self.last = 0
self.is_method = False
def __call__(self, *args, **kwargs):
if self.is_method:
tick = args[3]
else:
tick = args[2]
if self.last > tick:
delay = max_tick-self.last + tick
else:
delay = tick - self.last
if delay > threshold:
self._fn(*args, **kwargs)
print('call passed by debouncer {} {} {}'
.format(tick, self.last, threshold))
self.last = tick
else:
print('call filtered out by debouncer {} {} {}'
.format(tick, self.last, threshold))
def __get__(self, instance, type=None):
# with is called when an instance of `_decorated` is used as a class
# attribute, which is the case when decorating a method in a class
self.is_method = True
return functools.partial(self, instance)
return _decorated
| import functools
def Debounce(threshold=100):
"""
Simple debouncing decorator for apigpio callbacks.
Example:
`@Debouncer()
def my_cb(gpio, level, tick)
print('gpio cb: {} {} {}'.format(gpio, level, tick))
`
The threshold can be given to the decorator as an argument (in millisec).
This decorator can be used both on function and object's methods.
Warning: as the debouncer uses the tick from pigpio, which wraps around
after approximately 1 hour 12 minutes, you could theoretically miss one
call if your callback is called twice with that interval.
"""
threshold *= 1000
class _decorated(object):
def __init__(self, pigpio_cb):
self._fn = pigpio_cb
self.last = 0
self.is_method = False
def __call__(self, *args, **kwargs):
if self.is_method:
tick = args[3]
else:
tick = args[2]
if tick - self.last > threshold:
self._fn(*args, **kwargs)
self.last = tick
def __get__(self, instance, type=None):
# with is called when an instance of `_decorated` is used as a class
# attribute, which is the case when decorating a method in a class
self.is_method = True
return functools.partial(self, instance)
return _decorated
|
Update with lab app registration | // Config object to be passed to Msal on creation
const msalConfig = {
auth: {
clientId: "5dac5d6d-225c-4a98-a5e4-e29c82c0c4c9",
authority: "https://public.msidlabb2c.com/tfp/cpimtestpartners.onmicrosoft.com/b2c_1_signupsignin_userflow",
knownAuthorities: ["public.msidlabb2c.com"]
},
cache: {
cacheLocation: "localStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
},
system: {
telemetry: {
applicationName: 'msalVanillaTestApp',
applicationVersion: 'test1.0',
telemetryEmitter: (events) => {
console.log("Telemetry Events", events);
}
}
}
};
// Add here scopes for id token to be used at MS Identity Platform endpoints.
const loginRequest = {
scopes: ["openid", "profile"],
forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new token
};
const editProfileRequest = {
scopes: ["openid"],
authority: "https://public.msidlabb2c.com/tfp/cpimtestpartners.onmicrosoft.com/b2c_1_editprofile_userflow",
forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new token
}
| // Config object to be passed to Msal on creation
const msalConfig = {
auth: {
clientId: "e760cab2-b9a1-4c0d-86fb-ff7084abd902",
authority: "https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/b2c_1_susi",
knownAuthorities: ["fabrikamb2c.b2clogin.com"]
},
cache: {
cacheLocation: "localStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
},
system: {
telemetry: {
applicationName: 'msalVanillaTestApp',
applicationVersion: 'test1.0',
telemetryEmitter: (events) => {
console.log("Telemetry Events", events);
}
}
}
};
// Add here scopes for id token to be used at MS Identity Platform endpoints.
const loginRequest = {
scopes: ["https://fabrikamb2c.onmicrosoft.com/helloapi/demo.read"],
forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new token
};
const editProfileRequest = {
scopes: ["openid"],
authority: "https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/b2c_1_edit_profile",
forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new token
}
|
Make api_key of ApiKey required | @extends('layouts.app')
@section('title', '新增ApiKey')
@section('content')
<div class="mt-3 pb-3">
<div class="col-md-8 offset-md-2">
<h1>新增ApiKey</h1>
<div class="card">
<div class="card-block">
{{ Form::open(['route' => 'api-key.store']) }}
<div class="form-group row{{ $errors->has('api_key') ? ' has-danger' : '' }}">
<label for="api_key" class="col-md-2 col-form-label">ApiKey</label>
<div class="col-md-10">
{{ Form::text('api_key', null, ['class' => 'form-control', 'required']) }}
@if ($errors->has('api_key'))
<span class="form-control-feedback">
<strong>{{ $errors->first('api_key') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group row">
<div class="col-md-10 offset-md-2">
<button type="submit" class="btn btn-primary"> 確認</button>
<a href="{{ route('api-key.index') }}" class="btn btn-secondary">返回列表</a>
</div>
</div>
{{ Form::close() }}
</div>
</div>
</div>
</div>
@endsection
| @extends('layouts.app')
@section('title', '新增ApiKey')
@section('content')
<div class="mt-3 pb-3">
<div class="col-md-8 offset-md-2">
<h1>新增ApiKey</h1>
<div class="card">
<div class="card-block">
{{ Form::open(['route' => 'api-key.store']) }}
<div class="form-group row{{ $errors->has('api_key') ? ' has-danger' : '' }}">
<label for="api_key" class="col-md-2 col-form-label">ApiKey</label>
<div class="col-md-10">
{{ Form::text('api_key', null, ['class' => 'form-control']) }}
@if ($errors->has('api_key'))
<span class="form-control-feedback">
<strong>{{ $errors->first('api_key') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group row">
<div class="col-md-10 offset-md-2">
<button type="submit" class="btn btn-primary"> 確認</button>
<a href="{{ route('api-key.index') }}" class="btn btn-secondary">返回列表</a>
</div>
</div>
{{ Form::close() }}
</div>
</div>
</div>
</div>
@endsection
|
Add function within nested commandgroup to testcase | import expect from 'expect';
import isCommand from '../../../../src/cli/commands/helpers/isCommand';
describe('cli', () => {
describe('commands', () => {
describe('helpers', () => {
describe('isCommand', () => {
const commandsObject = {
meta: {
docs: {
command: () => {},
},
list: () => {},
extra: {
test: () => {},
},
},
run: 'run',
};
it('should correctly identify commands', () => {
expect(isCommand(commandsObject)('run')).toBeTruthy();
expect(isCommand(commandsObject)('meta')).toBeFalsy();
expect(isCommand(commandsObject.meta)('docs')).toBeTruthy();
expect(isCommand(commandsObject.meta)('list')).toBeTruthy();
expect(isCommand(commandsObject.meta)('extra')).toBeFalsy();
expect(isCommand(commandsObject.meta.extra)('test')).toBeTruthy();
});
});
});
});
});
| import expect from 'expect';
import isCommand from '../../../../src/cli/commands/helpers/isCommand';
describe('cli', () => {
describe('commands', () => {
describe('helpers', () => {
describe('isCommand', () => {
const commandsObject = {
meta: {
docs: {
command: () => {},
},
list: () => {},
extra: {
test: () => {},
},
},
run: 'run',
};
it('should correctly identify commands', () => {
expect(isCommand(commandsObject)('run')).toBeTruthy();
expect(isCommand(commandsObject)('meta')).toBeFalsy();
expect(isCommand(commandsObject.meta)('docs')).toBeTruthy();
expect(isCommand(commandsObject.meta)('list')).toBeTruthy();
expect(isCommand(commandsObject.meta)('extra')).toBeFalsy();
});
});
});
});
});
|
Use readme as the long description in pypi | #!/usr/bin/env python3
import version
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open("docs/README.md", "r") as fh:
long_description = fh.read()
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(name='robotframework-zoomba',
version=version.VERSION,
description='Robot Framework mini-framework.',
long_description=long_description,
url='https://github.com/Accruent/zoomba',
maintainer='Alex Calandra, Michael Hintz, Keith Smoland, Matthew Giardina, Brandon Wolfe, Neil Howell,'
' Tommy Hoang',
maintainer_email='[email protected]',
license='GPL-3.0',
keywords='Robot Framework robot-framework selenium requests appium soap winappdriver appium robotframework'
'desktop windows zoomba python robotframework-library appium-windows appiumlibrary api-rest api '
'soap-api',
platforms='any',
install_requires=requirements,
extras_require={
'testing': [
'Appium-Python-Client'
]
},
classifiers="""
Development Status :: 5 - Production/Stable
Operating System :: OS Independent
Programming Language :: Python :: 3
Topic :: Software Development :: Testing
Framework :: Robot Framework :: Library
""".strip().splitlines(),
package_dir={'': 'src'},
packages=['Zoomba']
)
| #!/usr/bin/env python3
import version
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(name='robotframework-zoomba',
version=version.VERSION,
description='Robot Framework mini-framework.',
long_description='Zoomba',
url='https://github.com/Accruent/zoomba',
maintainer='Alex Calandra, Michael Hintz, Keith Smoland, Matthew Giardina, Brandon Wolfe, Neil Howell, Tommy Hoang',
maintainer_email='[email protected]',
license='GPL-3.0',
keywords='Robot Framework robot-framework selenium requests appium soap winappdriver appium robotframework'
'desktop windows zoomba python robotframework-library appium-windows appiumlibrary api-rest api '
'soap-api',
platforms='any',
install_requires=requirements,
extras_require={
'testing': [
'Appium-Python-Client'
]
},
classifiers="""
Development Status :: 5 - Production/Stable
Operating System :: OS Independent
Programming Language :: Python :: 3
Topic :: Software Development :: Testing
Framework :: Robot Framework :: Library
""".strip().splitlines(),
package_dir={'': 'src'},
packages=['Zoomba']
)
|
Revert "x,y should be y,x"
This reverts commit 7636eb6ce4f23c6f787aed02590499b6d2ea60b2. | #!/usr/bin/env python
"""
Contains player and NPC-classes.
"""
import logging
from Item import Item
class Person(object):
"""
Base class for all characters in game.
"""
DEFAULT_HEALTH = 100
def __init__(self, health=DEFAULT_HEALTH, position):
"""
Defaults to facing north. Facing codes:
- 0: North
- 1: East
- 2: South
- 3: West
@param health The health that is given at init.
@param position [x, y] the position at init.
"""
if not isinstance(position, (tuple, list)):
logging.error(
"Position should be tuple/list with [x, y], set it to [0, 0]"
)
position = [0, 0]
self.health, self.position, self.facing = health, position, 0
class Player(Person):
"""
Contains the player-controlled character.
"""
def __init__(self, health=DEFAULT_HEALTH, position):
super(Player, self).__init__(health, position)
self.inventory = []
def give_item(self, item):
if not isinstance(item, Item):
logging.error(
"Item given to player is not item instance."
)
return
self.inventory.append(item)
class NPC(Person):
"""
Contains a character controlled by the game.
"""
def next_step():
"""
Since the game controls this character, some algorithm should say where
it moves.
TODO
"""
pass
| #!/usr/bin/env python
"""
Contains player and NPC-classes.
"""
import logging
from Item import Item
class Person(object):
"""
Base class for all characters in game.
"""
DEFAULT_HEALTH = 100
def __init__(self, health=DEFAULT_HEALTH, position):
"""
Defaults to facing north. Facing codes:
- 0: North
- 1: East
- 2: South
- 3: West
@param health The health that is given at init.
@param position [x, y] the position at init.
"""
if not isinstance(position, (tuple, list)):
logging.error(
"Position should be tuple/list with [y, x], set it to [0, 0]"
)
position = [0, 0]
self.health, self.position, self.facing = health, position, 0
class Player(Person):
"""
Contains the player-controlled character.
"""
def __init__(self, health=DEFAULT_HEALTH, position):
super(Player, self).__init__(health, position)
self.inventory = []
def give_item(self, item):
if not isinstance(item, Item):
logging.error(
"Item given to player is not item instance."
)
return
self.inventory.append(item)
class NPC(Person):
"""
Contains a character controlled by the game.
"""
def next_step():
"""
Since the game controls this character, some algorithm should say where
it moves.
TODO
"""
pass
|
Add comment about borschik usage | 'use strict';
var BORSCHIK_CSS_TECH = require('borschik/lib/techs/css'),
Q = require('q');
exports.API_VER = 2;
exports.techMixin = {
getBuildResultChunk : function(relPath) {
return '@import url(' + relPath + ');\n';
},
getBuildSuffixesMap: function() {
return {
css: ['css']
};
},
processBuildResult : function(res) {
var defer = Q.defer();
if (!res) {
defer.resolve([]);
return defer.promise;
}
this.compileBuildResult(res, defer);
return defer.promise;
},
/* stub method, override in your tech's code */
compileBuildResult: function(res, defer) {
return defer.resolve([]);
},
getBuildResult : function(filteredFiles, destSuffix, output, opts) {
return this.__base.apply(this, arguments)
.then(function(res) {
// use borschik here to preserve correct link to the images
var tech = new BORSCHIK_CSS_TECH.Tech({
comments : true,
freeze : false,
minimize : false
}),
file = new BORSCHIK_CSS_TECH.File(tech, output, 'include');
file.content = file.parse(res.join(''));
return this.processBuildResult(file.process(output));
}.bind(this));
}
};
| 'use strict';
var BORSCHIK_CSS_TECH = require('borschik/lib/techs/css'),
Q = require('q');
exports.API_VER = 2;
exports.techMixin = {
getBuildResultChunk : function(relPath) {
return '@import url(' + relPath + ');\n';
},
getBuildSuffixesMap: function() {
return {
css: ['css']
};
},
processBuildResult : function(res) {
var defer = Q.defer();
if (!res) {
defer.resolve([]);
return defer.promise;
}
this.compileBuildResult(res, defer);
return defer.promise;
},
/* stub method, override in your tech's code */
compileBuildResult: function(res, defer) {
return defer.resolve([]);
},
getBuildResult : function(filteredFiles, destSuffix, output, opts) {
return this.__base.apply(this, arguments)
.then(function(res) {
var tech = new BORSCHIK_CSS_TECH.Tech({
comments : true,
freeze : false,
minimize : false
}),
file = new BORSCHIK_CSS_TECH.File(tech, output, 'include');
file.content = file.parse(res.join(''));
return this.processBuildResult(file.process(output));
}.bind(this));
}
};
|
Remove now-extra specific excision of the version_info query string - the
"bare" option is invoked to do the job. | /**
* FileVersionModel.js
*/
(function (spiderOakApp, window, undefined) {
"use strict";
var console = window.console || {};
console.log = console.log || function(){};
var Backbone = window.Backbone,
_ = window._,
$ = window.$;
spiderOakApp.FileVersionModel = spiderOakApp.FileModel.extend({
defaults: {
isFavorite: false
},
composedUrl: function(bare) {
var urlTail = this.get("url");
var collection = this.collection;
var urlHead = this.get("urlBase") || this.urlBase;
var urlHeadObject = urlHead && this;
if (! urlHead && collection) {
urlHead = (collection.get("urlBase") ||
collection.urlBase ||
collection.url ||
"");
urlHeadObject = urlHead && collection;
}
if (typeof urlHead === "function") {
urlHead = urlHead.call(urlHeadObject);
}
if (typeof urlTail === "function") {
urlTail = urlTail.call(this);
}
if (bare) {
urlHead = urlHead.split("?")[0];
}
return (urlHead || "") + (urlTail || "");
}
});
})(window.spiderOakApp = window.spiderOakApp || {}, window);
| /**
* FileVersionModel.js
*/
(function (spiderOakApp, window, undefined) {
"use strict";
var console = window.console || {};
console.log = console.log || function(){};
var Backbone = window.Backbone,
_ = window._,
$ = window.$;
spiderOakApp.FileVersionModel = spiderOakApp.FileModel.extend({
defaults: {
isFavorite: false
},
composedUrl: function(bare) {
var urlTail = this.get("url");
var collection = this.collection;
var urlHead = this.get("urlBase") || this.urlBase;
var urlHeadObject = urlHead && this;
if (! urlHead && collection) {
urlHead = (collection.get("urlBase") ||
collection.urlBase ||
collection.url ||
"");
urlHeadObject = urlHead && collection;
}
if (typeof urlHead === "function") {
urlHead = urlHead.call(urlHeadObject);
}
if (typeof urlTail === "function") {
urlTail = urlTail.call(this);
}
// File versions have some extraneous query strings in their url
urlHead = urlHead.replace(
new RegExp(this.get("name") + "\\?format=version_info"), "");
if (bare) {
urlHead = urlHead.split("?")[0];
}
return (urlHead || "") + (urlTail || "");
}
});
})(window.spiderOakApp = window.spiderOakApp || {}, window);
|
Return the correctly formatted error message | "use strict";
var JSHINT = require("jshint").JSHINT,
assert = require("assert"),
glob = require("glob"),
path = require("path"),
fs = require("fs"),
_ = require('underscore');
var projectDir = path.normalize(path.join(__dirname, '..'));
var jsFiles = glob.sync(
"**/*.js",
{ cwd: projectDir }
);
var jshintrc = path.join(projectDir, '.jshintrc');
var jshintConfig = JSON.parse(fs.readFileSync(jshintrc).toString());
describe("Run jsHint on", function () {
jsFiles.forEach(function (file) {
if (/node_modules/.test(file)) {
return;
}
it(file, function () {
var content = fs.readFileSync(path.join(projectDir, file)).toString();
// Split the content into lines and replace whitespace only lines with
// empty strings so that this test behaviour mimics that of the command
// line tool.
var lines = _.map(
content.split(/[\n\r]/),
function (line) {
return (/^\s+$/).test(line) ? '' : line;
}
);
var success = JSHINT(
lines,
jshintConfig
);
var errorMessage = "";
if (!success) {
var error = JSHINT.data().errors[0];
// console.log(error);
errorMessage = "line " + error.line + ": " + error.reason;
}
assert.ok(success, errorMessage);
});
});
});
| "use strict";
var JSHINT = require("jshint").JSHINT,
assert = require("assert"),
glob = require("glob"),
path = require("path"),
fs = require("fs"),
_ = require('underscore');
var projectDir = path.normalize(path.join(__dirname, '..'));
var jsFiles = glob.sync(
"**/*.js",
{ cwd: projectDir }
);
var jshintrc = path.join(projectDir, '.jshintrc');
var jshintConfig = JSON.parse(fs.readFileSync(jshintrc).toString());
describe("Run jsHint on", function () {
jsFiles.forEach(function (file) {
if (/node_modules/.test(file)) {
return;
}
it(file, function () {
var content = fs.readFileSync(path.join(projectDir, file)).toString();
// Split the content into lines and replace whitespace only lines with
// empty strings so that this test behaviour mimics that of the command
// line tool.
var lines = _.map(
content.split(/[\n\r]/),
function (line) {
return (/^\s+$/).test(line) ? '' : line;
}
);
var success = JSHINT(
lines,
jshintConfig
);
var errorMessage = "";
if (!success) {
// console.log(JSHINT.errors[0]);
errorMessage = "line " + JSHINT.errors[0].line + ": " + JSHINT.errors[0].raw;
}
assert.ok(success, errorMessage);
});
});
});
|
tests: Disable some PHP insights sniffs | <?php
declare(strict_types=1);
return [
/*
|--------------------------------------------------------------------------
| Default Preset
|--------------------------------------------------------------------------
|
| This option controls the default preset that will be used by PHP Insights
| to make your code reliable, simple, and clean. However, you can always
| adjust the `Metrics` and `Insights` below in this configuration file.
|
| Supported: "default", "laravel", "symfony"
|
*/
'preset' => 'symfony',
/*
|--------------------------------------------------------------------------
| Configuration
|--------------------------------------------------------------------------
|
| Here you may adjust all the various `Insights` that will be used by PHP
| Insights. You can either add, remove or configure `Insights`. Keep in
| mind, that all added `Insights` must belong to a specific `Metric`.
|
*/
'add' => [
// ExampleMetric::class => [
// ExampleInsight::class,
// ]
],
'remove' => [
// ExampleInsight::class,
ObjectCalisthenics\Sniffs\NamingConventions\ElementNameMinimalLengthSniff::class,
ObjectCalisthenics\Sniffs\Classes\ForbiddenPublicPropertySniff::class,
ObjectCalisthenics\Sniffs\NamingConventions\NoSetterSniff::class,
PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting\SpaceAfterCastSniff::class,
PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting\SpaceAfterNotSniff::class,
SlevomatCodingStandard\Sniffs\Commenting\DocCommentSpacingSniff::class,
],
'config' => [
// ExampleInsight::class => [
// 'key' => 'value',
// ],
],
];
| <?php
declare(strict_types=1);
return [
/*
|--------------------------------------------------------------------------
| Default Preset
|--------------------------------------------------------------------------
|
| This option controls the default preset that will be used by PHP Insights
| to make your code reliable, simple, and clean. However, you can always
| adjust the `Metrics` and `Insights` below in this configuration file.
|
| Supported: "default", "laravel", "symfony"
|
*/
'preset' => 'symfony',
/*
|--------------------------------------------------------------------------
| Configuration
|--------------------------------------------------------------------------
|
| Here you may adjust all the various `Insights` that will be used by PHP
| Insights. You can either add, remove or configure `Insights`. Keep in
| mind, that all added `Insights` must belong to a specific `Metric`.
|
*/
'add' => [
// ExampleMetric::class => [
// ExampleInsight::class,
// ]
],
'remove' => [
// ExampleInsight::class,
ObjectCalisthenics\Sniffs\NamingConventions\ElementNameMinimalLengthSniff::class,
ObjectCalisthenics\Sniffs\Classes\ForbiddenPublicPropertySniff::class,
ObjectCalisthenics\Sniffs\NamingConventions\NoSetterSniff::class,
SlevomatCodingStandard\Sniffs\Commenting\DocCommentSpacingSniff::class,
],
'config' => [
// ExampleInsight::class => [
// 'key' => 'value',
// ],
],
];
|
Use Django's default update method | from django.conf import settings
from django.db import models
class ModelBase(models.Model):
"""Base class for SUMO models.
* Adds objects_range class method.
* Adds update method.
"""
class Meta:
abstract = True
@classmethod
def objects_range(cls, before=None, after=None):
"""
Returns a QuerySet of rows updated before, after or between the supplied datetimes.
The `updated_column_name` property must be defined on a model using this,
as that will be used as the column to filter on.
"""
column_name = getattr(cls, "updated_column_name", None)
if not column_name:
raise NotImplementedError
queryset = cls._default_manager
if before:
queryset = queryset.filter(**{f"{column_name}__lt": before})
if after:
queryset = queryset.filter(**{f"{column_name}__gt": after})
return queryset
def update(self, **kw):
"""Shortcicuit to the update method."""
self.__class__.objects.filter(pk=self.pk).update(**kw)
class LocaleField(models.CharField):
"""CharField with locale settings specific to SUMO defaults."""
def __init__(
self,
max_length=7,
default=settings.LANGUAGE_CODE,
choices=settings.LANGUAGE_CHOICES,
*args,
**kwargs,
):
return super(LocaleField, self).__init__(
max_length=max_length, default=default, choices=choices, *args, **kwargs
)
| from django.conf import settings
from django.db import models
class ModelBase(models.Model):
"""Base class for SUMO models.
* Adds objects_range class method.
* Adds update method.
"""
class Meta:
abstract = True
@classmethod
def objects_range(cls, before=None, after=None):
"""
Returns a QuerySet of rows updated before, after or between the supplied datetimes.
The `updated_column_name` property must be defined on a model using this,
as that will be used as the column to filter on.
"""
column_name = getattr(cls, "updated_column_name", None)
if not column_name:
raise NotImplementedError
queryset = cls._default_manager
if before:
queryset = queryset.filter(**{f"{column_name}__lt": before})
if after:
queryset = queryset.filter(**{f"{column_name}__gt": after})
return queryset
class LocaleField(models.CharField):
"""CharField with locale settings specific to SUMO defaults."""
def __init__(
self,
max_length=7,
default=settings.LANGUAGE_CODE,
choices=settings.LANGUAGE_CHOICES,
*args,
**kwargs,
):
return super(LocaleField, self).__init__(
max_length=max_length, default=default, choices=choices, *args, **kwargs
)
|
Stop checking if name is jude | <?php
namespace Jmlamo\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Jmlamo\DemoBundle\Entity\Author;
class ValidationController extends Controller
{
/**
* @Route("/validation")
* @Template()
*/
public function indexAction()
{
return array();
}
/**
* @Route("/validation/create/{name}")
*/
public function createAction(Request $request, $name = null)
{
$validator = $this->get('validator');
$session = $request->getSession();
$author = new Author();
$author->setName($name);
$errors = $validator->validate($author);
if (count($errors) > 0) {
$session->getFlashBag()->add(
'notice',
// @see __toString()
(string) $errors
);
} else {
$session->getFlashBag()->add(
'notice',
sprintf('%s is valid !', $author->getName())
);
}
return $this->redirect($this->generateUrl('jmlamo_demo_validation_index'));
}
}
| <?php
namespace Jmlamo\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Jmlamo\DemoBundle\Entity\Author;
class ValidationController extends Controller
{
/**
* @Route("/validation")
* @Template()
*/
public function indexAction()
{
return array();
}
/**
* @Route("/validation/create/{name}")
*/
public function createAction(Request $request, $name = null)
{
$validator = $this->get('validator');
$session = $request->getSession();
$author = new Author();
//for security reasons, we only allow "Jude"
if ('Jude' == $name) {
$author->setName($name);
}
$errors = $validator->validate($author);
if (count($errors) > 0) {
$session->getFlashBag()->add(
'notice',
// @see __toString()
(string) $errors
);
} else {
$session->getFlashBag()->add(
'notice',
sprintf('%s is valid !', $author->getName())
);
}
return $this->redirect($this->generateUrl('jmlamo_demo_validation_index'));
}
}
|
Remove default value for domain configuration | <?php
namespace Nasyrov\Laravel\Imgix;
use Illuminate\Support\ServiceProvider;
use Imgix\ShardStrategy;
use Imgix\UrlBuilder;
class ImgixServiceProvider extends ServiceProvider
{
const ALIAS = 'imgix';
/**
* Bootstrap any application services.
*/
public function boot()
{
$configFile = dirname(__DIR__) . '/config/imgix.php';
$this->mergeConfigFrom($configFile, static::ALIAS);
$this->publishes([
$configFile => config_path('imgix.php'),
], static::ALIAS);
}
/**
* Register any application services.
*/
public function register()
{
$this->app->singleton(UrlBuilder::class, function () {
return new UrlBuilder(
config('imgix.domains'),
config('imgix.useHttps', false),
config('imgix.signKey', ''),
config('imgix.shardStrategy', ShardStrategy::CRC),
config('imgix.includeLibraryParam', true)
);
});
$this->app->singleton(Imgix::class, function ($app) {
return new Imgix($app[UrlBuilder::class]);
});
$this->app->alias(Imgix::class, static::ALIAS);
}
}
| <?php
namespace Nasyrov\Laravel\Imgix;
use Illuminate\Support\ServiceProvider;
use Imgix\ShardStrategy;
use Imgix\UrlBuilder;
class ImgixServiceProvider extends ServiceProvider
{
const ALIAS = 'imgix';
/**
* Bootstrap any application services.
*/
public function boot()
{
$configFile = dirname(__DIR__) . '/config/imgix.php';
$this->mergeConfigFrom($configFile, static::ALIAS);
$this->publishes([
$configFile => config_path('imgix.php'),
], 'imgix');
}
/**
* Register any application services.
*/
public function register()
{
$this->app->singleton(UrlBuilder::class, function () {
return new UrlBuilder(
config('imgix.domains', []),
config('imgix.useHttps', false),
config('imgix.signKey', ''),
config('imgix.shardStrategy', ShardStrategy::CRC),
config('imgix.includeLibraryParam', true)
);
});
$this->app->singleton(Imgix::class, function ($app) {
return new Imgix($app[UrlBuilder::class]);
});
$this->app->alias(Imgix::class, static::ALIAS);
}
}
|
Apply position on mesh, not geometry | (function () {
"use strict";
var Frame = function (elem) {
if (typeof elem === 'string') {
elem = document.getElementById(elem);
}
var height = elem.scrollHeight;
var width = elem.scrollWidth;
var viewAngle = 45;
var aspect = width / (1.0 * height);
var near = 0.1;
var far = 10000;
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(viewAngle, aspect, near, far);
this.camera.position.z = 10;
this.scene.add(this.camera);
this.renderer = new THREE.WebGLRenderer();
this.renderer.setSize(width, height);
elem.appendChild(this.renderer.domElement);
};
window.Frame = Frame;
Frame.prototype.addNode = function (x, y, z) {
var geometry = new THREE.SphereGeometry(1);
var material = new THREE.MeshBasicMaterial({color: 0x00ff00, wireframe: true});
var cube = new THREE.Mesh(geometry, material);
cube.position = {x: x, y: y, z: z};
this.scene.add(cube);
};
Frame.prototype.render = function () {
this.renderer.render(this.scene, this.camera);
};
}());
| (function () {
"use strict";
var Frame = function (elem) {
if (typeof elem === 'string') {
elem = document.getElementById(elem);
}
var height = elem.scrollHeight;
var width = elem.scrollWidth;
var viewAngle = 45;
var aspect = width / (1.0 * height);
var near = 0.1;
var far = 10000;
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(viewAngle, aspect, near, far);
this.camera.position.z = 10;
this.scene.add(this.camera);
this.renderer = new THREE.WebGLRenderer();
this.renderer.setSize(width, height);
elem.appendChild(this.renderer.domElement);
};
window.Frame = Frame;
Frame.prototype.addNode = function (x, y, z) {
var geometry = new THREE.SphereGeometry(1);
geometry.position = {x: x, y: y, z: z};
var material = new THREE.MeshBasicMaterial({color: 0x00ff00, wireframe: true});
var cube = new THREE.Mesh(geometry, material);
this.scene.add(cube);
};
Frame.prototype.render = function () {
this.renderer.render(this.scene, this.camera);
};
}());
|
Support of old profile names | # -*- coding: utf-8 -*-
'''Generates the main page.'''
import re
from google.appengine.ext import webapp
import vkfeed.util
class MainPage(webapp.RequestHandler):
'''Generates the main page.'''
def get(self):
'''Processes a GET request.'''
self.response.out.write(vkfeed.util.render_template('main.html'))
def post(self):
'''Processes a POST request.'''
profile_url = self.request.get('profile_url', '')
match = re.match(r'''^
\s*
(?:https?://(?:www\.)?(?:vk\.com|vkontakte\.ru)/)?
(?P<profile_id>[a-zA-Z0-9._-]{5,})/?
\s*
$''', profile_url, re.IGNORECASE | re.VERBOSE)
if match:
self.redirect('/feed/' + match.group('profile_id') + '/wall')
else:
self.response.out.write(vkfeed.util.render_template('main.html', {
'post_error': u'''
Неверно указан URL профиля.
Адрес должен быть вида http://vkontakte.ru/имя_профиля.
Имя профиля должно удовлетворять требованиям, предъявляемым администрацией ВКонтакте.
'''
}))
| # -*- coding: utf-8 -*-
'''Generates the main page.'''
import re
from google.appengine.ext import webapp
import vkfeed.util
class MainPage(webapp.RequestHandler):
'''Generates the main page.'''
def get(self):
'''Processes a GET request.'''
self.response.out.write(vkfeed.util.render_template('main.html'))
def post(self):
'''Processes a POST request.'''
profile_url = self.request.get('profile_url', '')
match = re.match(r'''^
\s*
(?:https?://(?:www\.)?(?:vk\.com|vkontakte\.ru)/)?
(?P<profile_id>[a-zA-Z0-9_-]{5,})/?
\s*
$''', profile_url, re.IGNORECASE | re.VERBOSE)
if match:
self.redirect('/feed/' + match.group('profile_id') + '/wall')
else:
self.response.out.write(vkfeed.util.render_template('main.html', {
'post_error': u'''
Неверно указан URL профиля.
Адрес должен быть вида http://vkontakte.ru/имя_профиля.
Имя профиля должно удовлетворять требованиям, предъявляемым администрацией ВКонтакте.
'''
}))
|
Handle case when response is None | import datetime
import decimal
from django.utils import timezone
def convert_tstamp(response, field_name=None):
try:
if field_name and response[field_name]:
return datetime.datetime.fromtimestamp(
response[field_name],
timezone.utc
)
if response is not None and not field_name:
return datetime.datetime.fromtimestamp(
response,
timezone.utc
)
except KeyError:
pass
return None
# currencies those amount=1 means 100 cents
# https://support.stripe.com/questions/which-zero-decimal-currencies-does-stripe-support
ZERO_DECIMAL_CURRENCIES = [
"bif", "clp", "djf", "gnf", "jpy", "kmf", "krw",
"mga", "pyg", "rwf", "vuv", "xaf", "xof", "xpf",
]
def convert_amount_for_db(amount, currency="usd"):
if currency is None: # @@@ not sure if this is right; find out what we should do when API returns null for currency
currency = "usd"
return (amount / decimal.Decimal("100")) if currency.lower() not in ZERO_DECIMAL_CURRENCIES else decimal.Decimal(amount)
def convert_amount_for_api(amount, currency="usd"):
if currency is None:
currency = "usd"
return int(amount * 100) if currency.lower() not in ZERO_DECIMAL_CURRENCIES else int(amount)
| import datetime
import decimal
from django.utils import timezone
def convert_tstamp(response, field_name=None):
try:
if field_name and response[field_name]:
return datetime.datetime.fromtimestamp(
response[field_name],
timezone.utc
)
if not field_name:
return datetime.datetime.fromtimestamp(
response,
timezone.utc
)
except KeyError:
pass
return None
# currencies those amount=1 means 100 cents
# https://support.stripe.com/questions/which-zero-decimal-currencies-does-stripe-support
ZERO_DECIMAL_CURRENCIES = [
"bif", "clp", "djf", "gnf", "jpy", "kmf", "krw",
"mga", "pyg", "rwf", "vuv", "xaf", "xof", "xpf",
]
def convert_amount_for_db(amount, currency="usd"):
if currency is None: # @@@ not sure if this is right; find out what we should do when API returns null for currency
currency = "usd"
return (amount / decimal.Decimal("100")) if currency.lower() not in ZERO_DECIMAL_CURRENCIES else decimal.Decimal(amount)
def convert_amount_for_api(amount, currency="usd"):
if currency is None:
currency = "usd"
return int(amount * 100) if currency.lower() not in ZERO_DECIMAL_CURRENCIES else int(amount)
|
Add functionality to work with models using different database connections | <?php namespace GeneaLabs\LaravelGovernor\Listeners;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatingListener
{
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public function handle(string $event, array $models)
{
collect($models)
->filter(function ($model) {
return $model instanceof Model;
})
->each(function (Model $model) {
if (auth()->check()
&& ! (property_exists($model, 'isGoverned')
&& $model['isGoverned'] === false)
) {
$model->governor_created_by = auth()->user()->getKey();
$table = $model->getTable();
$connection = $model
->getConnection()
->getName();
if (! Schema::connection($connection)->hasColumn($table, 'governor_created_by')) {
Schema::connection($connection)->table($table, function (Blueprint $table) {
$table->integer('governor_created_by')->unsigned()->nullable();
});
}
}
});
}
}
| <?php namespace GeneaLabs\LaravelGovernor\Listeners;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatingListener
{
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public function handle(string $event, array $models)
{
collect($models)
->filter(function ($model) {
return $model instanceof Model;
})
->each(function ($model) {
if (auth()->check()
&& ! (property_exists($model, 'isGoverned')
&& $model['isGoverned'] === false)
) {
$model->governor_created_by = auth()->user()->getKey();
$table = $model->getTable();
if (! Schema::hasColumn($table, 'governor_created_by')) {
Schema::table($table, function (Blueprint $table) {
$table->integer('governor_created_by')->unsigned()->nullable();
});
}
}
});
}
}
|
Update to use L5 Directive | <?php namespace Rtablada\InspectorGadget;
use Illuminate\Support\ServiceProvider;
use Illuminate\View\Compilers\BladeCompiler;
class GadgetServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('gadget', function ($app) {
return new GadgetFactory($app);
});
}
public function boot()
{
$this->registerConfig();
$app = $this->app;
$view =$this->app['view'];
$gadgetFactory = $this->app['gadget'];
$view->share('gadgetFactory', $gadgetFactory);
$blade = $view->getEngineResolver()->resolve('blade')->getCompiler();
$blade->directive('gadget', function($expression) {
return "<?php echo app('gadget')->make{$expression}; ?>";
});
$aliases = $this->app['config']->get('inspector-gadget.aliases', []);
$namespace = $this->app['config']->get('inspector-gadget.namespace');
$gadgetFactory->registerAliases($aliases);
$gadgetFactory->setNamespace($namespace);
}
public function registerConfig()
{
$this->publishes([
__DIR__.'/config.php' => config_path('inspector-gadget.php'),
]);
}
public function provides()
{
return ['gadget'];
}
}
| <?php namespace Rtablada\InspectorGadget;
use Illuminate\Support\ServiceProvider;
use Illuminate\View\Compilers\BladeCompiler;
class GadgetServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('gadget', function ($app) {
return new GadgetFactory($app);
});
}
public function boot()
{
$this->registerConfig();
$app = $this->app;
$view =$this->app['view'];
$gadgetFactory = $this->app['gadget'];
$view->share('gadgetFactory', $gadgetFactory);
$blade = $view->getEngineResolver()->resolve('blade')->getCompiler();
$blade->extend(function($view, BladeCompiler $compiler) {
$pattern = $compiler->createMatcher('gadget');
return preg_replace($pattern, '<?php echo app(\'gadget\')->make$2; ?>', $view);
});
$aliases = $this->app['config']->get('inspector-gadget.aliases', []);
$namespace = $this->app['config']->get('inspector-gadget.namespace');
$gadgetFactory->registerAliases($aliases);
$gadgetFactory->setNamespace($namespace);
}
public function registerConfig()
{
$this->publishes([
__DIR__.'/config.php' => config_path('inspector-gadget.php'),
]);
}
public function provides()
{
return ['gadget'];
}
}
|
Call sys.exit when pkg-config fails | #!/usr/bin/env python
from setuptools import setup, Extension
import string
import subprocess
import sys
sys.path.append('./test')
with open("README.md") as f:
long_description = f.read()
def cmd(line):
try:
output = subprocess.check_output(line, shell=True)
except subprocess.CalledProcessError:
sys.stderr.write('Failed to find sentencepiece pkgconfig\n')
sys.exit(1)
return output.strip().split()
setup(name = 'sentencepiece',
author = 'Taku Kudo',
author_email='[email protected]',
description = 'SentencePiece python wrapper',
long_description = long_description,
url = 'https://github.com/google/sentencepiece',
license = 'Apache',
platforms = 'Unix',
py_modules=['sentencepiece'],
ext_modules = [Extension('_sentencepiece',
sources=['sentencepiece_wrap.cxx'],
extra_compile_args=['-std=c++11'] +
cmd('pkg-config sentencepiece --cflags'),
extra_link_args=cmd('pkg-config sentencepiece --libs'))
],
classifiers = [
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Operating System :: Unix',
'Programming Language :: Python',
'Topic :: Text Processing :: Linguistic',
'Topic :: Software Development :: Libraries :: Python Modules'
],
test_suite = 'sentencepiece_test.suite')
| #!/usr/bin/env python
from setuptools import setup, Extension
import string
import sys
import os
sys.path.append('./test')
with open("README.md") as f:
long_description = f.read()
def cmd(line):
return os.popen(line).readlines()[0][:-1].split()
setup(name = 'sentencepiece',
author = 'Taku Kudo',
author_email='[email protected]',
description = 'SentencePiece python wrapper',
long_description = long_description,
url = 'https://github.com/google/sentencepiece',
license = 'Apache',
platforms = 'Unix',
py_modules=['sentencepiece'],
ext_modules = [Extension('_sentencepiece',
sources=['sentencepiece_wrap.cxx'],
extra_compile_args=['-std=c++11'] +
cmd('pkg-config sentencepiece --cflags'),
extra_link_args=cmd('pkg-config sentencepiece --libs'))
],
classifiers = [
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Operating System :: Unix',
'Programming Language :: Python',
'Topic :: Text Processing :: Linguistic',
'Topic :: Software Development :: Libraries :: Python Modules'
],
test_suite = 'sentencepiece_test.suite')
|
Read Neo4j config from ENV if present | # -*- coding: utf-8 -*-
import os
from django.apps import AppConfig
from django.conf import settings
from django.db.models.signals import m2m_changed, post_migrate, post_save, pre_delete
from neomodel import config
config.AUTO_INSTALL_LABELS = False
class ChemTrailsConfig(AppConfig):
name = 'chemtrails'
def ready(self):
from .signals.handlers import (
m2m_changed_handler, post_migrate_handler,
post_save_handler, pre_delete_handler
)
m2m_changed.connect(receiver=m2m_changed_handler,
dispatch_uid='chemtrails.signals.handlers.m2m_changed_handler')
post_save.connect(receiver=post_save_handler,
dispatch_uid='chemtrails.signals.handlers.post_save_handler')
pre_delete.connect(receiver=pre_delete_handler,
dispatch_uid='chemtrails.signals.handlers.pre_delete_handler')
post_migrate.connect(receiver=post_migrate_handler,
dispatch_uid='neomodel.core.install_all_labels')
# Neo4j config
config.DATABASE_URL = getattr(settings, 'NEOMODEL_NEO4J_BOLT_URL',
os.environ.get('NEOMODEL_NEO4J_BOLT_URL', config.DATABASE_URL))
config.FORCE_TIMEZONE = getattr(settings, 'NEOMODEL_FORCE_TIMEZONE',
os.environ.get('NEOMODEL_FORCE_TIMEZONE', False))
| # -*- coding: utf-8 -*-
from django.apps import AppConfig
from django.conf import settings
from django.db.models.signals import m2m_changed, post_migrate, post_save, pre_delete
from neomodel import config
config.AUTO_INSTALL_LABELS = False
class ChemTrailsConfig(AppConfig):
name = 'chemtrails'
def ready(self):
from .signals.handlers import (
m2m_changed_handler, post_migrate_handler,
post_save_handler, pre_delete_handler
)
m2m_changed.connect(receiver=m2m_changed_handler,
dispatch_uid='chemtrails.signals.handlers.m2m_changed_handler')
post_save.connect(receiver=post_save_handler,
dispatch_uid='chemtrails.signals.handlers.post_save_handler')
pre_delete.connect(receiver=pre_delete_handler,
dispatch_uid='chemtrails.signals.handlers.pre_delete_handler')
post_migrate.connect(receiver=post_migrate_handler,
dispatch_uid='neomodel.core.install_all_labels')
# Neo4j config
config.DATABASE_URL = getattr(settings, 'NEOMODEL_NEO4J_BOLT_URL', config.DATABASE_URL)
config.FORCE_TIMEZONE = getattr(settings, 'NEOMODEL_FORCE_TIMEZONE', False)
|
Fix sidebar scrollbar not being displayed on slideshow edit on Chrome 53. | /*global angular, removeLocationFromFilter*/
/*jslint nomen: true, es5: true */
angular.module('slideshows').directive('slideshowSlidesHeightSetter', ['$window', '$timeout', '$rootScope', function ($window, $timeout, $rootScope) {
'use strict';
function link(scope, element, attrs) {
var window = angular.element($window);
var top = attrs.top;
var footerHeight = attrs.footerHeight;
var me = this;
var update = function () {
$timeout.cancel(lastTimeout);
lastTimeout = $timeout(function () {
var newHeight = window.height() - top - footerHeight,
overflowY = 'hidden',
slidesDivHeight = element.children().first().height();
element.height(newHeight);
if (slidesDivHeight > newHeight) {
overflowY = 'scroll';
}
if (!$rootScope.$$phase) {
$rootScope.$apply();
}
element.css('overflow-y', overflowY);
});
};
var lastTimeout;
var onResize = function () {
update();
};
window.on('resize', onResize);
update();
scope.$on('$destroy', function () {
window.off('resize', onResize);
});
scope.$watch('slidesHeightSetterStrategy().getSlides().length', function () {
update();
scope.slidesHeightSetterStrategy().reselectCurrentSlideToFixChormeHeightCalculationBug();
});
}
return {
link: link,
scope: {
slidesHeightSetterStrategy: '&',
slideshow: '&'
}
};
}]);
| /*global angular, removeLocationFromFilter*/
/*jslint nomen: true, es5: true */
angular.module('slideshows').directive('slideshowSlidesHeightSetter', ['$window', '$timeout', '$rootScope', function ($window, $timeout, $rootScope) {
'use strict';
function link(scope, element, attrs) {
var window = angular.element($window);
var top = attrs.top;
var footerHeight = attrs.footerHeight;
var me = this;
var update = function () {
$timeout.cancel(lastTimeout);
lastTimeout = $timeout(function () {
var newHeight = window.height() - top - footerHeight,
overflowY = 'hidden',
slidesDivHeight = element.children().first().height();
element.height(newHeight);
if (slidesDivHeight > newHeight) {
overflowY = 'scroll';
}
if (!$rootScope.$$phase) {
$rootScope.$apply();
}
element.css('overflow-Y', overflowY);
});
};
var lastTimeout;
var onResize = function () {
update();
};
window.on('resize', onResize);
update();
scope.$on('$destroy', function () {
window.off('resize', onResize);
});
scope.$watch('slidesHeightSetterStrategy().getSlides().length', function () {
update();
scope.slidesHeightSetterStrategy().reselectCurrentSlideToFixChormeHeightCalculationBug();
});
}
return {
link: link,
scope: {
slidesHeightSetterStrategy: '&',
slideshow: '&'
}
};
}]);
|
PROC-690: Fix to use ImmutableSet to avoid being modified via getter | package com.indeed.proctor.common.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.indeed.proctor.common.model.ConsumableTestDefinition;
import org.springframework.util.CollectionUtils;
import java.util.Objects;
import java.util.Set;
@JsonTypeName("meta_tags_filter")
public class MetaTagsFilter implements DynamicFilter {
private final Set<String> metaTags;
public MetaTagsFilter(@JsonProperty("meta_tags") final Set<String> metaTags) {
Preconditions.checkArgument(!CollectionUtils.isEmpty(metaTags), "meta_tags should be non-empty string list.");
this.metaTags = ImmutableSet.copyOf(metaTags);
}
@JsonProperty("meta_tags")
public Set<String> getMetaTags() {
return this.metaTags;
}
@Override
public boolean matches(final String testName, final ConsumableTestDefinition testDefinition) {
return testDefinition.getMetaTags().stream().anyMatch(this.metaTags::contains);
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final MetaTagsFilter that = (MetaTagsFilter) o;
return metaTags.equals(that.metaTags);
}
@Override
public int hashCode() {
return Objects.hash(metaTags);
}
}
| package com.indeed.proctor.common.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.base.Preconditions;
import com.indeed.proctor.common.model.ConsumableTestDefinition;
import org.springframework.util.CollectionUtils;
import java.util.Objects;
import java.util.Set;
@JsonTypeName("meta_tags_filter")
public class MetaTagsFilter implements DynamicFilter {
private final Set<String> metaTags;
public MetaTagsFilter(@JsonProperty("meta_tags") final Set<String> metaTags) {
Preconditions.checkArgument(!CollectionUtils.isEmpty(metaTags), "meta_tags should be non-empty string list.");
this.metaTags = metaTags;
}
@JsonProperty("meta_tags")
public Set<String> getMetaTags() {
return this.metaTags;
}
@Override
public boolean matches(final String testName, final ConsumableTestDefinition testDefinition) {
return testDefinition.getMetaTags().stream().anyMatch(this.metaTags::contains);
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final MetaTagsFilter that = (MetaTagsFilter) o;
return metaTags.equals(that.metaTags);
}
@Override
public int hashCode() {
return Objects.hash(metaTags);
}
}
|
Make loading config file safer | import os
import logging
import yaml
from pathlib import Path
class ConfigurationCore:
config_from_file = None
def __init__(self, config_path=None):
try:
if not config_path:
config_path = os.path.join(Path.home(), '.gitlabform', 'config.yml')
elif config_path in ['./config.yml', 'config.yml']:
config_path = os.path.join(os.getcwd(), 'config.yml')
logging.info("Reading config from: {}".format(config_path))
with open(config_path, 'r') as ymlfile:
self.config_from_file = yaml.safe_load(ymlfile)
except Exception as e:
raise ConfigFileNotFoundException(config_path)
def get(self, path):
"""
:param path: "path" to given element in YAML file, for example for:
group_settings:
sddc:
deploy_keys:
qa_puppet:
key: some key...
title: some title...
can_push: false
..a path to a single element array ['qa_puppet'] will be: "group_settings|sddc|deploy_keys".
To get the dict under it use: get("group_settings|sddc|deploy_keys")
:return: element from YAML file (dict, array, string...)
"""
tokens = path.split('|')
current = self.config_from_file
try:
for token in tokens:
current = current[token]
except:
raise KeyNotFoundException
return current
class ConfigFileNotFoundException(Exception):
pass
class KeyNotFoundException(Exception):
pass
| import os
import logging
import yaml
from pathlib import Path
class ConfigurationCore:
config_from_file = None
def __init__(self, config_path=None):
try:
if not config_path:
config_path = os.path.join(Path.home(), '.gitlabform', 'config.yml')
elif config_path in ['./config.yml', 'config.yml']:
config_path = os.path.join(os.getcwd(), 'config.yml')
logging.info("Reading config from: {}".format(config_path))
with open(config_path, 'r') as ymlfile:
self.config_from_file = yaml.load(ymlfile)
except Exception as e:
raise ConfigFileNotFoundException(config_path)
def get(self, path):
"""
:param path: "path" to given element in YAML file, for example for:
group_settings:
sddc:
deploy_keys:
qa_puppet:
key: some key...
title: some title...
can_push: false
..a path to a single element array ['qa_puppet'] will be: "group_settings|sddc|deploy_keys".
To get the dict under it use: get("group_settings|sddc|deploy_keys")
:return: element from YAML file (dict, array, string...)
"""
tokens = path.split('|')
current = self.config_from_file
try:
for token in tokens:
current = current[token]
except:
raise KeyNotFoundException
return current
class ConfigFileNotFoundException(Exception):
pass
class KeyNotFoundException(Exception):
pass
|
Add request_rectange to HybridLayoutDemo - no clue why this never was here, but it stops it actually working | from base import SubLayout, Rect
from sublayouts import VerticalStack, Floating
from subtile import SubTile
class HybridLayoutDemo(SubLayout):
def _init_sublayouts(self):
class TopWindow(VerticalStack):
def filter_windows(self, windows):
windows = [w for w in windows if w.name == "htop"]
return ([windows[0],] if len(windows) else [])
def request_rectangle(self, r, windows):
if windows:
return r.split_horizontal(height=300)
else:
return (Rect(), r)
self.sublayouts.append(Floating(self.clientStack,
self.theme,
parent=self,
)
)
self.sublayouts.append(TopWindow(self.clientStack,
self.theme,
parent=self,
autohide=True,
)
)
self.sublayouts.append(SubTile(self.clientStack,
self.theme,
parent=self,
master_windows = 2,
)
)
def filter(self, client):
return True
def request_rectangle(self, r, windows):
return (r, Rect())
| from base import SubLayout, Rect
from sublayouts import VerticalStack, Floating
from subtile import SubTile
class HybridLayoutDemo(SubLayout):
def _init_sublayouts(self):
class TopWindow(VerticalStack):
def filter_windows(self, windows):
windows = [w for w in windows if w.name == "htop"]
return ([windows[0],] if len(windows) else [])
def request_rectangle(self, r, windows):
if windows:
return r.split_horizontal(height=300)
else:
return (Rect(), r)
self.sublayouts.append(Floating(self.clientStack,
self.theme,
parent=self,
)
)
self.sublayouts.append(TopWindow(self.clientStack,
self.theme,
parent=self,
autohide=True,
)
)
self.sublayouts.append(SubTile(self.clientStack,
self.theme,
parent=self,
master_windows = 2,
)
)
def filter(self, client):
return True
|
Allow Postgres DB driver to return the list of tables | async function postgres_sql(args) {
/*
description("Postgres function")
base_component_id("postgres_server")
load_once_from_file(true)
only_run_on_server(true)
*/
var config = {
user: args.user,
database: args.database,
password: args.password,
host: args.host,
port: args.port
};
console.log("postgres_server: " + JSON.stringify(args,null,2));
var promise = new Promise(async function(returnFn) {
var dbconnection = new postgresdb.Client(config);
dbconnection.connect(function (err) {
if (err) {
console.log({error: '' + err});
returnFn({failed: err})
} else {
var useSql = args.sql
if (args.get_tables) {
useSql = "SELECT tablename as name FROM pg_catalog.pg_tables where schemaname = 'public';"
}
dbconnection.query(useSql, [], function (err, result) {
if (err) {
console.log({failed: '' + err});
} else {
console.log("row count: " + result.rows.length); // outputs: { name: 'brianc' }
if (args.limit) {
result.rows = result.rows.slice(0, args.limit);
}
returnFn({value: result.rows})
};
})
}
});
})
var ret = await promise
return ret
}
| async function postgres_sql(args) {
/*
description("Postgres function")
base_component_id("postgres_server")
load_once_from_file(true)
only_run_on_server(true)
*/
var config = {
user: args.user,
database: args.database,
password: args.password,
host: args.host,
port: args.port
};
console.log("postgres_server: " + JSON.stringify(args,null,2));
var promise = new Promise(async function(returnFn) {
var dbconnection = new postgresdb.Client(config);
dbconnection.connect(function (err) {
if (err) {
console.log({error: '' + err});
returnFn({failed: err})
} else {
dbconnection.query(args.sql, [], function (err, result) {
if (err) {
console.log({failed: '' + err});
} else {
console.log("row count: " + result.rows.length); // outputs: { name: 'brianc' }
if (args.limit) {
result.rows = result.rows.slice(0, args.limit);
}
returnFn({value: result.rows})
};
})
}
});
})
var ret = await promise
return ret
}
|
Fix french sentence in en lang file | <?php
return [
'vendor' => 'Log viewer by <a href="https://github.com/ARCANEDEV/LogViewer">Arcanedev</a>',
'menu' => [
'category' => "Logs",
'stats' => 'Statistics',
'reports' => 'Reports'
],
'stats' => [
'entries' => ':count entries - :percent %'
],
'list' => [
'title' => 'Logs list',
'actions' => 'Actions',
'deletequestion' => 'Are you sure you want to delete this log file ?',
],
'show' => [
'title' => ':date report',
'file' => ':date log',
'backtolist' => 'List of logs',
'download' => 'Download',
'delete' => 'Delete log file',
'levels' => 'Levels',
'loginfo' => 'Log info',
'filepath' => 'File path',
'logentries' => 'Log entries',
'size' => 'Size',
'createdat' => 'Created at',
'updatedat' => 'Updated at',
'page' => 'Page :current of :last',
'env' => 'Env',
'level' => 'Level',
'time' => 'Time',
'header' => 'Header'
]
]; | <?php
return [
'vendor' => 'Log viewer by <a href="https://github.com/ARCANEDEV/LogViewer">Arcanedev</a>',
'menu' => [
'category' => "Logs",
'stats' => 'Statistics',
'reports' => 'Reports'
],
'stats' => [
'entries' => ':count entries - :percent %'
],
'list' => [
'title' => 'Logs list',
'actions' => 'Actions',
'deletequestion' => 'Are you sure you want to delete this log file ?',
],
'show' => [
'title' => ':date report',
'file' => ':date log',
'backtolist' => 'Liste des fichiers',
'download' => 'Download',
'delete' => 'Delete log file',
'levels' => 'Levels',
'loginfo' => 'Log info',
'filepath' => 'File path',
'logentries' => 'Log entries',
'size' => 'Size',
'createdat' => 'Created at',
'updatedat' => 'Updated at',
'page' => 'Page :current of :last',
'env' => 'Env',
'level' => 'Level',
'time' => 'Time',
'header' => 'Header'
]
]; |
Hide delete button on subsequent tabs | function removeRedundantTabs() {
var t = 0;
if (django && django.jQuery) {
django
.jQuery('.changeform-tabs-item:contains("General")')
.each(function(index, tab) {
t++;
if (t > 1) {
tab.remove();
}
});
}
}
function addHashToInlinePaginator() {
// Make sure nested inline paginator links to the same inline tab
jQuery(".paginator a").each(function(index, btn) {
if (btn.href) {
btn.href = btn.href.split("#")[0];
btn.href += document.location.hash;
}
});
}
function replaceInlineActivityAddButton() {
django.jQuery("#activities-group .add-row a").unbind();
django.jQuery("#activities-group .add-row a").click(function(e) {
e.preventDefault();
var path = document.location.pathname;
path = path.replace(
"initiatives/initiative/",
"activities/activity/add/?initiative="
);
path = path.replace("/change/", "");
document.location.href = path;
});
}
function toggleDeleteButton() {
if (window.location.hash === "#/tab/module_0/") {
django.jQuery(".deletelink").show();
} else {
django.jQuery(".deletelink").hide();
}
}
function hideDeleteButton() {
toggleDeleteButton();
django.jQuery(window).on("hashchange", function(e) {
toggleDeleteButton();
});
}
window.onload = function() {
if (!django.jQuery && jQuery) {
django.jQuery = jQuery;
}
replaceInlineActivityAddButton();
removeRedundantTabs();
addHashToInlinePaginator();
hideDeleteButton();
window.onhashchange = addHashToInlinePaginator;
};
| function removeRedundantTabs() {
var t = 0;
if (django && django.jQuery) {
django.jQuery('.changeform-tabs-item:contains("General")').each(function(index, tab){
t++;
if (t > 1) {
tab.remove();
}
});
}
}
function addHashToInlinePaginator() {
// Make sure nested inline paginator links to the same inline tab
jQuery('.paginator a').each(function(index, btn){
if (btn.href) {
btn.href = btn.href.split('#')[0]
btn.href += document.location.hash;
}
});
}
function replaceInlineActivityAddButton() {
django.jQuery('#activities-group .add-row a').unbind();
django.jQuery('#activities-group .add-row a').click(function(e) {
e.preventDefault();
var path = document.location.pathname;
path = path.replace('initiatives/initiative/', 'activities/activity/add/?initiative=');
path = path.replace('/change/', '');
document.location.href = path
});
}
window.onload = function() {
if (!django.jQuery && jQuery) {
django.jQuery = jQuery;
}
replaceInlineActivityAddButton();
removeRedundantTabs();
addHashToInlinePaginator();
window.onhashchange = addHashToInlinePaginator;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.