text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Use shell=False when chowning logs folder.
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/bin/chown -R www-data:www-data /var/www/twweb/logs/', shell=False) sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development')
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/bin/chown -R www-data:www-data /var/www/twweb/logs/') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development')
Debug Google Cloud Run support
#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask if __name__ == "__main__": if not os.environ.get('K_SERVICE'): print('Running locally') os.system('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) else: print('Running HTTP service {} {} {} for Google Cloud', os.environ.get('K_SERVICE'), os.environ.get('K_REVISION'), os.environ.get('K_CONFIGURATION')) app = Flask(__name__) @app.route('/') def ContainerService(): return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))
#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask if __name__ == "__main__": if not os.environ.get('K_SERVICE'): print('Running locally') stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) output = stream.read() output else: print('Running HTTP service {} {} {} for Google Cloud', os.environ.get('K_SERVICE'), os.environ.get('K_REVISION'), os.environ.get('K_CONFIGURATION')) app = Flask(__name__) @app.route('/') def ContainerService(): return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))
Remove invalid argument for load command
"""Module for the custom Django updatedata command.""" from django.core import management class Command(management.base.BaseCommand): """Required command class for the custom Django updatedata command.""" help = "Update all data from content folders for all applications" def add_arguments(self, parser): """Add optional parameter to updatedata command.""" parser.add_argument( "--lite-load", action="store_true", dest="lite_load", help="Perform lite load (only load key content)", ) def handle(self, *args, **options): """Automatically called when the updatedata command is given.""" lite_load = options.get("lite_load") management.call_command("flush", interactive=False) management.call_command("loadresources", lite_load=lite_load) management.call_command("loadtopics", lite_load=lite_load) management.call_command("loadgeneralpages", lite_load=lite_load) management.call_command("loadclassicpages", lite_load=lite_load) management.call_command("loadactivities", lite_load=lite_load) management.call_command("load_at_a_distance_data") management.call_command("rebuild_search_indexes")
"""Module for the custom Django updatedata command.""" from django.core import management class Command(management.base.BaseCommand): """Required command class for the custom Django updatedata command.""" help = "Update all data from content folders for all applications" def add_arguments(self, parser): """Add optional parameter to updatedata command.""" parser.add_argument( "--lite-load", action="store_true", dest="lite_load", help="Perform lite load (only load key content)", ) def handle(self, *args, **options): """Automatically called when the updatedata command is given.""" lite_load = options.get("lite_load") management.call_command("flush", interactive=False) management.call_command("loadresources", lite_load=lite_load) management.call_command("loadtopics", lite_load=lite_load) management.call_command("loadgeneralpages", lite_load=lite_load) management.call_command("loadclassicpages", lite_load=lite_load) management.call_command("loadactivities", lite_load=lite_load) management.call_command("load_at_a_distance_data", lite_load=lite_load) management.call_command("rebuild_search_indexes")
Change fields order and add field url. Signed-off-by: Mariusz Fik <e22610367d206dca7aa58af34ebf008b556228c5@fidano.pl>
from django import forms from django.contrib.admin import widgets from datetimewidget.widgets import DateTimeWidget from .models import Event class LoginForm(forms.Form): username = forms.CharField(label='Nazwa użytkownika') password = forms.CharField(label='Hasło', widget=forms.PasswordInput()) data_time_options = { 'format': 'dd-mm-yyyy HH:ii' } def dt_widget(): return DateTimeWidget( bootstrap_version=3, usel10n=True, options=data_time_options ) class EventForm(forms.ModelForm): class Meta: model = Event fields = ( 'title', 'place', 'description', 'categories', 'start_time', 'end_time', 'image', 'url', ) widgets = { 'start_time': dt_widget(), 'end_time': dt_widget(), }
from django import forms from django.contrib.admin import widgets from datetimewidget.widgets import DateTimeWidget from .models import Event class LoginForm(forms.Form): username = forms.CharField(label='Nazwa użytkownika') password = forms.CharField(label='Hasło', widget=forms.PasswordInput()) data_time_options = { 'format': 'dd-mm-yyyy HH:ii' } def dt_widget(): return DateTimeWidget( bootstrap_version=3, usel10n=True, options=data_time_options ) class EventForm(forms.ModelForm): class Meta: model = Event fields = ( 'title', 'description', 'categories', 'start_time', 'end_time', 'image', 'place', ) widgets = { 'start_time': dt_widget(), 'end_time': dt_widget(), }
Add a comment id to template
<?php $account_name = BackendAccount::getName(); $Comment = new CommentObj($comment['id']); if ($Comment->array): $comment = $Comment->array; if (filter_var($comment[$account_name]['username'], FILTER_VALIDATE_EMAIL) && !$comment[$account_name]['confirmed']) { $posted_by = $comment[$account_name]['name']; if (!empty($comment[$account_name]['website'])) { $posted_by = '<a href="' . $comment['Account']['website'] . '">' . $posted_by . '</a>'; } } else { $posted_by = $comment[$account_name]['username']; if ($comment[$account_name]['confirmed']) { $posted_by = '<a href="?q=account/' . $comment['user_id'] . '">' . $posted_by . '</a>'; } } ?> <div id="comment_<?php echo $comment['id'] ?>"> <img src="<?php echo BackendAccount::getGravatar($comment[$account_name]['email'], 30) ?>" style="float: left; margin-right: 5px;" width="30px" height="30px"> <p class="quiet"> posted by <?php echo $posted_by ?> <span title="<?php echo $comment['added'] ?>"><?php echo time_elapsed($comment['added']) ?></a> </p> <p> <?php echo $comment['content'] ?> </p> <hr> </div> <?php endif; ?>
<?php $account_name = BackendAccount::getName(); $Comment = new CommentObj($comment['id']); if ($Comment->array): $comment = $Comment->array; if (filter_var($comment[$account_name]['username'], FILTER_VALIDATE_EMAIL) && !$comment[$account_name]['confirmed']) { $posted_by = $comment[$account_name]['name']; if (!empty($comment[$account_name]['website'])) { $posted_by = '<a href="' . $comment['Account']['website'] . '">' . $posted_by . '</a>'; } } else { $posted_by = $comment[$account_name]['username']; if ($comment[$account_name]['confirmed']) { $posted_by = '<a href="?q=account/' . $comment['user_id'] . '">' . $posted_by . '</a>'; } } ?> <div> <img src="<?php echo BackendAccount::getGravatar($comment[$account_name]['email'], 30) ?>" style="float: left; margin-right: 5px;" width="30px" height="30px"> <p class="quiet"> posted by <?php echo $posted_by ?> <span title="<?php echo $comment['added'] ?>"><?php echo time_elapsed($comment['added']) ?></a> </p> <p> <?php echo $comment['content'] ?> </p> <hr> </div> <?php endif; ?>
Add active class in participation navigation menu using JS
function currentLocationMatches(action_path) { return $("body.gobierto_participation_" + action_path).length > 0 } $(document).on('turbolinks:load', function() { // Toggle description for Process#show stages diagram $('.toggle_description').click(function() { $(this).parents('.timeline_row').toggleClass('toggled'); $(this).find('.fa').toggleClass('fa-caret-right fa-caret-down'); $(this).siblings('.description').toggle(); }); $.fn.extend({ toggleText: function(a, b){ return this.text(this.text() == b ? a : b); } }); $('.button_toggle').on('click', function() { $('.button.hidden').toggleClass('hidden'); }) if (currentLocationMatches("processes_poll_answers_new")) { window.GobiertoParticipation.process_polls_controller.show(); } else if (currentLocationMatches("processes_show")) { window.GobiertoParticipation.processes_controller.show(); } // fix this to be only in the home window.GobiertoParticipation.poll_teaser_controller.show(); // Add active class to menu $('nav a[href="' + window.location.pathname + '"]').parent().addClass('active'); });
function currentLocationMatches(action_path) { return $("body.gobierto_participation_" + action_path).length > 0 } $(document).on('turbolinks:load', function() { // Toggle description for Process#show stages diagram $('.toggle_description').click(function() { $(this).parents('.timeline_row').toggleClass('toggled'); $(this).find('.fa').toggleClass('fa-caret-right fa-caret-down'); $(this).siblings('.description').toggle(); }); $.fn.extend({ toggleText: function(a, b){ return this.text(this.text() == b ? a : b); } }); $('.button_toggle').on('click', function() { $('.button.hidden').toggleClass('hidden'); }) if (currentLocationMatches("processes_poll_answers_new")) { window.GobiertoParticipation.process_polls_controller.show(); } else if (currentLocationMatches("processes_show")) { window.GobiertoParticipation.processes_controller.show(); } // fix this to be only in the home window.GobiertoParticipation.poll_teaser_controller.show(); });
Fix init method, self.rows and capital booleans.
import numpy """ Board represents a four in a row game board. Author: Isaac Arvestad """ class Board: """ Initializes the game with a certain number of rows and columns. """ def __init__(self, rows, columns): self.rows = rows self.columns = columns self.boardMatrix = numpy.zeros((rows, columns)) """ Attempts to add a piece to a certain column. If the column is full the move is illegal and false is returned, otherwise true is returned. """ def addPiece(self, column, value): "Check if column is full." if self.boardMatrix.item(0,column) != 0: return False "Place piece." for y in range(self.rows): currentValue = self.boardMatrix.item(y, column) if currentValue == 0: if y == self.rows - 1: self.boardMatrix.itemset((y, column), value) else: continue return True
import numpy """ Board represents a four in a row game board. Author: Isaac Arvestad """ class Board: """ Initializes the game with a certain number of rows and columns. """ def __init(self, rows, columns): self.rows = rows self.columns = columns self.boardMatrix = numpy.zeros((rows, columns)) """ Attempts to add a piece to a certain column. If the column is full the move is illegal and false is returned, otherwise true is returned. """ def addPiece(self, column, value): "Check if column is full." if self.boardMatrix.item(0,column) != 0: return false "Place piece." for y in range(self.rows): currentValue = self.boardMatrix.item(y, column) if currentValue == 0: if y == rows - 1: self.boardMatrix.itemset((y, column), value) else: continue return true
Change structure of db constant
<?php // the path to your web site. // if you are at the root dir of your domain, this can be an empty string. // otherwise, use an url like http://example.com define('WEBROOT', ''); //just like above, just for the subfolder /ajax. //either /ajax //or http://example.com/ajax define('SERVICEPATH', '/ajax'); //chado database const DATABASE = array("1.0" => array( 'DB_ADAPTER' => 'pgsql', 'DB_CONNSTR' => 'pgsql:host=${chado_db_host};dbname=${chado_db_name};port=${chado_db_port}', 'DB_USERNAME' => '${chado_db_username}', 'DB_PASSWORD' => '${chado_db_password}' )); //set error reporting to a level that suits you error_reporting(E_ALL ^ E_STRICT ^ E_NOTICE); ini_set('display_errors', '0'); //uncomment for debugging if (isset($_REQUEST['DEBUG'])) define('DEBUG', true); error_reporting(E_ALL ); ini_set('display_errors', '1'); ?>
<?php // the path to your web site. // if you are at the root dir of your domain, this can be an empty string. // otherwise, use an url like http://example.com define('WEBROOT', ''); //just like above, just for the subfolder /ajax. //either /ajax //or http://example.com/ajax define('SERVICEPATH', '/ajax'); //chado database define('DB_ADAPTER','pgsql'); define('DB_CONNSTR', 'pgsql:host=${chado_db_host};dbname=${chado_db_name};port=${chado_db_port}'); define('DB_USERNAME', '${chado_db_username}'); define('DB_PASSWORD', '${chado_db_password}'); //set error reporting to a level that suits you error_reporting(E_ALL ^ E_STRICT ^ E_NOTICE); ini_set('display_errors', '0'); //uncomment for debugging if (isset($_REQUEST['DEBUG'])) define('DEBUG', true); error_reporting(E_ALL ); ini_set('display_errors', '1'); ?>
Fix javadoc reference to ThrowsAdvice See gh-27804
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 org.springframework.aop.framework.adapter; import java.io.Serializable; import org.aopalliance.aop.Advice; import org.aopalliance.intercept.MethodInterceptor; import org.springframework.aop.Advisor; import org.springframework.aop.ThrowsAdvice; /** * Adapter to enable {@link org.springframework.aop.ThrowsAdvice} * to be used in the Spring AOP framework. * * @author Rod Johnson * @author Juergen Hoeller */ @SuppressWarnings("serial") class ThrowsAdviceAdapter implements AdvisorAdapter, Serializable { @Override public boolean supportsAdvice(Advice advice) { return (advice instanceof ThrowsAdvice); } @Override public MethodInterceptor getInterceptor(Advisor advisor) { return new ThrowsAdviceInterceptor(advisor.getAdvice()); } }
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 org.springframework.aop.framework.adapter; import java.io.Serializable; import org.aopalliance.aop.Advice; import org.aopalliance.intercept.MethodInterceptor; import org.springframework.aop.Advisor; import org.springframework.aop.ThrowsAdvice; /** * Adapter to enable {@link org.springframework.aop.MethodBeforeAdvice} * to be used in the Spring AOP framework. * * @author Rod Johnson * @author Juergen Hoeller */ @SuppressWarnings("serial") class ThrowsAdviceAdapter implements AdvisorAdapter, Serializable { @Override public boolean supportsAdvice(Advice advice) { return (advice instanceof ThrowsAdvice); } @Override public MethodInterceptor getInterceptor(Advisor advisor) { return new ThrowsAdviceInterceptor(advisor.getAdvice()); } }
Fix in smarty v2 support
<? require_once(dirname(__FILE__).'/config.php'); require_once(dirname(__FILE__).'/User.php'); include(dirname(__FILE__).'/view/account/account_details.php'); # this yields Smarty onbject as $smarty if (preg_match("/^Smarty-3/",$smarty->_version)) { $smarty->setTemplateDir(UserConfig::$smarty_templates.'/account'); $smarty->setCompileDir(UserConfig::$smarty_compile); $smarty->setCacheDir(UserConfig::$smarty_cache); } elseif (preg_match("/^2\./",$smarty->_version)) { $smarty->template_dir = UserConfig::$smarty_templates.'/account'; $smarty->compile_dir = UserConfig::$smarty_compile; $smarty->cache_dir = UserConfig::$smarty_cache; } else { die("Cannot handle smarty version ".$smarty->_version); } require_once(UserConfig::$header); $smarty->display('account_details.tpl'); require_once(UserConfig::$footer);
<? require_once(dirname(__FILE__).'/config.php'); require_once(dirname(__FILE__).'/User.php'); include(dirname(__FILE__).'/view/account/account_details.php'); # this yields Smarty onbject as $smarty if (preg_match("/^Smarty-3/",$smarty->_version)) { $smarty->setTemplateDir(UserConfig::$smarty_templates.'/account'); $smarty->setCompileDir(UserConfig::$smarty_compile); $smarty->setCacheDir(UserConfig::$smarty_cache); } elseif (preg_match("/^2\./",$smarty->_version)) { $smarty->template_dir(UserConfig::$smarty_templates.'/account'); $smarty->compile_dir(UserConfig::$smarty_compile); $smarty->cache_dir(UserConfig::$smarty_cache); } else { die("Cannot handle smarty version ".$smarty->_version); } require_once(UserConfig::$header); $smarty->display('account_details.tpl'); require_once(UserConfig::$footer);
Put the version in the branch name to avoid potential conflicts with multiple updates to the same project
import env from '../config/environment' import GitHub from '../lib/github' import Repo from '../lib/repo' function handler(req, res, next) { let [owner, repoName] = req.body.repository.split('/') let {name, version} = req.body const gh = new GitHub(env.token, {cache: env.cache}) const repo = new Repo(owner, repoName, gh) let branchName = `update-${name}-${version}` return repo.findOrCreateBranch(branchName) .then( (branchRef) => { return repo.updateManifest(branchRef, name, version) }) .then( () => { let title = `Update ${name}` let body = `Update ${name} to ${version} :shipit:` let base = 'master' let head = branchName return repo.createPullRequest(title, body, base, head) }) .then( (pr) => { return res.send(pr) }) .catch(next) } export default handler
import env from '../config/environment' import GitHub from '../lib/github' import Repo from '../lib/repo' function handler(req, res, next) { let [owner, repoName] = req.body.repository.split('/') let {name, version} = req.body const gh = new GitHub(env.token, {cache: env.cache}) const repo = new Repo(owner, repoName, gh) let branchName = `update-${name}` return repo.findOrCreateBranch(branchName) .then( (branchRef) => { return repo.updateManifest(branchRef, name, version) }) .then( () => { let title = `Update ${name}` let body = `Update ${name} to ${version} :shipit:` let base = 'master' let head = branchName return repo.createPullRequest(title, body, base, head) }) .then( (pr) => { return res.send(pr) }) .catch(next) } export default handler
Add missing annotation to task property +review REVIEW-5932
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.plugins.quality.internal; import org.gradle.api.plugins.quality.FindBugsReports; import org.gradle.api.reporting.SingleFileReport; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.Optional; public interface FindBugsReportsInternal extends FindBugsReports { @Internal SingleFileReport getFirstEnabled(); @Input @Optional Boolean getWithMessagesFlag(); }
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.plugins.quality.internal; import org.gradle.api.plugins.quality.FindBugsReports; import org.gradle.api.reporting.SingleFileReport; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.Optional; public interface FindBugsReportsInternal extends FindBugsReports { SingleFileReport getFirstEnabled(); @Input @Optional Boolean getWithMessagesFlag(); }
Add unittests for geoip database version
from twisted.internet import defer from twisted.trial import unittest from ooni.tests import is_internet_connected from ooni import geoip class TestGeoIP(unittest.TestCase): def test_ip_to_location(self): location = geoip.IPToLocation('8.8.8.8') assert 'countrycode' in location assert 'asn' in location assert 'city' in location @defer.inlineCallbacks def test_probe_ip(self): if not is_internet_connected(): self.skipTest( "You must be connected to the internet to run this test" ) probe_ip = geoip.ProbeIP() res = yield probe_ip.lookup() assert len(res.split('.')) == 4 def test_geoip_database_version(self): version = geoip.database_version() assert 'GeoIP' in version.keys() assert 'GeoIPASNum' in version.keys() assert 'GeoLiteCity' in version.keys() assert len(version['GeoIP']['sha256']) == 64 assert isinstance(version['GeoIP']['timestamp'], float) assert len(version['GeoIPASNum']['sha256']) == 64 assert isinstance(version['GeoIPASNum']['timestamp'], float)
import os from twisted.internet import defer from twisted.trial import unittest from ooni.tests import is_internet_connected from ooni.settings import config from ooni import geoip class TestGeoIP(unittest.TestCase): def test_ip_to_location(self): location = geoip.IPToLocation('8.8.8.8') assert 'countrycode' in location assert 'asn' in location assert 'city' in location @defer.inlineCallbacks def test_probe_ip(self): if not is_internet_connected(): self.skipTest( "You must be connected to the internet to run this test" ) probe_ip = geoip.ProbeIP() res = yield probe_ip.lookup() assert len(res.split('.')) == 4
Refactor rating jquery to clear rating form on submit
$(document).ready(function() { $("#progress").on('submit', '.new_rating', function(event) { event.preventDefault(); const $form = $(this), url = $form.attr('action'), method = $form.attr('method'), data = $form.serialize(); $.ajax({ url: url, method: method, data: data, dataType: "json" }) .success(function(response) { $form.trigger('reset'); $form.closest('.modal')[0].style.display = "none"; // update score $form.closest('.collection-item').find('.current-score').text(response[0].score); // update goal partial $form.closest('.collection-item').find('.rating-partials-container') .prepend('<div class="rating-partial"><p class="confidence_score">Score: ' + response[0].score + '</p><p class="rating_comment">Comment: ' + response[0].comment + '</p></div>'); // update progress bar $('.current-level').text(response[1]); $('.progress-bar').css("width:" + response[2] + "%"); }) .fail(function(error) { console.log(error); }) }); });
$(document).ready(function() { $("#progress").on('submit', '.new_rating', function(event) { event.preventDefault(); const $form = $(this), url = $form.attr('action'), method = $form.attr('method'), data = $form.serialize(); $.ajax({ url: url, method: method, data: data, dataType: "json" }) .success(function(response) { $form.closest('.modal')[0].style.display = "none"; // update score $form.closest('.collection-item').find('.current-score').text(response[0].score); // update goal partial $form.closest('.collection-item').find('.rating-partials-container') .prepend('<div class="rating-partial"><p class="confidence_score">Score: ' + response[0].score + '</p><p class="rating_comment">Comment: ' + response[0].comment + '</p></div>'); // update progress bar $('.current-level').text(response[1]); $('.progress-bar').css("width:" + response[2] + "%"); }) .fail(function(error) { console.log(error); }) }); });
Replace another call to unsignedID.
# System Imports import StringIO import urllib # Package Imports from ..data.errors import Immutable class Image (object): @property def value (self): output = StringIO.StringIO() img = self._image_fn() img.scale(0.25).getPIL().save(output, format = "PNG") encoded = "data:image/png;base64," + urllib.quote(output.getvalue().encode('base64')) return encoded @property def type (self): return "Image" def serialize (self): if self.alias is None: return "[Image]" else: return str(self.alias) def __init__ (self, title, fn): self.alias = None self.title = title self._image_fn = fn def set (self, value): raise Immutable def setLogFile (self, logFile): pass def stopLogging (self): pass def __str__ (self): return "Image" def __repr__ (self): return "<%s at %s>" % ( self.__class__.__name__, hex(id(self)) )
# System Imports import StringIO import urllib # Twisted Imports from twisted.python.util import unsignedID # Package Imports from ..data.errors import Immutable class Image (object): @property def value (self): output = StringIO.StringIO() img = self._image_fn() img.scale(0.25).getPIL().save(output, format = "PNG") encoded = "data:image/png;base64," + urllib.quote(output.getvalue().encode('base64')) return encoded @property def type (self): return "Image" def serialize (self): if self.alias is None: return "[Image]" else: return str(self.alias) def __init__ (self, title, fn): self.alias = None self.title = title self._image_fn = fn def set (self, value): raise Immutable def setLogFile (self, logFile): pass def stopLogging (self): pass def __str__ (self): return "Image" def __repr__ (self): return "<%s at %s>" % ( self.__class__.__name__, hex(unsignedID(self)) )
Move on to new development cycle
#!/usr/bin/env python """ Erply-API --------- Python wrapper for Erply API """ from distutils.core import setup setup( name='ErplyAPI', version='0-2014.12.10-dev', description='Python wrapper for Erply API', license='BSD', author='Priit Laes', author_email='plaes@plaes.org', long_description=__doc__, install_requires=['requests'], py_modules=['erply_api'], classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Internet :: WWW/HTTP :: Site Management', 'Topic :: Office/Business :: Financial :: Point-Of-Sale', 'Topic :: Software Development :: Libraries', ] )
#!/usr/bin/env python """ Erply-API --------- Python wrapper for Erply API """ from distutils.core import setup setup( name='ErplyAPI', version='0-2014.12.10', description='Python wrapper for Erply API', license='BSD', author='Priit Laes', author_email='plaes@plaes.org', long_description=__doc__, install_requires=['requests'], py_modules=['erply_api'], classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Internet :: WWW/HTTP :: Site Management', 'Topic :: Office/Business :: Financial :: Point-Of-Sale', 'Topic :: Software Development :: Libraries', ] )
Allow single line comments to be empty (no characters between "//" and line break).
/* * grunt-strip-comments * https://github.com/kkemple/grunt-strip-comments * * Copyright (c) 2013 Kurtis Kemple * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('comments', 'Remove comments from production code', function() { var multilineComment = /\/\*[\s\S]*?\*\//g; var singleLineComment = /\/\/.*/g; var options = this.options({ singleline: true, multiline: true }); this.files[0].src.forEach(function (file) { var contents = grunt.file.read(file); if ( options.multiline ) { contents = contents.replace(multilineComment, ''); } if ( options.singleline ) { contents = contents.replace(singleLineComment, ''); } grunt.file.write(file, contents); }); }); };
/* * grunt-strip-comments * https://github.com/kkemple/grunt-strip-comments * * Copyright (c) 2013 Kurtis Kemple * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('comments', 'Remove comments from production code', function() { var multilineComment = /\/\*[\s\S]*?\*\//g; var singleLineComment = /\/\/.+/g; var options = this.options({ singleline: true, multiline: true }); this.files[0].src.forEach(function (file) { var contents = grunt.file.read(file); if ( options.multiline ) { contents = contents.replace(multilineComment, ''); } if ( options.singleline ) { contents = contents.replace(singleLineComment, ''); } grunt.file.write(file, contents); }); }); };
Add depends in our addon
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name" : "obuka", "version" : "1.0", "author" : "gdamjan", "category": 'Generic Modules', "description": "test test some description", 'website': 'http://damjan.softver.org.mk', 'init_xml': [], "depends" : ['base'], 'update_xml': ['obuka_view.xml'], 'demo_xml': [], 'test': [], 'installable': True, 'active': False, }
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name" : "obuka", "version" : "1.0", "author" : "gdamjan", "category": 'Generic Modules', "description": "test test some description", 'website': 'http://damjan.softver.org.mk', 'init_xml': [], "depends" : [], 'update_xml': ['obuka_view.xml'], 'demo_xml': [], 'test': [], 'installable': True, 'active': False, }
Fix asset url prefix config key
<?php namespace Craft; use InvalidArgumentException; use AssetRev\Utilities\FilenameRev; class AssetRevService extends BaseApplicationComponent { /** * Get the filename of a asset * * @param $file * @throws InvalidArgumentException * @return string */ public function getAssetFilename($file) { $revver = new FilenameRev( $this->parseEnvironmentString(craft()->config->get('manifestPath', 'assetrev')), $this->parseEnvironmentString(craft()->config->get('assetsBasePath', 'assetrev')), $this->parseEnvironmentString(craft()->config->get('assetUrlPrefix', 'assetrev')) ); $revver->setBasePath(CRAFT_BASE_PATH); return $revver->rev($file); } /** * Build an asset's URL * * @param string $basePath Base path to assets as defined in the plugin settings * @param string $file Asset filename * * @return string Path to the asset - environment variables having been replaced with their values. */ protected function parseEnvironmentString($string) { return craft()->config->parseEnvironmentString($string); } }
<?php namespace Craft; use InvalidArgumentException; use AssetRev\Utilities\FilenameRev; class AssetRevService extends BaseApplicationComponent { /** * Get the filename of a asset * * @param $file * @throws InvalidArgumentException * @return string */ public function getAssetFilename($file) { $revver = new FilenameRev( $this->parseEnvironmentString(craft()->config->get('manifestPath', 'assetrev')), $this->parseEnvironmentString(craft()->config->get('assetsBasePath', 'assetrev')), $this->parseEnvironmentString(craft()->config->get('assetPrefix', 'assetrev')) ); $revver->setBasePath(CRAFT_BASE_PATH); return $revver->rev($file); } /** * Build an asset's URL * * @param string $basePath Base path to assets as defined in the plugin settings * @param string $file Asset filename * * @return string Path to the asset - environment variables having been replaced with their values. */ protected function parseEnvironmentString($string) { return craft()->config->parseEnvironmentString($string); } }
Remove vendor bundle from here as well
var path = require('path'); var webpack = require('webpack'); module.exports = { entry: { ui: [ 'webpack-dev-server/client?http://localhost:3001', 'webpack/hot/only-dev-server', './lib/ui/main.js' ] }, output: { path: path.join(__dirname, 'dist'), filename: '[name].js', publicPath: '/dist/' }, module: { loaders: [{ test: /\.jsx?$/, exclude: /node_modules/, loaders: ['react-hot', 'babel'] },{ test: /\.json$/, loader: 'json' }] }, resolve: { alias: { bacon: "baconjs" } }, resolveLoader: { fallback: path.join(__dirname, "node_modules") }, plugins: [ new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/) ], externals: ['mdns'] }
var path = require('path'); var webpack = require('webpack'); module.exports = { entry: { ui: [ 'webpack-dev-server/client?http://localhost:3001', 'webpack/hot/only-dev-server', './lib/ui/main.js' ] }, output: { path: path.join(__dirname, 'dist'), filename: '[name].js', publicPath: '/dist/' }, module: { loaders: [{ test: /\.jsx?$/, exclude: /node_modules/, loaders: ['react-hot', 'babel'] },{ test: /\.json$/, loader: 'json' }] }, resolve: { alias: { bacon: "baconjs" } }, resolveLoader: { fallback: path.join(__dirname, "node_modules") }, plugins: [ new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'), new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/) ], externals: ['mdns'] }
Add missing callback to WebSocket 'send' wrapper Fix #301.
const EventEmitter = require('events'); // wrapper around the Node.js ws module // for use in browsers class WebSocketWrapper extends EventEmitter { constructor(url) { super(); this._ws = new WebSocket(url); this._ws.onopen = () => { this.emit('open'); }; this._ws.onclose = () => { this.emit('close'); }; this._ws.onmessage = (event) => { this.emit('message', event.data); }; this._ws.onerror = () => { this.emit('error', new Error('WebSocket error')); }; } close() { this._ws.close(); } send(data, callback) { try { this._ws.send(data); callback(); } catch (err) { callback(err); } } } module.exports = WebSocketWrapper;
const EventEmitter = require('events'); // wrapper around the Node.js ws module // for use in browsers class WebSocketWrapper extends EventEmitter { constructor(url) { super(); this._ws = new WebSocket(url); this._ws.onopen = () => { this.emit('open'); }; this._ws.onclose = () => { this.emit('close'); }; this._ws.onmessage = (event) => { this.emit('message', event.data); }; this._ws.onerror = () => { this.emit('error', new Error('WebSocket error')); }; } close() { this._ws.close(); } send(data) { this._ws.send(data); } } module.exports = WebSocketWrapper;
Use larger page size for ga4gh.
/*global require: false, module: false */ 'use strict'; var ga4gh = require('ga4gh-rxjs'); var clinvarMeta = require('./metadataStub'); var Rx = require('rx'); require('rx.experimental'); var _ = require('./underscore_ext'); // {url, dataset, chrom, start, end, fields} function variants({url, dataset, chrom, start, end}) { if (chrom.slice(0,3)==="chr"){ chrom=chrom.slice(3); } return ga4gh.all.variants(url, { variantSetIds: [dataset], pageSize: 1000, start: start, end: end, referenceName: chrom }); } // function variantSetsQuery (url) { return ga4gh.all.variantSets(url); } function metadata(host, dataset) { // stub, until the server is working var {variantSets} = clinvarMeta; //var md = _.find(variantSets, ds => ds.id === dataset).metadata; return Rx.Observable.return(variantSets); } module.exports = { variants: variants, variantSetsQuery: variantSetsQuery, metadata: metadata };
/*global require: false, module: false */ 'use strict'; var ga4gh = require('ga4gh-rxjs'); var clinvarMeta = require('./metadataStub'); var Rx = require('rx'); require('rx.experimental'); var _ = require('./underscore_ext'); // {url, dataset, chrom, start, end, fields} function variants({url, dataset, chrom, start, end}) { if (chrom.slice(0,3)==="chr"){ chrom=chrom.slice(3); } return ga4gh.all.variants(url, { variantSetIds: [dataset], start: start, end: end, referenceName: chrom }); } // function variantSetsQuery (url) { return ga4gh.all.variantSets(url); } function metadata(host, dataset) { // stub, until the server is working var {variantSets} = clinvarMeta; //var md = _.find(variantSets, ds => ds.id === dataset).metadata; return Rx.Observable.return(variantSets); } module.exports = { variants: variants, variantSetsQuery: variantSetsQuery, metadata: metadata };
Add cache expiration on class metadata
<?php namespace JPC\Test\MongoDB\ODM\Factory; use JPC\MongoDB\ODM\Factory\ClassMetadataFactory; use JPC\Test\MongoDB\ODM\Framework\TestCase; class ClassMetadataFactoryTest extends TestCase { /** * @var ClassMetadataFactory */ private $classMetadataFactory; public function setUp() { $this->classMetadataFactory = new ClassMetadataFactory(); } public function testGetMetadataForClassInexisting() { $this->expectException(\Exception::class); $this->classMetadataFactory->getMetadataForClass("Inexisting"); } public function testGetMetadataForClass() { $classMeta = $this->classMetadataFactory->getMetadataForClass("stdClass"); $this->assertInstanceOf(\JPC\MongoDB\ODM\Tools\ClassMetadata\ClassMetadata::class, $classMeta); } }
<?php namespace JPC\Test\MongoDB\ODM\Factory; use JPC\MongoDB\ODM\Factory\ClassMetadataFactory; use JPC\Test\MongoDB\ODM\Framework\TestCase; class ClassMetadataFactoryTest extends TestCase { /** * @var ClassMetadataFactory */ private $classMetadataFactory; public function setUp() { $this->classMetadataFactory = new ClassMetadataFactory(); } public function testGetMetadataForClassInexisting() { $this->expectException(\Exception::class); $this->classMetadataFactory->getMetadataForClass("Inexisting"); } public function testGetMetadataForClass() { $classMeta = $this->classMetadataFactory->getMetadataForClass("stdClass"); $this->assertInstanceOf(\JPC\MongoDB\ODM\Tools\ClassMetadata\ClassMetadata::class, $classMeta); $this->assertCount(1, $this->getPropertyValue($this->classMetadataFactory, "loadedMetadata")); } }
Make prosthetic-runner work with GAE SDK 1.6
from google.appengine.api import apiproxy_stub_map import os have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3')) if have_appserver: appid = os.environ.get('APPLICATION_ID') else: try: from google.appengine.tools import dev_appserver from .boot import PROJECT_DIR try: appconfig, unused = dev_appserver.LoadAppConfig(PROJECT_DIR, {}) except ValueError: # https://bitbucket.org/wkornewald/django-nonrel/issue/13/managepy-test-broken-with-gae-sdk-16 appconfig, unused, from_cache = dev_appserver.LoadAppConfig(PROJECT_DIR, {}) appid = appconfig.application except ImportError, e: raise Exception('Could not get appid. Is your app.yaml file missing? ' 'Error was: %s' % e) on_production_server = have_appserver and \ not os.environ.get('SERVER_SOFTWARE', '').lower().startswith('devel')
from google.appengine.api import apiproxy_stub_map import os have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3')) if have_appserver: appid = os.environ.get('APPLICATION_ID') else: try: from google.appengine.tools import dev_appserver from .boot import PROJECT_DIR appconfig, unused = dev_appserver.LoadAppConfig(PROJECT_DIR, {}) appid = appconfig.application except ImportError, e: raise Exception('Could not get appid. Is your app.yaml file missing? ' 'Error was: %s' % e) on_production_server = have_appserver and \ not os.environ.get('SERVER_SOFTWARE', '').lower().startswith('devel')
Store post data and query
<?php /** * @author Labs64 <netlicensing@labs64.com> * @license Apache-2.0 * @link http://netlicensing.io * @copyright 2017 Labs64 NetLicensing */ namespace NetLicensing; use Curl\Curl; class NetLicensingCurl extends Curl { public $data; public $query; /** * Build Post Data * * @access public * @param $data * * @return array|string */ public function buildPostData($data) { $this->data = $data; $query = parent::buildPostData($data); foreach ($data as $key => $value) { if (is_array($value)) $query = preg_replace('/&' . $key . '%5B%5D=/simU', '&' . $key . '=', $query); } $this->query = $query; return $query; } }
<?php /** * @author Labs64 <netlicensing@labs64.com> * @license Apache-2.0 * @link http://netlicensing.io * @copyright 2017 Labs64 NetLicensing */ namespace NetLicensing; use Curl\Curl; class NetLicensingCurl extends Curl { /** * Build Post Data * * @access public * @param $data * * @return array|string */ public function buildPostData($data) { $query = parent::buildPostData($data); foreach ($data as $key => $value) { if (is_array($value)) $query = preg_replace('/&' . $key . '%5B%5D=/simU', '&' . $key . '=', $query); } return $query; } }
Add export of Cancel icon
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ export { Button, ProgressBar } from 'react-native-ui-components'; export { AutocompleteSelector } from './AutocompleteSelector'; export { ExpiryTextInput } from './ExpiryTextInput'; export { FinaliseButton } from './FinaliseButton'; export { GenericChoiceList } from './GenericChoiceList'; export { IconCell } from './IconCell'; export { NavigationBar } from './NavigationBar'; export { OnePressButton } from './OnePressButton'; export { PageButton } from './PageButton'; export { PageInfo } from './PageInfo'; export { SequentialSteps } from './SequentialSteps'; export { Spinner } from './Spinner'; export { SyncState } from './SyncState'; export { TextEditor } from './TextEditor'; export { TextInput } from './TextInput'; export { ToggleBar } from './ToggleBar'; export { ToggleSelector } from './ToggleSelector'; export { NewExpiryDateInput } from './NewExpiryDateInput'; export { SortAscIcon, SortNeutralIcon, SortDescIcon, CheckedComponent, UncheckedComponent, DisabledCheckedComponent, DisabledUncheckedComponent, Cancel, } from './icons';
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ export { Button, ProgressBar } from 'react-native-ui-components'; export { AutocompleteSelector } from './AutocompleteSelector'; export { ExpiryTextInput } from './ExpiryTextInput'; export { FinaliseButton } from './FinaliseButton'; export { GenericChoiceList } from './GenericChoiceList'; export { IconCell } from './IconCell'; export { NavigationBar } from './NavigationBar'; export { OnePressButton } from './OnePressButton'; export { PageButton } from './PageButton'; export { PageInfo } from './PageInfo'; export { SequentialSteps } from './SequentialSteps'; export { Spinner } from './Spinner'; export { SyncState } from './SyncState'; export { TextEditor } from './TextEditor'; export { TextInput } from './TextInput'; export { ToggleBar } from './ToggleBar'; export { ToggleSelector } from './ToggleSelector'; export { NewExpiryDateInput } from './NewExpiryDateInput'; export { SortAscIcon, SortNeutralIcon, SortDescIcon, CheckedComponent, UncheckedComponent, DisabledCheckedComponent, DisabledUncheckedComponent, } from './icons';
Handle container types for discrete-time expr
"""This module provides discrete-time support. It introduces three special variables: n for discrete-time sequences k for discrete-frequency sequences z for z-transforms. Copyright 2020--2021 Michael Hayes, UCECE """ import sympy as sym from .sym import sympify from .nexpr import nexpr, n from .kexpr import kexpr, k from .zexpr import zexpr, z from .dsym import nsym, ksym, zsym, dt, df from .expr import expr as expr1 from .transform import transform as transform1 from .transform import call as call1 from .functions import Function from .ztransform import * from .seq import seq def expr(arg, **assumptions): # Handle container args. if not isinstance(arg, str) and hasattr(arg, '__iter__'): return expr1(arg, **assumptions) expr = sympify(arg, **assumptions) symbols = expr.free_symbols if nsym in symbols: return nexpr(expr, **assumptions) elif ksym in symbols: return kexpr(expr, **assumptions) elif zsym in symbols: return zexpr(expr, **assumptions) return expr1(arg, **assumptions)
"""This module provides discrete-time support. It introduces three special variables: n for discrete-time sequences k for discrete-frequency sequences z for z-transforms. Copyright 2020--2021 Michael Hayes, UCECE """ import sympy as sym from .sym import sympify from .nexpr import nexpr, n from .kexpr import kexpr, k from .zexpr import zexpr, z from .dsym import nsym, ksym, zsym, dt, df from .expr import expr as expr1 from .transform import transform as transform1 from .transform import call as call1 from .functions import Function from .ztransform import * from .seq import seq def expr(arg, **assumptions): expr = sympify(arg, **assumptions) symbols = expr.free_symbols if nsym in symbols: return nexpr(expr, **assumptions) elif ksym in symbols: return kexpr(expr, **assumptions) elif zsym in symbols: return zexpr(expr, **assumptions) return expr1(arg, **assumptions)
Add check for folder to save checkpoints
import os import tensorflow as tf import driving_data import model LOGDIR = './save' sess = tf.InteractiveSession() loss = tf.reduce_mean(tf.square(tf.sub(model.y_, model.y))) train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss) sess.run(tf.initialize_all_variables()) saver = tf.train.Saver() #train over the dataset about 30 times for i in range(int(driving_data.num_images * 0.3)): xs, ys = driving_data.LoadBatch(100) train_step.run(feed_dict={model.x: xs, model.y_: ys, model.keep_prob: 0.8}) if i % 10 == 0: print("step %d, train loss %g"%(i, loss.eval(feed_dict={ model.x:xs, model.y_: ys, model.keep_prob: 1.0}))) if i % 100 == 0: if not os.path.exists(LOGDIR): os.makedirs(LOGDIR) checkpoint_path = os.path.join(LOGDIR, "model.ckpt") filename = saver.save(sess, checkpoint_path) print("Model saved in file: %s" % filename)
import tensorflow as tf import driving_data import model sess = tf.InteractiveSession() loss = tf.reduce_mean(tf.square(tf.sub(model.y_, model.y))) train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss) sess.run(tf.initialize_all_variables()) saver = tf.train.Saver() #train over the dataset about 30 times for i in range(int(driving_data.num_images * 0.3)): xs, ys = driving_data.LoadBatch(100) train_step.run(feed_dict={model.x: xs, model.y_: ys, model.keep_prob: 0.8}) if i % 10 == 0: print("step %d, train loss %g"%(i, loss.eval(feed_dict={ model.x:xs, model.y_: ys, model.keep_prob: 1.0}))) if i % 100 == 0: save_path = saver.save(sess, "save/model.ckpt") print("Model saved in file: %s" % save_path)
Fix undefined property when no user logged in
<!doctype html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="csrf-token" content="{{ csrf_token() }}"> <meta name="api-base-url" content="{{ url('/api') }}"> @if(Auth::user()) <meta name="api-token" content="{{ Auth::user()->api_token }}"> @endif <title>@yield('title') | {{ config('app.name') }}</title> <link href="{{ asset('css/app.css') }}" rel="stylesheet"> <link href="{{ asset('css/open-iconic-bootstrap.css') }}" rel="stylesheet"> <link href="{{ asset('css/tempusdominus-bootstrap-4.css') }}" rel="stylesheet"> <link href="{{ asset('css/font-awesome.css') }}" rel="stylesheet"> </head> <body> <!-- Scripts --> <script src="{{ asset('js/app.js') }}"></script>
<!doctype html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="csrf-token" content="{{ csrf_token() }}"> <meta name="api-base-url" content="{{ url('/api') }}"> <meta name="api-token" content="{{ Auth::user()->api_token }}"> <title>@yield('title') | {{ config('app.name') }}</title> <link href="{{ asset('css/app.css') }}" rel="stylesheet"> <link href="{{ asset('css/open-iconic-bootstrap.css') }}" rel="stylesheet"> <link href="{{ asset('css/tempusdominus-bootstrap-4.css') }}" rel="stylesheet"> <link href="{{ asset('css/font-awesome.css') }}" rel="stylesheet"> </head> <body> <!-- Scripts --> <script src="{{ asset('js/app.js') }}"></script>
Make setup.py smoke test more specific again as requested in review
# # Copyright (c) 2009 Testrepository Contributors # # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause # license at the users choice. A copy of both licenses are available in the # project source as Apache-2.0 and BSD. You may not use this file except in # compliance with one of these two licences. # # Unless required by applicable law or agreed to in writing, software # distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # license you chose for the specific language governing permissions and # limitations under that license. """Tests for setup.py.""" import doctest import os import subprocess import sys from testtools import ( TestCase, ) from testtools.matchers import ( DocTestMatches, ) class TestCanSetup(TestCase): def test_bdist(self): # Single smoke test to make sure we can build a package. path = os.path.join(os.path.dirname(__file__), '..', '..', 'setup.py') proc = subprocess.Popen([sys.executable, path, 'bdist'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) output, _ = proc.communicate() self.assertEqual(0, proc.returncode) self.assertThat(output, DocTestMatches("""... running install_scripts ... adding '...testr' ...""", doctest.ELLIPSIS))
# # Copyright (c) 2009 Testrepository Contributors # # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause # license at the users choice. A copy of both licenses are available in the # project source as Apache-2.0 and BSD. You may not use this file except in # compliance with one of these two licences. # # Unless required by applicable law or agreed to in writing, software # distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # license you chose for the specific language governing permissions and # limitations under that license. """Tests for setup.py.""" import doctest import os import subprocess import sys from testtools import ( TestCase, ) from testtools.matchers import ( DocTestMatches, ) class TestCanSetup(TestCase): def test_bdist(self): # Single smoke test to make sure we can build a package. path = os.path.join(os.path.dirname(__file__), '..', '..', 'setup.py') proc = subprocess.Popen([sys.executable, path, 'bdist'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output, _ = proc.communicate() self.assertEqual(0, proc.returncode) self.assertThat(output, DocTestMatches("...running bdist...", doctest.ELLIPSIS))
Add page_url parameter to the init_folder_list function
/* * awa-storages -- Storages and folders * Copyright (C) 2012, 2016 Stephane Carrez * Written by Stephane Carrez (Stephane.Carrez@gmail.com) * * 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. */ var AWA = {}; function init_folder_list(id, idCreate, idCurrent, page_url) { $(id).list({ actionId: null, itemPrefix: 'folder-', editUrl: contextPath + '/storages/forms/create-folder-form.html', currentItem: '#folder-' + idCurrent, selectAction: function(element, item) { var id = element.getSelectedId(item); return ASF.Update(this, contextPath + page_url + '?folderId=' + id, '#document-list-editor'); } }); }
/* * awa-storages -- Storages and folders * Copyright (C) 2012 Stephane Carrez * Written by Stephane Carrez (Stephane.Carrez@gmail.com) * * 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. */ var AWA = {}; function init_folder_list(id, idCreate, idCurrent) { $(id).list({ actionId: null, itemPrefix: 'folder-', editUrl: contextPath + '/storages/forms/create-folder-form.html', currentItem: '#folder-' + idCurrent, selectAction: function(element, item) { var id = element.getSelectedId(item); return ASF.Update(this, contextPath + '/storages/lists/documents.html?folderId=' + id, '#document-list-editor'); } }); }
Mark routing exception as deprecated. I don't want to change RedirectRoute or RoutingMiddleware at this time as I don't want to break compatibility over a small value change.
<?php declare(strict_types=1); /** * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * @link https://cakephp.org CakePHP(tm) Project * @since 3.2.0 * @license https://opensource.org/licenses/mit-license.php MIT License */ namespace Cake\Routing\Exception; use Cake\Core\Exception\Exception; /** * An exception subclass used by the routing layer to indicate * that a route has resolved to a redirect. * * The URL and status code are provided as constructor arguments. * * ``` * throw new RedirectException('http://example.com/some/path', 301); * ``` * * If you need a more general purpose redirect exception use * Cake\Http\Exception\RedirectException instead of this class. * * @deprecated 4.1.0 Use Cake\Http\Exception\RedirectException instead. */ class RedirectException extends Exception { /** * @inheritDoc */ protected $_defaultCode = 302; }
<?php declare(strict_types=1); /** * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * @link https://cakephp.org CakePHP(tm) Project * @since 3.2.0 * @license https://opensource.org/licenses/mit-license.php MIT License */ namespace Cake\Routing\Exception; use Cake\Core\Exception\Exception; /** * An exception subclass used by the routing layer to indicate * that a route has resolved to a redirect. * * The URL and status code are provided as constructor arguments. * * ``` * throw new RedirectException('http://example.com/some/path', 301); * ``` * * If you need a more general purpose redirect exception use * Cake\Http\Exception\RedirectException instead of this class. */ class RedirectException extends Exception { /** * @inheritDoc */ protected $_defaultCode = 302; }
Add 'type' field to tab enumeration JSON protocol Review URL: https://codereview.chromium.org/12036084
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.sdk.internal.wip.protocol.input; import java.util.List; import org.chromium.sdk.internal.protocolparser.JsonOptionalField; import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException; import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting; import org.chromium.sdk.internal.protocolparser.JsonType; @JsonType(subtypesChosenManually=true) public interface WipTabList { @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException; @JsonType interface TabDescription { String faviconUrl(); String title(); String url(); String thumbnailUrl(); // TODO: consider adding enum here String type(); @JsonOptionalField String devtoolsFrontendUrl(); @JsonOptionalField String webSocketDebuggerUrl(); } }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.sdk.internal.wip.protocol.input; import java.util.List; import org.chromium.sdk.internal.protocolparser.JsonOptionalField; import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException; import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting; import org.chromium.sdk.internal.protocolparser.JsonType; @JsonType(subtypesChosenManually=true) public interface WipTabList { @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException; @JsonType interface TabDescription { String faviconUrl(); String title(); String url(); String thumbnailUrl(); @JsonOptionalField String devtoolsFrontendUrl(); @JsonOptionalField String webSocketDebuggerUrl(); } }
Make sure that user details are valid JSON
from django.db import models from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.contrib import admin from settings.models import VotingSystem import json # Create your models here. class Admin(models.Model): user = models.ForeignKey(User) system = models.ForeignKey(VotingSystem) def __unicode__(self): return u'[%s] %s' % (self.system.machine_name, self.user) class SuperAdmin(models.Model): user = models.ForeignKey(User) def __unicode__(self): return u'%s' % (self.user) class UserProfile(models.Model): user = models.OneToOneField(User, related_name="profile") details = models.TextField() def __unicode__(self): return u'[Profile] %s' % (self.user.username) def clean(self): # make sure that the details are a valid json object try: json.loads(self.details) except: raise ValidationError({ 'details': ValidationError('Details needs to be a valid JSON object', code='invalid') }) admin.site.register(Admin) admin.site.register(SuperAdmin) admin.site.register(UserProfile)
from django.db import models from django.contrib.auth.models import User from django.contrib import admin from settings.models import VotingSystem # Create your models here. class Admin(models.Model): user = models.ForeignKey(User) system = models.ForeignKey(VotingSystem) def __unicode__(self): return u'[%s] %s' % (self.system.machine_name, self.user) class SuperAdmin(models.Model): user = models.ForeignKey(User) def __unicode__(self): return u'%s' % (self.user) class UserProfile(models.Model): user = models.OneToOneField(User, related_name="profile") details = models.TextField() def __unicode__(self): return u'[Profile] %s' % (self.user.username) admin.site.register(Admin) admin.site.register(SuperAdmin) admin.site.register(UserProfile)
Prepare for PyCon Belarus 2018
# -*- coding: utf-8 -*- """ Eve Demo ~~~~~~~~ A demostration of a simple API powered by Eve REST API. The live demo is available at eve-demo.herokuapp.com. Please keep in mind that the it is running on Heroku's free tier using a free MongoHQ sandbox, which means that the first request to the service will probably be slow. The database gets a reset every now and then. :copyright: (c) 2016 by Nicola Iarocci. :license: BSD, see LICENSE for more details. """ from eve import Eve def codemotion(endpoint, response): for document in response['_items']: document['PYCON BELARUS'] = 'IS SO FREAKING COOL!' app = Eve() app.on_fetched_resource += codemotion if __name__ == '__main__': app.run()
# -*- coding: utf-8 -*- """ Eve Demo ~~~~~~~~ A demostration of a simple API powered by Eve REST API. The live demo is available at eve-demo.herokuapp.com. Please keep in mind that the it is running on Heroku's free tier using a free MongoHQ sandbox, which means that the first request to the service will probably be slow. The database gets a reset every now and then. :copyright: (c) 2016 by Nicola Iarocci. :license: BSD, see LICENSE for more details. """ from eve import Eve def codemotion(endpoint, response): for document in response['_items']: document['CODEMOTION'] = 'IS SO FREAKING COOL!' app = Eve() app.on_fetched_resource += codemotion if __name__ == '__main__': app.run()
Fix pep8 problem, extra new line after header Change-Id: I6503a000202d321300c5f3cea708d18cf228e77d
#! /usr/bin/env python # Copyright Lajos Katona # # 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. def summary(start=1, end=10): result = 0 for i in range(start, end): result += i return result if __name__ == '__main__': print(summary(1, 15))
#! /usr/bin/env python # Copyright Lajos Katona # # 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. def summary(start=1, end=10): result = 0 for i in range(start, end): result += i return result if __name__ == '__main__': print(summary(1, 15))
Add Astral shift to the absorbed ThroughputTracker
import SPELLS from 'common/SPELLS'; import CoreCooldownThroughputTracker, { BUILT_IN_SUMMARY_TYPES } from 'parser/shared/modules/CooldownThroughputTracker'; class CooldownThroughputTracker extends CoreCooldownThroughputTracker { static cooldownSpells = [ ...CoreCooldownThroughputTracker.cooldownSpells, { spell: SPELLS.ASCENDANCE_TALENT_ENHANCEMENT, summary: [ BUILT_IN_SUMMARY_TYPES.DAMAGE, ], }, { spell: SPELLS.ASTRAL_SHIFT, summary: [ BUILT_IN_SUMMARY_TYPES.ABSORBED, ], }, { spell: SPELLS.BERSERKING, summary: [ BUILT_IN_SUMMARY_TYPES.DAMAGE, ], }, ]; trackEvent(event) { this.activeCooldowns.forEach((cooldown) => { if (event.ability.guid !== SPELLS.DOOM_VORTEX.id) { cooldown.events.push(event); } }); } } export default CooldownThroughputTracker;
import SPELLS from 'common/SPELLS'; import CoreCooldownThroughputTracker, { BUILT_IN_SUMMARY_TYPES } from 'parser/shared/modules/CooldownThroughputTracker'; class CooldownThroughputTracker extends CoreCooldownThroughputTracker { static cooldownSpells = [ ...CoreCooldownThroughputTracker.cooldownSpells, { spell: SPELLS.ASCENDANCE_TALENT_ENHANCEMENT, summary: [ BUILT_IN_SUMMARY_TYPES.DAMAGE, ], }, { spell: SPELLS.BERSERKING, summary: [ BUILT_IN_SUMMARY_TYPES.DAMAGE, ], }, ]; trackEvent(event) { this.activeCooldowns.forEach((cooldown) => { if (event.ability.guid !== SPELLS.DOOM_VORTEX.id) { cooldown.events.push(event); } }); } } export default CooldownThroughputTracker;
Apply werkzeug ProxyFix so that request.remote_addr is correct.
import gevent.monkey gevent.monkey.patch_all() import logging handler = logging.StreamHandler() log_format = '{levelname}:etiquette.{module}.{funcName}: {message}' handler.setFormatter(logging.Formatter(log_format, style='{')) logging.getLogger().addHandler(handler) import etiquette_flask import gevent.pywsgi import gevent.wsgi import sys import werkzeug.contrib.fixers etiquette_flask.site.wsgi_app = werkzeug.contrib.fixers.ProxyFix(etiquette_flask.site.wsgi_app) if len(sys.argv) == 2: port = int(sys.argv[1]) else: port = 5000 if port == 443: http = gevent.pywsgi.WSGIServer( listener=('0.0.0.0', port), application=etiquette_flask.site, keyfile='D:\\git\\etiquette\\frontends\\etiquette_flask\\https\\etiquette.key', certfile='D:\\git\\etiquette\\frontends\\etiquette_flask\\https\\etiquette.crt', ) else: http = gevent.pywsgi.WSGIServer( listener=('0.0.0.0', port), application=etiquette_flask.site, ) print('Starting server on port %d' % port) http.serve_forever()
import gevent.monkey gevent.monkey.patch_all() import logging handler = logging.StreamHandler() log_format = '{levelname}:etiquette.{module}.{funcName}: {message}' handler.setFormatter(logging.Formatter(log_format, style='{')) logging.getLogger().addHandler(handler) import etiquette_flask import gevent.pywsgi import gevent.wsgi import sys if len(sys.argv) == 2: port = int(sys.argv[1]) else: port = 5000 if port == 443: http = gevent.pywsgi.WSGIServer( listener=('0.0.0.0', port), application=etiquette_flask.site, keyfile='D:\\git\\etiquette\\frontends\\etiquette_flask\\https\\etiquette.key', certfile='D:\\git\\etiquette\\frontends\\etiquette_flask\\https\\etiquette.crt', ) else: http = gevent.pywsgi.WSGIServer( listener=('0.0.0.0', port), application=etiquette_flask.site, ) print('Starting server on port %d' % port) http.serve_forever()
Add ability to go to individual invoice page
from django.conf.urls import url from django.views.generic import RedirectView from django.core.urlresolvers import reverse_lazy from .views import AppView, reports_export # Instead of using a wildcard for our app views we insert them one at a time # for naming purposes. This is so that users can change urls if they want and # the change will propagate throughout the site. urlpatterns = [ url(r'^reports/export/$', reports_export, name='reports-export'), url(r'^timesheet/$', AppView.as_view(), name='timesheet'), url(r'^clients/$', AppView.as_view(), name='clients'), url(r'^tasks/$', AppView.as_view(), name='tasks'), url(r'^reports/$', AppView.as_view(), name='reports'), url(r'^invoices/$', AppView.as_view(), name='invoices'), url(r'^invoices/([0-9]+)/$', AppView.as_view(), name='invoices'), url( r'^$', RedirectView.as_view(url=reverse_lazy('timesheet'), permanent=False), name='dashboard' ), ]
from django.conf.urls import url from django.views.generic import RedirectView from django.core.urlresolvers import reverse_lazy from .views import AppView, reports_export # Instead of using a wildcard for our app views we insert them one at a time # for naming purposes. This is so that users can change urls if they want and # the change will propagate throughout the site. urlpatterns = [ url(r'^reports/export/$', reports_export, name='reports-export'), url(r'^timesheet/$', AppView.as_view(), name='timesheet'), url(r'^clients/$', AppView.as_view(), name='clients'), url(r'^tasks/$', AppView.as_view(), name='tasks'), url(r'^reports/$', AppView.as_view(), name='reports'), url(r'^invoices/$', AppView.as_view(), name='invoices'), url( r'^$', RedirectView.as_view(url=reverse_lazy('timesheet'), permanent=False), name='dashboard' ), ]
Reset feedback after completing request
'use strict'; angular.module('personality.controller', []) .controller('PersonalityController', [ '$scope', '$http', 'personalityService', ($scope, $http, personalityService) => { $scope.roastOptions = [ 'light', 'medium', 'dark' ]; $scope.getData = () => { $http.put('/api/watson/' + $scope.twitter) .success(data => { $scope.array = data; $scope.preference = personalityService.determinePreference(data); $scope.curiosity = personalityService.getCuriosityPercentage(data); $scope.liberty = personalityService.getLibertyPercentage(data); }) .error(err => { console.log(err); }) .finally(() => resetFeedback()); }; $scope.submitFeedback = actualPreference => { $http .post('/api/feedback', { twitter_handle: $scope.twitter, expected_preference: $scope.preference, actual_preference: actualPreference }) .then(() => $scope.feedbackSubmitted = true); }; $scope.showRoastFeedbackOptions = () => { $scope.roastFeedbackVisible = true; }; function resetFeedback() { console.log('resetting feedback'); $scope.feedbackSubmitted = false; $scope.roastFeedbackVisible = false; } }]);
'use strict'; angular.module('personality.controller', []) .controller('PersonalityController', [ '$scope', '$http', 'personalityService', ($scope, $http, personalityService) => { $scope.roastOptions = [ 'light', 'medium', 'dark' ]; $scope.getData = () => { resetFeedback(); $http.put('/api/watson/' + $scope.twitter) .success(data => { $scope.array = data; $scope.preference = personalityService.determinePreference(data); $scope.curiosity = personalityService.getCuriosityPercentage(data); $scope.liberty = personalityService.getLibertyPercentage(data); }) .error(err => { console.log(err); }); }; $scope.submitFeedback = actualPreference => { $http .post('/api/feedback', { twitter_handle: $scope.twitter, expected_preference: $scope.preference, actual_preference: actualPreference }) .then(() => $scope.feedbackSubmitted = true); }; $scope.showRoastFeedbackOptions = () => { $scope.roastFeedbackVisible = true; }; function resetFeedback() { console.log('resetting feedback'); $scope.feedbackSubmitted = false; $scope.roastFeedbackVisible = false; } }]);
Fix form submission to handle CORS errors.
$(function() { var form = $('form'); var inputs = form.find(':input'); var required = inputs.filter('[required]'); var submit = inputs.filter('[type=submit]'); var confirmation = form.find('.confirmation'); // On touch devices, the links with drop-downs aren't normally hoverable, so // we need to disable their action to allow them to expand the drop-down only. if ('ontouchstart' in document.documentElement) { $('.menu-item:has(.menu-dropdown) > a').click(function() { return false; }); } // Primitive form validation; inform immediately on missing a required field required.blur(function() { var input = $(this); input.toggleClass('invalid', !input.val()); }); // Keep the submit button disabled until everything is valid required.keyup(function() { var valid = true; required.each(function() { return valid &= !!$(this).val(); }); submit.prop('disabled', !valid); }); // Submit asynchronously and show a confirmation message form.submit(function(event) { var url = form.attr('action'); var data = form.serialize(); confirmation.hide(); inputs.prop('disabled', true); $.post(url, data).always(function() { window.console.log('You can ignore the error above.'); inputs.prop('disabled', false); confirmation.show(); }); event.preventDefault(); return false; }); });
$(function() { var form = $('form'); var inputs = form.find(':input'); var required = inputs.filter('[required]'); var submit = inputs.filter('[type=submit]'); var confirmation = form.find('.confirmation'); // On touch devices, the links with drop-downs aren't normally hoverable, so // we need to disable their action to allow them to expand the drop-down only. if ('ontouchstart' in document.documentElement) { $('.menu-item:has(.menu-dropdown) > a').click(function() { return false; }); } // Primitive form validation; inform immediately on missing a required field required.blur(function() { var input = $(this); input.toggleClass('invalid', !input.val()); }); // Keep the submit button disabled until everything is valid required.keyup(function() { var valid = true; required.each(function() { return valid &= !!$(this).val(); }); submit.prop('disabled', !valid); }); // Submit asynchronously and show a confirmation message form.submit(function(event) { event.preventDefault(); confirmation.hide(); inputs.prop('disabled', true); var url = form.attr('action'); $.post(url, form.serialize()).done(function() { inputs.prop('disabled', false); confirmation.show(); }); return false; }); });
Update tour tests to use enzyme.
/* Copyright (C) 2017 Canonical Ltd. */ 'use strict'; const React = require('react'); const enzyme = require('enzyme'); const Tour = require('./tour'); const SvgIcon = require('../../svg-icon/svg-icon'); describe('Tour', () => { const renderComponent = (options = {}) => enzyme.shallow( <Tour close={options.close || sinon.stub()} endTour={options.endTour || sinon.stub()} staticURL={options.staticURL || '/static/'} /> ); it('renders', () => { const wrapper = renderComponent(); const expected = ( <span className="back-to-help" onClick={wrapper.find('.back-to-help').prop('onClick')}> <SvgIcon className="back-to-help__icon" name="chevron_down_16" size="16" /> Back to GUI help </span> ); assert.compareJSX(wrapper.find('.back-to-help'), expected); assert.deepEqual(wrapper.find('Lightbox').prop('extraClasses'), ['tour']); // Slides assert.equal(wrapper.find('.tour__slide').length, 7); }); });
/* Copyright (C) 2017 Canonical Ltd. */ 'use strict'; const React = require('react'); const Tour = require('./tour'); const SvgIcon = require('../../svg-icon/svg-icon'); const jsTestUtils = require('../../../utils/component-test-utils'); describe('Tour', () => { it('renders', () => { const renderer = jsTestUtils.shallowRender( <Tour close={sinon.stub()} endTour={sinon.stub()} staticURL="" />, true ); const output = renderer.getRenderOutput(); expect(output.props.children[0]).toEqualJSX( <span className="back-to-help" onClick={sinon.stub()}> <SvgIcon className="back-to-help__icon" name="chevron_down_16" size="16" /> Back to GUI help </span> ); assert.deepEqual(output.props.children[1].props.extraClasses, ['tour']); // Slides const slides = output.props.children[1].props.children; assert.isDefined(slides); assert.equal(slides.length, 7); slides.forEach(slide => { assert.deepEqual(slide.props.className, 'tour__slide'); }); }); });
Add alternative solution to confirmEdning.js
function confirmEnding(str, target) { if (str.split(" ").length > 1){ var lastChar = str.split(" "); var lastWord = lastChar[lastChar.length - 1]; if (target.length !== lastWord.length){ console.log(lastWord.slice(lastWord.length - target.length) === target); } else{ console.log(lastChar[lastChar.length - 1] === target); } } else{ console.log(str[str.length -1] === target); } } // Alternate Solution // function confirmEnding(str, target) { // return str.substr(-target.length) === target; // } confirmEnding("Bastian", "n"); confirmEnding("Connor", "n"); confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification"); confirmEnding("He has to give me a new name", "name"); confirmEnding("Open sesame", "same"); confirmEnding("Open sesame", "pen"); confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain");
function confirmEnding(str, target) { if (str.split(" ").length > 1){ var lastChar = str.split(" "); var lastWord = lastChar[lastChar.length - 1]; if (target.length !== lastWord.length){ console.log(lastWord.slice(lastWord.length - target.length) === target); } else{ console.log(lastChar[lastChar.length - 1] === target); } } else{ console.log(str[str.length -1] === target); } } confirmEnding("Bastian", "n"); confirmEnding("Connor", "n"); confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification"); confirmEnding("He has to give me a new name", "name"); confirmEnding("Open sesame", "same"); confirmEnding("Open sesame", "pen"); confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain");
samples: Add quickstarts to root module. Fixes checkstyle errors in samples.
/* Copyright 2016, Google, Inc. 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.example.translate; // [START translate_quickstart] // Imports the Google Cloud client library import com.google.cloud.translate.Translate; import com.google.cloud.translate.Translate.TranslateOption; import com.google.cloud.translate.TranslateOptions; import com.google.cloud.translate.Translation; public class QuickstartSample { public static void main(String... args) throws Exception { // Instantiates a client Translate translate = TranslateOptions.builder().apiKey("YOUR_API_KEY").build().service(); // The text to translate String text = "Hello, world!"; // Translates some text into Russian Translation translation = translate.translate( text, TranslateOption.sourceLanguage("en"), TranslateOption.targetLanguage("ru")); System.out.printf("Text: %s%n", text); System.out.printf("Translation: %s%n", translation.translatedText()); } } // [END translate_quickstart]
/* Copyright 2016, Google, Inc. 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.example.translate; // [START translate_quickstart] // Imports the Google Cloud client library import com.google.cloud.translate.Translate; import com.google.cloud.translate.Translate.TranslateOption; import com.google.cloud.translate.TranslateOptions; import com.google.cloud.translate.Translation; public class QuickstartSample { public static void main(String... args) throws Exception { // Instantiates a client Translate translate = TranslateOptions.builder().apiKey("YOUR_API_KEY").build().service(); // The text to translate String text = "Hello, world!"; // Translates some text into Russian Translation translation = translate.translate( text, TranslateOption.sourceLanguage("en"), TranslateOption.targetLanguage("ru") ); System.out.printf("Text: %s%n", text); System.out.printf("Translation: %s%n", translation.translatedText()); } } // [END translate_quickstart]
Delete the unused LOG code Change-Id: Ief253cdd226f8c2688429b0ff00785151a99759b
# Copyright 2017 Objectif Libre # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.utils.translation import ugettext_lazy as _ from horizon import forms from cloudkittydashboard.api import cloudkitty as api class EditPriorityForm(forms.SelfHandlingForm): priority = forms.IntegerField(label=_("Priority"), required=True) def handle(self, request, data): ck_client = api.cloudkittyclient(request) return ck_client.modules.update( module_id=self.initial["module_id"], priority=data["priority"] )
# Copyright 2017 Objectif Libre # # 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. import logging from django.utils.translation import ugettext_lazy as _ from horizon import forms from cloudkittydashboard.api import cloudkitty as api LOG = logging.getLogger(__name__) class EditPriorityForm(forms.SelfHandlingForm): priority = forms.IntegerField(label=_("Priority"), required=True) def handle(self, request, data): ck_client = api.cloudkittyclient(request) return ck_client.modules.update( module_id=self.initial["module_id"], priority=data["priority"] )
Correct number of samples per web worker.
export const simulate = (expr, inputs, numSamples) => { const data = {expr, numSamples: numSamples/window.workers.length, inputs} return Promise.all(window.workers.map(worker => simulateOnWorker(worker, data))).then( (results) => { let finalResult = {values: [], errors: []} for (let result of results) { finalResult.values = finalResult.values.concat(result.values) finalResult.errors = finalResult.errors.concat(result.errors) } return finalResult } ) } const simulateOnWorker = (worker, data) => { return new Promise( (resolve, reject) => { worker.onmessage = ({data}) => {resolve(JSON.parse(data))} worker.postMessage(JSON.stringify(data)) } ) }
export const simulate = (expr, inputs, numSamples) => { const data = {expr, numSamples: numSamples/4, inputs} return Promise.all(window.workers.map(worker => simulateOnWorker(worker, data))).then( (results) => { let finalResult = {values: [], errors: []} for (let result of results) { finalResult.values = finalResult.values.concat(result.values) finalResult.errors = finalResult.errors.concat(result.errors) } return finalResult } ) } const simulateOnWorker = (worker, data) => { return new Promise( (resolve, reject) => { worker.onmessage = ({data}) => {resolve(JSON.parse(data))} worker.postMessage(JSON.stringify(data)) } ) }
Use super in TweepError initialization
# Tweepy # Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. from __future__ import print_function import six class TweepError(Exception): """Tweepy exception""" def __init__(self, reason, response=None, api_code=None): self.reason = six.text_type(reason) self.response = response self.api_code = api_code super(TweepError, self).__init__(self, reason) def __str__(self): return self.reason def is_rate_limit_error_message(message): """Check if the supplied error message belongs to a rate limit error.""" return isinstance(message, list) \ and len(message) > 0 \ and 'code' in message[0] \ and message[0]['code'] == 88 class RateLimitError(TweepError): """Exception for Tweepy hitting the rate limit.""" # RateLimitError has the exact same properties and inner workings # as TweepError for backwards compatibility reasons. pass
# Tweepy # Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. from __future__ import print_function import six class TweepError(Exception): """Tweepy exception""" def __init__(self, reason, response=None, api_code=None): self.reason = six.text_type(reason) self.response = response self.api_code = api_code Exception.__init__(self, reason) def __str__(self): return self.reason def is_rate_limit_error_message(message): """Check if the supplied error message belongs to a rate limit error.""" return isinstance(message, list) \ and len(message) > 0 \ and 'code' in message[0] \ and message[0]['code'] == 88 class RateLimitError(TweepError): """Exception for Tweepy hitting the rate limit.""" # RateLimitError has the exact same properties and inner workings # as TweepError for backwards compatibility reasons. pass
Add whether to empty judgments
// Copyright 2014 The goyy Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package entity import ( "gopkg.in/goyy/goyy.v0/util/bytes" ) type String struct { base value []byte } func (me *String) Value() string { if me.value == nil || len(me.value) == 0 { return "" } return string(me.value) } func (me *String) ValuePtr() *[]byte { return &me.value } func (me *String) SetValue(v string) { me.value = []byte(v) me.field.SetModified(true) } func (me *String) SetDefault(v string) error { me.value = []byte(v) return nil } func (me *String) SetString(v string) error { if err := me.SetDefault(v); err != nil { return err } else { me.field.SetModified(true) return nil } } func (me *String) String() string { out := bytes.TrimRightNul(me.value) return string(out) } func (me *String) Name() string { return "string" }
// Copyright 2014 The goyy Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package entity import ( "gopkg.in/goyy/goyy.v0/util/bytes" ) type String struct { base value []byte } func (me *String) Value() string { return string(me.value) } func (me *String) ValuePtr() *[]byte { return &me.value } func (me *String) SetValue(v string) { me.value = []byte(v) me.field.SetModified(true) } func (me *String) SetDefault(v string) error { me.value = []byte(v) return nil } func (me *String) SetString(v string) error { if err := me.SetDefault(v); err != nil { return err } else { me.field.SetModified(true) return nil } } func (me *String) String() string { out := bytes.TrimRightNul(me.value) return string(out) } func (me *String) Name() string { return "string" }
Strengthen the unit test for ClassPathScanner. Show that the classes returned will contain at least one of the classes annotated with immutable, and doesn't happen to pick up a mutable class on the same classpath. /cc @lasombra
package org.mutabilitydetector; /* * #%L * MutabilityDetector * %% * Copyright (C) 2008 - 2015 Graham Allan * %% * 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. * #L% */ import org.junit.Test; import org.mutabilitydetector.benchmarks.ImmutableExample; import org.mutabilitydetector.benchmarks.settermethod.MutableByHavingSetterMethod; import org.mutabilitydetector.classpath.ClassPathScanner; import java.util.Set; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.not; public class ClassPathScannerTest { @Test public void scanClassPath() throws Exception { Set<Class<?>> immutableClasses = ClassPathScanner.findImmutableClasses("org.mutabilitydetector"); assertThat(immutableClasses, hasItem(ImmutableExample.class)); assertThat(immutableClasses, not(hasItem(MutableByHavingSetterMethod.class))); } }
package org.mutabilitydetector; /* * #%L * MutabilityDetector * %% * Copyright (C) 2008 - 2015 Graham Allan * %% * 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. * #L% */ import org.junit.Test; import org.mutabilitydetector.classpath.ClassPathScanner; import java.util.Set; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; public class ClassPathScannerTest { @Test public void scanClassPath() throws Exception { Set<Class<?>> immutableClasses = ClassPathScanner.findImmutableClasses("org.mutabilitydetector"); assertThat(immutableClasses, notNullValue()); assertThat(immutableClasses.size() > 0, is(true)); } }
Add getter for restapi instance
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.restapi; import com.yahoo.container.jdisc.HttpRequest; import com.yahoo.container.jdisc.HttpResponse; import com.yahoo.container.jdisc.LoggingRequestHandler; /** * @author bjorncs */ public abstract class RestApiRequestHandler<T extends RestApiRequestHandler<T>> extends LoggingRequestHandler { private final RestApi restApi; @FunctionalInterface public interface RestApiProvider<T> { RestApi createRestApi(T self); } /** * RestApi will usually refer to handler methods of subclass, which are not accessible before super constructor has completed. * This is hack to leak reference to subclass instance's "this" reference. * Caller must ensure that provider instance does not try to access any uninitialized fields. */ @SuppressWarnings("unchecked") protected RestApiRequestHandler(LoggingRequestHandler.Context context, RestApiProvider<T> provider) { super(context); this.restApi = provider.createRestApi((T)this); } protected RestApiRequestHandler(LoggingRequestHandler.Context context, RestApi restApi) { super(context); this.restApi = restApi; } @Override public final HttpResponse handle(HttpRequest request) { return restApi.handleRequest(request); } protected RestApi restApi() { return restApi; } }
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.restapi; import com.yahoo.container.jdisc.HttpRequest; import com.yahoo.container.jdisc.HttpResponse; import com.yahoo.container.jdisc.LoggingRequestHandler; /** * @author bjorncs */ public abstract class RestApiRequestHandler<T extends RestApiRequestHandler<T>> extends LoggingRequestHandler { private final RestApi restApi; @FunctionalInterface public interface RestApiProvider<T> { RestApi createRestApi(T self); } /** * RestApi will usually refer to handler methods of subclass, which are not accessible before super constructor has completed. * This is hack to leak reference to subclass instance's "this" reference. * Caller must ensure that provider instance does not try to access any uninitialized fields. */ @SuppressWarnings("unchecked") protected RestApiRequestHandler(LoggingRequestHandler.Context context, RestApiProvider<T> provider) { super(context); this.restApi = provider.createRestApi((T)this); } protected RestApiRequestHandler(LoggingRequestHandler.Context context, RestApi restApi) { super(context); this.restApi = restApi; } @Override public final HttpResponse handle(HttpRequest request) { return restApi.handleRequest(request); } }
[TASK] Validate all JS files in the 'Build/' subdir with JSHint
/** * Grunt-Contrib-JSHint * @description Validate files with JSHint. * @docs https://github.com/gruntjs/grunt-contrib-jshint */ var config = require('../Config'); module.exports = { options: { // Environments browser: true, jquery: true, // Enforcing options camelcase: true, curly: true, devel: true, eqeqeq: true, eqnull: true, immed: true, latedef: true, undef: true, strict: true, newcap: true, noarg: true, expr: true, evil: true, smarttabs: true, // Use the stylish JSHint output reporter: require('jshint-stylish'), // Globals globals: { // Modernizr Modernizr: true, // RequireJS module: true, require: true, requirejs: true, define: true, } }, files: [ 'Gruntfile.js', 'Build/**/*.js', config.JavaScripts.devDir + '/*.js', '!' + config.JavaScripts.devDir + '/Libaries/**/*', '!' + config.JavaScripts.distDir + '/Libaries/**/*' ] };
/** * Grunt-Contrib-JSHint * @description Validate files with JSHint. * @docs https://github.com/gruntjs/grunt-contrib-jshint */ var config = require('../Config'); module.exports = { options: { // Environments browser: true, jquery: true, // Enforcing options camelcase: true, curly: true, devel: true, eqeqeq: true, eqnull: true, immed: true, latedef: true, undef: true, strict: true, newcap: true, noarg: true, expr: true, evil: true, smarttabs: true, // Use the stylish JSHint output reporter: require('jshint-stylish'), // Globals globals: { // Modernizr Modernizr: true, // RequireJS module: true, require: true, requirejs: true, define: true, } }, files: [ 'Gruntfile.js', config.JavaScripts.devDir + '/*.js', '!' + config.JavaScripts.devDir + '/Libaries/**/*', '!' + config.JavaScripts.distDir + '/Libaries/**/*' ] };
Set max length on mapcode pieces Fixes #1.
'use strict'; var fs = require('fs'); var Download = require('download'); var CSV = require('comma-separated-values'); var arrayUniq = require('array-uniq'); new Download({extract: true}) .get('http://www.mapcode.com/kader/isotables.zip') .run(function (err, files) { var data = files[0].contents.toString(); var items = new CSV(data, {header: true}).parse(); var ret = []; items.forEach(function (el) { if (el.Territory !== '') { ret.push(el.Territory); } if (el['Local code'] !== '') { ret.push(el['Local code']); } if (el['Full code'] !== '') { ret.push(el['Full code']); } }); var out = '\'use strict\';\nmodule.exports = function () {\n\treturn /(?:(' + arrayUniq(ret).sort().join('|') + ') )?[A-Z0-9]{2,5}\.[A-Z0-9]{2,4}/g;\n};'; fs.writeFileSync('index.js', out); });
'use strict'; var fs = require('fs'); var Download = require('download'); var CSV = require('comma-separated-values'); var arrayUniq = require('array-uniq'); new Download({extract: true}) .get('http://www.mapcode.com/kader/isotables.zip') .run(function (err, files) { var data = files[0].contents.toString(); var items = new CSV(data, {header: true}).parse(); var ret = []; items.forEach(function (el) { if (el.Territory !== '') { ret.push(el.Territory); } if (el['Local code'] !== '') { ret.push(el['Local code']); } if (el['Full code'] !== '') { ret.push(el['Full code']); } }); var out = '\'use strict\';\nmodule.exports = function () {\n\treturn /(?:(' + arrayUniq(ret).sort().join('|') + ') )?[A-Z0-9]{2,}\.[A-Z0-9]{2,}/g;\n};'; fs.writeFileSync('index.js', out); });
Correct iterator so it doesn't skip the last device
/* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package de.ailis.usb4java.libusb; import java.util.Iterator; /** * Iterator for device list. * * @author Klaus Reimer (k@ailis.de) */ final class DeviceListIterator implements Iterator<Device> { /** The devices list. */ private final DeviceList devices; /** The current index. */ private int nextIndex; /** * Constructor. * * @param devices * The devices list. */ DeviceListIterator(final DeviceList devices) { this.devices = devices; } /** * @see java.util.Iterator#hasNext() */ @Override public boolean hasNext() { return this.nextIndex < this.devices.getSize(); } /** * @see java.util.Iterator#next() */ @Override public Device next() { return this.devices.get(this.nextIndex++); } /** * @see java.util.Iterator#remove() */ @Override public void remove() { throw new UnsupportedOperationException(); } }
/* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package de.ailis.usb4java.libusb; import java.util.Iterator; /** * Iterator for device list. * * @author Klaus Reimer (k@ailis.de) */ final class DeviceListIterator implements Iterator<Device> { /** The devices list. */ private final DeviceList devices; /** The current index. */ private int index; /** * Constructor. * * @param devices * The devices list. */ DeviceListIterator(final DeviceList devices) { this.devices = devices; } /** * @see java.util.Iterator#hasNext() */ @Override public boolean hasNext() { return this.index < this.devices.getSize() - 1; } /** * @see java.util.Iterator#next() */ @Override public Device next() { return this.devices.get(this.index++); } /** * @see java.util.Iterator#remove() */ @Override public void remove() { throw new UnsupportedOperationException(); } }
Fix indentation of main convert function
Emoji = {}; Emoji.baseImagePath = '/packages/davidfrancisco_twemoji/img/'; Emoji.convert = function (str) { if (typeof str !== 'string') { return ''; } return str.replace(/:[\+\-a-z0-9_]+:/gi, function(match) { var imgName = match.slice(1, -1), path = Emoji.baseImagePath + imgName + '.png'; return '<img class="emoji" alt="' + match + '" src="' + path + '" draggable="false" />'; }); }; // borrowed code from https://github.com/meteor/meteor/blob/devel/packages/showdown/template-integration.js if (Package.templating) { var Template = Package.templating.Template; var Blaze = Package.blaze.Blaze; // implied by `templating` var HTML = Package.htmljs.HTML; // implied by `blaze` Blaze.Template.registerHelper('emoji', new Template('emoji', function () { var view = this, content = ''; if (view.templateContentBlock) { // this is for the block usage eg: {{#emoji}}:smile:{{/emoji}} content = Blaze._toText(view.templateContentBlock, HTML.TEXTMODE.STRING); } else { // this is for the direct usage eg: {{> emoji ':blush:'}} content = view.parentView.dataVar.get(); } return HTML.Raw(Emoji.convert(content)); })); }
Emoji = {}; Emoji.baseImagePath = '/packages/davidfrancisco_twemoji/img/'; Emoji.convert = function (str) { if (typeof str !== 'string') { return ''; } return str.replace(/:[\+\-a-z0-9_]+:/gi, function(match) { var imgName = match.slice(1, -1), path = Emoji.baseImagePath + imgName + '.png'; return '<img class="emoji" alt="' + match + '" src="' + path + '" draggable="false" />'; }); }; // borrowed code from https://github.com/meteor/meteor/blob/devel/packages/showdown/template-integration.js if (Package.templating) { var Template = Package.templating.Template; var Blaze = Package.blaze.Blaze; // implied by `templating` var HTML = Package.htmljs.HTML; // implied by `blaze` Blaze.Template.registerHelper('emoji', new Template('emoji', function () { var view = this, content = ''; if (view.templateContentBlock) { // this is for the block usage eg: {{#emoji}}:smile:{{/emoji}} content = Blaze._toText(view.templateContentBlock, HTML.TEXTMODE.STRING); } else { // this is for the direct usage eg: {{> emoji ':blush:'}} content = view.parentView.dataVar.get(); } return HTML.Raw(Emoji.convert(content)); })); }
Change type of returning value
'use strict'; const EventEmitter = require('events'); /** * Tracker Manager * @interface */ class ITrackerManager extends EventEmitter { constructor() { super(); if (this.constructor === ITrackerManager) { throw new TypeError('Can not create new instance of interface'); } } /** * Include tracker in search * @param {ITracker} tracker * @return {string|undefined} UID of tracker in list */ include(tracker) { throw new TypeError('Method "include" is not implemented.'); } /** * Exclude tracker from search * @param {string} uid * @return {boolean} status of excluding */ exclude(uid) { throw new TypeError('Method "exclude" is not implemented.'); } /** * Search in all included trackers * @param {SearchParams} searchParams */ search(searchParams) { throw new TypeError('Method "search" is not implemented.'); } } module.exports = ITrackerManager;
'use strict'; const EventEmitter = require('events'); /** * Tracker Manager * @interface */ class ITrackerManager extends EventEmitter { constructor() { super(); if (this.constructor === ITrackerManager) { throw new TypeError('Can not create new instance of interface'); } } /** * Include tracker in search * @param {ITracker} tracker * @return {string|undefined} UID of tracker in list */ include(tracker) { throw new TypeError('Method "include" is not implemented.'); } /** * Exclude tracker from search * @param {string} uid * @return {ITracker|undefined} Excluded Tracker instance */ exclude(uid) { throw new TypeError('Method "exclude" is not implemented.'); } /** * Search in all included trackers * @param {SearchParams} searchParams */ search(searchParams) { throw new TypeError('Method "search" is not implemented.'); } } module.exports = ITrackerManager;
Increase maximum lines for Snackbar messages
package com.averi.worldscribe.utilities; import android.content.Context; import android.graphics.Color; import android.support.design.widget.Snackbar; import android.view.View; import android.widget.TextView; import com.averi.worldscribe.R; /** * Created by mark on 20/06/16. */ public class ErrorMessager { /** * The maximum number of lines that can be displayed by a Snackbar message. */ public static final int SNACKBAR_MAX_LINES = 5; public static void showSnackbarMessage(Context context, View parentView, String message) { Snackbar snackbar = Snackbar .make(parentView, message, Snackbar.LENGTH_LONG); View snackbarView = snackbar.getView(); snackbarView.setBackgroundColor(AttributeGetter.getColorAttribute(context, R.attr.colorPrimary)); TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text); textView.setTextColor(Color.WHITE); textView.setMaxLines(SNACKBAR_MAX_LINES); snackbar.show(); } }
package com.averi.worldscribe.utilities; import android.content.Context; import android.graphics.Color; import android.support.design.widget.Snackbar; import android.view.View; import android.widget.TextView; import com.averi.worldscribe.R; /** * Created by mark on 20/06/16. */ public class ErrorMessager { public static void showSnackbarMessage(Context context, View parentView, String message) { Snackbar snackbar = Snackbar .make(parentView, message, Snackbar.LENGTH_LONG); View snackbarView = snackbar.getView(); snackbarView.setBackgroundColor(AttributeGetter.getColorAttribute(context, R.attr.colorPrimary)); TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text); textView.setTextColor(Color.WHITE); snackbar.show(); } }
Add unit test for the internal state after removing controls
describe('Creating custom map controls', function () { var map; beforeEach(function() { map = map || new GMaps({ el : '#basic-map', lat: -12.0433, lng: -77.0283, zoom: 12 }); }); it('should add default styles for the control', function () { map.addControl({ position: 'top_right', content: 'Geolocate' }); expect(map.controls[0].position).toEqual(google.maps.ControlPosition.TOP_RIGHT); expect(map.controls[0].style.fontFamily).not.toEqual(''); }); it('should leave off default styles if requested', function () { map.addControl({ position: 'top_right', disableDefaultStyles: true, content: '<i class="icon"></i>' }); expect(map.controls[1].position).toEqual(google.maps.ControlPosition.TOP_RIGHT); expect(map.map.controls[google.maps.ControlPosition.TOP_RIGHT].length).toEqual(2); expect(map.controls[1].style.fontFamily).toEqual(''); }); it('should remove control', function () { var control = map.controls[0]; map.removeControl(control); expect(map.controls.length).toEqual(1); expect(map.map.controls[google.maps.ControlPosition.TOP_RIGHT].length).toEqual(1); expect(map.controls[0]).not.toEqual(control); }); });
describe('Creating custom map controls', function () { var map; beforeEach(function() { map = map || new GMaps({ el : '#basic-map', lat: -12.0433, lng: -77.0283, zoom: 12 }); }); it('should add default styles for the control', function () { map.addControl({ position: 'top_right', content: 'Geolocate' }); expect(map.controls[0].position).toEqual(google.maps.ControlPosition.TOP_RIGHT); expect(map.controls[0].style.fontFamily).not.toEqual(''); }); it('should leave off default styles if requested', function () { map.addControl({ position: 'top_right', disableDefaultStyles: true, content: '<i class="icon"></i>' }); expect(map.controls[1].position).toEqual(google.maps.ControlPosition.TOP_RIGHT); expect(map.controls[1].style.fontFamily).toEqual(''); }); it('should remove control', function () { var control = map.controls[0]; map.removeControl(control); expect(map.controls.length).toEqual(1); expect(map.controls[0]).not.toEqual(control); }); });
Add Laravel config into Service Provider
<?php namespace Philipbrown\WorldPay; use Illuminate\Support\Facades\Config; use Illuminate\Support\ServiceProvider; class WorldPayServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('philipbrown/worldpay'); } /** * Register the service provider. * * @return void */ public function register() { $this->app['worldpay'] = $this->app->share(function($app) { $wp = new PhilipBrown\WorldPay\WorldPay; $wp->setConfig(Config::get('worldpay')); }); $this->app->booting(function() { $loader = \Illuminate\Foundation\AliasLoader::getInstance(); $loader->alias('WorldPay', 'PhilipBrown\WorldPay\Facades\WorldPay'); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('WorldPay'); } }
<?php namespace Philipbrown\WorldPay; use Illuminate\Support\ServiceProvider; class WorldPayServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('philipbrown/worldpay'); } /** * Register the service provider. * * @return void */ public function register() { $this->app['worldpay'] = $this->app->share(function($app) { return new WorldPay; }); $this->app->booting(function() { $loader = \Illuminate\Foundation\AliasLoader::getInstance(); $loader->alias('WorldPay', 'PhilipBrown\WorldPay\Facades\WorldPay'); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('WorldPay'); } }
Fix removal of "Add new" page
/* * Do not display ability to add pages or Settings tab * loaded only when !Permission::check('SITETREE_REORGANISE') */ (function($){ $.entwine('ss', function($){ /* Hide Add Page button */ $('a[href="admin/pages/add/"]').entwine({ onmatch: function(){ this.hide(); } }); /* Hide Settings Tab */ $('ul.ui-tabs-nav > li').entwine({ onmatch: function(){ var c = this.text().trim(); if (c.match(/^Settings$/)) this.hide(); } }); /* Hide page "drag" bars in SiteTree */ $('div.cms-tree a ins.jstree-icon').entwine({ onmatch: function(){ if (!this.hasClass('jstree-checkbox')){ /* Fix cms inconsistencies when Pages loaded through ajax */ this.hide(); this.parent().css('padding-left', '0'); // Remove padding-left } } }); /* Hide Settings Tab */ $('button[name="action_unpublish"]').entwine({ onmatch: function(){ this.hide(); this.addClass('removed-no-edit') this.parent().children("button").not('.removed-no-edit').first().addClass('ui-corner-left'); } }); }); })(jQuery);
/* * Do not display ability to add pages or Settings tab * loaded only when !Permission::check('SITETREE_REORGANISE') */ (function($){ $.entwine('ss', function($){ /* Hide Add Page button */ $('a.cms-page-add-button').entwine({ onmatch: function(){ this.hide(); } }); /* Hide Settings Tab */ $('ul.ui-tabs-nav > li').entwine({ onmatch: function(){ var c = this.text().trim(); if (c.match(/^Settings$/)) this.hide(); } }); /* Hide page "drag" bars in SiteTree */ $('div.cms-tree a ins.jstree-icon').entwine({ onmatch: function(){ if (!this.hasClass('jstree-checkbox')){ /* Fix cms inconsistencies when Pages loaded through ajax */ this.hide(); this.parent().css('padding-left', '0'); // Remove padding-left } } }); /* Hide Settings Tab */ $('button[name="action_unpublish"]').entwine({ onmatch: function(){ this.hide(); this.addClass('removed-no-edit') this.parent().children("button").not('.removed-no-edit').first().addClass('ui-corner-left'); } }); }); })(jQuery);
Add article TODO for storing custom types in db
package petfind import ( "errors" "time" ) var ErrNotFound = errors.New("item not found") // Pet holds information about each pet of the application. type Pet struct { ID int64 Name string Age int Added time.Time } // Store describes the operations the application needs for persisting and // retrieving data. type Store interface { AddPet(*Pet) error GetAllPets() ([]Pet, error) CreateUser(*User) error GetUserByGithubID(githubID int64) (*User, error) GetUserBySessionID(sessionID string) (*User, error) CreateUserSession(*Session) error DeleteUserSession(sessionID string) error MakeSchema() error DropSchema() error } type User struct { ID int64 GithubID int64 Login string Name string Email string Added time.Time } type Session struct { ID string UserID int64 Added time.Time } // TODO(psimika): Useful article in case a custom type needs to be stored in // the database: // // https://husobee.github.io/golang/database/2015/06/12/scanner-valuer.html
package petfind import ( "errors" "time" ) var ErrNotFound = errors.New("item not found") // Pet holds information about each pet of the application. type Pet struct { ID int64 Name string Age int Added time.Time } // Store describes the operations the application needs for persisting and // retrieving data. type Store interface { AddPet(*Pet) error GetAllPets() ([]Pet, error) CreateUser(*User) error GetUserByGithubID(githubID int64) (*User, error) GetUserBySessionID(sessionID string) (*User, error) CreateUserSession(*Session) error DeleteUserSession(sessionID string) error MakeSchema() error DropSchema() error } type User struct { ID int64 GithubID int64 Login string Name string Email string Added time.Time } type Session struct { ID string UserID int64 Added time.Time }
Bump version: 0.1.2 → 0.1.3
# -*- coding: utf-8 -* """ `grappa_http` provides HTTP protocol assertion for `grappa` testing library. Example:: import grappa import grappa_http # Register plugin grappa.use(grappa_http) # Use plugin assertion res = requests.get('httpbin.org/status/204') res | should.have.status(204) For assertion operators and aliases, see `operators documentation`_. .. _`operators documentation`: operators.html Reference --------- """ # Export register function from . import adapters from .plugin import register from grappa import should, expect, use # Register Python operator __all__ = ('should', 'expect', 'register', 'adapters') # Package metadata __author__ = 'Tomas Aparicio' __license__ = 'MIT' # Current package version __version__ = '0.1.3' # Self-register plugin in grappa use(register)
# -*- coding: utf-8 -* """ `grappa_http` provides HTTP protocol assertion for `grappa` testing library. Example:: import grappa import grappa_http # Register plugin grappa.use(grappa_http) # Use plugin assertion res = requests.get('httpbin.org/status/204') res | should.have.status(204) For assertion operators and aliases, see `operators documentation`_. .. _`operators documentation`: operators.html Reference --------- """ # Export register function from . import adapters from .plugin import register from grappa import should, expect, use # Register Python operator __all__ = ('should', 'expect', 'register', 'adapters') # Package metadata __author__ = 'Tomas Aparicio' __license__ = 'MIT' # Current package version __version__ = '0.1.2' # Self-register plugin in grappa use(register)
Add Laracasts full width vdeo description
// ==UserScript== // @name Laracasts - Full Width Video // @namespace http://tampermonkey.net/ // @version 1.0 // @description Makes the Laracasts video player take up the full viewport. // @author You // @match https://laracasts.com/* // @grant none // ==/UserScript== (function() { 'use strict'; var videoPlayer = document.querySelector(".Video__player"); videoPlayer.style.width = '100%'; videoPlayer.style.maxWidth = '100%'; videoPlayer.style.padding = 0; videoPlayer.style.margin = 0; videoPlayer.style.border = 'none'; var videoWrap = document.querySelector(".Video__player-wrap"); videoWrap.style.border = 'none'; })();
// ==UserScript== // @name Laracasts - Full Width Video // @namespace http://tampermonkey.net/ // @version 1.0 // @description try to take over the world! // @author You // @match https://laracasts.com/* // @grant none // ==/UserScript== (function() { 'use strict'; var videoPlayer = document.querySelector(".Video__player"); videoPlayer.style.width = '100%'; videoPlayer.style.maxWidth = '100%'; videoPlayer.style.padding = 0; videoPlayer.style.margin = 0; videoPlayer.style.border = 'none'; var videoWrap = document.querySelector(".Video__player-wrap"); videoWrap.style.border = 'none'; })();
Remove extra %s from media path
import settings from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/(.*)', admin.site.root), (r'^publication/', include('stuff.publications.urls')), (r'^file/', include('stuff.files.urls')), (r'^photo/', include('stuff.picasaweb.urls')), (r'^bookmark/', include('stuff.delicious.urls')), (r'^project/', include('stuff.projects.urls')), (r'^multimedia/', include('stuff.multimedia.urls')), # (r'^db/(.*)', databrowse.site.root), (r'^$', 'stuff.views.index'), # Media serving (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True} ), )
import settings from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/(.*)', admin.site.root), (r'^publication/', include('stuff.publications.urls')), (r'^file/', include('stuff.files.urls')), (r'^photo/', include('stuff.picasaweb.urls')), (r'^bookmark/', include('stuff.delicious.urls')), (r'^project/', include('stuff.projects.urls')), (r'^multimedia/', include('stuff.multimedia.urls')), (r'^git/', include('stuff.dit.urls')), # (r'^db/(.*)', databrowse.site.root), (r'^$', 'stuff.views.index'), # Media serving (r'^%smedia/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True} ), )
Make the example reflect a normal use-case
// Copyright 2013 The Bufferpool Authors. All rights reserved. // Use of this source code is governed by the BSD 2-Clause license, // which can be found in the LICENSE file. package bufferpool_test import ( "bytes" "fmt" "testing" "github.com/pushrax/bufferpool" ) func TestTakeFromEmpty(t *testing.T) { bp := bufferpool.New(1, 1) poolBuf := bp.Take() if !bytes.Equal(poolBuf.Bytes(), []byte("")) { t.Fatalf("Buffer from empty bufferpool was allocated incorrectly.") } } func TestTakeFromFilled(t *testing.T) { bp := bufferpool.New(1, 1) bp.Give(bytes.NewBuffer([]byte("X"))) reusedBuf := bp.Take() if !bytes.Equal(reusedBuf.Bytes(), []byte("")) { t.Fatalf("Buffer from filled bufferpool was recycled incorrectly.") } } func ExampleNew() { bp := bufferpool.New(10, 255) dogBuffer := bp.Take() dogBuffer.writeString("Dog!") bp.Give(dogBuffer) catBuffer := bp.Take() // dogBuffer is reused and reset. catBuffer.WriteString("Cat!") fmt.Println(catBuffer) // Output: // Cat! }
// Copyright 2013 The Bufferpool Authors. All rights reserved. // Use of this source code is governed by the BSD 2-Clause license, // which can be found in the LICENSE file. package bufferpool_test import ( "bytes" "fmt" "testing" "github.com/pushrax/bufferpool" ) func TestTakeFromEmpty(t *testing.T) { bp := bufferpool.New(1, 1) poolBuf := bp.Take() if !bytes.Equal(poolBuf.Bytes(), []byte("")) { t.Fatalf("Buffer from empty bufferpool was allocated incorrectly.") } } func TestTakeFromFilled(t *testing.T) { bp := bufferpool.New(1, 1) bp.Give(bytes.NewBuffer([]byte("X"))) reusedBuf := bp.Take() if !bytes.Equal(reusedBuf.Bytes(), []byte("")) { t.Fatalf("Buffer from filled bufferpool was recycled incorrectly.") } } func ExampleNew() { catBuffer := bytes.NewBuffer([]byte("cat")) bp := bufferpool.New(10, catBuffer.Len()) bp.Give(catBuffer) // An error is returned, but not neccessary to check reusedBuffer := bp.Take() reusedBuffer.Write([]byte("dog")) fmt.Println(reusedBuffer) // Output: // dog }
Convert map iterator to list (for Python3 support)
"""EditorConfig version tools Provides ``join_version`` and ``split_version`` classes for converting __version__ strings to VERSION tuples and vice versa. """ import re __all__ = ['join_version', 'split_version'] _version_re = re.compile(r'^(\d+)\.(\d+)\.(\d+)(\..*)?$', re.VERBOSE) def join_version(version_tuple): """Return a string representation of version from given VERSION tuple""" version = "%s.%s.%s" % version_tuple[:3] if version_tuple[3] != "final": version += "-%s" % version_tuple[3] return version def split_version(version): """Return VERSION tuple for given string representation of version""" match = _version_re.search(version) if not match: return None else: split_version = list(match.groups()) if split_version[3] is None: split_version[3] = "final" split_version = list(map(int, split_version[:3])) + split_version[3:] return tuple(split_version)
"""EditorConfig version tools Provides ``join_version`` and ``split_version`` classes for converting __version__ strings to VERSION tuples and vice versa. """ import re __all__ = ['join_version', 'split_version'] _version_re = re.compile(r'^(\d+)\.(\d+)\.(\d+)(\..*)?$', re.VERBOSE) def join_version(version_tuple): """Return a string representation of version from given VERSION tuple""" version = "%s.%s.%s" % version_tuple[:3] if version_tuple[3] != "final": version += "-%s" % version_tuple[3] return version def split_version(version): """Return VERSION tuple for given string representation of version""" match = _version_re.search(version) if not match: return None else: split_version = list(match.groups()) if split_version[3] is None: split_version[3] = "final" split_version = map(int, split_version[:3]) + split_version[3:] return tuple(split_version)
Make VERSION easier to access Until now `algoliasearch.version.VERSION` was needed to obtain the current version. Only `algoliasearch.VERSION` is now needed. The change is backward compatible: it is still possible to do `algoliasearch.version.VERSION`.
# -*- coding: utf-8 -*- """ Copyright (c) 2013 Algolia http://www.algolia.com/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from . import client from . import index from . import helpers from . import version # Compatibility with old import class algoliasearch(object): VERSION = version.VERSION Client = client.Client Index = index.Index AlgoliaException = helpers.AlgoliaException
# -*- coding: utf-8 -*- """ Copyright (c) 2013 Algolia http://www.algolia.com/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from . import client from . import index from . import helpers # Compatibility with old import class algoliasearch(object): Client = client.Client Index = index.Index AlgoliaException = helpers.AlgoliaException
Change default value for line number
#!/usr/local/bin/python2.7 # -*- coding: utf-8 -*- """ Intelligence Platform CLI Fabric File """ __author__ = 'Dongjoon Hyun (dongjoon@apache.org)' __license__ = 'Apache License' __version__ = '0.2' from fabric.api import * @task def ls(inpath='/'): """ fab hdfs.ls:/sample """ cmd = '/usr/bin/hadoop fs -ls %(inpath)s 2> /dev/null' % locals() run(cmd) @task def count(inpath): """ fab hdfs.count:/data/text/newsgroup """ cmd = '/usr/bin/hadoop fs -count %(inpath)s 2> /dev/null' % locals() run(cmd) @task def du(inpath): """ fab hdfs.du:/sample """ cmd = '/usr/bin/hadoop fs -du -h %(inpath)s 2> /dev/null' % locals() run(cmd) @task def text(inpath, count=0): """ fab hdfs.text:/sample/hani_news.head.txt.gz,5 """ if count == 0: cmd = '/usr/bin/hadoop fs -text %(inpath)s 2> /dev/null' % locals() else: cmd = '/usr/bin/hadoop fs -text %(inpath)s 2> /dev/null | head -n %(count)s' % locals() run(cmd)
#!/usr/local/bin/python2.7 # -*- coding: utf-8 -*- """ Intelligence Platform CLI Fabric File """ __author__ = 'Dongjoon Hyun (dongjoon@apache.org)' __license__ = 'Apache License' __version__ = '0.2' from fabric.api import * @task def ls(inpath='/'): """ fab hdfs.ls:/sample """ cmd = '/usr/bin/hadoop fs -ls %(inpath)s 2> /dev/null' % locals() run(cmd) @task def count(inpath): """ fab hdfs.count:/data/text/newsgroup """ cmd = '/usr/bin/hadoop fs -count %(inpath)s 2> /dev/null' % locals() run(cmd) @task def du(inpath): """ fab hdfs.du:/sample """ cmd = '/usr/bin/hadoop fs -du -h %(inpath)s 2> /dev/null' % locals() run(cmd) @task def text(inpath, count=5): """ fab hdfs.text:/sample/hani_news.head.txt.gz,5 """ cmd = '/usr/bin/hadoop fs -text %(inpath)s 2> /dev/null | head -n %(count)s' % locals() run(cmd)
Add top margin to prevent status bar overlap on app's navbar
import Expo, { Constants } from 'expo'; import React from 'react'; import PropTypes from 'prop-types'; import { View } from 'react-native'; import App from './App'; // we don't want this to require transformation class AwakeInDevApp extends React.Component { static propTypes = { exp: PropTypes.object }; state = { isReady: false }; async componentWillMount() { await Expo.Font.loadAsync({ Roboto: require('native-base/Fonts/Roboto.ttf'), Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf'), Ionicons: require('@expo/vector-icons/fonts/Ionicons.ttf') }); this.setState({ isReady: true }); } render() { if (!this.state.isReady) { return <Expo.AppLoading />; } return React.createElement( View, { style: { flex: 1, marginTop: Constants.statusBarHeight } }, React.createElement(App, { expUri: this.props.exp ? this.props.exp.initialUri : null }), React.createElement(process.env.NODE_ENV === 'development' ? Expo.KeepAwake : View) ); } } Expo.registerRootComponent(AwakeInDevApp);
import Expo from 'expo'; import React from 'react'; import PropTypes from 'prop-types'; import { View } from 'react-native'; import App from './App'; // we don't want this to require transformation class AwakeInDevApp extends React.Component { static propTypes = { exp: PropTypes.object }; state = { isReady: false }; async componentWillMount() { await Expo.Font.loadAsync({ Roboto: require('native-base/Fonts/Roboto.ttf'), Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf'), Ionicons: require('@expo/vector-icons/fonts/Ionicons.ttf') }); this.setState({ isReady: true }); } render() { if (!this.state.isReady) { return <Expo.AppLoading />; } return React.createElement( View, { style: { flex: 1 } }, React.createElement(App, { expUri: this.props.exp ? this.props.exp.initialUri : null }), React.createElement(process.env.NODE_ENV === 'development' ? Expo.KeepAwake : View) ); } } Expo.registerRootComponent(AwakeInDevApp);
client: Update to upstream API change.
package main import ( "fmt" "io/ioutil" "runtime" "github.com/shurcooL/trayhost" ) func main() { runtime.LockOSThread() menuItems := []trayhost.MenuItem{ trayhost.MenuItem{ Title: "Instant Share", Handler: func() { fmt.Println("TODO: grab content, content-type of clipboard") fmt.Println("TODO: request URL") fmt.Println("TODO: display/put URL in clipboard") fmt.Println("TODO: upload image in background") }, }, trayhost.SeparatorMenuItem(), trayhost.MenuItem{ Title: "Quit", Handler: trayhost.Exit, }, } // TODO: Create a real icon and bake it into the binary. iconData, err := ioutil.ReadFile("./icon.png") if err != nil { panic(err) } trayhost.Initialize("InstantShare", iconData, menuItems) trayhost.EnterLoop() }
package main import ( "fmt" "io/ioutil" "runtime" "github.com/shurcooL/trayhost" ) func main() { runtime.LockOSThread() menuItems := trayhost.MenuItems{ trayhost.MenuItem{ Title: "Instant Share", Handler: func() { fmt.Println("TODO: grab content, content-type of clipboard") fmt.Println("TODO: request URL") fmt.Println("TODO: display/put URL in clipboard") fmt.Println("TODO: upload image in background") }, }, trayhost.SeparatorMenuItem(), trayhost.MenuItem{ Title: "Quit", Handler: trayhost.Exit, }, } // TODO: Create a real icon and bake it into the binary. iconData, err := ioutil.ReadFile("./icon.png") if err != nil { panic(err) } trayhost.Initialize("InstantShare", iconData, menuItems) trayhost.EnterLoop() }
Add File methods for proper JSON snapshots
'use strict'; var memoize = require('memoizee/plain') , validDb = require('dbjs/valid-dbjs') , defineFile = require('dbjs-ext/object/file') , defineJpegFile = require('dbjs-ext/object/file/image-file/jpeg-file') , docMimeTypes = require('../utils/microsoft-word-doc-mime-types'); module.exports = memoize(function (db) { var File, JpegFile; validDb(db); File = defineFile(db); File.prototype.url = function () { return this.path ? '/' + this.path.split('/').map(encodeURIComponent).join('/') : null; }; JpegFile = defineJpegFile(db); File.prototype.defineProperties({ preview: { type: File, value: function () { return this.isPreviewGenerated ? this.generatedPreview : this; } }, isPreviewGenerated: { type: db.Boolean, value: true }, generatedPreview: { type: File, nested: true }, thumb: { type: JpegFile, nested: true }, toJSON: { value: function (descriptor) { return { kind: 'file', url: this.url, thumbUrl: this.thumb.url }; } }, isEmpty: { value: function (ignore) { return !this.path; } } }); File.accept = ['image/jpeg', 'application/pdf', 'image/png'].concat(docMimeTypes); return File; }, { normalizer: require('memoizee/normalizers/get-1')() });
'use strict'; var memoize = require('memoizee/plain') , validDb = require('dbjs/valid-dbjs') , defineFile = require('dbjs-ext/object/file') , defineJpegFile = require('dbjs-ext/object/file/image-file/jpeg-file') , docMimeTypes = require('../utils/microsoft-word-doc-mime-types'); module.exports = memoize(function (db) { var File, JpegFile; validDb(db); File = defineFile(db); File.prototype.url = function () { return this.path ? '/' + this.path.split('/').map(encodeURIComponent).join('/') : null; }; JpegFile = defineJpegFile(db); File.prototype.defineProperties({ preview: { type: File, value: function () { return this.isPreviewGenerated ? this.generatedPreview : this; } }, isPreviewGenerated: { type: db.Boolean, value: true }, generatedPreview: { type: File, nested: true }, thumb: { type: JpegFile, nested: true } }); File.accept = ['image/jpeg', 'application/pdf', 'image/png'].concat(docMimeTypes); return File; }, { normalizer: require('memoizee/normalizers/get-1')() });
Use `Ember.computed` instead of `Function.prototype.property`
import Em from 'ember'; import ArraySlice from 'array-slice'; var computed = Em.computed; var get = Em.get; var set = Em.set; var ArrayPager = ArraySlice.extend({ // 1-based page: computed('offset', 'limit', function (key, page) { var limit = get(this, 'limit'); var offset; // default value if (arguments.length <= 1) { offset = get(this, 'offset') || 0; return Math.ceil(offset / limit) || 1; } // setter // no negative pages page = Math.max(page - 1, 0); offset = (limit * page) || 0; set(this, 'offset', offset); return page + 1; }), // 1-based pages: computed('content.length', 'limit', function () { var limit = get(this, 'limit'); var length = get(this, 'content.length'); var pages = Math.ceil(length / limit) || 1; if (pages === Infinity) { pages = 0; } return pages; }) }); ArrayPager.computed = { page: function (prop, page, limit) { return computed(function () { return ArrayPager.create({ content: get(this, prop), page: page, limit: limit }); }); } }; export default ArrayPager;
import Em from 'ember'; import ArraySlice from 'array-slice'; var get = Em.get; var set = Em.set; var ArrayPager = ArraySlice.extend({ // 1-based page: function (key, page) { var limit = get(this, 'limit'); var offset; // default value if (arguments.length <= 1) { offset = get(this, 'offset') || 0; return Math.ceil(offset / limit) || 1; } // setter // no negative pages page = Math.max(page - 1, 0); offset = (limit * page) || 0; set(this, 'offset', offset); return page + 1; }.property('offset', 'limit'), // 1-based pages: function () { var limit = get(this, 'limit'); var length = get(this, 'content.length'); var pages = Math.ceil(length / limit) || 1; if (pages === Infinity) { pages = 0; } return pages; }.property('content.length', 'limit') }); ArrayPager.computed = { page: function (prop, page, limit) { return Em.computed(prop, function () { return ArrayPager.create({ content: get(this, prop), page: page, limit: limit }); }); } }; export default ArrayPager;
Hide the flashes after 10 seconds
import PostForm from './post_form'; $(function() { $('#flash p').on( 'load', (function() { setTimeout(function() { $('#flash p').fadeOut(200); }, 10000); })() ); $(document.body).on('click', '#flash p', function(e) { e.preventDefault(); $(this).fadeOut(200); }); $('.site_nav__search, .site_nav__about').on( 'click', '.site_nav__link', function(e) { e.preventDefault(); $(this) .closest('li') .toggleClass('site_nav--open') .find(':input:visible') .eq(0) .focus(); } ); new PostForm({ postBodyInput: $('textarea#post_body'), postBodyPreview: $('.content_preview'), wordCountContainer: $('.word_count'), bodyWordLimitContainer: $('.word_limit'), bodyWordLimit: $('.word_limit').data('limit'), titleInput: $('input#post_title'), titleCharacterLimitContainer: $('.character_limit'), titleCharacterLimit: $('.character_limit').data('limit'), previewTitleContainer: $('.title_preview'), loadingIndicator: document.querySelector('.loading-indicator'), }).init(); });
import PostForm from './post_form'; $(function() { $(document.body).on('click', '#flash p', function(e) { e.preventDefault(); $(this).fadeOut(200); }); $('.site_nav__search, .site_nav__about').on( 'click', '.site_nav__link', function(e) { e.preventDefault(); $(this) .closest('li') .toggleClass('site_nav--open') .find(':input:visible') .eq(0) .focus(); } ); new PostForm({ postBodyInput: $('textarea#post_body'), postBodyPreview: $('.content_preview'), wordCountContainer: $('.word_count'), bodyWordLimitContainer: $('.word_limit'), bodyWordLimit: $('.word_limit').data('limit'), titleInput: $('input#post_title'), titleCharacterLimitContainer: $('.character_limit'), titleCharacterLimit: $('.character_limit').data('limit'), previewTitleContainer: $('.title_preview'), loadingIndicator: document.querySelector('.loading-indicator'), }).init(); });
Disable static to get something running
"""receipt_tracker URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.conf.urls.static import static from django.contrib import admin from receipt_tracker import settings urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('core.urls')), ] #urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
"""receipt_tracker URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.conf.urls.static import static from django.contrib import admin from receipt_tracker import settings urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('core.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
AddrIP: Return nil if given nil
package missinggo import ( "net" "strconv" ) // Extracts the port as an integer from an address string. func AddrPort(addr net.Addr) int { switch raw := addr.(type) { case *net.UDPAddr: return raw.Port default: _, port, err := net.SplitHostPort(addr.String()) if err != nil { panic(err) } i64, err := strconv.ParseInt(port, 0, 0) if err != nil { panic(err) } return int(i64) } } func AddrIP(addr net.Addr) net.IP { if addr == nil { return nil } switch raw := addr.(type) { case *net.UDPAddr: return raw.IP case *net.TCPAddr: return raw.IP default: host, _, err := net.SplitHostPort(addr.String()) if err != nil { panic(err) } return net.ParseIP(host) } }
package missinggo import ( "net" "strconv" ) // Extracts the port as an integer from an address string. func AddrPort(addr net.Addr) int { switch raw := addr.(type) { case *net.UDPAddr: return raw.Port default: _, port, err := net.SplitHostPort(addr.String()) if err != nil { panic(err) } i64, err := strconv.ParseInt(port, 0, 0) if err != nil { panic(err) } return int(i64) } } func AddrIP(addr net.Addr) net.IP { switch raw := addr.(type) { case *net.UDPAddr: return raw.IP case *net.TCPAddr: return raw.IP default: host, _, err := net.SplitHostPort(addr.String()) if err != nil { panic(err) } return net.ParseIP(host) } }
Send SIGTERM and SIGKILL to child processes. With the removal of subprocess there was no way to known what were the subprocesses, however after the introduction of Jobs tracking the PIDs it is now possible. Use those PIDs.
"""FreeBSD port building infrastructure.""" from __future__ import absolute_import from . import event def stop(kill=False, kill_clean=False): """Stop building ports and cleanup.""" from os import kill, killpg from signal import SIGTERM, SIGKILL from .builder import builders from .env import cpus, flags from .queue import attr_queue, clean_queue, queues if flags["no_op"]: raise SystemExit(254) flags["mode"] = "clean" kill_queues = (attr_queue,) + queues if kill_clean: kill_queues += (clean_queue,) # Kill all active jobs for queue in kill_queues: for pid in (job.pid for job in queue.active if job.pid): try: if kill: killpg(pid, SIGKILL) else: kill(pid, SIGTERM) except OSError: pass # Stop all queues attr_queue.load = 0 for queue in queues: queue.load = 0 # Make cleaning go a bit faster if kill_clean: clean_queue.load = 0 return else: clean_queue.load = cpus # Wait for all active ports to finish so that they may be cleaned active = set() for queue in queues: for job in queue.active: port = job.port active.add(port) port.stage_completed.connect(lambda x: x.clean()) # Clean all other outstanding ports for builder in builders: for port in builder.ports: if port not in active: port.clean()
"""FreeBSD port building infrastructure.""" from __future__ import absolute_import from . import event def stop(kill=False, kill_clean=False): """Stop building ports and cleanup.""" from os import killpg from signal import SIGTERM, SIGKILL from .builder import builders from .env import cpus, flags from .queue import attr_queue, clean_queue, queues if flags["no_op"]: raise SystemExit(254) flags["mode"] = "clean" # Stop all queues attr_queue.load = 0 for queue in queues: queue.load = 0 # Make cleaning go a bit faster if kill_clean: clean_queue.load = 0 return else: clean_queue.load = cpus # Wait for all active ports to finish so that they may be cleaned active = set() for queue in queues: for job in queue.active: port = job.port active.add(port) port.stage_completed.connect(lambda x: x.clean()) # Clean all other outstanding ports for builder in builders: for port in builder.ports: if port not in active: port.clean()
Fix use of Array.includes not supported in current node version
import FilterModule from "../FilterModule"; import { dependencies as Inject, singleton as Singleton } from "needlepoint"; import Promise from "bluebird"; import Threads from "../../util/Threads"; @Singleton @Inject(Threads) export default class ThreadFilter extends FilterModule { /** * @param {Threads} threads */ constructor(threads) { super(); this.threadsToListen = threads.getThreadIds(); } filter(msg) { const threadId = parseInt(msg.threadID); const shouldListen = this.threadsToListen.indexOf(threadId) !== -1; if (shouldListen) { return Promise.resolve(msg); } else { return Promise.reject("Received message from thread (" + threadId + ") we're not listening to"); } } }
import FilterModule from "../FilterModule"; import { dependencies as Inject, singleton as Singleton } from "needlepoint"; import Promise from "bluebird"; import Threads from "../../util/Threads"; @Singleton @Inject(Threads) export default class ThreadFilter extends FilterModule { /** * @param {Threads} threads */ constructor(threads) { super(); this.threadsToListen = threads.getThreadIds(); } filter(msg) { const threadId = parseInt(msg.threadID); const shouldListen = this.threadsToListen.includes(threadId); if (shouldListen) { return Promise.resolve(msg); } else { return Promise.reject("Received message from thread (" + threadId + ") we're not listening to"); } } }
Fix active menu item in OTUListPage
<?php namespace wcf\acp\page; use wcf\page\SortablePage; /** * Lists the blacklisted usernames * * @author Maximilian Mader * @copyright 2013 Maximilian Mader * @license BSD 3-Clause License <http://opensource.org/licenses/BSD-3-Clause> * @package be.bastelstu.max.wcf.otu * @subpackage acp.page * @category Community Framework */ class OTUListPage extends SortablePage { /** * @see \wcf\page\AbstractPage::$activeMenuItem */ public $activeMenuItem = 'wcf.acp.menu.link.user.management.otu'; /** * @see \wcf\page\SortablePage::$defaultSortField */ public $defaultSortField = 'username'; /** * @see \wcf\page\AbstractPage::$neededPermissions */ public $neededPermissions = array('admin.system.canEditOption'); /** * @see \wcf\page\MultipleLinkPage::$objectListClassName */ public $objectListClassName = '\wcf\data\user\otu\blacklist\entry\UserOtuBlacklistEntryList'; /** * @see \wcf\page\AbstractPage::$templateName */ public $templateName = 'otuList'; /** * @see \wcf\page\SortablePage::$validSortFields */ public $validSortFields = array('username', 'time', 'lastOwner', 'userID', 'entryID'); }
<?php namespace wcf\acp\page; use wcf\page\SortablePage; /** * Lists the blacklisted usernames * * @author Maximilian Mader * @copyright 2013 Maximilian Mader * @license BSD 3-Clause License <http://opensource.org/licenses/BSD-3-Clause> * @package be.bastelstu.max.wcf.otu * @subpackage acp.page * @category Community Framework */ class OTUListPage extends SortablePage { /** * @see \wcf\page\AbstractPage::$activeMenuItem */ public $activeMenuItem = 'wcf.acp.menu.link.otu.list'; /** * @see \wcf\page\SortablePage::$defaultSortField */ public $defaultSortField = 'username'; /** * @see \wcf\page\AbstractPage::$neededPermissions */ public $neededPermissions = array('admin.system.canEditOption'); /** * @see \wcf\page\MultipleLinkPage::$objectListClassName */ public $objectListClassName = '\wcf\data\user\otu\blacklist\entry\UserOtuBlacklistEntryList'; /** * @see \wcf\page\AbstractPage::$templateName */ public $templateName = 'otuList'; /** * @see \wcf\page\SortablePage::$validSortFields */ public $validSortFields = array('username', 'time', 'lastOwner', 'userID', 'entryID'); }
Mark user parameter as final
package com.github.mobile.android.repo; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.github.mobile.android.R.id; import com.github.mobile.android.util.AvatarHelper; import com.madgag.android.listviews.ViewHolder; import org.eclipse.egit.github.core.User; /** * View holder to display a user/organization */ public class OrgViewHolder implements ViewHolder<User> { private final AvatarHelper avatarHelper; private final TextView nameText; private final ImageView avatarView; /** * Create org view holder * * @param view * @param avatarHelper */ public OrgViewHolder(final View view, final AvatarHelper avatarHelper) { this.avatarHelper = avatarHelper; nameText = (TextView) view.findViewById(id.tv_org_name); avatarView = (ImageView) view.findViewById(id.iv_gravatar); } @Override public void updateViewFor(final User user) { nameText.setText(user.getLogin()); avatarView.setBackgroundDrawable(null); avatarHelper.bind(avatarView, user); } }
package com.github.mobile.android.repo; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.github.mobile.android.R.id; import com.github.mobile.android.util.AvatarHelper; import com.madgag.android.listviews.ViewHolder; import org.eclipse.egit.github.core.User; /** * View holder to display a user/organization */ public class OrgViewHolder implements ViewHolder<User> { private final AvatarHelper avatarHelper; private final TextView nameText; private final ImageView avatarView; /** * Create org view holder * * @param view * @param avatarHelper */ public OrgViewHolder(final View view, final AvatarHelper avatarHelper) { this.avatarHelper = avatarHelper; nameText = (TextView) view.findViewById(id.tv_org_name); avatarView = (ImageView) view.findViewById(id.iv_gravatar); } @Override public void updateViewFor(User user) { nameText.setText(user.getLogin()); avatarView.setBackgroundDrawable(null); avatarHelper.bind(avatarView, user); } }
Switch the os import to it's own line for pep8 compliance.
#!/usr/bin/env python import sys import os def main(): django_env_dir = os.path.abspath('%s/../' % os.path.dirname(__file__)) workon_home = os.environ.get('WORKON_HOME') if not workon_home: print "ERROR: The $WORKON_HOME environment variable is not set. Please check to make sure you've installed and setup virtualenvwrapper correctly." sys.exit() # symlink the django_env directory inside the $WORKON_HOME command = 'ln -sf %s "$WORKON_HOME/django_env"' % django_env_dir os.system(command) # add the ejango_env postmkvirtualenv hook to the virtualenvwrapper postmkvirtualenv hook postmkvirtualenv_cmd = 'source $WORKON_HOME/django_env/bin/postmkvirtualenv' workon_home = os.getenv('WORKON_HOME') postmkvirtualenv_path = os.path.join(workon_home, 'postmkvirtualenv') fh = open(postmkvirtualenv_path, "r") contents = fh.read() fh.close() if contents.find(postmkvirtualenv_cmd) == -1: fh = open(postmkvirtualenv_path, "a") fh.write("\n\n%s\n\n" % postmkvirtualenv_cmd) fh.close() print """ Django-environment is now installed. To create a django-environment run the following. mkvirtualenv [project_name] Example: mkvirtualenv example """ if __name__ == '__main__': main()
#!/usr/bin/env python import sys, os def main(): django_env_dir = os.path.abspath('%s/../' % os.path.dirname(__file__)) workon_home = os.environ.get('WORKON_HOME') if not workon_home: print "ERROR: The $WORKON_HOME environment variable is not set. Please check to make sure you've installed and setup virtualenvwrapper correctly." sys.exit() # symlink the django_env directory inside the $WORKON_HOME command = 'ln -sf %s "$WORKON_HOME/django_env"' % django_env_dir os.system(command) # add the ejango_env postmkvirtualenv hook to the virtualenvwrapper postmkvirtualenv hook postmkvirtualenv_cmd = 'source $WORKON_HOME/django_env/bin/postmkvirtualenv' workon_home = os.getenv('WORKON_HOME') postmkvirtualenv_path = os.path.join(workon_home, 'postmkvirtualenv') fh = open(postmkvirtualenv_path, "r") contents = fh.read() fh.close() if contents.find(postmkvirtualenv_cmd) == -1: fh = open(postmkvirtualenv_path, "a") fh.write("\n\n%s\n\n" % postmkvirtualenv_cmd) fh.close() print """ Django-environment is now installed. To create a django-environment run the following. mkvirtualenv [project_name] Example: mkvirtualenv example """ if __name__ == '__main__': main()
Set `contentTypeJson` default to true
module.exports = { // Prefix identifier that will be used inside storing and loading id: 'gjs-', // Enable/Disable autosaving autosave: 1, // Indicates if load data inside editor after init autoload: 1, // Indicates which storage to use. Available: local | remote type: 'local', // If autosave enabled, indicates how many steps (general changes to structure) // need to be done before save. Useful with remoteStorage to reduce remote calls stepsBeforeSave: 1, //Enable/Disable components model (JSON format) storeComponents: 1, //Enable/Disable styles model (JSON format) storeStyles: 1, //Enable/Disable saving HTML template storeHtml: 1, //Enable/Disable saving CSS template storeCss: 1, // ONLY FOR LOCAL STORAGE // If enabled, checks if browser supports Local Storage checkLocal: 1, // ONLY FOR REMOTE STORAGE // Custom parameters to pass with the remote storage request, eg. csrf token params: {}, // Custom headers for the remote storage request headers: {}, // Endpoint where to save all stuff urlStore: '', // Endpoint where to fetch data urlLoad: '', //Callback before request beforeSend(jqXHR, settings) {}, //Callback after request onComplete(jqXHR, status) {}, // set contentType paramater of $.ajax // true: application/json; charset=utf-8' // false: 'x-www-form-urlencoded' contentTypeJson: true, credentials: 'include' };
module.exports = { // Prefix identifier that will be used inside storing and loading id: 'gjs-', // Enable/Disable autosaving autosave: 1, // Indicates if load data inside editor after init autoload: 1, // Indicates which storage to use. Available: local | remote type: 'local', // If autosave enabled, indicates how many steps (general changes to structure) // need to be done before save. Useful with remoteStorage to reduce remote calls stepsBeforeSave: 1, //Enable/Disable components model (JSON format) storeComponents: 1, //Enable/Disable styles model (JSON format) storeStyles: 1, //Enable/Disable saving HTML template storeHtml: 1, //Enable/Disable saving CSS template storeCss: 1, // ONLY FOR LOCAL STORAGE // If enabled, checks if browser supports Local Storage checkLocal: 1, // ONLY FOR REMOTE STORAGE // Custom parameters to pass with the remote storage request, eg. csrf token params: {}, // Custom headers for the remote storage request headers: {}, // Endpoint where to save all stuff urlStore: '', // Endpoint where to fetch data urlLoad: '', //Callback before request beforeSend(jqXHR, settings) {}, //Callback after request onComplete(jqXHR, status) {}, // set contentType paramater of $.ajax // true: application/json; charset=utf-8' // false: 'x-www-form-urlencoded' contentTypeJson: false, credentials: 'include' };
Change the ctor visibility to `public`.
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.delivery; import io.spine.server.storage.ReadRequest; /** * A request to read a certain {@link InboxMessage} by its ID. */ public final class InboxReadRequest implements ReadRequest<InboxMessageId> { private final InboxMessageId messageId; public InboxReadRequest(InboxMessageId id) { messageId = id; } @Override public InboxMessageId recordId() { return messageId; } }
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.delivery; import io.spine.server.storage.ReadRequest; /** * A request to read a certain {@link InboxMessage} by its ID. */ public final class InboxReadRequest implements ReadRequest<InboxMessageId> { private final InboxMessageId messageId; private InboxReadRequest(InboxMessageId id) { messageId = id; } @Override public InboxMessageId recordId() { return messageId; } }
Use find_packages() to export all packages automatically on install
import os from setuptools import setup, find_packages def get_version_from_git_most_recent_tag(): return os.popen("git tag -l v* | tail --lines=1").read().strip().lstrip("v") def get_readme_content(): current_file_dir = os.path.dirname(__file__) readme_file_path = os.path.join(current_file_dir, "README.md") return open(readme_file_path).read() setup( name='telegram-bot', version=get_version_from_git_most_recent_tag(), description='Python Telegram bot API framework', long_description=get_readme_content(), url='https://github.com/alvarogzp/telegram-bot', author='Alvaro Gutierrez Perez', author_email='alvarogzp@gmail.com', license='GPL-3.0', packages=find_packages(), install_requires=[ 'requests', 'pytz' ], python_requires='>=3', )
import os from setuptools import setup def get_version_from_git_most_recent_tag(): return os.popen("git tag -l v* | tail --lines=1").read().strip().lstrip("v") def get_readme_content(): current_file_dir = os.path.dirname(__file__) readme_file_path = os.path.join(current_file_dir, "README.md") return open(readme_file_path).read() setup( name='telegram-bot', version=get_version_from_git_most_recent_tag(), description='Python Telegram bot API framework', long_description=get_readme_content(), url='https://github.com/alvarogzp/telegram-bot', author='Alvaro Gutierrez Perez', author_email='alvarogzp@gmail.com', license='GPL-3.0', packages=['bot'], install_requires=[ 'requests', 'pytz' ], python_requires='>=3', )
Add Twitter data source to factory
const path = require('path'); const yamlConfig = require('node-yaml-config'); const Todoist = require(path.resolve(__dirname, 'todoist.js')); const Poloniex = require(path.resolve(__dirname, 'poloniex.js')); const Twitter = require(path.resolve(__dirname, 'twitter.js')); class DataSourceFactory { /** * * @param {string} dataSourceName */ static create(dataSourceName) { let dataSource; const config = yamlConfig.load(path.resolve(__dirname, '../../config/config.yaml')); switch (dataSourceName) { case 'todoist': dataSource = new Todoist(config); break; case 'poloniex': dataSource = new Poloniex(config); break; case 'twitter': dataSource = new Twitter(config); break; default: throw new TypeError('Invalid Data Source name'); } return dataSource; } } module.exports = DataSourceFactory;
const path = require('path'); const yamlConfig = require('node-yaml-config'); const Todoist = require(path.resolve(__dirname, 'todoist.js')); const Poloniex = require(path.resolve(__dirname, 'poloniex.js')); class DataSourceFactory { /** * * @param {string} dataSourceName */ static create(dataSourceName) { let dataSource; const config = yamlConfig.load(path.resolve(__dirname, '../../config/config.yaml')); switch (dataSourceName) { case 'todoist': dataSource = new Todoist(config); break; case 'poloniex': dataSource = new Poloniex(config); break; default: throw new TypeError('Invalid Data Source name'); } return dataSource; } } module.exports = DataSourceFactory;
Use System.getProperty("spotbugs.experimental", "true") to simplify code
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2003-2008 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.classfile.engine.asm; import org.objectweb.asm.Opcodes; /** * @author pugh */ public class FindBugsASM { private static final boolean USE_EXPERIMENTAL = Boolean.parseBoolean(System.getProperty("spotbugs.experimental", "true")); public static final int ASM_VERSION = USE_EXPERIMENTAL ? Opcodes.ASM7_EXPERIMENTAL : Opcodes.ASM6; }
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2003-2008 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.classfile.engine.asm; import static java.lang.Boolean.parseBoolean; import static java.util.Objects.isNull; import org.objectweb.asm.Opcodes; /** * @author pugh */ public class FindBugsASM { private static final String EXPERIMENTAL_PROPERTY_VALUE = System.getProperty("spotbugs.experimental"); private static final boolean USE_EXPERIMENTAL = isNull(EXPERIMENTAL_PROPERTY_VALUE) || parseBoolean(EXPERIMENTAL_PROPERTY_VALUE); public static final int ASM_VERSION = USE_EXPERIMENTAL ? Opcodes.ASM7_EXPERIMENTAL : Opcodes.ASM6; }
Fix logic error under preparePageFrames
class Algorithm: """ Algorithm Class Base class for the page substitution algorithms. """ def __init__(self, input = []): """ Algorithm Constructor. Parameters ---------- input : list A list containing the the input page swap. """ if not input: #If the list is empty throw an exception. raise ValueError("The list must not be empty") #throws the exception. self.blocks = input[0] #Store the page frames size. self.pages = input[1:] #Store the pages to swap. self.missingPages = self.blocks #Count the lack of pages. def removeChuncks(self, list, start, stop): """ Remove a piece of a list. Parameters ---------- list : list The list to delete the elements start : int start point. stop : int stop point. """ del list[start:stop] #Delete range def preparePageFrame(self): """ Prepare the page frames. Returns ------- list The list with initialized Page frames """ pageFrame = [None] * self.blocks #Create the page frame with elements passed by the user. iterator = 0 for i in range(0, len(self.pages)): if self.pages[i] not in pageFrame: pageFrame[iterator] = self.pages[i] iterator = iterator + 1 if iterator == self.blocks: self.removeChuncks(self.pages, 0, i) #Remove part of the list that is on the page frame break return pageFrame #Return the list
class Algorithm: """ Algorithm Class Base class for the page substitution algorithms. """ def __init__(self, input = []): """ Algorithm Constructor. Parameters ---------- input : list A list containing the the input page swap. """ if not input: #If the list is empty throw an exception. raise ValueError("The list must not be empty") #throws the exception. self.blocks = input[0] #Store the page frames size. self.pages = input[1:] #Store the pages to swap. self.missingPages = self.blocks #Count the lack of pages. def removeChuncks(self, list, start, stop): """ Remove a piece of a list. Parameters ---------- list : list The list to delete the elements start : int start point. stop : int stop point. """ del list[start:stop] #Delete range def preparePageFrame(self): """ Prepare the page frames. Returns ------- list The list with initialized Page frames """ pageFrame = [self.pages[x] for x in range(0, self.blocks)] #Create the page frame with elements passed by the user. self.removeChuncks(self.pages, 0, self.blocks) #Remove part of the list that is on the page frame return pageFrame #Return the list
Clean up more in tests
import filecmp import os import tempfile import unittest import isomedia TESTDATA = os.path.join(os.path.dirname(__file__), 'testdata') class TestSanity(unittest.TestCase): def test_sanity(self): mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4') mp4file = open(mp4filename, 'rb') isofile = isomedia.load(mp4file) root = isofile.root moov_atom = [atom for atom in root.children if atom.type() == 'moov'] self.assertEqual(len(moov_atom), 1, 'There should be 1 moov atom.') mp4file.close() def test_lossless_write(self): mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4') infile = open(mp4filename, 'rb') isofile = isomedia.load(infile) outfile = tempfile.NamedTemporaryFile(delete=False) isofile.write(outfile) infile.close() outfile.close() self.assertTrue(filecmp.cmp(infile.name, outfile.name)) os.remove(outfile.name) if __name__ == '__main__': unittest.main()
import filecmp import os import tempfile import unittest import isomedia TESTDATA = os.path.join(os.path.dirname(__file__), 'testdata') class TestSanity(unittest.TestCase): def test_sanity(self): mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4') mp4file = open(mp4filename, 'rb') isofile = isomedia.load(mp4file) root = isofile.root moov_atom = [atom for atom in root.children if atom.type() == 'moov'] self.assertEqual(len(moov_atom), 1, 'There should be 1 moov atom.') def test_lossless_write(self): mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4') infile = open(mp4filename, 'rb') isofile = isomedia.load(infile) outfile = tempfile.NamedTemporaryFile(delete=False) isofile.write(outfile) infile.close() outfile.close() self.assertTrue(filecmp.cmp(infile.name, outfile.name)) if __name__ == '__main__': unittest.main()
:art: Use async/await instead of Promise().then
// Copyright (c) 2017 The Regents of the University of Michigan. // All Rights Reserved. Licensed according to the terms of the Revised // BSD License. See LICENSE.txt for details. const processTree = require("../lib/process-tree"); let treeSpy = function(logTree, runningProcess) { let spy = { }; spy.tree = logTree; spy.process = runningProcess; spy.messages = [ ]; spy.log = function(message) { spy.messages.push(message) }; return spy; }; let spy; let spyOnTree = async function(done, setup) { spy = await processTree(treeSpy, setup) done(); }; describe("a processTree with no children", () => { beforeEach(done => { spyOnTree(done, function(o) { }); }); it("returns a spy", () => { expect(spy.tree).toBeDefined(); }); });
// Copyright (c) 2017 The Regents of the University of Michigan. // All Rights Reserved. Licensed according to the terms of the Revised // BSD License. See LICENSE.txt for details. const processTree = require("../lib/process-tree"); let treeSpy = function(logTree, runningProcess) { let spy = { }; spy.tree = logTree; spy.process = runningProcess; spy.messages = [ ]; spy.log = function(message) { spy.messages.push(message) }; return spy; }; let spy; let spyOnTree = function(done, setup) { processTree(treeSpy, setup).then(logger => { spy = logger; done(); }); }; describe("a processTree with no children", () => { beforeEach(done => { spyOnTree(done, function(o) { }); }); it("returns a spy", () => { expect(spy.tree).toBeDefined(); }); });
[TestTemplateFunction] Add a missing debug info variant. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@359249 91177308-0d34-0410-b5e6-96231b3b80d8
""" Test that we can call C++ template fucntions. """ import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TemplateFunctionsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def do_test_template_function(self, add_cast): self.build() (_, _, thread, _) = lldbutil.run_to_name_breakpoint(self, "main") frame = thread.GetSelectedFrame() expr = "foo(42)" if add_cast: expr = "(int)" + expr expr_result = frame.EvaluateExpression(expr) self.assertTrue(expr_result.IsValid()) self.assertEqual(expr_result.GetValue(), "42") @skipIfWindows def test_template_function_with_cast(self): self.do_test_template_function(True) @skipIfWindows @expectedFailureAll(debug_info=["dwarf", "gmodules", "dwo"]) def test_template_function_without_cast(self): self.do_test_template_function(False)
""" Test that we can call C++ template fucntions. """ import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TemplateFunctionsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def do_test_template_function(self, add_cast): self.build() (_, _, thread, _) = lldbutil.run_to_name_breakpoint(self, "main") frame = thread.GetSelectedFrame() expr = "foo(42)" if add_cast: expr = "(int)" + expr expr_result = frame.EvaluateExpression(expr) self.assertTrue(expr_result.IsValid()) self.assertEqual(expr_result.GetValue(), "42") @skipIfWindows def test_template_function_with_cast(self): self.do_test_template_function(True) @skipIfWindows @expectedFailureAll(debug_info=["dwarf", "gmodules"]) def test_template_function_without_cast(self): self.do_test_template_function(False)
Add pretty-ms to display a friendlier error message on timeout
const RateLimiter = require("rolling-rate-limiter"); const prettyMs = require('pretty-ms'); const config = require('../config'); const validKeys = ['key1','key2', 'key3', 'key4', 'key5']; //TODO replace API keys in request with JWT-token? const limiter = RateLimiter({ interval: 60*60*1000, //1 hour in miliseconds maxInInterval: config.max_requests_per_hour }); const validator = { validateKey: function(req, res, next){ if(validKeys.indexOf(req.query.key)===-1){ res.status(401); res.json({"status":"401", "message":"invalid credentials"}); return; } next(); }, validateRate: function(req, res, next){ const timeLeft = limiter(req.query.key); if (timeLeft > 0) { // limit was exceeded, action should not be allowed // timeLeft is the number of ms until the next action will be allowed res.status(429); res.json({"status":"429", "message":"Request limit excceded- try after "+prettyMs(timeLeft)}); } else { next(); // limit was not exceeded, action should be allowed } } }; module.exports = validator;
const RateLimiter = require("rolling-rate-limiter"); const config = require('../config'); const validKeys = ['key1','key2', 'key3', 'key4', 'key5']; //TODO replace API keys in request with JWT-token? const limiter = RateLimiter({ interval: 60*60*1000, //1 hour in miliseconds maxInInterval: config.max_requests_per_hour }); const validator = { validateKey: function(req, res, next){ if(validKeys.indexOf(req.query.key)===-1){ res.status(401); res.json({"status":"401", "message":"invalid credentials"}); return; } next(); }, validateRate: function(req, res, next){ const timeLeft = limiter(req.query.key); if (timeLeft > 0) { // limit was exceeded, action should not be allowed // timeLeft is the number of ms until the next action will be allowed res.status(429); res.json({"status":"429", "message":"Request limit excceded- try after "+(timeLeft/1000)+"s"}); } else { next(); // limit was not exceeded, action should be allowed } } }; module.exports = validator;
Use correct frame name in pixel perfect hit test `gameObject.frame.key` doesn't exist and was passing an undefined value to `getPixelAlpha`. This just changes it to the correct `gameObject.frame.name` value.
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2018 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Creates a new Pixel Perfect Handler function. * * Access via `InputPlugin.makePixelPerfect` rather than calling it directly. * * @function Phaser.Input.CreatePixelPerfectHandler * @since 3.10.0 * * @param {Phaser.Textures.TextureManager} textureManager - A reference to the Texture Manager. * @param {integer} alphaTolerance - The alpha level that the pixel should be above to be included as a successful interaction. * * @return {function} The new Pixel Perfect Handler function. */ var CreatePixelPerfectHandler = function (textureManager, alphaTolerance) { return function (hitArea, x, y, gameObject) { var alpha = textureManager.getPixelAlpha(x, y, gameObject.texture.key, gameObject.frame.name); return (alpha && alpha >= alphaTolerance); }; }; module.exports = CreatePixelPerfectHandler;
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2018 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Creates a new Pixel Perfect Handler function. * * Access via `InputPlugin.makePixelPerfect` rather than calling it directly. * * @function Phaser.Input.CreatePixelPerfectHandler * @since 3.10.0 * * @param {Phaser.Textures.TextureManager} textureManager - A reference to the Texture Manager. * @param {integer} alphaTolerance - The alpha level that the pixel should be above to be included as a successful interaction. * * @return {function} The new Pixel Perfect Handler function. */ var CreatePixelPerfectHandler = function (textureManager, alphaTolerance) { return function (hitArea, x, y, gameObject) { var alpha = textureManager.getPixelAlpha(x, y, gameObject.texture.key, gameObject.frame.key); return (alpha && alpha >= alphaTolerance); }; }; module.exports = CreatePixelPerfectHandler;
Add Tests for existing functionality of ShardedCounterServiceImpl
package com.theupswell.appengine.counter.service; import junit.framework.TestCase; public class ShardedCounterServiceImplTest extends TestCase { public void setUp() throws Exception { super.setUp(); } public void testGetCounter() throws Exception { fail(); } public void testUpdateCounterDetails() throws Exception { fail(); } public void testOnTaskQueueCounterDeletion() throws Exception { fail(); } public void testGetOrCreateCounterData() throws Exception { fail(); } public void testIncrementMemcacheAtomic() throws Exception { fail(); } public void testAssembleCounterKeyforMemcache() throws Exception { fail(); } public void testIsMemcacheAvailable() throws Exception { fail(); } public void testGetLogger() throws Exception { fail(); } public void testAssertCounterAmountMutatable() throws Exception { fail(); } }
package com.theupswell.appengine.counter.service; import junit.framework.TestCase; public class ShardedCounterServiceImplTest extends TestCase { public void setUp() throws Exception { super.setUp(); } public void testGetCounter() throws Exception { } public void testUpdateCounterDetails() throws Exception { } public void testIncrement() throws Exception { } public void testIncrement1() throws Exception { } public void testIncrement2() throws Exception { } public void testDecrement() throws Exception { } public void testDecrement1() throws Exception { } public void testDelete() throws Exception { } public void testOnTaskQueueCounterDeletion() throws Exception { } public void testGetOrCreateCounterData() throws Exception { } public void testIncrementMemcacheAtomic() throws Exception { } public void testAssembleCounterKeyforMemcache() throws Exception { } public void testIsMemcacheAvailable() throws Exception { } public void testGetLogger() throws Exception { } public void testAssertCounterAmountMutatable() throws Exception { } }
Add docstrings to view classes
from django.http import HttpResponse from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.response import Response from registries.models import Organization from registries.serializers import DrillerListSerializer, DrillerSerializer class APIDrillerListCreateView(ListCreateAPIView): """ get: Return a list of all registered drilling organizations post: Create a new drilling organization instance """ queryset = Organization.objects.all().select_related('province_state') serializer_class = DrillerSerializer def list(self, request): queryset = self.get_queryset() serializer = DrillerListSerializer(queryset, many=True) return Response(serializer.data) class APIDrillerRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView): """ get: Return the specified drilling organization patch: Updates the specified drilling organization with the fields/values provided in the request body delete: Removes the specified drilling organization record """ queryset = Organization.objects.all() lookup_field = "org_guid" serializer_class = DrillerSerializer # Create your views here. def index(request): return HttpResponse("TEST: Driller Register app home index.")
from django.http import HttpResponse from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.response import Response from registries.models import Organization from registries.serializers import DrillerListSerializer, DrillerSerializer class APIDrillerListCreateView(ListCreateAPIView): queryset = Organization.objects.all().select_related('province_state') serializer_class = DrillerSerializer def list(self, request): queryset = self.get_queryset() serializer = DrillerListSerializer(queryset, many=True) return Response(serializer.data) class APIDrillerRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView): queryset = Organization.objects.all() lookup_field = "org_guid" serializer_class = DrillerSerializer # Create your views here. def index(request): return HttpResponse("TEST: Driller Register app home index.")
Fix missing comparison operator in StripColors
from twisted.plugin import IPlugin from txircd.module_interface import IMode, IModuleData, Mode, ModuleData from txircd.utils import ModeType, stripFormatting from zope.interface import implements class StripColors(ModuleData, Mode): implements(IPlugin, IModuleData, IMode) name = "StripColors" affectedActions = { "commandmodify-PRIVMSG": 10, "commandmodify-NOTICE": 10 } def channelModes(self): return [ ("S", ModeType.NoParam, self) ] def actions(self): return [ ("modeactioncheck-channel-S-commandmodify-PRIVMSG", 10, self.channelHasMode), ("modeactioncheck-channel-S-commandmodify-NOTICE", 10, self.channelHasMode) ] def channelHasMode(self, channel, user, data): if "S" in channel.modes: return "" return None def apply(self, actionName, channel, param, user, data): if channel in data["targetchans"] and not self.ircd.runActionUntilValue("checkexemptchanops", "stripcolor", channel, user): message = data["targetchans"][channel] data["targetchans"][channel] = stripFormatting(message) stripColors = StripColors()
from twisted.plugin import IPlugin from txircd.module_interface import IMode, IModuleData, Mode, ModuleData from txircd.utils import ModeType, stripFormatting from zope.interface import implements class StripColors(ModuleData, Mode): implements(IPlugin, IModuleData, IMode) name = "StripColors" affectedActions = { "commandmodify-PRIVMSG": 10, "commandmodify-NOTICE": 10 } def channelModes(self): return [ ("S", ModeType.NoParam, self) ] def actions(self): return [ ("modeactioncheck-channel-S-commandmodify-PRIVMSG", 10, self.channelHasMode), ("modeactioncheck-channel-S-commandmodify-NOTICE", 10, self.channelHasMode) ] def channelHasMode(self, channel, user, data): if "S" in channel.modes: return "" return None def apply(self, actionName, channel, param, user, data): if channel in data["targetchans"] not self.ircd.runActionUntilValue("checkexemptchanops", "stripcolor", channel, user): message = data["targetchans"][channel] data["targetchans"][channel] = stripFormatting(message) stripColors = StripColors()
Make challenges and discussion visibles This is based on https://github.com/swcarpentry/instructor-training/pull/437/files and https://github.com/swcarpentry/instructor-training/pull/439/files, both write by @ErinBecker.
// Make all tables striped by default. $("table").addClass("table table-striped"); // Handle foldable challenges and solutions (on click and at start). $(".solution").click(function(event) { var trigger = $(event.target).has(".fold-unfold").size() > 0 || $(event.target).filter(".fold-unfold").size() > 0; if (trigger) { $(">*:not(h2)", this).toggle(400); $(">h2>span.fold-unfold", this).toggleClass("glyphicon-collapse-down glyphicon-collapse-up"); event.stopPropagation(); } }); $(".solution").each(function() { $(">*:not(h2)", this).toggle(); var h2 = $("h2:first", this); h2.append("<span class='fold-unfold glyphicon glyphicon-collapse-down'></span>"); }); // Handle searches. // Relies on document having 'meta' element with name 'search-domain'. function google_search() { var query = document.getElementById("google-search").value; var domain = $("meta[name=search-domain]").attr("value"); window.open("https://www.google.com/search?q=" + query + "+site:" + domain); }
// Make all tables striped by default. $("table").addClass("table table-striped"); // Handle foldable challenges and solutions (on click and at start). $(".challenge,.discussion,.solution").click(function(event) { var trigger = $(event.target).has(".fold-unfold").size() > 0 || $(event.target).filter(".fold-unfold").size() > 0; if (trigger) { $(">*:not(h2)", this).toggle(400); $(">h2>span.fold-unfold", this).toggleClass("glyphicon-collapse-down glyphicon-collapse-up"); event.stopPropagation(); } }); $(".challenge,.discussion,.solution").each(function() { $(">*:not(h2)", this).toggle(); var h2 = $("h2:first", this); h2.append("<span class='fold-unfold glyphicon glyphicon-collapse-down'></span>"); }); // Handle searches. // Relies on document having 'meta' element with name 'search-domain'. function google_search() { var query = document.getElementById("google-search").value; var domain = $("meta[name=search-domain]").attr("value"); window.open("https://www.google.com/search?q=" + query + "+site:" + domain); }
Enforce regexp to start and end with an integer
var async = require('async'); var _ = require('lodash'); /** * pollCount - return the sum of all votes for a poll * * @param {Object} args requires pollId * @return {Object} count as the sum of the values of the poll */ function pollCount (args, done) { var seneca = this; var plugin = args.role; var ENTITY_NS = ('cd/polls_results'); var pollId = args.pollId; seneca.make$(ENTITY_NS).list$(["SELECT sum(CAST (value AS INTEGER)), count(*) FROM cd_polls_results WHERE poll_id = $1 AND value ~ '^([0-9])+$'", pollId], function(err, count){ if(err) return done(err); var result = 0; var participation = 0; if (count.length > 0) { result = count[0].sum; participation = count[0].count; } done(null, {sum: result, count: participation}); }); } module.exports = pollCount;
var async = require('async'); var _ = require('lodash'); /** * pollCount - return the sum of all votes for a poll * * @param {Object} args requires pollId * @return {Object} count as the sum of the values of the poll */ function pollCount (args, done) { var seneca = this; var plugin = args.role; var ENTITY_NS = ('cd/polls_results'); var pollId = args.pollId; seneca.make$(ENTITY_NS).list$(["SELECT sum(CAST (value AS INTEGER)), count(*) FROM cd_polls_results WHERE poll_id = $1 AND value ~ '([0-9])+'", pollId], function(err, count){ if(err) return done(err); var result = 0; var participation = 0; if (count.length > 0) { result = count[0].sum; participation = count[0].count; } done(null, {sum: result, count: participation}); }); } module.exports = pollCount;
Fix up error case. This would be so much easier with socket.io :fire:
var express = require('express'); var app = express(); var http = require('http').Server(app); // TODO: Use socket.io, which requires swift on the ios side, but would make all of this code // not necessary. var io = require('websocket.io').attach(http); app.use(express.static('public')); app.get('/', function(req, res){ res.sendFile(__dirname + 'public/index.html'); }); var clients = []; function broadcast(msg, socket) { clients.forEach(function(client) { if (client === socket) { return; } client.send(msg); }) } function addClient(socket) { for (client in clients) { if (client === socket) { return; // Already in the list } } clients.push(socket); } function removeClient(socket) { clients = clients.filter(function(client) { return (client !== socket); }); } io.on('connection', function(socket) { addClient(socket); broadcast(JSON.stringify({'clientConnections': clients.length})); socket.on('message', function(msg) { broadcast(msg, socket); }); socket.on('close', function() { removeClient(socket); broadcast(JSON.stringify({'clientConnections': clients.length})); }); socket.on('error', function(error) { // Remove the socket in an error case removeClient(socket); broadcast(JSON.stringify({'clientConnections': clients.length})); }) }); http.listen(6565, function() { console.log('listening on *:6565'); });
var express = require('express'); var app = express(); var http = require('http').Server(app); // TODO: Use socket.io, which requires swift on the ios side, but would make all of this code // not necessary. var io = require('websocket.io').attach(http); app.use(express.static('public')); app.get('/', function(req, res){ res.sendFile(__dirname + 'public/index.html'); }); var clients = []; function broadcast(msg, socket) { clients.forEach(function(client) { if (client === socket) { return; } client.send(msg); }) } function addClient(socket) { for (client in clients) { if (client === socket) { return; // Already in the list } } clients.push(socket); } function removeClient(socket) { clients.filter(function(client) { return (client !== socket); }); } io.on('connection', function(socket) { addClient(socket); broadcast(JSON.stringify({'clientConnections': clients.length})); socket.on('message', function(msg) { broadcast(msg, socket); }); socket.on('close', function () { removeClient(socket); broadcast(JSON.stringify({'clientConnections': clients.length})); }); }); http.listen(6565, function() { console.log('listening on *:6565'); });
Use `any-promise` instead of `bluebird`.
'use strict' var toArray = require('stream-to-array') var Promise = require('any-promise') module.exports = streamToPromise function streamToPromise (stream) { if (stream.readable) return fromReadable(stream) if (stream.writable) return fromWritable(stream) return Promise.resolve() } function fromReadable (stream) { var promise = toArray(stream) // Ensure stream is in flowing mode if (stream.resume) stream.resume() return promise .then(function concat (parts) { if (stream._readableState && stream._readableState.objectMode) { return parts } return Buffer.concat(parts.map(bufferize)) }) } function fromWritable (stream) { return new Promise(function (resolve, reject) { stream.once('finish', resolve) stream.once('error', reject) }) } function bufferize (chunk) { return Buffer.isBuffer(chunk) ? chunk : new Buffer(chunk) }
'use strict' var toArray = require('stream-to-array') var Promise = require('bluebird') module.exports = streamToPromise function streamToPromise (stream) { if (stream.readable) return fromReadable(stream) if (stream.writable) return fromWritable(stream) return Promise.resolve() } function fromReadable (stream) { var promise = toArray(stream) // Ensure stream is in flowing mode if (stream.resume) stream.resume() return promise .then(function concat (parts) { if (stream._readableState && stream._readableState.objectMode) { return parts } return Buffer.concat(parts.map(bufferize)) }) } function fromWritable (stream) { return new Promise(function (resolve, reject) { stream.once('finish', resolve) stream.once('error', reject) }) } function bufferize (chunk) { return Buffer.isBuffer(chunk) ? chunk : new Buffer(chunk) }
Add a new category: "participações sociais"
<?php /* * This file is part of Bens Penhorados, an undergraduate capstone project. * * (c) Fábio Santos <ffsantos92@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Illuminate\Database\Seeder; class ItemCategoriesTableSeeder extends Seeder { public function run() { DB::table('item_categories')->delete(); $categories = [ ['name' => 'Veículos', 'slug' => 'veiculos', 'code' => '01'], ['name' => 'Imóveis', 'slug' => 'imoveis', 'code' => '02'], ['name' => 'Participações sociais', 'slug' => 'part-sociais', 'code' => '05'], ['name' => 'Outros', 'slug' => 'outros', 'code' => '09'], ]; DB::table('item_categories')->insert($categories); } }
<?php /* * This file is part of Bens Penhorados, an undergraduate capstone project. * * (c) Fábio Santos <ffsantos92@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Illuminate\Database\Seeder; class ItemCategoriesTableSeeder extends Seeder { public function run() { DB::table('item_categories')->delete(); $categories = [ ['name' => 'Veículos', 'slug' => 'veiculos', 'code' => '01'], ['name' => 'Imóveis', 'slug' => 'imoveis', 'code' => '02'], ['name' => 'Outros', 'slug' => 'outros', 'code' => '09'], ]; DB::table('item_categories')->insert($categories); } }
Use spread operator to map action creators
// This file bootstraps the app with the boilerplate necessary // to support hot reloading in Redux import React, {PropTypes} from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import FuelSavingsApp from '../components/FuelSavingsApp'; import * as FuelSavingsActions from '../actions/fuelSavingsActions'; import * as cmsActions from '../actions/cmsActions'; import CmsApp from '../components/CmsApp'; class App extends React.Component { render() { const { fuelSavingsAppState, actions } = this.props; return ( <div> <FuelSavingsApp fuelSavingsAppState={fuelSavingsAppState} actions={actions}> </FuelSavingsApp> <CmsApp></CmsApp> </div> ); } } App.propTypes = { actions: PropTypes.object.isRequired, fuelSavingsAppState: PropTypes.object.isRequired }; function mapStateToProps(state) { return { fuelSavingsAppState: state.fuelSavingsAppState }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators({...FuelSavingsActions, ...cmsActions}, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(App);
// This file bootstraps the app with the boilerplate necessary // to support hot reloading in Redux import React, {PropTypes} from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import FuelSavingsApp from '../components/FuelSavingsApp'; import * as FuelSavingsActions from '../actions/fuelSavingsActions'; import * as cmsActions from '../actions/cmsActions'; import CmsApp from '../components/CmsApp'; class App extends React.Component { render() { const { fuelSavingsAppState, actions } = this.props; return ( <div> <FuelSavingsApp fuelSavingsAppState={fuelSavingsAppState} actions={actions}> </FuelSavingsApp> <CmsApp></CmsApp> </div> ); } } App.propTypes = { actions: PropTypes.object.isRequired, fuelSavingsAppState: PropTypes.object.isRequired }; function mapStateToProps(state) { return { fuelSavingsAppState: state.fuelSavingsAppState }; } function mapDispatchToProps(dispatch) { let actionCreators = Object.assign({}, FuelSavingsActions, cmsActions); return { actions: bindActionCreators(actionCreators, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(App);
Add 'defaultCollapsed' option to treeConfig
/** * @license Angular UI Tree v2.10.0 * (c) 2010-2015. https://github.com/angular-ui-tree/angular-ui-tree * License: MIT */ (function () { 'use strict'; angular.module('ui.tree', []) .constant('treeConfig', { treeClass: 'angular-ui-tree', emptyTreeClass: 'angular-ui-tree-empty', hiddenClass: 'angular-ui-tree-hidden', nodesClass: 'angular-ui-tree-nodes', nodeClass: 'angular-ui-tree-node', handleClass: 'angular-ui-tree-handle', placeholderClass: 'angular-ui-tree-placeholder', dragClass: 'angular-ui-tree-drag', dragThreshold: 3, levelThreshold: 30, defaultCollapsed: false }); })();
/** * @license Angular UI Tree v2.10.0 * (c) 2010-2015. https://github.com/angular-ui-tree/angular-ui-tree * License: MIT */ (function () { 'use strict'; angular.module('ui.tree', []) .constant('treeConfig', { treeClass: 'angular-ui-tree', emptyTreeClass: 'angular-ui-tree-empty', hiddenClass: 'angular-ui-tree-hidden', nodesClass: 'angular-ui-tree-nodes', nodeClass: 'angular-ui-tree-node', handleClass: 'angular-ui-tree-handle', placeholderClass: 'angular-ui-tree-placeholder', dragClass: 'angular-ui-tree-drag', dragThreshold: 3, levelThreshold: 30 }); })();