text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Set default logging level to ERROR, to avoid excessive "No handlers could be found" messages.
# urllib3/__init__.py # Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt) # # This module is part of urllib3 and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ urllib3 - Thread-safe connection pooling and re-using. """ __author__ = "Andrey Petrov (andrey.petrov@shazow.net)" __license__ = "MIT" __version__ = "$Rev$" from .connectionpool import ( HTTPConnectionPool, HTTPSConnectionPool, connection_from_url, get_host, make_headers) from .exceptions import ( HTTPError, MaxRetryError, SSLError, TimeoutError) from .poolmanager import PoolManager from .response import HTTPResponse from .filepost import encode_multipart_formdata import logging logging.getLogger(__name__).setLevel(logging.ERROR) del logging
# urllib3/__init__.py # Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt) # # This module is part of urllib3 and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ urllib3 - Thread-safe connection pooling and re-using. """ __author__ = "Andrey Petrov (andrey.petrov@shazow.net)" __license__ = "MIT" __version__ = "$Rev$" from .connectionpool import ( HTTPConnectionPool, HTTPSConnectionPool, connection_from_url, get_host, make_headers) from .exceptions import ( HTTPError, MaxRetryError, SSLError, TimeoutError) from .poolmanager import PoolManager from .response import HTTPResponse from .filepost import encode_multipart_formdata
Add utility method to get attribute value
/* * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.xdi.ldap.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.gluu.site.ldap.persistence.annotation.LdapAttributesList; import org.gluu.site.ldap.persistence.annotation.LdapEntry; import org.gluu.site.ldap.persistence.annotation.LdapObjectClass; import org.xdi.util.StringHelper; /** * @author Yuriy Movchan Date: 04/08/2014 */ @LdapEntry @LdapObjectClass(values = { "top" }) public class CustomEntry extends BaseEntry implements Serializable { private static final long serialVersionUID = -7686468010219068788L; @LdapAttributesList(name = "name", value = "values", sortByName = true) private List<CustomAttribute> customAttributes = new ArrayList<CustomAttribute>(); public List<CustomAttribute> getCustomAttributes() { return customAttributes; } public String getCustomAttributeValue(String attributeName) { if (customAttributes == null) { return null; } for (CustomAttribute customAttribute : customAttributes) { if (StringHelper.equalsIgnoreCase(attributeName, customAttribute.getName())) { return customAttribute.getValue(); } } return null; } public void setCustomAttributes(List<CustomAttribute> customAttributes) { this.customAttributes = customAttributes; } }
/* * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.xdi.ldap.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.gluu.site.ldap.persistence.annotation.LdapAttributesList; import org.gluu.site.ldap.persistence.annotation.LdapEntry; import org.gluu.site.ldap.persistence.annotation.LdapObjectClass; /** * @author Yuriy Movchan Date: 04/08/2014 */ @LdapEntry @LdapObjectClass(values = { "top" }) public class CustomEntry extends BaseEntry implements Serializable { private static final long serialVersionUID = -7686468010219068788L; @LdapAttributesList(name = "name", value = "values", sortByName = true) private List<CustomAttribute> customAttributes = new ArrayList<CustomAttribute>(); public List<CustomAttribute> getCustomAttributes() { return customAttributes; } public void setCustomAttributes(List<CustomAttribute> customAttributes) { this.customAttributes = customAttributes; } }
Increase timeout time for "slow" systems
package com.torodb.packaging; import com.torodb.packaging.config.model.Config; import com.torodb.packaging.config.model.backend.derby.Derby; import com.torodb.packaging.config.model.generic.LogLevel; import com.torodb.packaging.config.util.ConfigUtils; import java.time.Clock; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.junit.Before; import org.junit.Test; /** * * @author gortiz */ public class ToroDBServerTest { private Config config; @Before public void setUp() { config = new Config(); config.getProtocol().getMongo().setReplication(null); config.getBackend().setBackendImplementation(new Derby()); config.getBackend().asDerby().setPassword("torodb"); config.getGeneric().setLogLevel(LogLevel.TRACE); ConfigUtils.validateBean(config); } @Test public void testCreate() { ToroDBServer.create(config, Clock.systemUTC()); } @Test public void testInitiate() throws TimeoutException { ToroDBServer server = ToroDBServer.create(config, Clock.systemUTC()); server.startAsync(); server.awaitRunning(10, TimeUnit.SECONDS); server.stopAsync(); server.awaitTerminated(10, TimeUnit.SECONDS); } }
package com.torodb.packaging; import com.torodb.packaging.config.model.Config; import com.torodb.packaging.config.model.backend.derby.Derby; import com.torodb.packaging.config.model.generic.LogLevel; import com.torodb.packaging.config.util.ConfigUtils; import java.time.Clock; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.junit.Before; import org.junit.Test; /** * * @author gortiz */ public class ToroDBServerTest { private Config config; @Before public void setUp() { config = new Config(); config.getProtocol().getMongo().setReplication(null); config.getBackend().setBackendImplementation(new Derby()); config.getBackend().asDerby().setPassword("torodb"); config.getGeneric().setLogLevel(LogLevel.TRACE); ConfigUtils.validateBean(config); } @Test public void testCreate() { ToroDBServer.create(config, Clock.systemUTC()); } @Test public void testInitiate() throws TimeoutException { ToroDBServer server = ToroDBServer.create(config, Clock.systemUTC()); server.startAsync(); server.awaitRunning(5, TimeUnit.SECONDS); server.stopAsync(); server.awaitTerminated(5, TimeUnit.SECONDS); } }
Fix name of production CSS file
const MiniCssExtractPlugin = require('mini-css-extract-plugin') const externals = require('webpack-node-externals') const path = require('path') const devMode = process.env.NODE_ENV !== 'production' module.exports = [ { mode: devMode ? 'development' : 'production', entry: './client', output: { path: path.resolve('dist'), filename: 'client.js' }, devtool: 'cheap-source-map', module: { rules: [ { test: /\.less$/, use: [ devMode ? 'style-loader' : MiniCssExtractPlugin.loader, 'css-loader', 'less-loader' ] } ] }, plugins: [ new MiniCssExtractPlugin({ filename: 'client.css' }) ] }, { mode: devMode ? 'development' : 'production', entry: { server: './server', loader: './server/loader' }, output: { path: path.resolve('dist'), filename: '[name].js' }, devtool: 'cheap-source-map', target: 'node', externals: externals(), node: false } ]
const MiniCssExtractPlugin = require('mini-css-extract-plugin') const externals = require('webpack-node-externals') const path = require('path') const devMode = process.env.NODE_ENV !== 'production' module.exports = [ { mode: devMode ? 'development' : 'production', entry: './client', output: { path: path.resolve('dist'), filename: 'client.js' }, devtool: 'cheap-source-map', module: { rules: [ { test: /\.less$/, use: [ devMode ? 'style-loader' : MiniCssExtractPlugin.loader, 'css-loader', 'less-loader' ] } ] }, plugins: [ new MiniCssExtractPlugin() ] }, { mode: devMode ? 'development' : 'production', entry: { server: './server', loader: './server/loader' }, output: { path: path.resolve('dist'), filename: '[name].js' }, devtool: 'cheap-source-map', target: 'node', externals: externals(), node: false } ]
Make ExpParser also handle dates.
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.lib.json; import foam.lib.parse.*; import java.util.concurrent.ConcurrentHashMap; import java.util.Map; public class ExprParser extends foam.lib.parse.ProxyParser { private final static Map map__ = new ConcurrentHashMap(); private final static Parser instance__ = new ExprParser(); public static Parser instance() { return instance__; } /** * Implement the multiton pattern so we don't create the same * parser more than once. **/ public static Parser create(Class cls) { if ( cls == null ) return instance(); Parser p = (Parser) map__.get(cls.getName()); if ( p == null ) { p = new ExprParser(cls); map__.put(cls.getName(), p); } return p; } private ExprParser() { this(null); } private ExprParser(final Class defaultClass) { super(new Alt( new PropertyReferenceParser(), ClassReferenceParser.instance(), ObjectDateParser.instance(), FObjectParser.create(defaultClass))); } }
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.lib.json; import foam.lib.parse.*; import java.util.concurrent.ConcurrentHashMap; import java.util.Map; public class ExprParser extends foam.lib.parse.ProxyParser { private final static Map map__ = new ConcurrentHashMap(); private final static Parser instance__ = new ExprParser(); public static Parser instance() { return instance__; } /** * Implement the multiton pattern so we don't create the same * parser more than once. **/ public static Parser create(Class cls) { if ( cls == null ) return instance(); Parser p = (Parser) map__.get(cls.getName()); if ( p == null ) { p = new ExprParser(cls); map__.put(cls.getName(), p); } return p; } private ExprParser() { this(null); } private ExprParser(final Class defaultClass) { super(new Alt( new PropertyReferenceParser(), ClassReferenceParser.instance(), FObjectParser.create(defaultClass))); } }
Update URL to current point to gitlab.com
#!/usr/bin/env python3 from setuptools import setup setup( name='todoman', description='A simple CalDav-based todo manager.', author='Hugo Osvaldo Barrera', author_email='hugo@barrera.io', url='https://gitlab.com/hobarrera/todoman', license='MIT', packages=['todoman'], entry_points={ 'console_scripts': [ 'todo = todoman.cli:run', ] }, install_requires=[ 'click', 'icalendar', 'urwid', 'pyxdg', 'atomicwrites', # https://github.com/tehmaze/ansi/pull/7 'ansi>=0.1.3', 'parsedatetime', 'setuptools_scm', ], use_scm_version={'version_scheme': 'post-release'}, setup_requires=['setuptools_scm'], # TODO: classifiers )
#!/usr/bin/env python3 from setuptools import setup setup( name='todoman', description='A simple CalDav-based todo manager.', author='Hugo Osvaldo Barrera', author_email='hugo@barrera.io', url='https://git.barrera.io/hobarrera/todoman', license='MIT', packages=['todoman'], entry_points={ 'console_scripts': [ 'todo = todoman.cli:run', ] }, install_requires=[ 'click', 'icalendar', 'urwid', 'pyxdg', 'atomicwrites', # https://github.com/tehmaze/ansi/pull/7 'ansi>=0.1.3', 'parsedatetime', 'setuptools_scm', ], use_scm_version={'version_scheme': 'post-release'}, setup_requires=['setuptools_scm'], # TODO: classifiers )
Add Javadoc for factory methods.
package org.hamcrest.text; import java.util.regex.Pattern; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; public class MatchesPattern extends TypeSafeMatcher<String> { private final Pattern pattern; public MatchesPattern(Pattern pattern) { this.pattern = pattern; } @Override protected boolean matchesSafely(String item) { return pattern.matcher(item).matches(); } @Override public void describeTo(Description description) { description.appendText("a string matching the pattern '" + pattern + "'"); } /** * Creates a matcher of {@link String} that matches when the examined string * exactly matches the given {@link Pattern}. */ @Factory public static Matcher<String> matchesPattern(Pattern pattern) { return new MatchesPattern(pattern); } /** * Creates a matcher of {@link String} that matches when the examined string * exactly matches the given regular expression, treated as a {@link Pattern}. */ @Factory public static Matcher<String> matchesPattern(String regex) { return new MatchesPattern(Pattern.compile(regex)); } }
package org.hamcrest.text; import java.util.regex.Pattern; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; public class MatchesPattern extends TypeSafeMatcher<String> { private final Pattern pattern; public MatchesPattern(Pattern pattern) { this.pattern = pattern; } @Override protected boolean matchesSafely(String item) { return pattern.matcher(item).matches(); } @Override public void describeTo(Description description) { description.appendText("a string matching the pattern '" + pattern + "'"); } @Factory public static Matcher<String> matchesPattern(Pattern pattern) { return new MatchesPattern(pattern); } @Factory public static Matcher<String> matchesPattern(String regex) { return new MatchesPattern(Pattern.compile(regex)); } }
Add styling and some navigation to header.
import React from 'react'; import { Link, IndexLink } from 'react-router'; import AppBar from 'material-ui/AppBar'; import IconButton from 'material-ui/IconButton'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'; import NavigationClose from 'material-ui/svg-icons/navigation/close'; import { darkWhite } from 'material-ui/styles/colors'; import typography from 'material-ui/styles/typography'; const styles = { appBar: { position: 'fixed', top: 0, }, }; const Header = () => ( <AppBar title="Kasih.in" style={styles.root} iconElementLeft={ <IconButton containerElement={<Link to="/" />}> <NavigationClose /> </IconButton>} iconElementRight={ //TODO: Change the icon once you have <IconMenu iconButtonElement={ <IconButton><MoreVertIcon /></IconButton> } targetOrigin={{ horizontal: 'right', vertical: 'top' }} anchorOrigin={{ horizontal: 'right', vertical: 'top' }} > <MenuItem primaryText="About" containerElement={<Link to="/about" />} /> <MenuItem primaryText="Sign out" /> </IconMenu> } /> ); export default Header;
import React from 'react'; import { Link, IndexLink } from 'react-router'; import AppBar from 'material-ui/AppBar'; import IconButton from 'material-ui/IconButton'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'; import NavigationClose from 'material-ui/svg-icons/navigation/close'; const Header = () => { return ( <AppBar title="Kasih.in" iconElementLeft={<IconButton><NavigationClose /></IconButton>} iconElementRight={ <IconMenu iconButtonElement={ <IconButton><MoreVertIcon /></IconButton> } targetOrigin={{ horizontal: 'right', vertical: 'top' }} anchorOrigin={{ horizontal: 'right', vertical: 'top' }} > <MenuItem primaryText="Refresh" /> <MenuItem primaryText="Help" /> <MenuItem primaryText="Sign out" /> </IconMenu> } /> ); }; export default Header;
Use ipv4 in wincat port forward
// +build windows /* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package dockershim import ( "bytes" "fmt" "io" "k8s.io/kubernetes/pkg/kubelet/util/ioutils" ) func (r *streamingRuntime) portForward(podSandboxID string, port int32, stream io.ReadWriteCloser) error { stderr := new(bytes.Buffer) err := r.exec(podSandboxID, []string{"wincat.exe", "127.0.0.1", fmt.Sprint(port)}, stream, stream, ioutils.WriteCloserWrapper(stderr), false, nil, 0) if err != nil { return fmt.Errorf("%v: %s", err, stderr.String()) } return nil }
// +build windows /* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package dockershim import ( "bytes" "fmt" "io" "k8s.io/kubernetes/pkg/kubelet/util/ioutils" ) func (r *streamingRuntime) portForward(podSandboxID string, port int32, stream io.ReadWriteCloser) error { stderr := new(bytes.Buffer) err := r.exec(podSandboxID, []string{"wincat.exe", "localhost", fmt.Sprint(port)}, stream, stream, ioutils.WriteCloserWrapper(stderr), false, nil, 0) if err != nil { return fmt.Errorf("%v: %s", err, stderr.String()) } return nil }
Hide nav on document click
$(function(){ 'use strict'; //--- Global variables ---// //--- Helper functions ---// //--- In-page scroll ---// $('.scroll').on('click',function(e,target){ e.preventDefault(); var o = 0, t = 900; //offset (px), time delay (ms) var $anchor = $(this).attr('href'); $('html, body').stop().animate({ scrollTop: ($($anchor).offset().top) - o }, t); }); //--- Header nav menu hamburger ---// // Cache elements in vars var $header = $('.header'), $nav = $('#nav'); // Toggle nav on button click $('.hamburger').on('click',function(e){ e.preventDefault(); $nav.toggleClass('visible'); }) // Hide nav on document click (except header) $(document).on('click', function(e) { // if the target of the click isn't the container, nor a descendant of the container if (!$header.is(e.target) && $header.has(e.target).length === 0) { $nav.removeClass('visible'); } }); //--- Linkblog Quicksearch ---// $('.quicksearchForm').on('submit',function(e){ e.preventDefault(); }).find('#quicksearch').quicksearch('.lb li',{ 'noResults': '.noResults' }); //--- Config popup ---// var $config = $( $('#config_tmpl').html() ); $('body').prepend($config); $('.configBtn').on('click',function(e){ e.preventDefault(); $config.slideToggle(240); }); });
$(function(){ 'use strict'; //--- Global variables ---// //--- Helper functions ---// //--- In-page scroll ---// $('.scroll').on('click',function(e,target){ e.preventDefault(); var o = 0, t = 900; //offset (px), time delay (ms) var $anchor = $(this).attr('href'); $('html, body').stop().animate({ scrollTop: ($($anchor).offset().top) - o }, t); }); //--- Header nav menu hamburger ---// $('.hamburger').on('click',function(e){ e.preventDefault(); $('#nav').toggleClass('visible'); }) //--- Linkblog Quicksearch ---// $('.quicksearchForm').on('submit',function(e){ e.preventDefault(); }).find('#quicksearch').quicksearch('.lb li',{ 'noResults': '.noResults' }); //--- Config popup ---// var $config = $( $('#config_tmpl').html() ); $('body').prepend($config); $('.configBtn').on('click',function(e){ e.preventDefault(); $config.slideToggle(240); }); });
Change type for private blog settings refs #5614 and #5503 - update private blog type, including update to settings.edit - switch order of populate settings & update fixtures + populate all settings Private blog settings should not be returned by public endpoints therefore they need a type which is not `blog` or `theme`. `core` doesn't suit either, as those settings don't usually have UI To resolve this, I created a new type `private` which can be used for any setting which has a UI but should not be public data
import AuthenticatedRoute from 'ghost/routes/authenticated'; import CurrentUserSettings from 'ghost/mixins/current-user-settings'; import styleBody from 'ghost/mixins/style-body'; export default AuthenticatedRoute.extend(styleBody, CurrentUserSettings, { titleToken: 'Settings - General', classNames: ['settings-view-general'], beforeModel: function (transition) { this._super(transition); return this.get('session.user') .then(this.transitionAuthor()) .then(this.transitionEditor()); }, model: function () { return this.store.find('setting', {type: 'blog,theme,private'}).then(function (records) { return records.get('firstObject'); }); }, actions: { save: function () { this.get('controller').send('save'); } } });
import AuthenticatedRoute from 'ghost/routes/authenticated'; import CurrentUserSettings from 'ghost/mixins/current-user-settings'; import styleBody from 'ghost/mixins/style-body'; export default AuthenticatedRoute.extend(styleBody, CurrentUserSettings, { titleToken: 'Settings - General', classNames: ['settings-view-general'], beforeModel: function (transition) { this._super(transition); return this.get('session.user') .then(this.transitionAuthor()) .then(this.transitionEditor()); }, model: function () { return this.store.find('setting', {type: 'blog,theme'}).then(function (records) { return records.get('firstObject'); }); }, actions: { save: function () { this.get('controller').send('save'); } } });
Add hash_id column to user-info output
''' This module will retrieve info about students registered in the course ''' def user_info(edx_obj): edx_obj.collections = ['certificates_generatedcertificate', 'auth_userprofile','user_id_map','student_courseenrollment'] cursor = edx_obj.collections['auth_userprofile'].find() result = [] for item in cursor: user_id = item['user_id'] try: final_grade = edx_obj.collections['certificates_generatedcertificate'].find_one({'user_id' : user_id})['grade'] user_id_map = edx_obj.collections['user_id_map'].find_one({'id' : user_id}) username = user_id_map['username'] hash_id = user_id_map['hash_id'] enrollment_date = edx_obj.collections['student_courseenrollment'].find_one({'user_id' : user_id})['created'] result.append([user_id, username, hash_id, item['name'], final_grade, item['gender'], item['year_of_birth'], item['level_of_education'], item['country'], item['city'], enrollment_date]) except KeyError: print "Exception occurred for user_id {0}".format(user_id) edx_obj.generate_csv(result, ['User ID', 'Username', 'User Hash ID', 'Name', 'Final Grade', 'Gender', 'Year of Birth', 'Level of Education', 'Country', 'City','Enrollment Date'], output_file=edx_obj.db.name+'_user_info.csv')
''' This module will retrieve info about students registered in the course ''' def user_info(edx_obj): edx_obj.collections = ['certificates_generatedcertificate', 'auth_userprofile','user_id_map','student_courseenrollment'] cursor = edx_obj.collections['auth_userprofile'].find() result = [] for item in cursor: user_id = item['user_id'] try: final_grade = edx_obj.collections['certificates_generatedcertificate'].find_one({'user_id' : user_id})['grade'] username = edx_obj.collections['user_id_map'].find_one({'id' : user_id})['username'] enrollment_date = edx_obj.collections['student_courseenrollment'].find_one({'user_id' : user_id})['created'] result.append([user_id, item['name'], final_grade, username, item['gender'], item['year_of_birth'], item['level_of_education'], item['country'], item['city'], enrollment_date]) except: print "Exception occurred for user_id {0}".format(user_id) edx_obj.generate_csv(result, ['User ID','Name', 'Final Grade', 'Username', 'Gender', 'Year of Birth', 'Level of Education', 'Country', 'City','Enrollment Date'], output_file=edx_obj.db.name+'_user_info.csv')
Add Android Virtual Device IP
package com.example.todocloud.app; public class AppConfig { /*private static String prefix = "http://192.168.1.100/todo_cloud/";*/ // LAN IP /*private static String prefix = "http://192.168.56.1/todo_cloud/";*/ // Genymotion IP private static String prefix = "http://10.0.2.2/todo_cloud/"; // AVD IP /*private static String prefix = "http://192.168.173.1/todo_cloud/";*/ // ad hoc network IP public static String URL_REGISTER = prefix + "v1/user/register"; public static String URL_LOGIN = prefix + "v1/user/login"; public static String URL_GET_TODOS = prefix + "v1/todo/:row_version"; public static String URL_GET_LISTS = prefix + "v1/list/:row_version"; public static String URL_GET_CATEGORIES = prefix + "v1/category/:row_version"; public static String URL_UPDATE_TODO = prefix + "v1/todo/update"; public static String URL_UPDATE_LIST = prefix + "v1/list/update"; public static String URL_UPDATE_CATEGORY = prefix + "v1/category/update"; public static String URL_INSERT_TODO = prefix + "v1/todo/insert"; public static String URL_INSERT_LIST = prefix + "v1/list/insert"; public static String URL_INSERT_CATEGORY = prefix + "v1/category/insert"; }
package com.example.todocloud.app; public class AppConfig { private static String prefix = "http://192.168.1.100/todo_cloud/"; // LAN IP /*private static String prefix = "http://192.168.56.1/todo_cloud/";*/ // Genymotion IP /*private static String prefix = "http://192.168.173.1/todo_cloud/";*/ // ad hoc network IP public static String URL_REGISTER = prefix + "v1/user/register"; public static String URL_LOGIN = prefix + "v1/user/login"; public static String URL_GET_TODOS = prefix + "v1/todo/:row_version"; public static String URL_GET_LISTS = prefix + "v1/list/:row_version"; public static String URL_GET_CATEGORIES = prefix + "v1/category/:row_version"; public static String URL_UPDATE_TODO = prefix + "v1/todo/update"; public static String URL_UPDATE_LIST = prefix + "v1/list/update"; public static String URL_UPDATE_CATEGORY = prefix + "v1/category/update"; public static String URL_INSERT_TODO = prefix + "v1/todo/insert"; public static String URL_INSERT_LIST = prefix + "v1/list/insert"; public static String URL_INSERT_CATEGORY = prefix + "v1/category/insert"; }
Add PlayTime class and tie it to user profiles Created a PlayTime class in account with from and to times. Added ManyToManyField to UserProfile to keep track of play times.
from django.db import models from django.contrib.auth.models import User, Group from evewspace.Map.models import Map from django.db.models.signals import post_save # Create your models here. class PlayTime(models.Model): """PlayTime represents a choice of play times for use in several forms.""" fromtime = models.TimeField() totime = models.TimeField() class UserProfile(models.Model): """UserProfile defines custom fields tied to each User record in the Django auth DB.""" user = models.ForeignKey(User, unique = True) jabberid = models.EmailField(blank = True, null=True) defaultmap = models.ForeignKey(Map, related_name = "defaultusers", blank=True, null=True) playtimes = models.ManyToManyField(PlayTime) class GroupProfile(models.Model): """GroupProfile defines custom fields tied to each Group record.""" group = models.ForeignKey(Group, unique=True) description = models.CharField(max_length=200, blank=True, null=True) def create_user_profile(sender, instance, created, **kwargs): """Handle user creation event and create a new profile to match the new user""" if created: UserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) def create_group_profile(sender, instance, created, **kwargs): """Handle group creation even and create a new group profile.""" if created: GroupProfile.objects.create(group=instance) post_save.connect(create_group_profile, sender=Group)
from django.db import models from django.contrib.auth.models import User, Group from evewspace.Map.models import Map from django.db.models.signals import post_save # Create your models here. class UserProfile(models.Model): """UserProfile defines custom fields tied to each User record in the Django auth DB.""" user = models.ForeignKey(User, unique = True) jabberid = models.EmailField(blank = True, null=True) defaultmap = models.ForeignKey(Map, related_name = "defaultusers", blank=True, null=True) class GroupProfile(models.Model): """GroupProfile defines custom fields tied to each Group record.""" group = models.ForeignKey(Group, unique=True) description = models.CharField(max_length=200, blank=True, null=True) def create_user_profile(sender, instance, created, **kwargs): """Handle user creation event and create a new profile to match the new user""" if created: UserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) def create_group_profile(sender, instance, created, **kwargs): """Handle group creation even and create a new group profile.""" if created: GroupProfile.objects.create(group=instance) post_save.connect(create_group_profile, sender=Group)
Test the new tos view
# Yith Library Server is a password storage server. # Copyright (C) 2012 Yaco Sistemas # Copyright (C) 2012 Alejandro Blanco Escudero <alejandro.b.e@gmail.com> # Copyright (C) 2012 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. from yithlibraryserver import testing class ViewTests(testing.TestCase): def test_home(self): res = self.testapp.get('/') self.assertEqual(res.status, '200 OK') def test_tos(self): res = self.testapp.get('/tos') self.assertEqual(res.status, '200 OK')
# Yith Library Server is a password storage server. # Copyright (C) 2012 Yaco Sistemas # Copyright (C) 2012 Alejandro Blanco Escudero <alejandro.b.e@gmail.com> # Copyright (C) 2012 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. from yithlibraryserver import testing class ViewTests(testing.TestCase): def test_home(self): res = self.testapp.get('/') self.assertEqual(res.status, '200 OK')
Remove default value for createSleepPromise options
// Store a reference to the global setTimeout, // in case it gets replaced (e.g. sinon.useFakeTimers()) const cachedSetTimeout = setTimeout; function createSleepPromise(timeout, { useCachedSetTimeout }) { const timeoutFunction = useCachedSetTimeout ? cachedSetTimeout : setTimeout; return new Promise((resolve) => { timeoutFunction(resolve, timeout); }); } export default function sleep(timeout, { useCachedSetTimeout } = {}) { const sleepPromise = createSleepPromise(timeout, { useCachedSetTimeout }); // Pass value through, if used in a promise chain function promiseFunction(value) { return sleepPromise.then(() => value); } // Normal promise promiseFunction.then = (...args) => sleepPromise.then(...args); promiseFunction.catch = Promise.resolve().catch; return promiseFunction; }
// Store a reference to the global setTimeout, // in case it gets replaced (e.g. sinon.useFakeTimers()) const cachedSetTimeout = setTimeout; function createSleepPromise(timeout, { useCachedSetTimeout } = {}) { const timeoutFunction = useCachedSetTimeout ? cachedSetTimeout : setTimeout; return new Promise((resolve) => { timeoutFunction(resolve, timeout); }); } export default function sleep(timeout, { useCachedSetTimeout } = {}) { const sleepPromise = createSleepPromise(timeout, { useCachedSetTimeout }); // Pass value through, if used in a promise chain function promiseFunction(value) { return sleepPromise.then(() => value); } // Normal promise promiseFunction.then = (...args) => sleepPromise.then(...args); promiseFunction.catch = Promise.resolve().catch; return promiseFunction; }
Revert "Fixed typo in javadoc" This reverts commit b95fda354b618a5fa75b57f0400719e47cb7f91f.
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.karaf.shell.api.action.lifecycle; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * A class annotated with {@link @Service} can have fields * annotated with <code>@Service</code> in which case matching * services will be retrieved from the * {@link org.apache.karaf.shell.api.console.Registry} and * injected. * * If a field has a {@link java.util.List} type, it will be injected * with a list containing all matching services. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface Reference { boolean optional() default false; }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.karaf.shell.api.action.lifecycle; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * A class annotated with {@link @Service} can have fields * annotated with <code>@Reference</code> in which case matching * services will be retrieved from the * {@link org.apache.karaf.shell.api.console.Registry} and * injected. * * If a field has a {@link java.util.List} type, it will be injected * with a list containing all matching services. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface Reference { boolean optional() default false; }
Fix database connection leak in tests Without this, each flask app created in tests will hold one database connection until all tests are finished. This may result in test failure if database limits number of concurrent connections.
"""Unit and functional test suite for SkyLines.""" import os import shutil from skylines.model import db from tests.data.bootstrap import bootstrap __all__ = ['setup_db', 'setup_app', 'teardown_db'] def setup_db(): """Method used to build a database""" db.create_all() def setup_dirs(app): filesdir = app.config['SKYLINES_FILES_PATH'] if os.path.exists(filesdir): shutil.rmtree(filesdir) os.makedirs(filesdir) def setup_app(app): setup_db() setup_dirs(app) def teardown_db(): """Method used to destroy a database""" db.session.remove() db.drop_all() db.session.bind.dispose() def clean_db(): """Clean all data, leaving schema as is Suitable to be run before each db-aware test. This is much faster than dropping whole schema an recreating from scratch. """ for table in reversed(db.metadata.sorted_tables): db.session.execute(table.delete()) def clean_db_and_bootstrap(): clean_db() bootstrap() db.session.commit()
"""Unit and functional test suite for SkyLines.""" import os import shutil from skylines.model import db from tests.data.bootstrap import bootstrap __all__ = ['setup_db', 'setup_app', 'teardown_db'] def setup_db(): """Method used to build a database""" db.create_all() def setup_dirs(app): filesdir = app.config['SKYLINES_FILES_PATH'] if os.path.exists(filesdir): shutil.rmtree(filesdir) os.makedirs(filesdir) def setup_app(app): setup_db() setup_dirs(app) def teardown_db(): """Method used to destroy a database""" db.session.remove() db.drop_all() def clean_db(): """Clean all data, leaving schema as is Suitable to be run before each db-aware test. This is much faster than dropping whole schema an recreating from scratch. """ for table in reversed(db.metadata.sorted_tables): db.session.execute(table.delete()) def clean_db_and_bootstrap(): clean_db() bootstrap() db.session.commit()
Add New Class To Link
;(function() { "use strict"; angular. module("bookApp"). component("bookApp", { template: ` <div class="nav"><a href="new-book" class="nav-click">Add new book</a></div> <div class="book-container" ng-repeat="book in $ctrl.books"> <h3>{{book.title}}</h3> <img ng-src="http://theproactiveprogrammer.com/wp-content/uploads/2014/09/js_good_parts.png" alt="" /> <p>{{book.rate}}</p> <p>{{book.author}}</p> <p>{{book.descroption}}</p> </div> `, controller: BookAppController }); BookAppController.$inject = ["$scope"]; function BookAppController($scope) { let vm = this, bookRef = firebase.database().ref("Books"); vm.books = []; bookRef.on("value", function(snapshot) { // vm.users.push(snapshot.val()); snapshot.forEach(function(subSnap) { vm.books.push(subSnap.val()); }); if(!$scope.$$phase) $scope.$apply(); }); } })();
;(function() { "use strict"; angular. module("bookApp"). component("bookApp", { template: ` <div class="nav"><a href="new-book">Add new book</a></div> <div class="book-container" ng-repeat="book in $ctrl.books"> <h3>{{book.title}}</h3> <img ng-src="http://theproactiveprogrammer.com/wp-content/uploads/2014/09/js_good_parts.png" alt="" /> <p>{{book.rate}}</p> <p>{{book.author}}</p> <p>{{book.descroption}}</p> </div> `, controller: BookAppController }); BookAppController.$inject = ["$scope"]; function BookAppController($scope) { let vm = this, bookRef = firebase.database().ref("Books"); vm.books = []; bookRef.on("value", function(snapshot) { // vm.users.push(snapshot.val()); snapshot.forEach(function(subSnap) { vm.books.push(subSnap.val()); }); if(!$scope.$$phase) $scope.$apply(); }); } })();
Reduce to 3 the number of days for the method test.
package cl.fatman.capital.fund; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; public class ControllerTest { private static Controller control; private static PersistenceData persistence; @BeforeClass public static void setUp() { control = Controller.getInstance(); control.setUp(); List<FundType> ftList = new ArrayList<FundType>(); FundType type = new FundType(1, "Deuda < 90 días"); ftList.add(type); persistence = PersistenceData.getInstance(); persistence.insertObjectList(ftList); } @AfterClass public static void tearDown() { control.tearDown(); } @Test public void storeFundDataTest() { LocalDate endDate = LocalDate.now(); LocalDate startDate = endDate.minusDays(2); control.storeFundData(startDate, endDate); List<?> rList = persistence.selectAllObjects("from FundRate", FundRate.class); assertThat("Fund rate list should be greater than 0.", rList.size(), greaterThan(0)); } }
package cl.fatman.capital.fund; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; public class ControllerTest { private static Controller control; private static PersistenceData persistence; @BeforeClass public static void setUp() { control = Controller.getInstance(); control.setUp(); List<FundType> ftList = new ArrayList<FundType>(); FundType type = new FundType(1, "Deuda < 90 días"); ftList.add(type); persistence = PersistenceData.getInstance(); persistence.insertObjectList(ftList); } @AfterClass public static void tearDown() { control.tearDown(); } @Test public void storeFundDataTest() { LocalDate endDate = LocalDate.now(); LocalDate startDate = endDate.minusDays(3); control.storeFundData(startDate, endDate); List<?> rList = persistence.selectAllObjects("from FundRate", FundRate.class); assertThat("Fund rate list should be greater than 0.", rList.size(), greaterThan(0)); } }
Use Array.map to transform classes response
/*jslint browser: true, undef: true *//*global Ext*/ Ext.define('SlateAdmin.store.people.UserClasses', { extend: 'Ext.data.Store', requires: [ 'SlateAdmin.proxy.API' ], idProperty: 'value', fields: [{ name: 'value', type: 'string' }], proxy: { type: 'slateapi', url: '/people/*classes', extraParams: { interface: 'user' }, reader: { type: 'json', transform: function(response) { return Ext.Array.map(response.data, function (cls) { return { value: cls } }); } } } });
/*jslint browser: true, undef: true *//*global Ext*/ Ext.define('SlateAdmin.store.people.UserClasses', { extend: 'Ext.data.Store', requires: [ 'SlateAdmin.proxy.API' ], idProperty: 'value', fields: [{ name: 'value', type: 'string' }], proxy: { type: 'slateapi', url: '/people/*classes', extraParams: { interface: 'user' }, reader: { type: 'json', transform: function(response) { var records = []; Ext.iterate(response.data, function(key, value) { records.push({ value: value }); }); return records; } } } });
Add logic to handle function summaries
<?php namespace Phamda\Builder; use Phamda\Phamda; use PhpParser\Node\Expr; class SimpleMethodBuilder extends AbstractMethodBuilder { const COMMENT_ROW_PREFIX = ' *'; public function build() { return parent::build()->makeStatic(); } protected function createComment() { $rows = explode("\n", $this->source->getDocComment()); $exampleStart = Phamda::findIndex(function ($row) { return strpos($row, '@') !== false; }, $rows); return implode("\n", array_merge( array_slice($rows, 0, $exampleStart), array_map(function ($row) { return self::COMMENT_ROW_PREFIX . ' ' . $row; }, (new CommentExampleBuilder($this->source))->getRows()), [self::COMMENT_ROW_PREFIX], array_slice($rows, $exampleStart) )); } }
<?php namespace Phamda\Builder; use PhpParser\Node\Expr; class SimpleMethodBuilder extends AbstractMethodBuilder { const COMMENT_ROW_PREFIX = ' *'; public function build() { return parent::build()->makeStatic(); } protected function createComment() { $rows = explode("\n", $this->source->getDocComment()); return implode("\n", array_merge( array_slice($rows, 0, 1), array_map(function ($row) { return self::COMMENT_ROW_PREFIX . ' ' . $row; }, (new CommentExampleBuilder($this->source))->getRows()), [self::COMMENT_ROW_PREFIX], array_slice($rows, 1) )); } }
Remove header added to gold file
""" python TestPostprocessorPluginManager_test_script.py """ import matplotlib.pyplot as plt import mooseutils # Create Figure and Axes figure = plt.figure(facecolor='white') axes0 = figure.add_subplot(111) axes1 = axes0.twinx() # Read Postprocessor Data data = mooseutils.PostprocessorReader('../input/white_elephant_jan_2016.csv') x = data('time') y = data('air_temp_set_1') axes1.plot(x, y, marker='', linewidth=5.0, color=[0.2, 0.627, 0.173, 1.0], markersize=1, linestyle=u'--', label='air_temp_set_1') # Axes Settings axes1.legend(loc='lower right') axes0.set_title('Snow Data') # y1-axis Settings axes1.set_ylabel('Air Temperature [C]') axes1.set_ylim([0.0, 35.939999999999998]) # Show figure and write pdf plt.show() figure.savefig("output.pdf")
#* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/licenses/lgpl-2.1.html """ python TestPostprocessorPluginManager_test_script.py """ import matplotlib.pyplot as plt import mooseutils # Create Figure and Axes figure = plt.figure(facecolor='white') axes0 = figure.add_subplot(111) axes1 = axes0.twinx() # Read Postprocessor Data data = mooseutils.PostprocessorReader('../input/white_elephant_jan_2016.csv') x = data('time') y = data('air_temp_set_1') axes1.plot(x, y, marker='', linewidth=5.0, color=[0.2, 0.627, 0.173, 1.0], markersize=1, linestyle=u'--', label='air_temp_set_1') # Axes Settings axes1.legend(loc='lower right') axes0.set_title('Snow Data') # y1-axis Settings axes1.set_ylabel('Air Temperature [C]') axes1.set_ylim([0.0, 35.939999999999998]) # Show figure and write pdf plt.show() figure.savefig("output.pdf")
Revert "Try a lambda instead of a method reference for java 8 support" This reverts commit 84d3e987405adeeab8ab60bd8a4e2e54e227a253.
package me.proxer.library.api; import me.proxer.library.util.ProxerUtils; import retrofit2.Converter; import retrofit2.Retrofit; import java.lang.annotation.Annotation; import java.lang.reflect.Type; /** * @author Ruben Gees */ final class EnumRetrofitConverterFactory extends Converter.Factory { @Override public Converter<?, String> stringConverter(final Type type, final Annotation[] annotations, final Retrofit retrofit) { if (((Class<?>) type).isEnum()) { return (Converter<Enum<?>, String>) ProxerUtils::getApiEnumName; } return null; } }
package me.proxer.library.api; import me.proxer.library.util.ProxerUtils; import retrofit2.Converter; import retrofit2.Retrofit; import java.lang.annotation.Annotation; import java.lang.reflect.Type; /** * @author Ruben Gees */ final class EnumRetrofitConverterFactory extends Converter.Factory { @Override public Converter<?, String> stringConverter(final Type type, final Annotation[] annotations, final Retrofit retrofit) { if (((Class<?>) type).isEnum()) { return (Converter<Enum<?>, String>) value -> ProxerUtils.getApiEnumName(value); } return null; } }
Make constructor of DefaultFilterSet compatible - arguments had different names than FilterSet before
import django_filters class PagedFilterSet(django_filters.FilterSet): """Removes page parameters from the query when applying filters.""" page_kwarg = 'page' def __init__(self, data, *args, **kwargs): if self.page_kwarg in data: # Create a mutable copy data = data.copy() del data[self.page_kwarg] return super().__init__(data=data, *args, **kwargs) class DefaultsFilterSet(PagedFilterSet): """Extend to define default filter values. Set the defaults attribute. E.g.: defaults = { 'is_archived': 'false' } """ defaults = None def __init__(self, data, *args, **kwargs): data = data.copy() # Set the defaults if they are not manually set yet for key, value in self.defaults.items(): if key not in data: data[key] = value super().__init__(data, *args, **kwargs)
import django_filters class PagedFilterSet(django_filters.FilterSet): """Removes page parameters from the query when applying filters.""" page_kwarg = 'page' def __init__(self, data, *args, **kwargs): if self.page_kwarg in data: # Create a mutable copy data = data.copy() del data[self.page_kwarg] return super().__init__(data=data, *args, **kwargs) class DefaultsFilterSet(PagedFilterSet): """Extend to define default filter values. Set the defaults attribute. E.g.: defaults = { 'is_archived': 'false' } """ defaults = None def __init__(self, query_data, *args, **kwargs): data = query_data.copy() # Set the defaults if they are not manually set yet for key, value in self.defaults.items(): if key not in data: data[key] = value super().__init__(data, *args, **kwargs)
Fix XSS on API Integrations H1 1753684
<?php defined('C5_EXECUTE') or die("Access Denied."); /** * @var \Concrete\Core\Search\Pagination\Pagination $pagination */ if ($pagination->getTotalResults() > 0) { ?> <table class="ccm-search-results-table"> <thead> <tr> <th><?=t('ID')?></th> <th><?=t('Name')?></th> </tr> </thead> <tbody> <?php foreach ($pagination->getCurrentPageResults() as $client) { ?> <tr data-details-url="<?=$view->action('view_client', $client->getIdentifier())?>"> <td class="text-nowrap"><?=$client->getIdentifier()?></td> <td class="ccm-search-results-name w-100"><?=h($client->getName())?></td> </tr> <?php } ?> </tbody> </table> <?php if ($pagination->getTotalPages() > 1) { ?> <?php echo $pagination->renderView('dashboard'); ?> <?php } ?> <?php } else { ?> <p><?=t('No API integrations found.')?></p> <?php } ?>
<?php defined('C5_EXECUTE') or die("Access Denied."); /** * @var \Concrete\Core\Search\Pagination\Pagination $pagination */ if ($pagination->getTotalResults() > 0) { ?> <table class="ccm-search-results-table"> <thead> <tr> <th><?=t('ID')?></th> <th><?=t('Name')?></th> </tr> </thead> <tbody> <?php foreach ($pagination->getCurrentPageResults() as $client) { ?> <tr data-details-url="<?=$view->action('view_client', $client->getIdentifier())?>"> <td class="text-nowrap"><?=$client->getIdentifier()?></td> <td class="ccm-search-results-name w-100"><?=$client->getName()?></td> </tr> <?php } ?> </tbody> </table> <?php if ($pagination->getTotalPages() > 1) { ?> <?php echo $pagination->renderView('dashboard'); ?> <?php } ?> <?php } else { ?> <p><?=t('No API integrations found.')?></p> <?php } ?>
Fix fatal error when using Logger::devLog - Error message is "Call to a member function log() on null in src/Core/Logger.php:304"
<?php namespace Friendica\Factory; use Friendica\App; use Friendica\Core\Config\Cache; use Friendica\Factory; use Friendica\Util\BasePath; class DependencyFactory { /** * Setting all default-dependencies of a friendica execution * * @param string $channel The channel of this execution * @param string $directory The base directory * @param bool $isBackend True, if it's a backend execution, otherwise false (Default true) * * @return App The application * * @throws \Exception */ public static function setUp($channel, $directory, $isBackend = true) { $basePath = BasePath::create($directory, $_SERVER); $configLoader = new Cache\ConfigCacheLoader($basePath); $configCache = Factory\ConfigFactory::createCache($configLoader); $profiler = Factory\ProfilerFactory::create($configCache); Factory\DBFactory::init($basePath, $configCache, $profiler, $_SERVER); $config = Factory\ConfigFactory::createConfig($configCache); // needed to call PConfig::init() Factory\ConfigFactory::createPConfig($configCache); $logger = Factory\LoggerFactory::create($channel, $config); Factory\LoggerFactory::createDev($channel, $config); return new App($basePath, $config, $logger, $profiler, $isBackend); } }
<?php namespace Friendica\Factory; use Friendica\App; use Friendica\Core\Config\Cache; use Friendica\Factory; use Friendica\Util\BasePath; class DependencyFactory { /** * Setting all default-dependencies of a friendica execution * * @param string $channel The channel of this execution * @param string $directory The base directory * @param bool $isBackend True, if it's a backend execution, otherwise false (Default true) * * @return App The application * * @throws \Exception */ public static function setUp($channel, $directory, $isBackend = true) { $basePath = BasePath::create($directory, $_SERVER); $configLoader = new Cache\ConfigCacheLoader($basePath); $configCache = Factory\ConfigFactory::createCache($configLoader); $profiler = Factory\ProfilerFactory::create($configCache); Factory\DBFactory::init($basePath, $configCache, $profiler, $_SERVER); $config = Factory\ConfigFactory::createConfig($configCache); // needed to call PConfig::init() Factory\ConfigFactory::createPConfig($configCache); $logger = Factory\LoggerFactory::create($channel, $config); return new App($basePath, $config, $logger, $profiler, $isBackend); } }
Add cellContents: nbsp for now
var rows = 0; var cols = 10; var table; var edit_border = "thin dotted grey"; function text(str) { return document.createTextNode(str); } function cellContents(rowindex, colindex) { return "&nbsp;"; } function init() { table = document.getElementById("wftable"); addRows(4); } function addRows(numrows) { numrows += rows; if (table.tBodies.length < 1) { table.appendChild(document.createElement('tbody')); } for (; rows < numrows; rows++) { table.tBodies[table.tBodies.length - 1].appendChild(text("\n")); var row = table.insertRow(-1); row.appendChild(text("\n")); for (c = 0; c < cols; c++) { var cell = row.insertCell(-1); cell.innerHTML = cellContents(rows, c); cell.style.border = edit_border; row.appendChild(text("\n")); } } } function addCols(numcols) { cols += numcols; for (r = 0; r < rows; r++) { var row = table.rows[r]; for (c = row.cells.length; c < cols; c++) { var cell = row.insertCell(-1); cell.innerHTML = cellContents(r, c); cell.style.border = edit_border; row.appendChild(text("\n")); } } }
var rows = 0; var cols = 10; var table; var edit_border = "thin dotted grey"; function text(str) { return document.createTextNode(str); } function init() { table = document.getElementById("wftable"); addRows(4); } function addRows(numrows) { numrows += rows; if (table.tBodies.length < 1) { table.appendChild(document.createElement('tbody')); } for (; rows < numrows; rows++) { table.tBodies[table.tBodies.length - 1].appendChild(text("\n")); var row = table.insertRow(-1); row.appendChild(text("\n")); for (c = 0; c < cols; c++) { var cell = row.insertCell(-1); cell.innerHTML = rows.toString().concat(",", c.toString()); cell.style.border = edit_border; row.appendChild(text("\n")); } } } function addCols(numcols) { cols += numcols; for (r = 0; r < rows; r++) { var row = table.rows[r]; for (c = row.cells.length; c < cols; c++) { var cell = row.insertCell(-1); cell.innerHTML = r.toString().concat(",", c.toString()); cell.style.border = edit_border; row.appendChild(text("\n")); } } }
Add new line at the end of test files
const Alfred = require('../index'); const Builder = Alfred.Builder; const bot = new Alfred(); bot.login('username', 'password') .then(() => bot.send('servernotifyregister', { 'event': 'server' })) .then(() => bot.send('servernotifyregister', { 'event': 'textprivate' })) .then(() => console.log('Connected with clid', bot.get('clid'))) .catch(console.error); bot.use(Alfred.User); bot.on('cliententerview', data => console.log(data.user.get('name'), 'connected', '[db:' + data.user.get('dbid') + ']')); bot.on('clientleftview', data => console.log(data.user.get('name'), 'disconnected')); bot.on('textmessage', data => { let msg = "" + data.msg; console.log(JSON.stringify(data)); if (msg.startsWith("!exit")) { bot.disconnect(); console.log("disconnected"); } if (msg.startsWith("!kickserver")) { data.user.serverKick(Builder.underline("Bye from the server!")); } if (msg.startsWith("!kickchannel")) { data.user.channelKick(Builder.italic("bye have great day!")); } });
const Alfred = require('../index'); const Builder = Alfred.Builder; const bot = new Alfred(); bot.login('username', 'password') .then(() => bot.send('servernotifyregister', { 'event': 'server' })) .then(() => bot.send('servernotifyregister', { 'event': 'textprivate' })) .then(() => console.log('Connected with clid', bot.get('clid'))) .catch(console.error); bot.use(Alfred.User); bot.on('cliententerview', data => console.log(data.user.get('name'), 'connected', '[db:' + data.user.get('dbid') + ']')); bot.on('clientleftview', data => console.log(data.user.get('name'), 'disconnected')); bot.on('textmessage', data => { let msg = "" + data.msg; console.log(JSON.stringify(data)); if (msg.startsWith("!exit")) { bot.disconnect(); console.log("disconnected"); } if (msg.startsWith("!kickserver")) { data.user.serverKick(Builder.underline("Bye from the server!")); } if (msg.startsWith("!kickchannel")) { data.user.channelKick(Builder.italic("bye have great day!")); } });
Add module.py test and modify some others for better coverage. Remove files not used.
import pytest import os from SCNIC.general import simulate_correls from SCNIC.between_correls import between_correls @pytest.fixture() def args(): class Arguments(object): def __init__(self): self.table1 = "table1.biom" self.table2 = "table2.biom" self.output = "out_dir" self.correl_method = "spearman" self.p_adjust = "bh" self.min_sample = None self.min_p = None self.min_r = None self.sparcc_filter = True self.force = False self.procs = 1 return Arguments() def test_between_correls(args, tmpdir): table1 = simulate_correls() table2 = simulate_correls() loc = tmpdir.mkdir("with_correls_test") table1.to_json("madebyme", open(str(loc)+"/table1.biom", 'w')) table2.to_json("madebyme", open(str(loc) + "/table2.biom", 'w')) os.chdir(str(loc)) between_correls(args) files = os.listdir(str(loc)+'/out_dir') assert "correls.txt" in files assert "crossnet.gml" in files
import pytest import os from SCNIC.general import simulate_correls from SCNIC.between_correls import between_correls @pytest.fixture() def args(): class Arguments(object): def __init__(self): self.table1 = "table1.biom" self.table2 = "table2.biom" self.output = "out_dir" self.correl_method = "spearman" self.p_adjust = "bh" self.min_sample = None self.min_p = None self.min_r = None self.sparcc_filter = False self.force = False self.procs = 1 return Arguments() def test_between_correls(args, tmpdir): table1 = simulate_correls() table2 = simulate_correls() loc = tmpdir.mkdir("with_correls_test") table1.to_json("madebyme", open(str(loc)+"/table1.biom", 'w')) table2.to_json("madebyme", open(str(loc) + "/table2.biom", 'w')) os.chdir(str(loc)) between_correls(args) files = os.listdir(str(loc)+'/out_dir') assert "correls.txt" in files assert "crossnet.gml" in files
Fix some bullshit with generics.
package codechicken.lib.util.registry; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.registry.LegacyNamespacedRegistry; import javax.annotation.Nullable; import java.util.HashMap; public class DuplicateValueRegistry extends LegacyNamespacedRegistry { private final LegacyNamespacedRegistry wrapped; private final HashMap<Object, ResourceLocation> classMap = new HashMap<>(); public DuplicateValueRegistry(LegacyNamespacedRegistry wrapped) { this.wrapped = wrapped; } @SuppressWarnings ("unchecked") @Nullable @Override public ResourceLocation getNameForObject(Object value) { if (classMap.containsKey(value)) { return classMap.get(value); } return (ResourceLocation) wrapped.getNameForObject(value); } public void addMapping(Object clazz, ResourceLocation mapping) { classMap.put(clazz, mapping); } }
package codechicken.lib.util.registry; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.registry.LegacyNamespacedRegistry; import javax.annotation.Nullable; import java.util.HashMap; public class DuplicateValueRegistry<V> extends LegacyNamespacedRegistry<V> { private final LegacyNamespacedRegistry<V> wrapped; private final HashMap<V, ResourceLocation> classMap = new HashMap<>(); public DuplicateValueRegistry(LegacyNamespacedRegistry<V> wrapped) { this.wrapped = wrapped; } @Nullable @Override public ResourceLocation getNameForObject(V value) { if (classMap.containsKey(value)) { return classMap.get(value); } return wrapped.getNameForObject(value); } public void addMapping(V clazz, ResourceLocation mapping) { classMap.put(clazz, mapping); } }
Refactor react-counter example to "redux style"
import React, { Component, PropTypes } from 'react'; const reducer = (state = { counter: 0 }, action) => { switch (action.type) { case 'INCREMENT': return { counter: state.counter + 1 }; case 'DECREMENT': return { counter: state.counter - 1 }; default: return state; } }; class Counter extends Component { constructor() { super(); this.state = { counter: 0 }; this.increment = this.increment.bind(this); this.decrement = this.decrement.bind(this); } dispatch(action) { this.setState(reducer(this.state, action)); } increment() { this.dispatch({ type: 'INCREMENT' }); } decrement() { this.dispatch({ type: 'DECREMENT' }); } render() { const { counter } = this.state; return ( <p> Clicked: {counter} times {' '} <button onClick={this.increment}>+</button> {' '} <button onClick={this.decrement}>-</button> </p> ); } } export default Counter;
import React, { Component, PropTypes } from 'react'; class Counter extends Component { constructor() { super(); this.state = { counter: 0 }; this.increment = this.increment.bind(this); this.decrement = this.decrement.bind(this); } increment() { this.setState({ counter: this.state.counter + 1 }); } decrement() { this.setState({ counter: this.state.counter - 1 }); } render() { const { counter } = this.state; return ( <p> Clicked: {counter} times {' '} <button onClick={this.increment}>+</button> {' '} <button onClick={this.decrement}>-</button> </p> ); } } export default Counter;
Fix comment describing pypi incantation
#from distutils.core import setup from setuptools import setup, find_packages setup( name='Flask-MongoMyAdmin', version='0.1', url='http://github.com/classicspecs/Flask-MongoMyAdmin/', author='Jay Goel', author_email='jay@classicspecs.com', description='Simple MongoDB Administrative Interface for Flask', long_description=open('README.rst').read(), #packages=['flask_mongomyadmin'], packages=find_packages(), include_package_data=True, zip_safe=False, platforms='any', install_requires=[ 'Flask', 'pymongo', ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) # To update pypi: `python setup.py register sdist upload`
#from distutils.core import setup from setuptools import setup, find_packages setup( name='Flask-MongoMyAdmin', version='0.1', url='http://github.com/classicspecs/Flask-MongoMyAdmin/', author='Jay Goel', author_email='jay@classicspecs.com', description='Simple MongoDB Administrative Interface for Flask', long_description=open('README.rst').read(), #packages=['flask_mongomyadmin'], packages=find_packages(), include_package_data=True, zip_safe=False, platforms='any', install_requires=[ 'Flask', 'pymongo', ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) # To update pypi: `python setup.py register sdist bdist_wininst upload`
Remove keyboard shortcuts used in design
$(document).ready(function($) { // header dropdowns $('.mainItem a, ul.dropdown').hover(function() { $(this).parent().toggleClass('hover'); }); // sticky footer $(window).bind('load resize', function() { var h = $(window).height(); var a = $('#about').outerHeight(); $('#wrapper').css({ 'min-height' : (h-a) }); $('#ohnoes').css({'height': (h-a-71) }); }); // vertical align class $(window).bind('load resize', function() { $('.vAlign').each(function() { var h = $(this).parent().siblings('.vMaster').outerHeight(); var w = $(this).parent().width(); $(this).css({ height : h }); $(this).css({ width : w }); }); }); });
$(document).ready(function($) { // header dropdowns $('.mainItem a, ul.dropdown').hover(function() { $(this).parent().toggleClass('hover'); }); // sticky footer $(window).bind('load resize', function() { var h = $(window).height(); var a = $('#about').outerHeight(); $('#wrapper').css({ 'min-height' : (h-a) }); $('#ohnoes').css({'height': (h-a-71) }); }); // vertical align class $(window).bind('load resize', function() { $('.vAlign').each(function() { var h = $(this).parent().siblings('.vMaster').outerHeight(); var w = $(this).parent().width(); $(this).css({ height : h }); $(this).css({ width : w }); }); }); // keyboard shortcuts $(document.documentElement).keyup(function (event) { if (event.keyCode == 71) { $('#grid').fadeToggle(100); // G toggles grid } }); });
Include recently added matchers in callee.__all__
""" callee """ __version__ = "0.0.1" __description__ = "Argument matcher for unittest.mock" __author__ = "Karol Kuczmarski" __license__ = "Simplified BSD" from callee.base import And, Or, Not from callee.collections import Dict, List, Mapping, Iterable, Sequence, Set from callee.general import \ Any, ArgThat, IsA, Inherits, InstanceOf, Matching, SubclassOf from callee.strings import Bytes, String, Unicode __all__ = [ 'BaseMatcher', 'Eq', 'Not', 'And', 'Or', 'Iterable', 'Sequence', 'List', 'Set', 'Mapping', 'Dict', 'Any', 'Matching', 'ArgThat', 'Callable', 'Function', 'GeneratorFunction', 'InstanceOf', 'IsA', 'SubclassOf', 'Inherits', 'Type', 'Class', 'String', 'Unicode', 'Bytes', ] # TODO(xion): operator-based matchers (GreaterThan, ShorterThan, etc.) # TODO(xion): matchers for positional & keyword arguments
""" callee """ __version__ = "0.0.1" __description__ = "Argument matcher for unittest.mock" __author__ = "Karol Kuczmarski" __license__ = "Simplified BSD" from callee.base import And, Or, Not from callee.general import \ Any, ArgThat, IsA, Inherits, InstanceOf, Matching, SubclassOf from callee.strings import Bytes, String, Unicode __all__ = [ 'Not', 'And', 'Or', 'Any', 'Matching', 'ArgThat', 'InstanceOf', 'IsA', 'SubclassOf', 'Inherits', 'String', 'Unicode', 'Bytes', ] # TODO(xion): operator-based matchers (GreaterThan, ShorterThan, etc.) # TODO(xion): collection matchers (lists, sequences, dicts, ...) # TODO(xion): matchers for positional & keyword arguments
Use variables to initialize the maze
(function(document, MazeGenerator, MazePainter, MazeInteraction) { 'use strict'; // DOM Elements var canvas = document.getElementById('maze'); var bGenerate = document.getElementById('bGenerate'); var bSolve = document.getElementById('bSolve'); // Initialization variables var cellSize = 20; var cellColor = '#fff'; var frontierColor = '#f00'; var wallColor = '#000'; var entryColor = '#0f0'; var exitColor = '#0f0'; var solutionColor = '#0f0'; var userSolutionColor = '#00f'; // Start painting loop MazePainter.startPainting(); bGenerate.addEventListener('click', function() { // Initialize modules MazeGenerator.init(canvas.width, canvas.height, cellSize); MazePainter.init(canvas, cellSize, cellColor, frontierColor, wallColor, entryColor, exitColor, solutionColor, userSolutionColor); MazeGenerator.generate(); MazeGenerator.selectEntry(); MazeGenerator.selectExit(); MazeInteraction.init(canvas, cellSize, MazeGenerator.getMaze()); MazeInteraction.startListeningUserEvents(); }); bSolve.addEventListener('click', function() { if (MazePainter.isMazePainted()) { MazeGenerator.solve(); } }); }(document, MazeGenerator, MazePainter, MazeInteraction));
(function(document, MazeGenerator, MazePainter, MazeInteraction) { 'use strict'; // DOM Elements var canvas = document.getElementById('maze'); var bGenerate = document.getElementById('bGenerate'); var bSolve = document.getElementById('bSolve'); // Start painting loop MazePainter.startPainting(); bGenerate.addEventListener('click', function() { // Initialize modules MazeGenerator.init(canvas.width, canvas.height, 20); MazePainter.init(canvas, 20, '#fff', '#f00', '#000', '#0f0', '#0f0', '#0f0', '#00f'); MazeGenerator.generate(); MazeGenerator.selectEntry(); MazeGenerator.selectExit(); MazeInteraction.init(canvas, 20, MazeGenerator.getMaze()); MazeInteraction.startListeningUserEvents(); }); bSolve.addEventListener('click', function() { if (MazePainter.isMazePainted()) { MazeGenerator.solve(); } }); }(document, MazeGenerator, MazePainter, MazeInteraction));
Update grunt to watch for sass changes
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.initConfig({ watch: { sass: { files: ['xmd/style/**/*.scss', 'actions/**/css/*.scss', 'inc/widgets/**/css/*.scss', 'modules/**/css/*.scss', '!**/_*.scss'], tasks: ['sass:dev'], options: { spawn: false } } }, sass: { dist: { files: [{ expand: true, files: ['xmd/style/**/*.scss', 'actions/**/css/*.scss', 'inc/widgets/**/css/*.scss', 'modules/**/css/*.scss'], ext: '.css' }] }, dev: { files: {} } } }); grunt.registerTask('default', [ 'watch' ]); grunt.event.on('watch', function(action, filepath, target) { var filedest = filepath.slice(0, filepath.lastIndexOf(".")); filedest += '.css' var files = {}; files[filedest] = filepath; grunt.config.set('sass.dev.files', files); }); };
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.initConfig({ watch: { sass: { files: ['xmd/style/**/*.scss', 'actions/**/css/*.scss', 'inc/widgets/**/css/*.scss', 'modules/**/css/*.scss'], tasks: ['sass'] } }, sass: { dist: { files: [{ expand: true, src: ['xmd/style/**/*.scss', 'actions/**/css/*.scss', 'inc/widgets/**/css/*.scss', 'modules/**/css/*.scss'], ext: '.css' }] } } // autoprefixer: { // options: { // browsers: ['last 1 version'] // }, // dist: { // files: [{ // expand: true, // cwd: '.tmp/styles/', // src: '{,*/}*.css', // dest: '.tmp/styles/' // }] // } // } }); grunt.registerTask('default', [ // 'autoprefixer', 'watch' ]); };
Use DisplayIf in the licence.
import React from 'react'; import PropTypes from 'prop-types'; import { areWeFunYet, translate as $t } from '../../helpers'; import ExternalLink from './external-link.js'; import DisplayIf from './display-if'; let showLicense = areWeFunYet(); const LoadingMessage = props => { let message = props.message || $t('client.spinner.generic'); return ( <div className="loading-modal"> <h3>{$t('client.spinner.title')}</h3> <div> <div className="spinner" /> <div>{message}</div> <DisplayIf condition={showLicense}> <div> {$t('client.spinner.license')} <ExternalLink href="https://liberapay.com/Kresus">Kresus</ExternalLink> </div> </DisplayIf> </div> </div> ); }; LoadingMessage.propTypes = { // Message indicating why we're doing background loading (and the UI is // frozen). message: PropTypes.string }; export default LoadingMessage;
import React from 'react'; import PropTypes from 'prop-types'; import { areWeFunYet, translate as $t } from '../../helpers'; import ExternalLink from './external-link.js'; let showLicense = areWeFunYet(); const LoadingMessage = props => { let message = props.message || $t('client.spinner.generic'); let license = showLicense ? ( <div> {$t('client.spinner.license')} <ExternalLink href="https://liberapay.com/Kresus">Kresus</ExternalLink> </div> ) : null; return ( <div className="loading-modal"> <h3>{$t('client.spinner.title')}</h3> <div> <div className="spinner" /> <div>{message}</div> {license} </div> </div> ); }; LoadingMessage.propTypes = { // Message indicating why we're doing background loading (and the UI is // frozen). message: PropTypes.string }; export default LoadingMessage;
Clean up File edit view
from __future__ import unicode_literals from flask import url_for from flask_mongoengine.wtf import model_form from mongoengine import * from core.observables import Observable from core.database import StringListField class File(Observable): value = StringField(verbose_name="Value") mime_type = StringField(verbose_name="MIME type") hashes = DictField(verbose_name="Hashes") body = ReferenceField("AttachedFile") filenames = ListField(StringField(), verbose_name="Filenames") DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")] exclude_fields = Observable.exclude_fields + ['hashes', 'body'] @classmethod def get_form(klass): form = model_form(klass, exclude=klass.exclude_fields) form.filenames = StringListField("Filenames") return form @staticmethod def check_type(txt): return True def info(self): i = Observable.info(self) i['mime_type'] = self.mime_type i['hashes'] = self.hashes return i
from __future__ import unicode_literals from mongoengine import * from core.observables import Observable from core.observables import Hash class File(Observable): value = StringField(verbose_name="SHA256 hash") mime_type = StringField(verbose_name="MIME type") hashes = DictField(verbose_name="Hashes") body = ReferenceField("AttachedFile") filenames = ListField(StringField(), verbose_name="Filenames") DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")] @staticmethod def check_type(txt): return True def info(self): i = Observable.info(self) i['mime_type'] = self.mime_type i['hashes'] = self.hashes return i
Use the first workload owner id in e2e test
const expect = require('chai').expect const dataHelper = require('../helpers/data/aggregated-data-helper') var workloadOwnerId var workloadOwnerGrade describe('View overview', function () { before(function () { return dataHelper.selectIdsForWorkloadOwner() .then(function (results) { var workloadOwnerIds = results.filter((item) => item.table === 'workload_owner') workloadOwnerId = workloadOwnerIds[0].id return results }) .then(function (results) { dataHelper.selectGradeForWorkloadOwner(workloadOwnerId) .then(function (gradeResult) { workloadOwnerGrade = gradeResult }) }) }) it('should navigate to the overview page', function () { return browser.url('/offender-manager/' + workloadOwnerId + '/overview') .waitForExist('.breadcrumbs') .waitForExist('.sln-subnav') .waitForExist('.sln-grade') .getText('.sln-grade') .then(function (text) { expect(text).to.equal(workloadOwnerGrade) }) }) })
const expect = require('chai').expect const dataHelper = require('../helpers/data/aggregated-data-helper') var workloadOwnerId var workloadOwnerGrade describe('View overview', function () { before(function () { return dataHelper.selectIdsForWorkloadOwner() .then(function (results) { var workloadOwnerIds = results.filter((item) => item.table === 'workload_owner') workloadOwnerId = workloadOwnerIds[workloadOwnerIds.length - 1].id return results }) .then(function (results) { dataHelper.selectGradeForWorkloadOwner(workloadOwnerId) .then(function (gradeResult) { workloadOwnerGrade = gradeResult }) }) }) it('should navigate to the overview page', function () { return browser.url('/offender-manager/' + workloadOwnerId + '/overview') .waitForExist('.breadcrumbs') .waitForExist('.sln-subnav') .waitForExist('.sln-grade') .getText('.sln-grade') .then(function (text) { expect(text).to.equal(workloadOwnerGrade) }) }) })
Add more helpful output to the user
package cmd import ( "fmt" "log" "github.com/codegangsta/cli" "github.com/exercism/cli/api" "github.com/exercism/cli/config" "github.com/exercism/cli/user" ) // Tracks lists available tracks. func Tracks(ctx *cli.Context) { c, err := config.New(ctx.GlobalString("config")) if err != nil { log.Fatal(err) } client := api.NewClient(c) tracks, err := client.Tracks() if err != nil { log.Fatal(err) } curr := user.NewCurriculum(tracks) fmt.Println("\nActive language tracks:") curr.Report(user.TrackActive) fmt.Println("\nInactive language tracks:") curr.Report(user.TrackInactive) // TODO: implement `list` command to list problems in a track msg := ` Related commands: exercism fetch (see 'exercism help fetch') exercism lisp (see 'exercism help list') ` fmt.Println(msg) }
package cmd import ( "fmt" "log" "github.com/codegangsta/cli" "github.com/exercism/cli/api" "github.com/exercism/cli/config" "github.com/exercism/cli/user" ) // Tracks lists available tracks. func Tracks(ctx *cli.Context) { c, err := config.New(ctx.GlobalString("config")) if err != nil { log.Fatal(err) } client := api.NewClient(c) tracks, err := client.Tracks() if err != nil { log.Fatal(err) } curr := user.NewCurriculum(tracks) fmt.Println("\nActive language tracks:") curr.Report(user.TrackActive) fmt.Println("\nInactive language tracks:") curr.Report(user.TrackInactive) // TODO: implement `list` command to list problems in a track msg := ` Related commands: exercism fetch (see 'exercism help fetch') ` fmt.Println(msg) }
Add resource name to FlightStatus
from ..base import Resource from .flight_segment import FlightSegment class FlightStatus(Resource): _resource_name = 'flight_statuses' _as_is_fields = [ 'current_segment', 'departure_service_action', 'flags', 'href', 'id', 'internal', 'segments_order', 'state', ] @property def _resource_fields(self): # Prevent Import Loop from ..booking import ( DepartureService, FlightService, ) return [ ('departure_service', DepartureService), ('flight_service', FlightService), ('next_status', 'FlightStatus'), ('previous_status', 'FlightStatus'), ] @property def _model_collection_fields(self): from ..booking import Customer return [ ('customers', Customer), ('segments', FlightSegment), ]
from ..base import Resource from .flight_segment import FlightSegment class FlightStatus(Resource): _as_is_fields = [ 'current_segment', 'departure_service_action', 'flags', 'href', 'id', 'internal', 'segments_order', 'state', ] @property def _resource_fields(self): # Prevent Import Loop from ..booking import ( DepartureService, FlightService, ) return [ ('departure_service', DepartureService), ('flight_service', FlightService), ('next_status', 'FlightStatus'), ('previous_status', 'FlightStatus'), ] @property def _model_collection_fields(self): from ..booking import Customer return [ ('customers', Customer), ('segments', FlightSegment), ]
Simplify the way modes are loaded into a lattice
import os import csv from pml import lattice, element, device def load(directory, mode, control_system): lat = lattice.Lattice(mode, control_system) with open(os.path.join(directory, mode, 'elements.csv')) as elements: csv_reader = csv.DictReader(elements) for item in csv_reader: e = element.Element(item['name'], float(item['length']), item['type'], None) e.add_to_family(item['type']) lat.add_element(e) with open(os.path.join(directory, mode, 'devices.csv')) as devices: csv_reader = csv.DictReader(devices) for item in csv_reader: d = device.Device(None, item['get_pv'], item['set_pv']) lat[int(item['id']) - 1].add_device(item['field'], d, None) with open(os.path.join(directory, mode, 'families.csv')) as families: csv_reader = csv.DictReader(families) for item in csv_reader: lat[int(item['id']) - 1].add_to_family(item['family']) return lat
import os import csv from pml import lattice, element, device def load(directory, name, control_system): lat = lattice.Lattice(name, control_system) with open(os.path.join(directory, 'elements.csv')) as elements: csv_reader = csv.DictReader(elements) for item in csv_reader: e = element.Element(item['name'], float(item['length']), item['type'], None) e.add_to_family(item['type']) lat.add_element(e) with open(os.path.join(directory, 'devices.csv')) as devices: csv_reader = csv.DictReader(devices) for item in csv_reader: d = device.Device(None, item['get_pv'], item['set_pv']) lat[int(item['id']) - 1].add_device(item['field'], d, None) with open(os.path.join(directory, 'families.csv')) as families: csv_reader = csv.DictReader(families) for item in csv_reader: lat[int(item['id']) - 1].add_to_family(item['family']) return lat
Use gwtSetup instead of constructor in gwt test
/* * Copyright 2013, The gwtquery team. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.query.client.ajax; import com.google.gwt.core.client.GWT; /** * Test for data binding and Ajax which is run in gwt */ public class AjaxTestGwt extends AjaxTests { @Override public String getModuleName() { return "com.google.gwt.query.QueryTest"; } protected void gwtSetUp() throws Exception { echoUrl = GWT.getHostPageBaseURL() + servletPath; echoUrlCORS = echoUrl.replaceFirst("http://[\\d\\.]+:", "http://localhost:") + "?cors=true"; } }
/* * Copyright 2013, The gwtquery team. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.query.client.ajax; import com.google.gwt.core.client.GWT; /** * Test for data binding and Ajax which is run in gwt */ public class AjaxTestGwt extends AjaxTests { @Override public String getModuleName() { return "com.google.gwt.query.QueryTest"; } public AjaxTestGwt() { echoUrl = (GWT.isClient() ? GWT.getHostPageBaseURL() : "http://localhost:3333/") + servletPath; echoUrlCORS = echoUrl.replaceFirst("http://[\\d\\.]+:", "http://localhost:") + "?cors=true"; } }
Set autocrlf=false in Git configurations in Eclipse. Testing...
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.WindowConstants; public class CardTrick extends JFrame { public static void main(String[] args) { new CardTrick(); } CardTrick() { setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setSize(Globals.FRAME_WI, Globals.FRAME_HI); add(new Board()); setVisible(true); } private void addButton(JButton button, int locX, int locY, int Wi, int Hi) { button.setBounds(locX, locY, Wi, Hi); // button.setBackground(Color.CYAN); // button.setForeground(Color.BLUE); button.setBorderPainted(true); //button.addActionListener(l); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buttonPressed(button, e); } }); add(button); } public void buttonPressed(JButton button, ActionEvent e) { } } //geese: testing a commit to git //geese: testing a commit to geese_branch //geese: testing Windows style line endings
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.WindowConstants; public class CardTrick extends JFrame { public static void main(String[] args) { new CardTrick(); } CardTrick() { setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setSize(Globals.FRAME_WI, Globals.FRAME_HI); add(new Board()); setVisible(true); } private void addButton(JButton button, int locX, int locY, int Wi, int Hi) { button.setBounds(locX, locY, Wi, Hi); // button.setBackground(Color.CYAN); // button.setForeground(Color.BLUE); button.setBorderPainted(true); //button.addActionListener(l); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buttonPressed(button, e); } }); add(button); } public void buttonPressed(JButton button, ActionEvent e) { } } //geese: testing a commit to git //geese: testing a commit to geese_branch
Make the addition of hosts sync It now adds a host and continues to the next. It's a shame we cant use promises, and do it all aync. Maybe the splice of the hosts array is a bit strange, and a index with counter on it would be better. Ref: #2
import hostile from 'hostile'; function addHosts(done) { // TODO: Get data from configuration manager var dummyDataHosts = [ { ip: '127.0.0.1', hostname: 'localhost.example.com' }, { ip: '127.0.0.1', hostname: 'localhost2.example.com' }, { ip: '127.0.0.1', hostname: 'localhost3.example.com' } ]; const hosts = dummyDataHosts.slice(0); // Clone the hosts array function insertCollection(callback) { 'use strict'; var hosts = dummyDataHosts.slice(0); // Clone the hosts array (function insertOne() { var host = hosts.splice(0, 1)[0]; // get the first record and reduce by one hostile.set(host.ip, host.hostname, function (err) { if (err) { console.error(err); } else { console.log('Successfully added:', host.ip, host.hostname); if (hosts.length === 0) { callback(); } else { insertOne(); } } }); })(); } insertCollection(function() { console.log('All hosts added.'); done(); }); } module.exports = addHosts;
import hostile from 'hostile'; function addHosts(done) { // TODO: Get data from configuration manager var dummyDataHosts = [ { ip: '127.0.0.1', hostname: 'localhost.example.com' }, { ip: '127.0.0.1', hostname: 'localhost2.example.com' }, { ip: '127.0.0.1', hostname: 'localhost3.example.com' } ]; const hosts = dummyDataHosts.slice(0); // Clone the hosts array let addHostPromises = hosts.map(host => { new Promise((resolve, reject) => { hostile.set(host.ip, host.hostname, function (err) { if (err) { reject(); console.error(err); } else { console.log('Successfully added:', host.ip, host.hostname); resolve(); } }); }); }); Promise.all(addHostPromises).then(values => { console.log('All hosts added.'); done() }); } module.exports = addHosts;
Disable rollbar for test env Fixes #12
/* jshint node: true */ 'use strict'; var fs = require('fs'); var path = require('path'); var merge = require('lodash-node/modern/object/merge'); var template = require('lodash-node/modern/string/template'); module.exports = { name: 'ember-cli-rollbar', contentFor: function(type, config) { var environment = this.app.env; config = config.rollbar || {}; var isProductionEnv = ['development', 'test'].indexOf(environment) === -1; var includeScript = isProductionEnv || config.enabled; if (type === 'head' && includeScript) { var rollbarConfig = merge({ enabled: isProductionEnv, captureUncaught: true, payload: { environment: environment } }, config); var snippetPath = path.join(__dirname, 'addon', 'rollbar-snippet.html'); var snippetContent = fs.readFileSync(snippetPath, 'utf-8'); return template(snippetContent)({ rollbarConfig: JSON.stringify(rollbarConfig) }); } } };
/* jshint node: true */ 'use strict'; var fs = require('fs'); var path = require('path'); var merge = require('lodash-node/modern/object/merge'); var template = require('lodash-node/modern/string/template'); module.exports = { name: 'ember-cli-rollbar', contentFor: function(type, config) { var environment = this.app.env; config = config.rollbar || {}; var includeScript = environment !== 'development' || config.enabled; if (type === 'head' && includeScript) { var rollbarConfig = merge({ enabled: environment !== 'development', captureUncaught: true, payload: { environment: environment } }, config); var snippetPath = path.join(__dirname, 'addon', 'rollbar-snippet.html'); var snippetContent = fs.readFileSync(snippetPath, 'utf-8'); return template(snippetContent)({ rollbarConfig: JSON.stringify(rollbarConfig) }); } } };
Set petitions page title to "Petitionen"
import React from 'react'; import Helmet from 'react-helmet'; import { connect } from 'react-redux'; import { fetchPetitions } from 'actions/PetitionActions'; import Petitions from 'components/Petitions'; const PetitionsContainer = React.createClass({ componentDidMount () { this.props.fetchPetitions(this.props); }, render () { return ( <div> <Helmet title='Petitionen' /> <Petitions {...this.props} /> </div> ); } }); PetitionsContainer.fetchData = ({ store, location, params, history }) => { return store.dispatch(fetchPetitions({ location, params, history })); }; PetitionsContainer.propTypes = { petitions: React.PropTypes.array, total: React.PropTypes.number, currentPage: React.PropTypes.number, perPage: React.PropTypes.number, fetchPetitions: React.PropTypes.func }; const mapStateToProps = ({ petitions }) => ({ petitions: petitions.data || [], total: petitions.total, currentPage: petitions.currentPage, perPage: petitions.perPage }); // Add dispatchers to the component props, // for fetching the data _client side_ const mapDispatchToProps = (dispatch) => { return { fetchPetitions: (options) => dispatch(fetchPetitions(options)) }; }; export default connect( mapStateToProps, mapDispatchToProps )(PetitionsContainer);
import React from 'react'; import Helmet from 'react-helmet'; import { connect } from 'react-redux'; import { fetchPetitions } from 'actions/PetitionActions'; import Petitions from 'components/Petitions'; const PetitionsContainer = React.createClass({ componentDidMount () { this.props.fetchPetitions(this.props); }, render () { return ( <div> <Helmet title='Petitions' /> <Petitions {...this.props} /> </div> ); } }); PetitionsContainer.fetchData = ({ store, location, params, history }) => { return store.dispatch(fetchPetitions({ location, params, history })); }; PetitionsContainer.propTypes = { petitions: React.PropTypes.array, total: React.PropTypes.number, currentPage: React.PropTypes.number, perPage: React.PropTypes.number, fetchPetitions: React.PropTypes.func }; const mapStateToProps = ({ petitions }) => ({ petitions: petitions.data || [], total: petitions.total, currentPage: petitions.currentPage, perPage: petitions.perPage }); // Add dispatchers to the component props, // for fetching the data _client side_ const mapDispatchToProps = (dispatch) => { return { fetchPetitions: (options) => dispatch(fetchPetitions(options)) }; }; export default connect( mapStateToProps, mapDispatchToProps )(PetitionsContainer);
Add type annotation to worker_shutdown_stop, which was called in a typed context
#!/usr/bin/env python """TaskProcess class to provide helper methods around worker task's process. Attributes: log (logging.Logger): the log object for this module """ import asyncio import logging import os import signal from asyncio.subprocess import Process log = logging.getLogger(__name__) class TaskProcess: """Wraps worker task's process.""" def __init__(self, process: Process): """Constructor. Args: process (Process): task process """ self.process = process self.stopped_due_to_worker_shutdown = False async def worker_shutdown_stop(self) -> None: """Invoke on worker shutdown to stop task process.""" self.stopped_due_to_worker_shutdown = True await self.stop() async def stop(self): """Stop the current task process. Starts with SIGTERM, gives the process 1 second to terminate, then kills it """ # negate pid so that signals apply to process group pgid = -self.process.pid try: os.kill(pgid, signal.SIGTERM) await asyncio.sleep(1) os.kill(pgid, signal.SIGKILL) except (OSError, ProcessLookupError): return
#!/usr/bin/env python """TaskProcess class to provide helper methods around worker task's process. Attributes: log (logging.Logger): the log object for this module """ import asyncio import logging import os import signal from asyncio.subprocess import Process log = logging.getLogger(__name__) class TaskProcess: """Wraps worker task's process.""" def __init__(self, process: Process): """Constructor. Args: process (Process): task process """ self.process = process self.stopped_due_to_worker_shutdown = False async def worker_shutdown_stop(self): """Invoke on worker shutdown to stop task process.""" self.stopped_due_to_worker_shutdown = True await self.stop() async def stop(self): """Stop the current task process. Starts with SIGTERM, gives the process 1 second to terminate, then kills it """ # negate pid so that signals apply to process group pgid = -self.process.pid try: os.kill(pgid, signal.SIGTERM) await asyncio.sleep(1) os.kill(pgid, signal.SIGKILL) except (OSError, ProcessLookupError): return
Remove trailing slashes from routes.
import StringIO import base64 import signal import flask from quiver.plotter import FieldPlotter app = flask.Flask(__name__) @app.route('/') def quiver(): '''Route for homepage''' return flask.render_template('quiver.html') @app.route('/plot', methods=['GET',]) def plot(): equation_string = flask.request.args.get('equation') diff_equation = FieldPlotter() diff_equation.set_equation_from_string(equation_string) diff_equation.make_plot() # If plotting was successful, write plot out if diff_equation.figure: # Write output to memory and add to response object output = StringIO.StringIO() response = flask.make_response(base64.b64encode(diff_equation.write_data(output))) response.mimetype = 'image/png' return response else: return flask.make_response('') @app.route('/data', methods=['GET',]) def data(): equation_string = flask.request.args.get('equation') plotter = FieldPlotter() plotter.set_equation_from_string(equation_string) plotter.make_data() if __name__ == '__main__': app.run(debug=True)
import StringIO import base64 import signal import flask from quiver.plotter import FieldPlotter app = flask.Flask(__name__) @app.route('/') def quiver(): '''Route for homepage''' return flask.render_template('quiver.html') @app.route('/plot/', methods=['GET',]) def plot(): equation_string = flask.request.args.get('equation') diff_equation = FieldPlotter() diff_equation.set_equation_from_string(equation_string) diff_equation.make_plot() # If plotting was successful, write plot out if diff_equation.figure: # Write output to memory and add to response object output = StringIO.StringIO() response = flask.make_response(base64.b64encode(diff_equation.write_data(output))) response.mimetype = 'image/png' return response else: return flask.make_response('') @app.route('/data/', methods=['GET',]) def data(): equation_string = flask.request.args.get('equation') plotter = FieldPlotter() plotter.set_equation_from_string(equation_string) plotter.make_data() if __name__ == '__main__': app.run(debug=True)
Update TwitterStatus test to remove mock of Twit module
jest.dontMock('../lib/twitter-status'); import TwitterStatus from '../lib/twitter-status'; var Twit = require('twit'); var client = new Twit({}); describe('TwitterStatus', function() { describe('#showStatusFor', function() { it('calls with correct params', function() { var twitterStatus = new TwitterStatus(client); twitterStatus.showStatusFor('videodrome_pod' ); expect(client.get.mock.calls.length).toEqual(1); expect(client.get.mock.calls[0][0]).toEqual('statuses/user_timeline') expect(client.get.mock.calls[0][1]).toEqual({screen_name: 'videodrome_pod'}) }); }); describe('#displayFollowers', function() { it('returns this', function() { var tweet = { text: 'Hello Twitter' } ; var tweets = [tweet]; var twitterStatus = new TwitterStatus(client); expect(twitterStatus.displayTweets(tweets)).toEqual(twitterStatus); }); }); });
jest.dontMock('../lib/twitter-status'); import TwitterStatus from '../lib/twitter-status'; jest.mock('Twit'); var ReadYaml = require('read-yaml'); var Twit = require('twit'); var config = ReadYaml.sync('twitter.yml'); var client = new Twit({}); describe('TwitterStatus', function() { describe('#showStatusFor', function() { it('calls with correct params', function() { var twitterStatus = new TwitterStatus(client); twitterStatus.showStatusFor('videodrom_pod' ); expect(client.get.mock.calls.length).toEqual(1); expect(client.get.mock.calls[0][0]).toEqual('statuses/user_timeline') expect(client.get.mock.calls[0][1]).toEqual({screen_name: 'videodrom_pod'}) }); }); describe('#displayFollowers', function() { it('returns this', function() { var tweet = { text: 'Hello Twitter' } ; var tweets = [tweet]; var twitterStatus = new TwitterStatus(client); expect(twitterStatus.displayTweets(tweets)).toEqual(twitterStatus); }); }); });
Allow reserving both tokens and percentage for same address
import { observable, action } from 'mobx'; class ReservedTokenStore { @observable tokens; constructor(tokens = []) { this.tokens = tokens; } @action addToken = (token) => { const currentToken = this.tokens.find(t => t.addr === token.addr && t.dim == token.dim) if (currentToken) { const index = this.tokens.indexOf(currentToken) this.tokens[index] = token } else { this.tokens.push(token); } } @action setTokenProperty = (index, property, value) => { let newToken = {...this.tokens[index]}; newToken[property] = value; this.tokens[index] = newToken; } @action removeToken = (index) => { this.tokens.splice(index,1); } findToken(inputToken) { return this.tokens.find((token) => { if (inputToken['dim'] === token['dim'] && inputToken['addr'] === token['addr'] && inputToken['val'] === token['val']) { return true; } return false; }); } } const reservedTokenStore = new ReservedTokenStore(); export default reservedTokenStore; export { ReservedTokenStore };
import { observable, action } from 'mobx'; class ReservedTokenStore { @observable tokens; constructor(tokens = []) { this.tokens = tokens; } @action addToken = (token) => { const currentToken = this.tokens.find(t => t.addr === token.addr) if (currentToken) { const index = this.tokens.indexOf(currentToken) this.tokens[index] = token } else { this.tokens.push(token); } } @action setTokenProperty = (index, property, value) => { let newToken = {...this.tokens[index]}; newToken[property] = value; this.tokens[index] = newToken; } @action removeToken = (index) => { this.tokens.splice(index,1); } findToken(inputToken) { return this.tokens.find((token) => { if (inputToken['dim'] === token['dim'] && inputToken['addr'] === token['addr'] && inputToken['val'] === token['val']) { return true; } return false; }); } } const reservedTokenStore = new ReservedTokenStore(); export default reservedTokenStore; export { ReservedTokenStore };
Check firm object exists to avoid error
<!--- <?php if (!empty(Yii::app()->session['user'])) { $user = Yii::app()->session['user']; } else { $user = User::model()->findByPk(Yii::app()->user->id); } $firm = Firm::model()->findByPk($this->selectedFirmId); if (file_exists("/etc/hostname")) { $hostname = trim(file_get_contents("/etc/hostname")); } else { $hostname = trim(`hostname`); } if (is_object($user)) { $username = "$user->username ($user->id)"; if($firm) { $firm = "$firm->name ($firm->id)"; } else { $firm = 'Not found'; // selectedFirmId seems to not be getting initialised sometimes } } else { $username = 'Not logged in'; $firm = 'Not logged in'; } $commit = preg_replace('/[\s\t].*$/s','',@file_get_contents(@$_SERVER['DOCUMENT_ROOT']."/.git/FETCH_HEAD")); ?> Server: <?php echo $hostname?> Date: <?php echo date('d.m.Y H:i:s')?> Commit: <?php echo $commit?> User agent: <?php echo @$_SERVER['HTTP_USER_AGENT']?> Client IP: <?php echo @$_SERVER['REMOTE_ADDR']?> Username: <?php echo $username?> Firm: <?php echo $firm?> -->
<!--- <?php if (!empty(Yii::app()->session['user'])) { $user = Yii::app()->session['user']; } else { $user = User::model()->findByPk(Yii::app()->user->id); } $firm = Firm::model()->findByPk($this->selectedFirmId); if (file_exists("/etc/hostname")) { $hostname = trim(file_get_contents("/etc/hostname")); } else { $hostname = trim(`hostname`); } if (is_object($user)) { $username = "$user->username ($user->id)"; $firm = "$firm->name ($firm->id)"; } else { $username = 'Not logged in'; $firm = 'Not logged in'; } $commit = preg_replace('/[\s\t].*$/s','',@file_get_contents(@$_SERVER['DOCUMENT_ROOT']."/.git/FETCH_HEAD")); ?> Server: <?php echo $hostname?> Date: <?php echo date('d.m.Y H:i:s')?> Commit: <?php echo $commit?> User agent: <?php echo @$_SERVER['HTTP_USER_AGENT']?> Client IP: <?php echo @$_SERVER['REMOTE_ADDR']?> Username: <?php echo $username?> Firm: <?php echo $firm?> -->
Fix click and dblclick toggling bug After triggering click event to keep the text unfolded, toggling it back with dblclick wouldn't work as CSS wouldn't fire.
const elements = document.querySelectorAll('bracket-less'); function expandBrackets() { this.innerHTML = this.dataset.bracketless; this.classList.toggle('bracket-less'); } function collapseBrackets() { this.innerHTML = '...'; this.classList.toggle('bracket-less'); } elements.forEach(el => el.addEventListener('click', expandBrackets.bind(el))); elements.forEach(el => el.addEventListener('dblclick', collapseBrackets.bind(el))); function toggleCollapse(state) { if (state.collapse) { // play -> text collapsed elements.forEach(el => el.classList.add('bracket-less')); } else { // pause -> text displayed elements.forEach(el => el.classList.remove('bracket-less')); } } chrome.runtime.onMessage.addListener((state, sender, sendResponse) => { sendResponse(toggleCollapse(state)); });
const elements = document.querySelectorAll('bracket-less'); function expandBrackets() { this.innerHTML = this.dataset.bracketless; this.classList.remove('bracket-less'); } function collapseBrackets() { this.innerHTML = '...'; this.classList.add('bracket-less'); } elements.forEach(el => el.addEventListener('click', expandBrackets.bind(el))); elements.forEach(el => el.addEventListener('dblclick', collapseBrackets.bind(el))); function toggleCollapse(state) { if (state.collapse) { // play -> text collapsed elements.forEach(el => el.classList.add('bracket-less')); } else { // pause -> text displayed elements.forEach(el => el.classList.remove('bracket-less')); } } chrome.runtime.onMessage.addListener((state, sender, sendResponse) => { sendResponse(toggleCollapse(state)); });
fix(uglify): Fix the order of uglify.
const browserify = require('browserify') const path = require('path') const uglifyify = require('uglifyify') const transform = require('./js-transform') module.exports = function ({ config, entry, env, minify }) { const pipeline = browserify(entry, { basedir: process.cwd(), cache: {}, debug: true, packageCache: {}, paths: [ path.join(__dirname, '/../node_modules'), path.join(process.cwd(), '/node_modules') ], transform: transform({ config, env }) }) .on('error', function (err) { console.error(err.message) console.error(err.stack) process.exit(0) }) .on('log', function (message) { console.log(message) }) if (minify) { pipeline.transform(uglifyify, {global: true}) } return pipeline }
const browserify = require('browserify') const path = require('path') const uglifyify = require('uglifyify') const transform = require('./js-transform') module.exports = function ({ config, entry, env, minify }) { const pipeline = browserify(entry, { basedir: process.cwd(), cache: {}, debug: true, packageCache: {}, paths: [ path.join(__dirname, '/../node_modules'), path.join(process.cwd(), '/node_modules') ], transform: transform({ config, env }) }) .on('error', function (err) { console.error(err.message) console.error(err.stack) process.exit(0) }) .on('log', function (message) { console.log(message) }) if (minify) { pipeline.transform({ global: true }, uglifyify) } return pipeline }
Exclude test project from package - round 2 Also change development status to Alpha
from setuptools import setup, find_packages import django_cassandra_engine as meta DESCRIPTION = 'Cassandra backend for Django-nonrel' LONG_DESCRIPTION = None try: LONG_DESCRIPTION = open('README.rst').read() except IOError: pass setup( name='django-cassandra-engine', version='.'.join(map(str, meta.__version__)), author=meta.__author__, author_email=meta.__contact__, url=meta.__homepage__, license='2-clause BSD', description=DESCRIPTION, long_description=LONG_DESCRIPTION, install_requires=['cassandra-driver', 'djangotoolbox>=1.6.0', 'cqlengine'], packages=find_packages( exclude=['tests', 'tests.*', 'testproject', 'testproject.*']), zip_safe=False, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: Database', 'Topic :: Internet', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
from setuptools import setup, find_packages import django_cassandra_engine as meta DESCRIPTION = 'Cassandra backend for Django-nonrel' LONG_DESCRIPTION = None try: LONG_DESCRIPTION = open('README.rst').read() except IOError: pass setup( name='django-cassandra-engine', version='.'.join(map(str, meta.__version__)), author=meta.__author__, author_email=meta.__contact__, url=meta.__homepage__, license='2-clause BSD', description=DESCRIPTION, long_description=LONG_DESCRIPTION, install_requires=['cassandra-driver', 'djangotoolbox>=1.6.0', 'cqlengine'], packages=find_packages(exclude=['tests', 'tests.*', 'testproject']), zip_safe=False, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: Database', 'Topic :: Internet', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Add Subject and Keyword fields to PDF metadata
<?php # THIS ONE DOES NOT HAVE AddPageByArray ANY MORE :-) include("../mpdf.php"); $html_data = file_get_contents("body.html"); $html = substr($html_data, 12, strlen($html_data)-27); $style_data = file_get_contents("style_current.css"); $frontmatter_data = file_get_contents("frontmatter_current.html"); // Create new PDF with font subsetting, 234mm wide, 297mm high $mpdf = new mPDF('s', array(234,297)); // Make it DOUBLE SIDED document with 4mm bleed $mpdf->mirrorMargins = 1; $mpdf->bleedMargin = 4; $mpdf->h2toc = array(); $mpdf->WriteHTML($style_data, 1); $mpdf->WriteHTML($frontmatter_data, 2); $mpdf->WriteHTML($html, 2); $mpdf->SetTitle("An Example Title"); $mpdf->SetAuthor("Aco"); $mpdf->SetCreator("Booktype 2.0 and mPDF 6.0"); $mpdf->SetSubject("History"); $mpdf->SetKeywords("Middle Ages, Jet Travel"); $mpdf->Output(); ?>
<?php # THIS ONE DOES NOT HAVE AddPageByArray ANY MORE :-) include("../mpdf.php"); $html_data = file_get_contents("body.html"); $html = substr($html_data, 12, strlen($html_data)-27); $style_data = file_get_contents("style_current.css"); $frontmatter_data = file_get_contents("frontmatter_current.html"); // Create new PDF with font subsetting, 234mm wide, 297mm high $mpdf = new mPDF('s', array(234,297)); // Make it DOUBLE SIDED document with 4mm bleed $mpdf->mirrorMargins = 1; $mpdf->bleedMargin = 4; $mpdf->h2toc = array(); $mpdf->WriteHTML($style_data, 1); $mpdf->WriteHTML($frontmatter_data, 2); $mpdf->WriteHTML($html, 2); $mpdf->SetTitle("An Example Title"); $mpdf->SetAuthor("Aco"); $mpdf->SetCreator("Booktype 2.0 and mPDF 6.0"); $mpdf->Output(); ?>
Fix the way the combineReducer handles paths.
import get from 'lodash.get'; import isFunction from 'lodash.isfunction'; export function combineReducers(stateReducerMap, rootPath) { return function(state, action) { let changed = false; const nextState = {}; Object.entries(stateReducerMap).forEach(([path, module]) => { const fullPath = rootPath ? [rootPath, path] : path; const ownState = get(state, path); if (isFunction(module.integrator)) { nextState[path] = module.integrator(fullPath)(ownState, action, fullPath); } else { nextState[path] = module(ownState, action, fullPath); } if (nextState[path] !== get(state, path)) { changed = true; } }); return changed ? nextState : state; }; } export function isString(str) { return typeof str === 'string'; }
import get from 'lodash.get'; import isFunction from 'lodash.isfunction'; export function combineReducers(stateReducerMap, rootPath) { return function(state, action) { let changed = false; const nextState = {}; Object.entries(stateReducerMap).forEach(([path, module]) => { const fullPath = rootPath ? `${rootPath}.${path}` : path; const ownState = get(state, path); if (isFunction(module.integrator)) { nextState[path] = module.integrator(fullPath)(ownState, action, fullPath); } else { nextState[path] = module(ownState, action, fullPath); } if (nextState[path] !== get(state, path)) { changed = true; } }); return changed ? nextState : state; }; } export function isString(str) { return typeof str === 'string'; }
Make lifecycle component a React class component since it requires React-Lifecycle states
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, {Component} from 'react' import Api from '../../../../data/SingleClient' class LifeCycle extends Component { constructor(props) { super(props); this.api = new Api(); } render() { return ( <h1> Life cycle Page </h1> ); } } export default LifeCycle
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react' const LifeCycle = (props) => { return ( <h1> Life cycle Page </h1> ); }; export default LifeCycle
Include req.baseUrl is asset path If app is namespaced under another route then this needs to be taken into account when importing assets
var path = require('path'), servestatic = require('serve-static'); var basedir = path.dirname(require.resolve('govuk_template_mustache/package.json')); module.exports = { setup: function (app, options) { options = options || {}; options.path = options.path || '/govuk-assets'; app.use(options.path, servestatic(path.join(basedir, './assets'), options)); app.use(function (req, res, next) { res.locals.govukAssetPath = req.baseUrl + options.path + '/'; res.locals.partials = res.locals.partials || {}; res.locals.partials['govuk-template'] = path.resolve(__dirname, './govuk_template'); next(); }); } };
var path = require('path'), servestatic = require('serve-static'); var basedir = path.dirname(require.resolve('govuk_template_mustache/package.json')); module.exports = { setup: function (app, options) { options = options || {}; options.path = options.path || '/govuk-assets'; app.use(options.path, servestatic(path.join(basedir, './assets'), options)); app.use(function (req, res, next) { res.locals.govukAssetPath = options.path + '/'; res.locals.partials = res.locals.partials || {}; res.locals.partials['govuk-template'] = path.resolve(__dirname, './govuk_template'); next(); }); } };
Replace URLSearchParams with Edge/IE-compatible regex Fix #589
/** * User login. * * 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/. */ 'use strict'; (function() { var form = document.getElementById('login-form'); var email = document.getElementById('email'); var password = document.getElementById('password'); var errorSubmission = document.getElementById('error-submission'); form.addEventListener('submit', (e) => { e.preventDefault(); errorSubmission.classList.add('hidden'); const emailValue = email.value; const passwordValue = password.value; window.API.login(emailValue, passwordValue). then(() => { console.log('~~~ log in success ~~~'); const search = window.location.search; const match = search.match(/url=([^=&]+)/); let url = '/'; if (match) { url = decodeURIComponent(match[1]); } window.location.href = url; }). catch((err) => { errorSubmission.classList.remove('hidden'); errorSubmission.textContent = err.message; console.error(err); }); }) })();
/** * User login. * * 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/. */ 'use strict'; (function() { var form = document.getElementById('login-form'); var email = document.getElementById('email'); var password = document.getElementById('password'); var errorSubmission = document.getElementById('error-submission'); form.addEventListener('submit', (e) => { e.preventDefault(); errorSubmission.classList.add('hidden'); const emailValue = email.value; const passwordValue = password.value; window.API.login(emailValue, passwordValue). then(() => { console.log('~~~ log in success ~~~'); const urlParams = new URLSearchParams(window.location.search); let url = '/'; if (urlParams.has('url')) { url = decodeURIComponent(urlParams.get('url')); } window.location.href = url; }). catch((err) => { errorSubmission.classList.remove('hidden'); errorSubmission.textContent = err.message; console.error(err); }); }) })();
Clean up memory on tab close
// Storage var tabs = {} // Incoming request chrome.extension.onRequest.addListener( function( request, sender, response ) { switch( request.action ) { // Bird spotted case 'twitterUser': // new tab, or tab changed URL if( tabs[ 't'+ sender.tab.id ] === undefined || tabs[ 't'+ sender.tab.id ].href != request.href ) { tabs[ 't'+ sender.tab.id ] = { users: {}, amount: 0 } } tabs[ 't'+ sender.tab.id ].users[ request.user.username.toLowerCase() ] = request.user tabs[ 't'+ sender.tab.id ].amount++ tabs[ 't'+ sender.tab.id ].href = request.href // display icon chrome.pageAction.show( sender.tab.id ) // all good response({ status: 'ok' }) break; // Popup wants something case 'getUsers': response( tabs[ 't'+ request.tabId ] ) break; } }) // !Tab closed chrome.tabs.onRemoved.addListener( function( tabId, removeInfo ) { if( tabs[ 't'+ tabId ] !== undefined ) { delete tabs[ 't'+ tabId ] } })
// Storage var tabs = {} // Incoming request chrome.extension.onRequest.addListener( function( request, sender, response ) { switch( request.action ) { // Bird spotted case 'twitterUser': // new tab, or tab changed URL if( tabs[ 't'+ sender.tab.id ] === undefined || tabs[ 't'+ sender.tab.id ].href != request.href ) { tabs[ 't'+ sender.tab.id ] = { users: {}, amount: 0 } } tabs[ 't'+ sender.tab.id ].users[ request.user.username.toLowerCase() ] = request.user tabs[ 't'+ sender.tab.id ].amount++ tabs[ 't'+ sender.tab.id ].href = request.href // display icon chrome.pageAction.show( sender.tab.id ) // all good response({ status: 'ok' }) break; // Popup wants something case 'getUsers': response( tabs[ 't'+ request.tabId ] ) break; } })
Fix a problem with the celery cli commoand Allows runserver to be used separately from celery.
# manage.py import os import subprocess from flask_migrate import Migrate, MigrateCommand from flask_script import Manager, Shell, Command from app import create_app, db from app.models import Users, Agencies, Requests, Responses, Events, Reasons, Permissions, Roles app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) class Celery(Command): """ Runs Celery """ def run(self): subprocess.call(['celery', 'worker', '-A', 'celery_worker.celery', '--loglevel=info']) def make_shell_context(): return dict( app=app, db=db, Users=Users, Agencies=Agencies, Requests=Requests, Responses=Responses, Events=Events, Reasons=Reasons, Permissions=Permissions, Roles=Roles ) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command("db", MigrateCommand) manager.add_command("celery", Celery()) if __name__ == "__main__": manager.run()
# manage.py import os import subprocess from flask_migrate import Migrate, MigrateCommand from flask_script import Manager, Shell from app import create_app, db from app.models import Users, Agencies, Requests, Responses, Events, Reasons, Permissions, Roles app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) def make_shell_context(): return dict( app=app, db=db, Users=Users, Agencies=Agencies, Requests=Requests, Responses=Responses, Events=Events, Reasons=Reasons, Permissions=Permissions, Roles=Roles ) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) @manager def celery(): subprocess.call(['celery', 'worker', '-A', 'celery_worker.celery', '--loglevel=info']) if __name__ == "__main__": manager.run()
Use !empty instead of isset to prevent accidental deletion of the last used repository URL when firmware update gitsync settings have been saved without a repository URL.
#!/usr/local/bin/php -f <?php /* upgrade embedded users serial console */ require_once("globals.inc"); require_once("config.inc"); require_once("functions.inc"); if(file_exists("/usr/local/bin/git") && isset($config['system']['gitsync']['synconupgrade'])) { if(!empty($config['system']['gitsync']['repositoryurl'])) exec("cd /root/pfsense/pfSenseGITREPO/pfSenseGITREPO && git config remote.origin.url " . escapeshellarg($config['system']['gitsync']['repositoryurl'])); if(!empty($config['system']['gitsync']['branch'])) system("pfSsh.php playback gitsync " . escapeshellarg($config['system']['gitsync']['branch']) . " --upgrading"); } if($g['platform'] == "embedded") { $config['system']['enableserial'] = true; write_config(); } $newslicedir = ""; if ($ARGV[1] != "") $newslicedir = '/tmp' . $ARGV[1]; setup_serial_port("upgrade", $newslicedir); $files_to_process = file("/etc/pfSense.obsoletedfiles"); foreach($files_to_process as $filename) if(file_exists($filename)) exec("/bin/rm -f $filename"); ?>
#!/usr/local/bin/php -f <?php /* upgrade embedded users serial console */ require_once("globals.inc"); require_once("config.inc"); require_once("functions.inc"); if(file_exists("/usr/local/bin/git") && isset($config['system']['gitsync']['synconupgrade'])) { if(isset($config['system']['gitsync']['repositoryurl'])) exec("cd /root/pfsense/pfSenseGITREPO/pfSenseGITREPO && git config remote.origin.url " . escapeshellarg($config['system']['gitsync']['repositoryurl'])); if(isset($config['system']['gitsync']['branch'])) system("pfSsh.php playback gitsync " . escapeshellarg($config['system']['gitsync']['branch']) . " --upgrading"); } if($g['platform'] == "embedded") { $config['system']['enableserial'] = true; write_config(); } $newslicedir = ""; if ($ARGV[1] != "") $newslicedir = '/tmp' . $ARGV[1]; setup_serial_port("upgrade", $newslicedir); $files_to_process = file("/etc/pfSense.obsoletedfiles"); foreach($files_to_process as $filename) if(file_exists($filename)) exec("/bin/rm -f $filename"); ?>
Change .env to settings.ini file
from decouple import AutoConfig from ereuse_workbench.test import TestDataStorageLength class WorkbenchConfig: # Path where find settings.ini file config = AutoConfig(search_path='/home/user/') # Env variables for DH parameters DH_TOKEN = config('DH_TOKEN') DH_HOST = config('DH_HOST') DH_DATABASE = config('DH_DATABASE') DEVICEHUB_URL = 'https://{host}/{db}/'.format( host=DH_HOST, db=DH_DATABASE ) # type: str ## Env variables for WB parameters WB_BENCHMARK = config('WB_BENCHMARK', default=False, cast=bool) WB_STRESS_TEST = config('WB_STRESS_TEST', default=0, cast=int) WB_SMART_TEST = config('WB_SMART_TEST', default='') ## Erase parameters WB_ERASE = config('WB_ERASE') WB_ERASE_STEPS = config('WB_ERASE_STEPS', default=1, cast=int) WB_ERASE_LEADING_ZEROS = config('WB_ERASE_LEADING_ZERO', default=False, cast=bool) WB_DEBUG = config('WB_DEBUG', default=True, cast=bool)
from decouple import AutoConfig from ereuse_workbench.test import TestDataStorageLength class WorkbenchConfig: # Path where find .env file config = AutoConfig(search_path='/home/user/') # Env variables for DH parameters DH_TOKEN = config('DH_TOKEN') DH_HOST = config('DH_HOST') DH_DATABASE = config('DH_DATABASE') DEVICEHUB_URL = 'https://{host}/{db}/'.format( host=DH_HOST, db=DH_DATABASE ) # type: str ## Env variables for WB parameters WB_BENCHMARK = config('WB_BENCHMARK', default=True, cast=bool) WB_STRESS_TEST = config('WB_STRESS_TEST', default=0, cast=int) WB_SMART_TEST = config('WB_SMART_TEST', default='') ## Erase parameters WB_ERASE = config('WB_ERASE') WB_ERASE_STEPS = config('WB_ERASE_STEPS', default=1, cast=int) WB_ERASE_LEADING_ZEROS = config('WB_ERASE_LEADING_ZERO', default=False, cast=bool) WB_DEBUG = config('WB_DEBUG', default=True, cast=bool)
Fix up put webpack build
const nodeExternals = require('webpack-node-externals'); const path = require('path'); module.exports = { target: 'node', externals: [nodeExternals()], entry: { authorizerGithub: ['./bootstrap', './src/authorizers/github.js'], put: ['./bootstrap', './src/put/index.js'], get: ['./bootstrap', './src/get/index.js'], distTagsGet: ['./bootstrap', './src/dist-tags/get.js'], distTagsPut: ['./bootstrap', './src/dist-tags/put.js'], distTagsDelete: ['./bootstrap', './src/dist-tags/delete.js'], userPut: ['./bootstrap', './src/user/put.js'], tarGet: ['./bootstrap', './src/tar/get.js'], }, output: { libraryTarget: 'commonjs', path: path.join(__dirname, '.webpack'), filename: '[name].js', }, module: { loaders: [{ test: /\.js$/, loader: 'babel', include: /src/, exclude: /node_modules/, }, { test: /\.json$/, loader: 'json-loader', }], }, };
const nodeExternals = require('webpack-node-externals'); const path = require('path'); module.exports = { target: 'node', externals: [nodeExternals()], entry: { authorizerGithub: ['./bootstrap', './src/authorizers/github.js'], put: ['./bootstrap', './src/put.js'], get: ['./bootstrap', './src/get/index.js'], distTagsGet: ['./bootstrap', './src/dist-tags/get.js'], distTagsPut: ['./bootstrap', './src/dist-tags/put.js'], distTagsDelete: ['./bootstrap', './src/dist-tags/delete.js'], userPut: ['./bootstrap', './src/user/put.js'], tarGet: ['./bootstrap', './src/tar/get.js'], }, output: { libraryTarget: 'commonjs', path: path.join(__dirname, '.webpack'), filename: '[name].js', }, module: { loaders: [{ test: /\.js$/, loader: 'babel', include: /src/, exclude: /node_modules/, }, { test: /\.json$/, loader: 'json-loader', }], }, };
Fix : add default value for homepage portal
package fr.treeptik.cloudunit.controller; import fr.treeptik.cloudunit.dto.AboutResource; import fr.treeptik.cloudunit.dto.HomepageResource; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Created by nicolas on 12/12/2016. */ @Controller @RequestMapping("/homepage") public class HomepageController { @Value("#{environment.CU_JENKINS_DOMAIN ?: 'jenkins.cloudunit.dev'}") private String jenkins; @Value("#{environment.CU_GITLAB_DOMAIN} ?: 'gitlab.cloudunit.dev'") private String gitlab; @Value("#{environment.CU_NEXUS_DOMAIN} ?: 'nexus.cloudunit.dev'") private String nexus; @Value("#{environment.CU_KIBANA_DOMAIN ?: 'kibana.cloudunit.dev'}") private String kibana; @Value("#{environment.CU_SONAR_DOMAIN} ?: 'sonar.cloudunit.dev'") private String sonar; @Value("#{environment.CU_LETSCHAT_DOMAIN} ?: 'letschat.cloudunit.dev'") private String letschat; @RequestMapping(value = "/friends", method = RequestMethod.GET) public ResponseEntity<?> listFriends() { HomepageResource resource = new HomepageResource(jenkins, gitlab, kibana, nexus, sonar, letschat); return ResponseEntity.ok(resource); } }
package fr.treeptik.cloudunit.controller; import fr.treeptik.cloudunit.dto.AboutResource; import fr.treeptik.cloudunit.dto.HomepageResource; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Created by nicolas on 12/12/2016. */ @Controller @RequestMapping("/homepage") public class HomepageController { @Value("#{environment.CU_JENKINS_DOMAIN}") private String jenkins; @Value("#{environment.CU_GITLAB_DOMAIN}") private String gitlab; @Value("#{environment.CU_NEXUS_DOMAIN}") private String nexus; @Value("#{environment.CU_KIBANA_DOMAIN}") private String kibana; @Value("#{environment.CU_SONAR_DOMAIN}") private String sonar; @Value("#{environment.CU_LETSCHAT_DOMAIN}") private String letschat; @RequestMapping(value = "/friends", method = RequestMethod.GET) public ResponseEntity<?> listFriends() { HomepageResource resource = new HomepageResource(jenkins, gitlab, kibana, nexus, sonar, letschat); return ResponseEntity.ok(resource); } }
Disable unit test console logging
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html const path = require('path'); process.env.CHROME_BIN = require('puppeteer').executablePath(); module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client:{ captureConsole: false, clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: path.join(__dirname, 'coverage/app'), reports: ['html'], fixWebpackSourcePaths: true }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['ChromeHeadless'], singleRun: false, restartOnFileChange: true }); };
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html const path = require('path'); process.env.CHROME_BIN = require('puppeteer').executablePath(); module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: path.join(__dirname, 'coverage/app'), reports: ['html'], fixWebpackSourcePaths: true }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['ChromeHeadless'], singleRun: false, restartOnFileChange: true }); };
Update view to include count of complete files awaiting review.
function viewCollectionDetails(collectionName) { $.ajax({ url: "/zebedee/collection/" + collectionName, type: "get", headers:{ "X-Florence-Token":accessToken() }, crossDomain: true }).done(function (data) { var collection_summary = '<h1>' + data.name + '</h1>' + '<p>' + data.inProgressUris.length + ' Pages in progress</p>' + '<p>' + data.completeUris.length + ' Pages awaiting review</p>' + '<p>' + data.reviewedUris.length + ' Pages awaiting approval</p>'; $('.fl-panel--collection-details-container').html(collection_summary); }); $('.fl-work-on-collection-button').click(function () { document.cookie = "collection=" + collectionName + ";path=/"; localStorage.setItem("collection", collectionName); viewController('workspace'); }); $('.fl-button--cancel').click(function () { //perhaps need to rethink this if we do decide to animate panel transitions within this view viewController('collections'); }); }
function viewCollectionDetails(collectionName) { $.ajax({ url: "/zebedee/collection/" + collectionName, type: "get", headers:{ "X-Florence-Token":accessToken() }, crossDomain: true }).done(function (data) { var collection_summary = '<h1>' + data.name + '</h1>' + '<p>0 New pages (todo)</p>' + '<p>0 Edited pages (todo)</p>' + '<p>0 Deleted pages (todo)</p>' + '<p>' + data.inProgressUris.length + ' Pages awaiting review</p>' + '<p>' + data.approvedUris.length + ' Pages approved</p>'; $('.fl-panel--collection-details-container').html(collection_summary); }); $('.fl-work-on-collection-button').click(function () { document.cookie = "collection=" + collectionName + ";path=/"; localStorage.setItem("collection", collectionName); viewController('workspace'); }); $('.fl-button--cancel').click(function () { //perhaps need to rethink this if we do decide to animate panel transitions within this view viewController('collections'); }); }
Fix resolution of revision steps
// BusinessProcess processing steps resolution 'use strict'; var memoize = require('memoizee/plain') , defineMultipleProcess = require('../lib/multiple-process') , defineProcessingStepBase = require('../processing-step-base') , defineBusinessProcess = require('./base'); module.exports = memoize(function (db/* options */) { var BusinessProcess = defineBusinessProcess(db, arguments[1]) , MultipleProcess = defineMultipleProcess(db) , ProcessingStepBase = defineProcessingStepBase(db); BusinessProcess.prototype.defineProperties({ processingSteps: { type: MultipleProcess, nested: true } }); BusinessProcess.prototype.processingSteps.map._descriptorPrototype_.type = ProcessingStepBase; BusinessProcess.prototype.processingSteps.defineProperties({ // Applicable procesing steps applicable: { type: ProcessingStepBase }, // Revision processing steps revisions: { type: ProcessingStepBase, multiple: true, value: function (_observe) { var result = [], type = this.database.RevisionProcessingStep; if (!type) return; this.applicable.forEach(function (step) { if (step instanceof type) result.push(step); }); return result; } } }); return BusinessProcess; }, { normalizer: require('memoizee/normalizers/get-1')() });
// BusinessProcess processing steps resolution 'use strict'; var memoize = require('memoizee/plain') , defineMultipleProcess = require('../lib/multiple-process') , defineProcessingStepBase = require('../processing-step-base') , defineBusinessProcess = require('./base'); module.exports = memoize(function (db/* options */) { var BusinessProcess = defineBusinessProcess(db, arguments[1]) , MultipleProcess = defineMultipleProcess(db) , ProcessingStepBase = defineProcessingStepBase(db); BusinessProcess.prototype.defineProperties({ processingSteps: { type: MultipleProcess, nested: true } }); BusinessProcess.prototype.processingSteps.map._descriptorPrototype_.type = ProcessingStepBase; BusinessProcess.prototype.processingSteps.defineProperties({ // Applicable procesing steps applicable: { type: ProcessingStepBase }, // Revision processing steps revisions: { type: ProcessingStepBase, multiple: true, value: function (_observe) { var result = [] , revision = this.map.revision; if (revision) { var isApplicable = revision._get ? _observe(revision._isApplicable) : revision.isApplicable; if (isApplicable) result.push(revision); } return result; } } }); return BusinessProcess; }, { normalizer: require('memoizee/normalizers/get-1')() });
Use get_include instead of get_numpy_include.
#!/usr/bin/env python """Install file for example on how to use Pyrex with Numpy. For more details, see: http://www.scipy.org/Cookbook/Pyrex_and_NumPy http://www.scipy.org/Cookbook/ArrayStruct_and_Pyrex """ from distutils.core import setup from distutils.extension import Extension # Make this usable by people who don't have pyrex installed (I've committed # the generated C sources to SVN). try: from Pyrex.Distutils import build_ext has_pyrex = True except ImportError: has_pyrex = False import numpy # Define a pyrex-based extension module, using the generated sources if pyrex # is not available. if has_pyrex: pyx_sources = ['numpyx.pyx'] cmdclass = {'build_ext': build_ext} else: pyx_sources = ['numpyx.c'] cmdclass = {} pyx_ext = Extension('numpyx', pyx_sources, include_dirs = [numpy.get_include()]) # Call the routine which does the real work setup(name = 'numpyx', description = 'Small example on using Pyrex to write a Numpy extension', url = 'http://www.scipy.org/Cookbook/Pyrex_and_NumPy', ext_modules = [pyx_ext], cmdclass = cmdclass, )
#!/usr/bin/env python """Install file for example on how to use Pyrex with Numpy. For more details, see: http://www.scipy.org/Cookbook/Pyrex_and_NumPy http://www.scipy.org/Cookbook/ArrayStruct_and_Pyrex """ from distutils.core import setup from distutils.extension import Extension # Make this usable by people who don't have pyrex installed (I've committed # the generated C sources to SVN). try: from Pyrex.Distutils import build_ext has_pyrex = True except ImportError: has_pyrex = False import numpy # Define a pyrex-based extension module, using the generated sources if pyrex # is not available. if has_pyrex: pyx_sources = ['numpyx.pyx'] cmdclass = {'build_ext': build_ext} else: pyx_sources = ['numpyx.c'] cmdclass = {} pyx_ext = Extension('numpyx', pyx_sources, include_dirs = [numpy.get_numpy_include()]) # Call the routine which does the real work setup(name = 'numpyx', description = 'Small example on using Pyrex to write a Numpy extension', url = 'http://www.scipy.org/Cookbook/Pyrex_and_NumPy', ext_modules = [pyx_ext], cmdclass = cmdclass, )
Add the appropriate file header.
/** * SurveyViewTrigger component. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import { useMount } from 'react-use'; import PropTypes from 'prop-types'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { CORE_SITE } from '../../googlesitekit/datastore/site/constants'; import { CORE_USER } from '../../googlesitekit/datastore/user/constants'; const { useSelect, useDispatch } = Data; const SurveyViewTrigger = ( { triggerID, ttl } ) => { const usingProxy = useSelect( ( select ) => select( CORE_SITE ).isUsingProxy() ); const { triggerSurvey } = useDispatch( CORE_USER ); useMount( () => { if ( usingProxy ) { triggerSurvey( { triggerID, ttl } ); } } ); return null; }; SurveyViewTrigger.propTypes = { triggerID: PropTypes.string.isRequired, ttl: PropTypes.number, }; SurveyViewTrigger.defaultProps = { ttl: null, }; export default SurveyViewTrigger;
/** * External dependencies */ import { useMount } from 'react-use'; import PropTypes from 'prop-types'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { CORE_SITE } from '../../googlesitekit/datastore/site/constants'; import { CORE_USER } from '../../googlesitekit/datastore/user/constants'; const { useSelect, useDispatch } = Data; const SurveyViewTrigger = ( { triggerID, ttl } ) => { const usingProxy = useSelect( ( select ) => select( CORE_SITE ).isUsingProxy() ); const { triggerSurvey } = useDispatch( CORE_USER ); useMount( () => { if ( usingProxy ) { triggerSurvey( { triggerID, ttl } ); } } ); return null; }; SurveyViewTrigger.propTypes = { triggerID: PropTypes.string.isRequired, ttl: PropTypes.number, }; SurveyViewTrigger.defaultProps = { ttl: null, }; export default SurveyViewTrigger;
Allow functions in global exposure bodies
import createGraph from '../query/lib/createGraph.js'; import {Match} from 'meteor/check'; export const ExposureDefaults = { blocking: false, method: true, publication: true, }; export const ExposureSchema = { firewall: Match.Maybe( Match.OneOf(Function, [Function]) ), maxLimit: Match.Maybe(Match.Integer), maxDepth: Match.Maybe(Match.Integer), publication: Match.Maybe(Boolean), method: Match.Maybe(Boolean), blocking: Match.Maybe(Boolean), body: Match.Maybe(Match.OneOf(Object, Function)), restrictedFields: Match.Maybe([String]), restrictLinks: Match.Maybe( Match.OneOf(Function, [String]) ), }; export function validateBody(collection, body) { try { createGraph(collection, body); } catch (e) { throw new Meteor.Error('invalid-body', 'We could not build a valid graph when trying to create your exposure: ' + e.toString()) } }
import createGraph from '../query/lib/createGraph.js'; import {Match} from 'meteor/check'; export const ExposureDefaults = { blocking: false, method: true, publication: true, }; export const ExposureSchema = { firewall: Match.Maybe( Match.OneOf(Function, [Function]) ), maxLimit: Match.Maybe(Match.Integer), maxDepth: Match.Maybe(Match.Integer), publication: Match.Maybe(Boolean), method: Match.Maybe(Boolean), blocking: Match.Maybe(Boolean), body: Match.Maybe(Object), restrictedFields: Match.Maybe([String]), restrictLinks: Match.Maybe( Match.OneOf(Function, [String]) ), }; export function validateBody(collection, body) { try { createGraph(collection, body); } catch (e) { throw new Meteor.Error('invalid-body', 'We could not build a valid graph when trying to create your exposure: ' + e.toString()) } }
Add verbose name to Conf model.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.db import models from django.db.models.signals import post_save from django.contrib.sites.models import Site from django.dispatch import receiver class Conf(models.Model): site = models.OneToOneField(Site, related_name='conf', on_delete=models.CASCADE) color = models.CharField(max_length=5, blank=True) class Meta: verbose_name = 'Configuration' verbose_name_plural = 'Configuration' def __str__(self): return 'Configuration for {}'.format(self.site.name) @receiver(post_save, sender=Site) def create_conf(sender, instance, created, **kwargs): if created: Conf.objects.create(site=instance) @receiver(post_save, sender=Site) def save_conf(sender, instance, **kwargs): instance.conf.save() class SitePermission(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) sites = models.ManyToManyField('sites.Site', blank=True) objects = models.Manager() class Meta: verbose_name = 'Site permission' verbose_name_plural = 'Site permissions' def __str__(self): return 'Site permissions for {}'.format(self.user)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.db import models from django.db.models.signals import post_save from django.contrib.sites.models import Site from django.dispatch import receiver class Conf(models.Model): site = models.OneToOneField(Site, related_name='conf', on_delete=models.CASCADE) color = models.CharField(max_length=5, blank=True) def __str__(self): return 'Configuration' @receiver(post_save, sender=Site) def create_conf(sender, instance, created, **kwargs): if created: Conf.objects.create(site=instance) @receiver(post_save, sender=Site) def save_conf(sender, instance, **kwargs): instance.conf.save() class SitePermission(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) sites = models.ManyToManyField('sites.Site', blank=True) objects = models.Manager() class Meta: verbose_name = 'Site permission' verbose_name_plural = 'Site permissions' def __str__(self): return 'Site permissions for {}'.format(self.user)
Change author_email to my own email My personal email is definitely the one that'll keep working in the long run.
#!/usr/bin/env python3 from setuptools import setup, find_packages setup( name='django-afip', version='0.8.0', description='AFIP integration for django', author='Hugo Osvaldo Barrera', author_email='hugo@barrera.io', url='https://gitlab.com/hobarrera/django-afip', license='ISC', packages=find_packages(), include_package_data=True, long_description=open('README.rst').read(), install_requires=open('requirements.txt').read().splitlines()[:-1] + ['suds-py3==1.0.0.0'], dependency_links=( 'git+https://github.com/hobarrera/suds-py3.git#egg=suds-py3-1.0.0.0', ), use_scm_version={'version_scheme': 'post-release'}, setup_requires=['setuptools_scm'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
#!/usr/bin/env python3 from setuptools import setup, find_packages setup( name='django-afip', version='0.8.0', description='AFIP integration for django', author='Hugo Osvaldo Barrera', author_email='hbarrera@z47.io', url='https://gitlab.com/hobarrera/django-afip', license='ISC', packages=find_packages(), include_package_data=True, long_description=open('README.rst').read(), install_requires=open('requirements.txt').read().splitlines()[:-1] + ['suds-py3==1.0.0.0'], dependency_links=( 'git+https://github.com/hobarrera/suds-py3.git#egg=suds-py3-1.0.0.0', ), use_scm_version={'version_scheme': 'post-release'}, setup_requires=['setuptools_scm'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Add clientsClaim and skipWaiting options
let pkg = require('./package.json'); module.exports = { baseUrl: process.env.NODE_ENV === 'production' ? '/guess-them-all/' : '/', pwa: { name: pkg.description, themeColor: '#448AFF', appleMobileWebAppCapable: true, // configure the workbox plugin workboxOptions: { swDest: 'sw.js', runtimeCaching: [ { urlPattern: new RegExp('fonts.(gstatic|googleapis).com/(.*)'), handler: 'staleWhileRevalidate', }, ], navigateFallback: '/', directoryIndex: 'index.html', clientsClaim: true, skipWaiting: true, }, }, };
let pkg = require('./package.json'); module.exports = { baseUrl: process.env.NODE_ENV === 'production' ? '/guess-them-all/' : '/', pwa: { name: pkg.description, themeColor: '#448AFF', appleMobileWebAppCapable: true, // configure the workbox plugin workboxOptions: { swDest: 'sw.js', runtimeCaching: [ { urlPattern: new RegExp('fonts.(gstatic|googleapis).com/(.*)'), handler: 'staleWhileRevalidate', }, ], navigateFallback: '/', directoryIndex: 'index.html', }, }, };
Clear the error message after it has been displayed once
<!DOCTYPE HTML> <?php session_start(); if($_SESSION['errorMessage'] == null) { $_SESSION['errorMessage']=""; } else { $errorMessage = $_SESSION['errorMessage']; $_SESSION['errorMessage']=""; } $uName=""; $pWord=""; ?> <html> <head> <title>Login</title> <meta charset="utf-8" /> <link rel="stylesheet" type="text/css" href="main.css" /> </head> <header><h1>Login</h1></header> <body> <br> <form action="bibliography_management.php" method="post"> Name: <br><input type="text" name="name"><br> Password: <br><input type="password" name="password"><br><br> <input id="button" type="submit" name="submit" value="Log-In"> </form><br> <?php echo $errorMessage; ?><br> <a href="register.php">Register</a> </body> </html>
<!DOCTYPE HTML> <?php session_start(); if($_SESSION['errorMessage'] == null) { $_SESSION['errorMessage']=""; } $uName=""; $pWord=""; ?> <html> <head> <title>Login</title> <meta charset="utf-8" /> <link rel="stylesheet" type="text/css" href="main.css" /> </head> <header><h1>Login</h1></header> <body> <br> <form action="bibliography_management.php" method="post"> Name: <br><input type="text" name="name"><br> Password: <br><input type="password" name="password"><br><br> <input id="button" type="submit" name="submit" value="Log-In"> </form><br> <?php echo $_SESSION['errorMessage']; ?><br> <a href="register.php">Register</a> </body> </html>
Make it work on flusspferd.
exports.setup = function(Tests){ var Suite = require('lib/suite').Suite; Tests.describe('Suites', function(it, setup){ setup('beforeEach', function(){ }); it('should error out if no `it` named argument is declared', function(expect){ var error = null; try { new Suite('Fail', function(){}); } catch(e){ error = e; } finally { expect(error).toBeAnInstanceOf(Error); expect(error.message).toBe('Suite function does not explicitly define an `it` argument.'); } }); it('should pass an `it` and `setup` function', function(expect){ expect.perform(2); new Suite('Pass', function(it, setup){ expect(it).toBeAnInstanceOf(Function); expect(setup).toBeAnInstanceOf(Function); }).run(); }); }); };
exports.setup = function(Tests){ var Suite = require('lib/suite').Suite; Tests.describe('Suites', function(it, setup){ setup('beforeEach', function(){ }); it('should error out if no `it` named argument is declared', function(expect){ var error = null; try { new Suite('Fail', function(){}); } catch(e){ error = e; } finally { expect(error).toBeAnInstanceOf(Error); expect(error.message).toBe('Suite function does not explicitly define an `it` argument.'); } }); it('should pass an `it` and `setup` function', function(expect){ new Suite('Pass', function(it, setup){ expect(it).toBeAnInstanceOf(Function); expect(setup).toBeAnInstanceOf(Function); }).run(); }); }); };
Add the ability to override the readFile function
import { createFilter } from 'rollup-pluginutils'; import { resolve as resolveSourceMap } from 'source-map-resolve'; import * as fs from 'fs'; export default function sourcemaps({ include, exclude, readFile = fs.readFile } = {}) { const filter = createFilter(include, exclude); return { name: 'sourcemaps', load(id) { if (!filter(id)) { return null; } return new Promise(resolve => { readFile(id, 'utf8', (err, code) => { if (err) { // Failed reading file, let the next plugin deal with it resolve(null); } else { resolveSourceMap(code, id, readFile, (err, sourceMap) => { if (err || sourceMap === null) { // Either something went wrong, or there was no source map resolve(code); } else { const { map, sourcesContent } = sourceMap; map.sourcesContent = sourcesContent; resolve({ code, map }); } }); } }); }); }, }; }
import { createFilter } from 'rollup-pluginutils'; import { resolve as resolveSourceMap } from 'source-map-resolve'; import { readFile } from 'fs'; export default function sourcemaps({ include, exclude } = {}) { const filter = createFilter(include, exclude); return { name: 'sourcemaps', load(id) { if (!filter(id)) { return null; } return new Promise(resolve => { readFile(id, 'utf8', (err, code) => { if (err) { // Failed reading file, let the next plugin deal with it resolve(null); } else { resolveSourceMap(code, id, readFile, (err, sourceMap) => { if (err || sourceMap === null) { // Either something went wrong, or there was no source map resolve(code); } else { const { map, sourcesContent } = sourceMap; map.sourcesContent = sourcesContent; resolve({ code, map }); } }); } }); }); }, }; }
Fix bump version to federal senate script
from setuptools import setup REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox' setup( author='Serenata de Amor', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Topic :: Utilities', ], description='Toolbox for Serenata de Amor project', zip_safe=False, install_requires=[ 'aiofiles', 'aiohttp', 'boto3', 'beautifulsoup4>=4.4', 'lxml>=3.6', 'pandas>=0.18', 'tqdm' ], keywords='serenata de amor, data science, brazil, corruption', license='MIT', long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL), name='serenata-toolbox', packages=['serenata_toolbox.chamber_of_deputies', 'serenata_toolbox.datasets'], url=REPO_URL, version='9.0.4' )
from setuptools import setup REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox' setup( author='Serenata de Amor', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Topic :: Utilities', ], description='Toolbox for Serenata de Amor project', zip_safe=False, install_requires=[ 'aiofiles', 'aiohttp', 'boto3', 'beautifulsoup4>=4.4', 'lxml>=3.6', 'pandas>=0.18', 'tqdm' ], keywords='serenata de amor, data science, brazil, corruption', license='MIT', long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL), name='serenata-toolbox', packages=['serenata_toolbox.chamber_of_deputies', 'serenata_toolbox.datasets'], url=REPO_URL, version='9.0.3' )
Add filtering for "Best BLAHBLAHBLAH ever made"
// ==UserScript== // @name Steam Review filter // @namespace https://github.com/somoso/steam_user_review_filter/raw/master/steam_user_review_filter.user.js // @version 0.31 // @description try to filter out the crap on steam // @author You // @match http://store.steampowered.com/app/* // @grant none // @require http://code.jquery.com/jquery-latest.js // ==/UserScript== /* jshint -W097 */ 'use strict'; var searchStr = ".review_box"; console.log("Starting steam user review filter"); var reviews = $(searchStr); for (i = 0; i < reviews.length; i++) { if ($(reviews[i]).hasClass('partial')) { continue; } var filterReview = false; var urgh = reviews[i].innerText; if (urgh.includes('10/10')) { filterReview = true; } else if (urgh.match(/\bign\b/i)) { filterReview = true; } else if (urgh.match(/\bbest ([A-Za-z0-9_-]+ ){1,3}ever( made)?\b/i)) { filterReview = true; } if (filterReview) { $(reviews[i]).remove(); } }) } console.log("Ending steam user review filter");
// ==UserScript== // @name Steam Review filter // @namespace https://github.com/somoso/steam_user_review_filter/raw/master/steam_user_review_filter.user.js // @version 0.31 // @description try to filter out the crap on steam // @author You // @match http://store.steampowered.com/app/* // @grant none // @require http://code.jquery.com/jquery-latest.js // ==/UserScript== /* jshint -W097 */ 'use strict'; var searchStr = ".review_box"; console.log("Starting steam user review filter"); var reviews = $(searchStr); for (i = 0; i < reviews.length; i++) { if ($(reviews[i]).hasClass('partial')) { continue; } var urgh = reviews[i].innerText; if (urgh.includes('10/10')) { $(reviews[i]).remove(); } else if (urgh.match(/\bign\b/i)) { $(reviews[i]).remove(); } } console.log("Ending steam user review filter");
Make Primitive\Num tests much more nicer
<?php declare(strict_types=1); namespace test\Primitive; use Eris\TestTrait; use Eris\Generator; use Widmogrod\Helpful\SetoidLaws; use Widmogrod\Primitive\Num; class NumTest extends \PHPUnit\Framework\TestCase { use TestTrait; public function test_it_should_obay_setoid_laws() { $this->forAll( Generator\choose(0, 1000), Generator\choose(1000, 4000), Generator\choose(4000, 100000) )->then(function (int $x, int $y, int $z) { SetoidLaws::test( [$this, 'assertEquals'], Num::of($x), Num::of($y), Num::of($z) ); }); } }
<?php declare(strict_types=1); namespace test\Primitive; use Widmogrod\Helpful\SetoidLaws; use Widmogrod\Primitive\Num; class NumTest extends \PHPUnit\Framework\TestCase { /** * @dataProvider provideSetoidLaws */ public function test_it_should_obay_setoid_laws( $a, $b, $c ) { SetoidLaws::test( [$this, 'assertEquals'], $a, $b, $c ); } private function randomize() { return Num::of(random_int(-100000000, 100000000)); } public function provideSetoidLaws() { return array_map(function () { return [ $this->randomize(), $this->randomize(), $this->randomize(), ]; }, array_fill(0, 50, null)); } }
Update switch schema to eliminate Meta and add standard top-level fields
package schema // Sample is an individual measurement taken by DISCO. type Sample struct { Timestamp int64 `json:"timestamp,int64" bigquery:"timestamp"` Value float32 `json:"value,float32" bigquery:"value"` } // SwitchStats represents a row of data taken from the raw DISCO export file. type SwitchStats struct { TaskFilename string `json:"task_filename,string" bigquery:"task_filename"` TestID string `json:"test_id,string" bigquery:"test_id"` ParseTime int64 `json:"parse_time,int64" bigquery:"parse_time"` LogTime int64 `json:"log_time,int64" bigquery:"log_time"` Sample []Sample `json:"sample" bigquery:"sample"` Metric string `json:"metric" bigquery:"metric"` Hostname string `json:"hostname" bigquery:"hostname"` Experiment string `json:"experiment" bigquery:"experiment"` } // Size estimates the number of bytes in the SwitchStats object. func (s *SwitchStats) Size() int { return (len(s.TaskFilename) + len(s.TestID) + 8 + 12*len(s.Sample) + len(s.Metric) + len(s.Hostname) + len(s.Experiment)) }
package schema // TODO: copy disco schema here. // Meta contains the archive and parse metadata. type Meta struct { FileName string `json:"task_filename,string" bigquery:"task_filename"` TestName string `json:"test_id,string" bigquery:"test_id"` ParseTime int64 `json:"parse_time,int64" bigquery:"parse_time"` } // Sample is an individual measurement taken by DISCO. type Sample struct { Timestamp int64 `json:"timestamp,int64" bigquery:"timestamp"` Value float32 `json:"value,float32" bigquery:"value"` } // SwitchStats represents a row of data taken from the raw DISCO export file. type SwitchStats struct { Meta Meta `json:"meta" bigquery:"meta"` Sample []Sample `json:"sample" bigquery:"sample"` Metric string `json:"metric" bigquery:"metric"` Hostname string `json:"hostname" bigquery:"hostname"` Experiment string `json:"experiment" bigquery:"experiment"` } // Size estimates the number of bytes in the SwitchStats object. func (s *SwitchStats) Size() int { return (len(s.Meta.FileName) + len(s.Meta.TestName) + 8 + 12*len(s.Sample) + len(s.Metric) + len(s.Hostname) + len(s.Experiment)) }
Fix typo and throw exception.
<?php namespace mcordingley\ProbabilityDistribution\Discrete; use InvalidArgumentException; use mcordingley\ProbabilityDistribution\AbstractProbabilityDistribution; abstract class AbstractDiscreteProbabilityDistribution extends AbstractProbabilityDistribution { /* These versions of getCdf and getPpf are guaranteed to be correct for * all discrete distributions. In the case of certain distributions, it's * possible to find these values analytically. Where possible, that is * the preferred method of finding the values, as they should be more * performant. */ public function getCdf($x) { $sum = 0; for ($count = 0; $count <= $x; $count++) { $sum += $this->getPdf($count); } return $sum; } public function getPpf($x) { if ($x > 1) { throw new InvalidArgumentException('Cannot ask for the percent-point function of greater than 100% probability.'); } $i = 0; $cdf = 0; while ($cdf < $x) { $cdf += $this->getPdf($i); $i++; } return $i - 1; } }
<?php namespace mcordingley\ProbabilityDistribution\Discrete; use mcordingley\ProbabilityDistribution\AbstractProbabilityDistribution; abstract class AbstractDiscreteProbabilityDistribution extends AbstractProbabilityDistribution { /* These versions of getCdf and getPpf are guaranteed to be correct for * all discrete distributions. In the case of certain distributions, it's * possible to find these values analytically. Where possible, that is * the preferred method of finding the values, as they should be more * performance. */ public function getCdf($x) { $sum = 0; for ($count = 0; $count <= $x; $count++) { $sum += $this->getPdf($count); } return $sum; } public function getPpf($x) { if ($x >= 1) return INF; //Prevents infinite loops. $i = 0; $cdf = 0; while ($cdf < $x) { $cdf += $this->getPdf($i); $i++; } return $i - 1; } }
Exclude Windows tests from linter.
//+build windows // Copyright (c) 2017-2018 Tigera, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package windataplane_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/projectcalico/felix/config" "github.com/projectcalico/felix/dataplane/windows" ) var _ = Describe("Constructor test", func() { var configParams *config.Config var dpConfig windataplane.Config JustBeforeEach(func() { configParams = config.New() dpConfig = windataplane.Config{ IPv6Enabled: configParams.Ipv6Support, } }) It("should be constructable", func() { var dp = windataplane.NewWinDataplaneDriver(dpConfig) Expect(dp).ToNot(BeNil()) }) })
// Copyright (c) 2017 Tigera, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package windataplane_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/projectcalico/felix/config" "github.com/projectcalico/felix/dataplane/windows" ) var _ = Describe("Constructor test", func() { var configParams *config.Config var dpConfig windataplane.Config JustBeforeEach(func() { configParams = config.New() dpConfig := windataplane.Config{ IPv6Enabled: configParams.Ipv6Support, } }) It("should be constructable", func() { var dp = windataplane.NewWinDataplaneDriver(dpConfig) Expect(dp).ToNot(BeNil()) }) })
[FIX] medical_prescription_sale_stock_us: Add dependency * Add dependency on medical_prescription_us to manifest file. This is needed for successful installation.
# -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Medical Prescription Sale Stock - US', 'summary': 'Provides US Locale to Medical Prescription Sale Stock', 'version': '9.0.1.0.0', 'author': "LasLabs, Odoo Community Association (OCA)", 'category': 'Medical', 'depends': [ 'medical_base_us', 'medical_prescription_sale_stock', 'medical_prescription_us', ], 'data': [ 'views/procurement_order_view.xml', ], "website": "https://laslabs.com", "license": "AGPL-3", 'installable': True, 'auto_install': False, }
# -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Medical Prescription Sale Stock - US', 'summary': 'Provides US Locale to Medical Prescription Sale Stock', 'version': '9.0.1.0.0', 'author': "LasLabs, Odoo Community Association (OCA)", 'category': 'Medical', 'depends': [ 'medical_base_us', 'medical_prescription_sale_stock', ], 'data': [ 'views/procurement_order_view.xml', ], "website": "https://laslabs.com", "license": "AGPL-3", 'installable': True, 'auto_install': False, }
Use composer version of jQuery IAS only
<?php namespace kop\y2sp\assets; use yii\web\AssetBundle; /** * This is "InfiniteAjaxScrollAsset" class. * * This class is an asset bundle for {@link http://infiniteajaxscroll.com/ JQuery Infinite Ajax Scroll plugin}. * * @link http://kop.github.io/yii2-scroll-pager Y2SP project page. * @license https://github.com/kop/yii2-scroll-pager/blob/master/LICENSE.md MIT * * @author Ivan Koptiev <ikoptev@gmail.com> * @version 2.2 */ class InfiniteAjaxScrollAsset extends AssetBundle { /** * @var array List of bundle class names that this bundle depends on. */ public $depends = [ 'yii\web\JqueryAsset', ]; /** * @inheritdoc */ public function init() { $this->sourcePath = '@vendor/webcreate/jquery-ias/src'; $this->js = [ 'callbacks.js', 'jquery-ias.js', 'extension/history.js', 'extension/noneleft.js', 'extension/paging.js', 'extension/spinner.js', 'extension/trigger.js' ]; } }
<?php namespace kop\y2sp\assets; use yii\web\AssetBundle; /** * This is "InfiniteAjaxScrollAsset" class. * * This class is an asset bundle for {@link http://infiniteajaxscroll.com/ JQuery Infinite Ajax Scroll plugin}. * * @link http://kop.github.io/yii2-scroll-pager Y2SP project page. * @license https://github.com/kop/yii2-scroll-pager/blob/master/LICENSE.md MIT * * @author Ivan Koptiev <ikoptev@gmail.com> * @version 2.1.2 */ class InfiniteAjaxScrollAsset extends AssetBundle { /** * @var array List of bundle class names that this bundle depends on. */ public $depends = [ 'yii\web\JqueryAsset', ]; /** * @inheritdoc */ public function init() { $this->sourcePath = '@vendor/webcreate/jquery-ias/src'; $this->js = [ 'callbacks.js', 'jquery-ias.js', 'extension/history.js', 'extension/noneleft.js', 'extension/paging.js', 'extension/spinner.js', 'extension/trigger.js' ]; } }
Use null coalescing for indicator value indicator getter
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import Realm from 'realm'; /** * An abstract object which contains metadata describing an indicator row or column. * * @property {string} id * @property {string} storeId * @property {Period} period * @property {IndicatorAttribute} column * @property {IndicatorAttribute} row * @property {string} value */ export class IndicatorValue extends Realm.Object { get indicator() { return this.row.indicator ?? this.column.indicator; } } export default IndicatorValue; IndicatorValue.schema = { name: 'IndicatorValue', primaryKey: 'id', properties: { id: 'string', storeId: 'string', period: 'Period', column: 'IndicatorAttribute', row: 'IndicatorAttribute', value: 'string', }, };
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import Realm from 'realm'; /** * An abstract object which contains metadata describing an indicator row or column. * * @property {string} id * @property {string} storeId * @property {Period} period * @property {IndicatorAttribute} column * @property {IndicatorAttribute} row * @property {string} value */ export class IndicatorValue extends Realm.Object { get indicator() { const { indicator: rowIndicator } = this.row; const { indicator: columnIndicator } = this.column; return rowIndicator || columnIndicator; } } export default IndicatorValue; IndicatorValue.schema = { name: 'IndicatorValue', primaryKey: 'id', properties: { id: 'string', storeId: 'string', period: 'Period', column: 'IndicatorAttribute', row: 'IndicatorAttribute', value: 'string', }, };
Change of arguments, remove unused modules, source is now a directory
import json import click import subprocess import utils import os import logging @click.command() @click.argument('sources', type=click.Path(exists=True), required=True) @click.argument('output', type=click.Path(exists=True), required=True) @click.argument('min_zoom', default=5) @click.argument('max_zoom', default=14) def vectorTiling(sources, output, min_zoom, max_zoom): """ Function that creates vector tiles PARAMS: - sources : directory where the geojson file(s) are - output : directory for the generated data """ files = [] for file in utils.get_files(sources): if not os.path.isdir(file): if file.split('.')[1] == 'geojson': files.append(file) logging.info("{} geojson found".format(len(files))) paths_string = '' for file in files: with open(file, 'rb') as f: geojson = json.load(f) features = geojson['features'] for item in features: paths_string += item['properties']['path'] + ' ' command = 'tippecanoe -f -o ' + output + '/result.mbtiles ' + paths_string + ' -z {} -Z {}'.format(max_zoom, min_zoom) subprocess.call(command,shell=True) if __name__ == '__main__': vectorTiling()
import json import os from urlparse import urlparse import zipfile import click import adapters from filters import BasicFilterer import utils import subprocess @click.command() @click.argument('file', type=click.Path(exists=True), required=True) def vectorTiling(file): """ Function that creates vector tiles INPUT: geojson file generated by process.py OUTPUT: mbtiles file containing vector tiles """ # Variables to change in production path = '/Users/athissen/Documents/' min_zoom = 0 max_zoom = 14 paths_string = '' with open(file, 'rb') as f: geojson = json.load(f) features = geojson['features'] for item in features: paths_string += path + item['properties']['path'] + ' ' command = 'tippecanoe -f -o ' + 'result.mbtiles ' + paths_string + ' -z {} -Z {}'.format(max_zoom, min_zoom) subprocess.call(command,shell=True) if __name__ == '__main__': vectorTiling()
Add constants for authorization scopes.
/* * Copyright 2014 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.dsu.configuration; /** * An interface containing shared properties for OAuth2 configurations. * * @author Emerson Farrugia */ public interface OAuth2Properties { public static final String CLIENT_ROLE = "ROLE_CLIENT"; public static final String END_USER_ROLE = "ROLE_END_USER"; public static final String DATA_POINT_RESOURCE_ID = "dataPoint"; public static final String DATA_POINT_READ_SCOPE = "read"; public static final String DATA_POINT_WRITE_SCOPE = "write"; public static final String DATA_POINT_DELETE_SCOPE = "delete"; }
/* * Copyright 2014 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.dsu.configuration; /** * An interface containing shared properties for OAuth2 configurations. * * @author Emerson Farrugia */ public interface OAuth2Properties { public static final String CLIENT_ROLE = "ROLE_CLIENT"; public static final String END_USER_ROLE = "ROLE_END_USER"; public static final String DATA_POINT_RESOURCE_ID = "dataPoint"; }
Move registration box to news page
import React from 'react'; import { get } from '../fetcher'; import NewsPost from './NewsPost'; import RegistrationBox from './RegistrationBox' const NewsPage = React.createClass({ getInitialState() { return { posts: [] }; }, componentDidMount() { get('/posts').then(posts => this.setState({ posts })); }, render() { const { posts } = this.state; return ( <section> <RegistrationBox /> {posts.map(post => ( <NewsPost key={post._id} post={post}/> ))} </section> ); } }); export default NewsPage;
import React from 'react'; import { get } from '../fetcher'; import NewsPost from './NewsPost'; const NewsPage = React.createClass({ getInitialState() { return { posts: [] }; }, componentDidMount() { get('/posts').then(posts => this.setState({ posts })); }, render() { const { posts } = this.state; return ( <section> {posts.map(post => ( <NewsPost key={post._id} post={post}/> ))} </section> ); } }); export default NewsPage;
Add missing setters for handshake.
package net.md_5.bungee.protocol.packet; import io.netty.buffer.ByteBuf; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString @EqualsAndHashCode(callSuper = false) public class Packet2Handshake extends DefinedPacket { private byte protocolVersion; private String username; private String host; private int port; private Packet2Handshake() { super( 0x02 ); } @Override public void read(ByteBuf buf) { protocolVersion = buf.readByte(); username = readString( buf ); host = readString( buf ); port = buf.readInt(); } @Override public void write(ByteBuf buf) { buf.writeByte( protocolVersion ); writeString( username, buf ); writeString( host, buf ); buf.writeInt( port ); } @Override public void handle(AbstractPacketHandler handler) throws Exception { handler.handle( this ); } }
package net.md_5.bungee.protocol.packet; import io.netty.buffer.ByteBuf; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; @Getter @ToString @EqualsAndHashCode(callSuper = false) public class Packet2Handshake extends DefinedPacket { private byte protocolVersion; private String username; private String host; private int port; private Packet2Handshake() { super( 0x02 ); } @Override public void read(ByteBuf buf) { protocolVersion = buf.readByte(); username = readString( buf ); host = readString( buf ); port = buf.readInt(); } @Override public void write(ByteBuf buf) { buf.writeByte( protocolVersion ); writeString( username, buf ); writeString( host, buf ); buf.writeInt( port ); } @Override public void handle(AbstractPacketHandler handler) throws Exception { handler.handle( this ); } }
Set stories_set to read only field
from rest_framework import serializers from users.serializers import AuthorSerializer from .models import Story, StoryLine class StoryLineSerializer(serializers.ModelSerializer): class Meta: model = StoryLine fields = ('id', 'content', 'posted_on') class StorySerializer(serializers.ModelSerializer): title = serializers.CharField(min_length=3, max_length=100) author = AuthorSerializer(read_only=True) storyline_set = StoryLineSerializer(read_only=True, many=True) class Meta: model = Story fields = ('id', 'title', 'author', 'posted_on', 'storyline_set') def create(self, validated_data): request = self.context['request'] author = request.user.author return Story.objects.create(author=author, **validated_data)
from rest_framework import serializers from users.serializers import AuthorSerializer from .models import Story, StoryLine class StoryLineSerializer(serializers.ModelSerializer): class Meta: model = StoryLine fields = ('id', 'content', 'posted_on') class StorySerializer(serializers.ModelSerializer): title = serializers.CharField(min_length=3, max_length=100) author = AuthorSerializer(read_only=True) storyline_set = StoryLineSerializer(many=True) class Meta: model = Story fields = ('id', 'title', 'author', 'posted_on', 'storyline_set') def create(self, validated_data): request = self.context['request'] author = request.user.author return Story.objects.create(author=author, **validated_data)
Fix Permission denied on Configuration tab for Administrator Strangely, `this.get('session.user.isAdmin')` returned undefined even though session.user was correctly set. Replacing with working `this.get('session').get('user').get('isAdmin')`
/** * Nanocloud turns any traditional software into a cloud solution, without * changing or redeveloping existing source code. * * Copyright (C) 2016 Nanocloud Software * * This file is part of Nanocloud. * * Nanocloud is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Nanocloud is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General * Public License * along with this program. If not, see * <http://www.gnu.org/licenses/>. */ import Ember from 'ember'; export default Ember.Route.extend({ session: Ember.inject.service(), model() { return Ember.RSVP.hash({ groups: this.store.findAll('group', { reload: true }) }); }, beforeModel() { if (!this.get('session').get('user').get('isAdmin')) { this.toast.error('Permission denied'); this.transitionTo('protected.dashboard'); } } });
/** * Nanocloud turns any traditional software into a cloud solution, without * changing or redeveloping existing source code. * * Copyright (C) 2016 Nanocloud Software * * This file is part of Nanocloud. * * Nanocloud is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Nanocloud is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General * Public License * along with this program. If not, see * <http://www.gnu.org/licenses/>. */ import Ember from 'ember'; export default Ember.Route.extend({ session: Ember.inject.service(), model() { return Ember.RSVP.hash({ groups: this.store.findAll('group', { reload: true }) }); }, beforeModel() { if (!this.get('session.user.isAdmin')) { this.toast.error('Permission denied'); this.transitionTo('protected.dashboard'); } } });
Add back code which is needed.
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import import logging from st2client.models import core LOG = logging.getLogger(__name__) class KeyValuePair(core.Resource): _alias = 'Key' _display_name = 'Key Value Pair' _plural = 'Keys' _plural_display_name = 'Key Value Pairs' _repr_attributes = ['name', 'value'] # Note: This is a temporary hack until we refactor client and make it support non id PKs def get_id(self): return self.name def set_id(self, value): pass id = property(get_id, set_id)
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import import logging from st2client.models import core LOG = logging.getLogger(__name__) class KeyValuePair(core.Resource): _alias = 'Key' _display_name = 'Key Value Pair' _plural = 'Keys' _plural_display_name = 'Key Value Pairs' _repr_attributes = ['name', 'value'] # Note: This is a temporary hack until we refactor client and make it support non id PKs
Add global navigator setting to modify the error, 'navigator is not defined', in testing with react-router link
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
Introduce a warning to test the shiny new CI
package main import ( "bufio" "fmt" "net/http" "net/http/httptest" "net/http/httputil" "golang.org/x/crypto/ssh" ) func handleDirectTCPIPChannel(channel ssh.Channel, port uint32) (string, error) { switch port { case 80: return handleHTTPChannel(channel) return "", nil default: return "", fmt.Errorf("unsupported port %v", port) } } func handleHTTPChannel(channel ssh.Channel) (string, error) { request, err := http.ReadRequest(bufio.NewReader(channel)) if err != nil { return "", err } requestBytes, err := httputil.DumpRequest(request, true) if err != nil { return "", err } responseRecorder := httptest.NewRecorder() http.NotFound(responseRecorder, request) if err := responseRecorder.Result().Write(channel); err != nil { return "", err } return string(requestBytes), nil }
package main import ( "bufio" "fmt" "net/http" "net/http/httptest" "net/http/httputil" "golang.org/x/crypto/ssh" ) func handleDirectTCPIPChannel(channel ssh.Channel, port uint32) (string, error) { switch port { case 80: return handleHTTPChannel(channel) default: return "", fmt.Errorf("unsupported port %v", port) } } func handleHTTPChannel(channel ssh.Channel) (string, error) { request, err := http.ReadRequest(bufio.NewReader(channel)) if err != nil { return "", err } requestBytes, err := httputil.DumpRequest(request, true) if err != nil { return "", err } responseRecorder := httptest.NewRecorder() http.NotFound(responseRecorder, request) if err := responseRecorder.Result().Write(channel); err != nil { return "", err } return string(requestBytes), nil }
Switch libraryTarget from var to umd
module.exports = { context: __dirname, entry: './src/index.jsx', output: { path: './build', filename: 'index.js', library: 'CalendarHeatmap', libraryTarget: 'umd' }, resolve: { extensions: ['', '.js', '.jsx'], modulesDirectories: ['node_modules'] }, externals: { 'react': { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' } }, module: { loaders: [ { test: /\.jsx?$/, exclude: /(node_modules)/, loader: 'babel' } ] } };
module.exports = { context: __dirname, entry: './src/index.jsx', output: { path: './build', filename: 'index.js', library: 'CalendarHeatmap', libraryTarget: 'var' }, resolve: { extensions: ['', '.js', '.jsx'], modulesDirectories: ['node_modules'] }, externals: { 'react': { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' } }, module: { loaders: [ { test: /\.jsx?$/, exclude: /(node_modules)/, loader: 'babel' } ] } };
Add exception if instagram result has non 200 status
<?php namespace Codenetix\SocialMediaImporter\Importers; use Codenetix\SocialMediaImporter\Exceptions\ImportException; use Codenetix\SocialMediaImporter\Exceptions\RequestedDataNotFoundException; use Codenetix\SocialMediaImporter\FactoryMethods\InstagramMediaAdapterFactoryMethod; use Codenetix\SocialMediaImporter\Scrapers\InstagramScraper; /** * @author Andrey Vorobiov<andrew.sprw@gmail.com> */ class InstagramSingleMediaImporter extends AInstagramMediaImporter { public function importByURL($url) { $item = $this->instagramClient->getMedia((new InstagramScraper($url))->id()); if(!$item){ throw new RequestedDataNotFoundException("Requested media was not found"); } if($item->meta->code != 200){ throw new ImportException($item->meta->error_message); } return (new InstagramMediaAdapterFactoryMethod())->make($item->data->type, $item->data)->transform($this->mediaFactoryMethod); } }
<?php namespace Codenetix\SocialMediaImporter\Importers; use Codenetix\SocialMediaImporter\Exceptions\RequestedDataNotFoundException; use Codenetix\SocialMediaImporter\FactoryMethods\InstagramMediaAdapterFactoryMethod; use Codenetix\SocialMediaImporter\Scrapers\InstagramScraper; /** * @author Andrey Vorobiov<andrew.sprw@gmail.com> */ class InstagramSingleMediaImporter extends AInstagramMediaImporter { public function importByURL($url) { $item = $this->instagramClient->getMedia((new InstagramScraper($url))->id()); if(!$item){ throw new RequestedDataNotFoundException("Requested media was not found"); } return (new InstagramMediaAdapterFactoryMethod())->make($item->data->type, $item->data)->transform($this->mediaFactoryMethod); } }
Add servlet to handle text request submissions and send to Dialogflow
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.servlets; import java.io.IOException; import java.io.BufferedReader; import java.util.stream.Collectors; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.cloud.dialogflow.v2.QueryInput; import com.google.cloud.dialogflow.v2.QueryResult; import com.google.sps.utils.TextUtils; /** Servlet that takes in user text input and retrieves ** QueryResult from Dialogflow input string to display. */ @WebServlet("/text-input") public class TextInputServlet extends HttpServlet { @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String userQuestion = request.getParameter("request-input"); QueryResult result = TextUtils.detectIntentStream(userQuestion); String agentResponse = result.getFulfillmentText(); System.out.println(agentResponse); } }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.servlets; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Servlet that takes in audio stream and retrieves ** user input string to display. */ @WebServlet("/textinput") public class TextInputServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html;"); response.getWriter().println("<h1>Hello world!</h1>"); } }