text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix tokenization of +1/-1 emojis
import lunr from 'lunr' import data from '../../data' var index = lunr(function() { this.pipeline.reset() this.field('short_name', { boost: 2 }) this.field('emoticons') this.field('name') this.ref('id') }) for (let emoji in data.emojis) { let emojiData = data.emojis[emoji], { short_name, name, emoticons } = emojiData index.add({ id: short_name, emoticons: emoticons, short_name: tokenize(short_name), name: tokenize(name), }) } function search(value, maxResults = 75) { var results = null if (value.length) { results = index.search(tokenize(value)).map((result) => result.ref ) results = results.slice(0, maxResults) } return results } function tokenize (string = '') { if (string[0] == '-' || string[0] == '+') { return string.split('') } if (/(:|;|=)-/.test(string)) { return [string] } return string.split(/[-|_|\s]+/) } export default { search }
import lunr from 'lunr' import data from '../../data' var index = lunr(function() { this.pipeline.reset() this.field('short_name', { boost: 2 }) this.field('emoticons') this.field('name') this.ref('id') }) for (let emoji in data.emojis) { let emojiData = data.emojis[emoji], { short_name, name, emoticons } = emojiData index.add({ id: short_name, emoticons: emoticons, short_name: tokenize(short_name), name: tokenize(name), }) } function search(value, maxResults = 75) { var results = null if (value.length) { results = index.search(tokenize(value)).map((result) => result.ref ) results = results.slice(0, maxResults) } return results } function tokenize (string) { if (['-', '-1', '+', '+1'].indexOf(string) == 0) { return string.split('') } if (/(:|;|=)-/.test(string)) { return [string] } return string.split(/[-|_|\s]+/) } export default { search }
Add zebra background color for table section.
W.TableSections = function () { var win = UI.Win({title:'Table Sections'}); // Create the first TableViewSections. var section1 = Ti.UI.createTableViewSection({headerTitle:'Header 1'}); // Add some rows to this table. for (var i = 0; i < 4; i++) { section1.add(Ti.UI.createTableViewRow({ title:'Row ' + i })); } // Create the second TableViewSections. var section2 = Ti.UI.createTableViewSection({headerTitle:'Header 2'}); // Add some rows to this table. for (var i = 4; i < 20; i++) { var backgroundColor = (i % 2 == 0) ? '#FFFFFF' : '#EEEEEE'; section2.add(Ti.UI.createTableViewRow({ title:'Row ' + i, backgroundColor:backgroundColor })); } // Create a normal table view and add the sections as data. var table = Ti.UI.createTableView({ data:[section1,section2] }); win.add(table); return win; }
W.TableSections = function () { var win = UI.Win({title:'Table Sections'}); // Create the first TableViewSections. var section1 = Ti.UI.createTableViewSection({headerTitle:'Header 1'}); // Add some rows to this table. for (var i = 0; i < 4; i++) { section1.add(Ti.UI.createTableViewRow({ title:'Row ' + i })); } // Create the second TableViewSections. var section2 = Ti.UI.createTableViewSection({headerTitle:'Header 2'}); // Add some rows to this table. for (var i = 4; i < 20; i++) { section2.add(Ti.UI.createTableViewRow({ title:'Row ' + i })); } // Create a normal table view and add the sections as data. var table = Ti.UI.createTableView({ data:[section1,section2] }); win.add(table); return win; }
Increase concurrent access in tests
package utils import ( "math/rand" "sync" "testing" "github.com/stretchr/testify/assert" ) func TestRandomString(t *testing.T) { rand.Seed(42) s1 := RandomString(10) s2 := RandomString(20) rand.Seed(42) s3 := RandomString(10) s4 := RandomString(20) assert.Len(t, s1, 10) assert.Len(t, s2, 20) assert.Len(t, s3, 10) assert.Len(t, s4, 20) assert.NotEqual(t, s1, s2) assert.Equal(t, s1, s3) assert.Equal(t, s2, s4) } func TestRandomStringConcurrentAccess(t *testing.T) { n := 10000 var wg sync.WaitGroup wg.Add(n) for i := 0; i < n; i++ { go func() { RandomString(10) wg.Done() }() } wg.Wait() }
package utils import ( "math/rand" "sync" "testing" "github.com/stretchr/testify/assert" ) func TestRandomString(t *testing.T) { rand.Seed(42) s1 := RandomString(10) s2 := RandomString(20) rand.Seed(42) s3 := RandomString(10) s4 := RandomString(20) assert.Len(t, s1, 10) assert.Len(t, s2, 20) assert.Len(t, s3, 10) assert.Len(t, s4, 20) assert.NotEqual(t, s1, s2) assert.Equal(t, s1, s3) assert.Equal(t, s2, s4) } func TestRandomStringConcurrentAccess(t *testing.T) { n := 1000 var wg sync.WaitGroup wg.Add(n) for i := 0; i < n; i++ { go func() { RandomString(10) wg.Done() }() } wg.Wait() }
WIP: Enable operations that write to the DB to be rolled back on error by wrapping them in transactions. Clean up: Make LabeledNodeWithPropertiesManager class abstract.
package managers.nodes; import com.fasterxml.jackson.databind.JsonNode; import java.util.List; import managers.functions.JsonFunction; import models.nodes.LabeledNodeWithProperties; import models.nodes.Node; import neo4play.Neo4jService; import play.libs.F.Promise; import play.libs.WS; public abstract class LabeledNodeWithPropertiesManager extends LabeledNodeManager { public Promise<? extends List<? extends Node>> all() { return null; } public Promise<? extends Node> get(JsonNode properties) { return null; } protected Promise<Boolean> connect( JsonNode startNode, JsonNode endNode, String location) { return null; } protected Promise<Boolean> disconnect( JsonNode startNode, JsonNode endNode, String location) { return null; } public static Promise<JsonNode> get(LabeledNodeWithProperties node) { Promise<WS.Response> response = Neo4jService .getLabeledNodeWithProperties( node.getLabel(), node.jsonProperties); return response.map(new JsonFunction()); } }
package managers.nodes; import com.fasterxml.jackson.databind.JsonNode; import java.util.List; import managers.functions.JsonFunction; import models.nodes.LabeledNodeWithProperties; import models.nodes.Node; import neo4play.Neo4jService; import play.libs.F.Promise; import play.libs.WS; public class LabeledNodeWithPropertiesManager extends LabeledNodeManager { public Promise<? extends List<? extends Node>> all() { return null; } public Promise<? extends Node> get(JsonNode properties) { return null; } protected Promise<Boolean> connect( JsonNode startNode, JsonNode endNode, String location) { return null; } protected Promise<Boolean> disconnect( JsonNode startNode, JsonNode endNode, String location) { return null; } public static Promise<JsonNode> get(LabeledNodeWithProperties node) { Promise<WS.Response> response = Neo4jService .getLabeledNodeWithProperties( node.getLabel(), node.jsonProperties); return response.map(new JsonFunction()); } }
Refactor: Break number apart into digits using math instead of string operations.
package org.asaph.happynumber; import java.util.HashSet; import java.util.Set; public class HappyNumber { public static int nextNumber(int number) { int sum = 0; while (number != 0) { int digit = number % 10; sum += digit * digit; number = (number - digit) / 10; } return sum; } public static boolean isHappy(int number) { return isHappy(number, new HashSet<Integer>()); } public static boolean isHappy(int number, Set<Integer> numbersSoFar) { int next = nextNumber(number); if (next == 1) { return true; } if (numbersSoFar.contains(next)) { return false; } numbersSoFar.add(next); return isHappy(next, numbersSoFar); } public static void main(String[] args) { for (int i=1; i<=1000; i++) { if (isHappy(i)) { System.out.println(i); } } } }
package org.asaph.happynumber; import java.util.HashSet; import java.util.Set; public class HappyNumber { public static int nextNumber(int number) { String numberString = Integer.toString(number); int sum=0; for (int i=0, length=numberString.length(); i<length; i++) { char ch = numberString.charAt(i); int digit = Integer.parseInt("" + ch); int square = digit * digit; sum += square; } return sum; } public static boolean isHappy(int number) { return isHappy(number, new HashSet<Integer>()); } public static boolean isHappy(int number, Set<Integer> numbersSoFar) { int next = nextNumber(number); if (next == 1) { return true; } if (numbersSoFar.contains(next)) { return false; } numbersSoFar.add(next); return isHappy(next, numbersSoFar); } public static void main(String[] args) { for (int i=1; i<=1000; i++) { if (isHappy(i)) { System.out.println(i); } } } }
Fix className warning (toString bem-cn)
import React from 'react' import PropTypes from 'prop-types' import block from '../../../helpers/bem-cn' import './Row.css' const row = block('j-row') const column = block('j-col') const propTypes = { children: PropTypes.node, col: PropTypes.bool, className: PropTypes.string } const emptyRow = (className, cn) => <div className={cn('item').mix(className)()} /> const wrapChild = (child, cn, className) => ( <div className={cn('item').mix(className)()} > {child} </div> ) const wrapChildren = (children, cn) => children.map((item, index) => ( <div className={cn('item')()} key={index} > {item} </div> )) const Row = ({ children, className, col, alignCenter, fullwidth }) => { const cn = col ? column : row if (children === null) return emptyRow(className, cn) if (children.length > 1) { return ( <div className={alignCenter ? cn({ 'centered': true })({ fullwidth }).mix(className)() : cn({ fullwidth }).mix(className)()}> { wrapChildren(children, cn) } </div> ) } return wrapChild(children, cn, className) } Row.propTypes = propTypes export default Row
import React from 'react' import PropTypes from 'prop-types' import block from '../../../helpers/bem-cn' import './Row.css' const row = block('j-row') const column = block('j-col') const propTypes = { children: PropTypes.node, col: PropTypes.bool, className: PropTypes.string } const emptyRow = (className, cn) => <div className={cn('item').mix(className)} /> const wrapChild = (child, cn, className) => ( <div className={cn('item').mix(className)()} > {child} </div> ) const wrapChildren = (children, cn) => children.map((item, index) => ( <div className={cn('item')()} key={index} > {item} </div> )) const Row = ({ children, className, col, alignCenter, fullwidth }) => { const cn = col ? column : row if (children === null) return emptyRow(className, cn) if (children.length > 1) { return ( <div className={alignCenter ? cn({ 'centered': true })({ fullwidth }).mix(className)() : cn({ fullwidth }).mix(className)()}> { wrapChildren(children, cn) } </div> ) } return wrapChild(children, cn, className) } Row.propTypes = propTypes export default Row
Update page title to match others.
<?php include '_templates/sitewide.php'; $page['name'] = '403'; $page['title'] = 'Access Denied &sdot; elementary'; include $template['header']; ?> <script> ga('send', 'event', '403: Forbidden', window.location.host); </script> <div class="row"> <div class="column alert"> <i class="warning fa fa-warning"></i> </div> <div class="column alert"> <h3>Access Denied.</h3> <p>You don't have permission to view the requested resource.</p> </div> <div class="row"> <a class="button suggested-action" href="/">Go to Home Page</a> </div> </div> <?php include $template['footer']; ?>
<?php include '_templates/sitewide.php'; $page['name'] = '403'; $page['title'] = 'Forbidden &sdot; elementary'; include $template['header']; ?> <script> ga('send', 'event', '403: Forbidden', window.location.host); </script> <div class="row"> <div class="column alert"> <i class="warning fa fa-warning"></i> </div> <div class="column alert"> <h3>Access denied.</h3> <p>You don't have permission to view the requested resource.</p> </div> <div class="row"> <a class="button suggested-action" href="/">Go to Home Page</a> </div> </div> <?php include $template['footer']; ?>
Make Settings object accessible through $rootScope
Controllers.controller("ToolbarCtrl", ["$scope", "$rootScope", "Connection", "User", "Settings", function ($scope, $rootScope, Connection, User, Settings) { $scope.user = User.get("~"); $scope.settings = $.parseJSON($.cookie("settings") || "{}"); $rootScope.settings = $scope.settings; $scope.setAway = function () { if ($scope.user.awayMsg) { Connection.send("AWAY") $scope.user.awayMsg = ""; } else { Connection.send("AWAY :afk") $scope.user.awayMsg = "afk"; } } $scope.rejoin = function (tab) { Connection.send("PART " + tab.name + " :rejoining"); Connection.send("JOIN " + tab.name) } $scope.clearLines = function (tab) { tab.clear(); } $rootScope.$watch(function (scope) { Settings.save($scope.settings); scope.settings = $scope.settings; }); }])
Controllers.controller("ToolbarCtrl", ["$scope", "$rootScope", "Connection", "User", "Settings", function ($scope, $rootScope, Connection, User, Settings) { $scope.user = User.get("~"); $scope.settings = $.parseJSON($.cookie("settings") || "{}"); $scope.setAway = function () { if ($scope.user.awayMsg) { Connection.send("AWAY") $scope.user.awayMsg = ""; } else { Connection.send("AWAY :afk") $scope.user.awayMsg = "afk"; } } $scope.rejoin = function (tab) { Connection.send("PART " + tab.name + " :rejoining"); Connection.send("JOIN " + tab.name) } $scope.clearLines = function (tab) { tab.clear(); } $rootScope.$watch(function () { Settings.save($scope.settings); }); }])
Attach js to the turbolink load event
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery.turbolinks //= require jquery_ujs //= require jquery-ui //= require bootstrap-wysihtml5 //= require autocomplete-rails //= require jquery-ui/datepicker-pt-BR //= require alert_message //= require turbolinks $(document).on('turbolinks:load', function() { // Jquery ui $('.datepicker').datepicker(); // active (function(){ var location = window.location.pathname; location = location.split('/'); var url = ''; for (var i = 1; i < location.length; i++) { url += '/' + location[i]; $('a[href="'+ url +'"]').addClass('active'); } })(); // Editor $('.wysihtml5').each(function(i, elem) { $(elem).wysihtml5(); }); })
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery.turbolinks //= require jquery_ujs //= require jquery-ui //= require bootstrap-wysihtml5 //= require autocomplete-rails //= require jquery-ui/datepicker-pt-BR //= require alert_message //= require turbolinks $(document).ready(function() { // Jquery ui $('.datepicker').datepicker(); // active (function(){ var location = window.location.pathname; location = location.split('/'); var url = ''; for (var i = 1; i < location.length; i++) { url += '/' + location[i]; $('a[href="'+ url +'"]').addClass('active'); } })(); // Editor $('.wysihtml5').each(function(i, elem) { $(elem).wysihtml5(); }); })
Refactor repeated checking to a helper method.
// Obtain ALL anchors on the page. var links = document.links; // The previous/next urls if they exist. var prev = findHref("prev"); var next = findHref("next"); /** * Find the href for a given name. * @param {String} name - The name of the anchor to search for. * @return {String} The href for a given tag, otherwise an empty string. */ function findHref(name) { for (var index = 0; index < links.length; ++index) { // The complete anchor HTML element (<a>). var anchor = links[index]; // Does the name exist in the anchor? if (isNameInAnchor(name, anchor.rel) || isNameInAnchor(name, anchor.text.toLowerCase()) || isNameInAnchor(name, anchor.className)) { return anchor.href } } } /** * Does the word exist in a given element? * @param {String} name - The name to search for. * @param {String} element - The element to search in. * @return {Boolean} True if the name exists in the element, otherwise false. */ function isNameInAnchor(name, element) { if (element !== undefined && element.indexOf(name) > -1) return true; else return false } // Go to the next/previous pages using the arrow keys. document.addEventListener('keydown', function(event) { if(event.keyCode == 37) { if (prev) chrome.extension.sendMessage({redirect: prev}); } else if(event.keyCode == 39) { if (next) chrome.extension.sendMessage({redirect: next}); } });
// Obtain ALL anchors on the page. var links = document.links; // The previous/next urls if they exist. var prev = findHref("prev"); var next = findHref("next"); /** * Find the href for a given name. * @param {String} The name of the anchor to search for. * @return {String} The href for a given tag, otherwise an empty string. */ function findHref(name) { for (var index = 0; index < links.length; ++index) { // The complete anchor HTML element (<a>). var anchor = links[index]; // Not all anchors have text, rels or classes defined. var rel = (anchor.rel !== undefined) ? anchor.rel : ''; var text = (anchor.text !== undefined) ? anchor.text.toLowerCase() : ''; var class_name = (anchor.className !== undefined) ? anchor.className : ''; if (rel.indexOf(name) > -1 || text.indexOf(name) > -1 || class_name.indexOf(name) > -1) { return anchor.href; } } } // Go to the next/previous pages using the arrow keys. document.addEventListener('keydown', function(event) { if(event.keyCode == 37) { if (prev) chrome.extension.sendMessage({redirect: prev}); } else if(event.keyCode == 39) { if (next) chrome.extension.sendMessage({redirect: next}); } });
Update exception copy with function name
<?php /* * By adding type hints and enabling strict type checking, code can become * easier to read, self-documenting and reduce the number of potential bugs. * By default, type declarations are non-strict, which means they will attempt * to change the original type to match the type specified by the * type-declaration. * * In other words, if you pass a string to a function requiring a float, * it will attempt to convert the string value to a float. * * To enable strict mode, a single declare directive must be placed at the top * of the file. * This means that the strictness of typing is configured on a per-file basis. * This directive not only affects the type declarations of parameters, but also * a function's return type. * * For more info review the Concept on strict type checking in the PHP track * <link>. * * To disable strict typing, comment out the directive below. */ declare(strict_types=1); function isIsogram(string $word): bool { throw new \BadFunctionCallException("Implement the isIsogram function"); }
<?php /* * By adding type hints and enabling strict type checking, code can become * easier to read, self-documenting and reduce the number of potential bugs. * By default, type declarations are non-strict, which means they will attempt * to change the original type to match the type specified by the * type-declaration. * * In other words, if you pass a string to a function requiring a float, * it will attempt to convert the string value to a float. * * To enable strict mode, a single declare directive must be placed at the top * of the file. * This means that the strictness of typing is configured on a per-file basis. * This directive not only affects the type declarations of parameters, but also * a function's return type. * * For more info review the Concept on strict type checking in the PHP track * <link>. * * To disable strict typing, comment out the directive below. */ declare(strict_types=1); function isIsogram(string $word): bool { throw new \BadFunctionCallException("Implement the isogram function"); }
Change name of local variable
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy import segment def calc_adjacency_matrix(label_img, n_region): A = numpy.diag([1] * n_region) h, w = label_img.shape[0], label_img.shape[1] for y in range(h): for x in range(w): here = label_img[y, x] if y < h - 1: b = label_img[y + 1, x] A[here, b] = A[b, here] = 1 if x < w - 1: r = label_img[y, x + 1] A[here, r] = A[r, here] = 1 return A
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy import segment def calc_adjacency_matrix(label_img, n_region): adjacency = numpy.diag([1] * n_region) h, w = label_img.shape[0], label_img.shape[1] for y in range(h): for x in range(w): here = label_img[y, x] if y < h - 1: b = label_img[y + 1, x] adjacency[here, b] = adjacency[b, here] = 1 if x < w - 1: r = label_img[y, x + 1] adjacency[here, r] = adjacency[r, here] = 1 return adjacency
Format `Delete` as “⌦” on macOS “Delete” is the wrong label to show humans for keyboard shortcuts using the `Delete` key on macOS, because Apple label their `Backspace` key “Delete”, and they don’t tend to have a dedicated `Delete` key. On most or all keyboards they sell now, Fn-Delete is what’s actually required to get what the rest of the world calls Delete. For the `Backspace` key code, Apple uses “Delete” in long form, and “⌫”, U+232B ERASE TO THE LEFT, for the more common short form. The `Delete` key code, Apple documentation calls “Forward Delete” in, and I find “Fn-Delete” mentioned in one place (as something keyboard-dependent, for which Control-D should be equivalent). I can’t quickly find any keyboard shortcuts in menus that use `Delete`, but a decade ago when they still sold keyboards with a `Delete` key, they printed “delete ⌦” on that key, using U+2326 ERASE TO THE RIGHT, so that’s clear and definite precedent. “⌦” probably won’t be visually recognised by most (and may even be confused for “⌫”), but it’s rare that we should want to format a shortcut containing `Delete` anyway, and producing “Delete” is just *wrong* and *definitely* confusing, since we don’t mean what the local platform means by it—and we’ve had a report of such confusion from one of our staff members in a place where we currently use `Delete` (where we should actually be using `⌘⌫` on macOS).
import '../core/String'; // For String#capitalise import { isMac } from '../ua/UA'; const platformKeys = { ArrowUp: '↑', ArrowDown: '↓', ArrowRight: '→', ArrowLeft: '←', Alt: isMac ? '⌥' : 'Alt-', Cmd: isMac ? '⌘' : 'Ctrl-', Ctrl: isMac ? '⌃' : 'Ctrl-', Meta: isMac ? '⌘' : 'Meta-', Shift: isMac ? '⇧' : 'Shift-', Escape: 'Esc', Enter: isMac ? '↵' : 'Enter', Backspace: isMac ? '⌫' : 'Backspace', Delete: isMac ? '⌦' : 'Delete', }; /** Function: O.formatKeyForPlatform Parameters: shortcut - {String} The keyboard shorcut, in the same format as taken by <O.GlobalKeyboardShortcuts#register>. Returns: {String} The shortcut formatted for display on the user's platform. */ export default function formatKeyForPlatform ( shortcut ) { return shortcut.split( '-' ).map( key => platformKeys[ key ] || key.capitalise() ).join( '' ); }
import '../core/String'; // For String#capitalise import { isMac } from '../ua/UA'; const platformKeys = { ArrowUp: '↑', ArrowDown: '↓', ArrowRight: '→', ArrowLeft: '←', Alt: isMac ? '⌥' : 'Alt-', Cmd: isMac ? '⌘' : 'Ctrl-', Ctrl: isMac ? '⌃' : 'Ctrl-', Meta: isMac ? '⌘' : 'Meta-', Shift: isMac ? '⇧' : 'Shift-', Escape: 'Esc', Enter: isMac ? '↵' : 'Enter', Backspace: isMac ? '⌫' : 'Backspace', }; /** Function: O.formatKeyForPlatform Parameters: shortcut - {String} The keyboard shorcut, in the same format as taken by <O.GlobalKeyboardShortcuts#register>. Returns: {String} The shortcut formatted for display on the user's platform. */ export default function formatKeyForPlatform ( shortcut ) { return shortcut.split( '-' ).map( key => platformKeys[ key ] || key.capitalise() ).join( '' ); }
Use a while loop rather than a c-style for loop
package com.maxmind.geoip2.record; import java.util.*; import org.json.*; public abstract class RecordWithNames { private HashMap<String, String> names; private Integer geoNameId; private Integer confidence; protected RecordWithNames(JSONObject json) throws JSONException { geoNameId = json.getInt("geoname_id"); names = new HashMap<String, String>(); if (json.has("names")) { JSONObject jnames = json.getJSONObject("names"); Iterator<?> i = jnames.keys(); while (i.hasNext()){ String key = (String) i.next(); String value = jnames.getString(key); names.put(key, value); } } if (json.has("confidence")) { confidence = new Integer(json.getInt("confidence")); } } protected RecordWithNames() { names = new HashMap<String, String>(); } public String getName(String l) { return names.get(l); } public int getGeoNameId() { return geoNameId; } public Integer getConfidence() { return confidence; } }
package com.maxmind.geoip2.record; import java.util.*; import org.json.*; public abstract class RecordWithNames { private HashMap<String, String> names; private Integer geoNameId; private Integer confidence; protected RecordWithNames(JSONObject json) throws JSONException { geoNameId = json.getInt("geoname_id"); names = new HashMap<String, String>(); if (json.has("names")) { JSONObject jnames = json.getJSONObject("names"); for (Iterator<String> i = jnames.keys(); i.hasNext();) { String key = i.next(); String value = jnames.getString(key); names.put(key, value); } } if (json.has("confidence")) { confidence = new Integer(json.getInt("confidence")); } } protected RecordWithNames() { names = new HashMap<String, String>(); } public String getName(String l) { return names.get(l); } public int getGeoNameId() { return geoNameId; } public Integer getConfidence() { return confidence; } }
Fix imports for Django 1.6 and above
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@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. try: from django.conf.urls import patterns, handler500, url # Fallback for Django versions < 1.4 except ImportError: from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views', url(r'^login/$', 'login', name='saml2_login'), url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'), url(r'^logout/$', 'logout', name='saml2_logout'), url(r'^ls/$', 'logout_service', name='saml2_ls'), url(r'^metadata/$', 'metadata', name='saml2_metadata'), ) handler500 = handler500
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@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. from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views', url(r'^login/$', 'login', name='saml2_login'), url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'), url(r'^logout/$', 'logout', name='saml2_logout'), url(r'^ls/$', 'logout_service', name='saml2_ls'), url(r'^metadata/$', 'metadata', name='saml2_metadata'), ) handler500 = handler500
Fix compatibility with newer apispec
from collections import defaultdict from flask import current_app from .operation import Operation from .utils import flask_path_to_swagger, get_state rules = {} def schema_path_helper(spec, path, view, **kwargs): """Path helper that uses resty views :param view: an `ApiView` object """ resource = get_state(current_app).views[view] rule = rules[resource.rule] operations = defaultdict(Operation) view_instance = view() view_instance.spec_declaration(view, operations, spec) # add path arguments parameters = [] for arg in rule.arguments: parameters.append({ 'name': arg, 'in': 'path', 'required': True, 'type': 'string', }) if parameters: operations['parameters'] = parameters path.path = flask_path_to_swagger(resource.rule) path.operations = dict(**operations) def setup(spec): """Setup for the marshmallow plugin.""" spec.register_path_helper(schema_path_helper) global rules rules = { rule.rule: rule for rule in current_app.url_map.iter_rules() }
from collections import defaultdict from flask import current_app from .operation import Operation from .utils import flask_path_to_swagger, get_state rules = {} def schema_path_helper(spec, path, view, **kwargs): """Path helper that uses resty views :param view: an `ApiView` object """ resource = get_state(current_app).views[view] rule = rules[resource.rule] operations = defaultdict(Operation) view_instance = view() view_instance.spec_declaration(view, operations, spec) # add path arguments parameters = [] for arg in rule.arguments: parameters.append({ 'name': arg, 'in': 'path', 'required': True, 'type': 'string', }) if parameters: path['parameters'] = parameters path.path = flask_path_to_swagger(resource.rule) path.operations = dict(**operations) def setup(spec): """Setup for the marshmallow plugin.""" spec.register_path_helper(schema_path_helper) global rules rules = { rule.rule: rule for rule in current_app.url_map.iter_rules() }
Fix removal of antecedent '?' or '&' in fidRemove
(function($, undefined) { // Is History API reliably supported? (based on Modernizr & PJAX) if (!(window.history && history.pushState && window.history.replaceState && !navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]|WebApps\/.+CFNetwork)/))) return; // thx to @ic (http://forum.nette.org/cs/profile.php?id=1985, http://forum.nette.org/cs/4405-flash-zpravicky-bez-fid-v-url#p43713) $.nette.ext('fidRemove', { init: function () { var that = this; setTimeout(function () { var url = window.location.toString(); var pos = url.indexOf('_fid='); if (pos !== -1) { window.history.replaceState({}, null, that.removeFid(url, pos)); } }, this.timeout); } }, { timeout: 3000, removeFid: function (url, pos) { url = url.substr(0, pos) + url.substr(pos + 9); if ((url.substr(pos - 1, 1) === '?') || (url.substr(pos - 1, 1) === '&')) { url = url.substr(0, pos - 1) + url.substr(pos); } return url; } }); })(jQuery);
(function($, undefined) { // Is History API reliably supported? (based on Modernizr & PJAX) if (!(window.history && history.pushState && window.history.replaceState && !navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]|WebApps\/.+CFNetwork)/))) return; // thx to @ic (http://forum.nette.org/cs/profile.php?id=1985, http://forum.nette.org/cs/4405-flash-zpravicky-bez-fid-v-url#p43713) $.nette.ext('fidRemove', { init: function () { var that = this; setTimeout(function () { var url = window.location.toString(); var pos = url.indexOf('_fid='); if (pos !== -1) { window.history.replaceState({}, null, that.removeFid(url, pos)); } }, this.timeout); } }, { timeout: 3000, removeFid: function (url, pos) { if ((url.substr(url.length - 1) === '?') || (url.substr(url.length - 1) === '&')) { url = url.substr(0, url.length - 1); url = url.substr(0, pos) + url.substr(pos + 9); } return url; } }); })(jQuery);
Comment out the google ads git-svn-id: 798f9e0ce1eefcecf757a5f2b692a26d86a9651c@418 c66dcb5a-e80b-0410-ab0e-bb6a4f3ddef9
<?php /** * HTML footer * * @url $URL$ * @date $Date$ * @version $Revision$ * @author $Author$ * * @package Beirdobot * /**/ ?> <hr > <p>IRC Logs collected by <a href="http://trac.beirdo.ca/projects/beirdobot/">BeirdoBot</a>.<br /> Please use the above link to report any bugs. </p> <!-- <script type="text/javascript"><!-- google_ad_client = "pub-5082450290612770"; google_ad_width = 728; google_ad_height = 90; google_ad_format = "728x90_as"; google_ad_type = "text_image"; google_ad_channel ="0019728144"; google_color_border = "607090"; google_color_bg = "191939"; google_color_link = "60A0E0"; google_color_url = "99E0E9"; google_color_text = "BBBBBC"; //--></script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> --> </body> </html>
<?php /** * HTML footer * * @url $URL$ * @date $Date$ * @version $Revision$ * @author $Author$ * * @package Beirdobot * /**/ ?> <hr > <p>IRC Logs collected by <a href="http://trac.beirdo.ca/projects/beirdobot/">BeirdoBot</a>.<br /> Please use the above link to report any bugs. </p> <script type="text/javascript"><!-- google_ad_client = "pub-5082450290612770"; google_ad_width = 728; google_ad_height = 90; google_ad_format = "728x90_as"; google_ad_type = "text_image"; google_ad_channel ="0019728144"; google_color_border = "607090"; google_color_bg = "191939"; google_color_link = "60A0E0"; google_color_url = "99E0E9"; google_color_text = "BBBBBC"; //--></script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> </body> </html>
Fix installing packages with blueprint
/* global module */ const postCSSCompilingPackages = [ { name: 'broccoli-funnel', target: '^1.1.0' }, { name: 'broccoli-merge-trees',target: '^1.2.1' }, { name: 'broccoli-postcss-single', target: '^1.2.0' }, { name: 'postcss-cssnext', target: '^2.9.0' }, { name: 'postcss-import', target: '^9.0.0' } ]; module.exports = { description: 'install ticketfly-css into an Ember CLI project', normalizeEntityName: function() {}, beforeInstall: function(options) { return this.addPackagesToProject(postCSSCompilingPackages); } // locals: function(options) { // // Return custom template variables here. // return { // foo: options.entity.options.foo // }; // } // afterInstall: function(options) { // // Perform extra work here. // } };
/* global module */ const postCSSCompilingPackages = [ { name: 'broccoli-funnel', target: '^1.1.0' }, { name: 'broccoli-merge-trees',target: '^1.2.1' }, { name: 'broccoli-postcss-single', target: '^1.2.0' }, { name: 'postcss-cssnext', target: '^2.9.0' }, { name: 'postcss-import', target: '^9.0.0' } ]; module.exports = { description: 'install ticketfly-css into an Ember CLI project', normalizeEntityName: function() {}, afterInstall: function(options) { return this.addPackagesToProject(postCSSCompilingPackages); } // locals: function(options) { // // Return custom template variables here. // return { // foo: options.entity.options.foo // }; // } // afterInstall: function(options) { // // Perform extra work here. // } };
Test to validate trimming scenario
from grazer.core import crawler from bs4 import BeautifulSoup def test_extract_links(): text = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> </body> </html> """ bs = BeautifulSoup(text, "html.parser") links = crawler.extract_links(bs) expected = ["http://example.com/elsie", "http://example.com/lacie", "http://example.com/tillie"] assert links == expected def test_link_trimmer(): result = crawler.trim_link("http://example.com/lacie", "http://example.com") assert result == "/lacie" def test_trim_link_without_trailing_slash(): result = crawler.trim_link("http://example.com", "http://example.com") assert result == "http://example.com"
from grazer.core import crawler from bs4 import BeautifulSoup def test_extract_links(): text = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> </body> </html> """ bs = BeautifulSoup(text, "html.parser") links = crawler.extract_links(bs) expected = ["http://example.com/elsie", "http://example.com/lacie", "http://example.com/tillie"] assert links == expected def test_link_trimmer(): result = crawler.trim_link("http://example.com/lacie", "http://example.com") assert result == "/lacie"
Add signing to custom-sidebar integration.
// Deps var crypto = require('crypto'); var express = require('express'); var bodyParser = require('body-parser'); // Config: var port = process.env.PORT || 8000; var root = __dirname + '/'; var sendFileConfig = { root: root }; var secret = '123abc'; // App: var app = express(); var bodyParserMiddleware = bodyParser.urlencoded({ verify: function (req, res, buf, encoding) { // Get hash of message using shared secret: var hasher = crypto.createHmac('sha1', secret); hasher.update(buf.toString()); var hash = hasher.digest('base64'); // Compare hash to Acuity signature: if (hash !== req.header('X-Acuity-Signature')) { throw new Error('This message was forged!'); } } }); app.get('/', function (req, res) { res.sendFile('index.html', sendFileConfig); }); app.post('/custom-sidebar', bodyParserMiddleware, function (req, res) { setTimeout(function () { res.send( '<pre>' + JSON.stringify(req.body, null, ' ') + '</pre>' ); }, 500); }); // Server: var server = app.listen(port, function () { console.log('Listening on %s', port); }); server.on('error', function (e) { if (e.code === 'EADDRINUSE') { console.error('Error listening on %s', port); } else { console.error(e); } });
// Deps var express = require('express'); var bodyParser = require('body-parser'); // Config: var port = process.env.PORT || 8000; var root = __dirname + '/'; var sendFileConfig = { root: root }; // App: var app = express(); app.use(bodyParser.urlencoded()); app.get('/', function (req, res) { res.sendFile('index.html', sendFileConfig); }); app.post('/custom-sidebar', function (req, res) { setTimeout(function () { res.send( '<pre>' + JSON.stringify(req.body, null, ' ') + '</pre>' ); }, 500); }); // Server: var server = app.listen(port, function () { console.log('Listening on %s', port); }); server.on('error', function (e) { if (e.code === 'EADDRINUSE') { console.error('Error listening on %s', port); } else { console.error(e); } });
Fix broken camel art and add a better message
'use strict'; var chalk = require('chalk'); var greetings = '\n' + chalk.yellow(' ,,__ \n') + chalk.yellow(" .. .. / o._) .---. \n") + chalk.yellow(" /--'/--\ \-'|| .----. .' '. \n") + chalk.yellow(" / \_/ / | .' '..' '-. \n") + chalk.yellow(" .'\ \__\ __.'.' .' '-._ \n") + chalk.yellow(" )\ | )\ | _.' \n") + chalk.yellow(' // \\ // \\ \n') + chalk.yellow(" ||_ \\|_ \\_ \n") + chalk.yellow(" '--' '--'' '--' \n") + chalk.yellow('\n Yo OCaml! ') + chalk.gray('A Yeoman generator that provides a functional boilerplate to easily scaffold OCaml modules. \n') + chalk.yellow("\n Let's talk about your new module? \n"); module.exports = greetings;
var chalk = require('chalk'); var greetings = "" + chalk.yellow(" .. .. / o._) .---.") + chalk.yellow(" /--'/--\ \-'|| .----. .' '.") + chalk.yellow(" / \_/ / | .' '..' '-.") + chalk.yellow(".'\ \__\ __.'.' .' ì-._") + chalk.yellow(" )\ | )\ | _.'") + chalk.yellow("// \\ // \\") + chalk.yellow("||_ \\|_ \\_") + chalk.yellow("'--' '--'' '--'") + chalk.gray("\n Yo OCaml! A Yeoman generator that provides a functional boilerplate to easily scaffold OCaml modules. \n"); module.exports = greetings;
Add methods for 403 and 409 HTTP errors
<?php namespace Neomerx\JsonApi\Contracts\Integration; /** * Copyright 2015 info@neomerx.com (www.neomerx.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. */ /** * @package Neomerx\JsonApi */ interface ExceptionThrowerInterface { /** * Throw 'Bad request' exception (HTTP code 400). * * @return void */ public function throwBadRequest(); /** * Throw 'Forbidden' exception (HTTP code 403). * * @return void */ public function throwForbidden(); /** * Throw 'Not Acceptable' exception (HTTP code 406). * * @return void */ public function throwNotAcceptable(); /** * Throw 'Conflict' exception (HTTP code 409). * * @return void */ public function throwConflict(); /** * Throw 'Unsupported Media Type' exception (HTTP code 415). * * @return void */ public function throwUnsupportedMediaType(); }
<?php namespace Neomerx\JsonApi\Contracts\Integration; /** * Copyright 2015 info@neomerx.com (www.neomerx.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. */ /** * @package Neomerx\JsonApi */ interface ExceptionThrowerInterface { /** * Throw 'Bad request' exception (HTTP code 400). * * @return void */ public function throwBadRequest(); /** * Throw 'Not Acceptable' exception (HTTP code 406). * * @return void */ public function throwNotAcceptable(); /** * Throw 'Unsupported Media Type' exception (HTTP code 415). * * @return void */ public function throwUnsupportedMediaType(); }
Fix for broken payload when no internal actions
const _ = require('lodash'); const Client = require('ci-client'); const commands = require('./commands'); module.exports.start = (commonConfig) => { const commandNames = _.flatten(commands.map(cmd => cmd.commands)); console.log('Internal commands found', commandNames); const clientConfig = Object.assign({ name: 'internal-client', commands: commandNames }, commonConfig); const client = new Client(clientConfig); const messageReceiver = (action, message, context, reply) => { console.log(`Message received ${message}`); console.log('Should do an action now'); }; client.setReceiver(messageReceiver); const commandBroker = (command, params, context, reply) => { console.log('Command received', command); console.log('Command params', params); const internalCommand = _.find(commands, cmd => cmd.commands.indexOf(command) !== -1); console.log(internalCommand); if (internalCommand !== undefined) { console.log('Internal command'); internalCommand.commandHandler(command, params, context, reply); } else { console.log('Something weird happening, no internal command here'); } }; client.setCommandHandler(commandBroker); };
const _ = require('lodash'); const Client = require('ci-client'); const commands = require('./commands'); module.exports.start = (commonConfig) => { const commandNames = _.flatten(commands.map(cmd => cmd.commands)); console.log('Internal commands found', commandNames); const clientConfig = Object.assign({ name: 'internal-client', commands: commandNames, actions: [] }, commonConfig); const client = new Client(clientConfig); const messageReceiver = (action, message, context, reply) => { console.log(`Message received ${message}`); console.log('Should do an action now'); }; client.setReceiver(messageReceiver); const commandBroker = (command, params, context, reply) => { console.log('Command received', command); console.log('Command params', params); const internalCommand = _.find(commands, cmd => cmd.commands.indexOf(command) !== -1); console.log(internalCommand); if (internalCommand !== undefined) { console.log('Internal command'); internalCommand.commandHandler(command, params, context, reply); } else { console.log('Something weird happening, no internal command here'); } }; client.setCommandHandler(commandBroker); };
Add support for Node.js v4 and v5
'use strict'; // eslint-disable-line strict, lines-around-directive const socketIo = require('socket.io'); const gatherOsMetrics = require('./gather-os-metrics'); let io; module.exports = (server, spans) => { if (io === null || io === undefined) { io = socketIo(server); io.on('connection', (socket) => { socket.emit('start', spans); socket.on('change', () => { socket.emit('start', spans); }); }); spans.forEach((currentSpan) => { const span = currentSpan; span.os = []; span.responses = []; const interval = setInterval(() => gatherOsMetrics(io, span), span.interval * 1000); interval.unref(); // don't keep node.js process up }); } };
const socketIo = require('socket.io'); const gatherOsMetrics = require('./gather-os-metrics'); let io; module.exports = (server, spans) => { if (io === null || io === undefined) { io = socketIo(server); io.on('connection', (socket) => { socket.emit('start', spans); socket.on('change', () => { socket.emit('start', spans); }); }); spans.forEach((currentSpan) => { const span = currentSpan; span.os = []; span.responses = []; const interval = setInterval(() => gatherOsMetrics(io, span), span.interval * 1000); interval.unref(); // don't keep node.js process up }); } };
Remove no longer needed python libs
#!/usr/local/bin/python3 -u __author__ = 'Oliver Ratzesberger <https://github.com/fxstein>' __copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger' __license__ = 'Apache License, Version 2.0' # Make sure we have access to SentientHome commons import os, sys sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') # Sentient Home Application from common.shapp import shApp from common.sheventhandler import shEventHandler # Simple loadtest that 'fires' events as fast as possible with shApp('loadtest') as app: app.run() handler = shEventHandler(app) count = 0 while True: count += 1 event = [{ 'name': 'loadtest', # Time Series Name 'columns': ['count'], # Keys 'points': [[count]] # Data points }] handler.postEvent(event)
#!/usr/local/bin/python3 -u __author__ = 'Oliver Ratzesberger <https://github.com/fxstein>' __copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger' __license__ = 'Apache License, Version 2.0' # Make sure we have access to SentientHome commons import os, sys sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') # Sentient Home Application from common.shapp import shApp from common.sheventhandler import shEventHandler import logging as log import time # Simple loadtest that 'fires' events as fast as possible with shApp('loadtest') as app: app.run() handler = shEventHandler(app) count = 0 while True: count += 1 event = [{ 'name': 'loadtest', # Time Series Name 'columns': ['count'], # Keys 'points': [[count]] # Data points }] handler.postEvent(event)
Fix inline script visibility in enum handler
'use strict'; var assign = require('es5-ext/object/assign') , mixin = require('es5-ext/object/mixin') , d = require('d') , autoBind = require('d/auto-bind') , DOMRadio = require('dbjs-dom/input/enum').Radio , RadioBtnGroup = require('./_inline-button-group') , createOption = DOMRadio.prototype.createOption , reload = DOMRadio.prototype.reload , Radio; module.exports = Radio = function (document, type/*, options*/) { var options = Object(arguments[2]); this.controlsOptions = Object(options.controls); DOMRadio.call(this, document, type, options); }; Radio.prototype = Object.create(DOMRadio.prototype); mixin(Radio.prototype, RadioBtnGroup.prototype); Object.defineProperties(Radio.prototype, assign({ constructor: d(Radio), createOption: d(function (name) { var dom = createOption.call(this, name); this.listItems[name] = dom = dom.firstChild; return dom; }) }, autoBind({ reload: d(function () { reload.apply(this, arguments); this.dom.appendChild(this.classHandlerScript); }) })));
'use strict'; var mixin = require('es5-ext/object/mixin') , d = require('d') , DOMRadio = require('dbjs-dom/input/enum').Radio , RadioBtnGroup = require('./_inline-button-group') , createOption = DOMRadio.prototype.createOption , Radio; module.exports = Radio = function (document, type/*, options*/) { var options = Object(arguments[2]); this.controlsOptions = Object(options.controls); DOMRadio.call(this, document, type, options); }; Radio.prototype = Object.create(DOMRadio.prototype); mixin(Radio.prototype, RadioBtnGroup.prototype); Object.defineProperties(Radio.prototype, { constructor: d(Radio), createOption: d(function (name) { var dom = createOption.call(this, name); this.listItems[name] = dom = dom.firstChild; return dom; }) });
Add print statement to indicate server is running
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/hostname", hostnameHandler) http.HandleFunc("/time", timeHandler) http.HandleFunc("/issue", issueHandler) fmt.Println("Serving on port 3000...") http.ListenAndServe(":3000", nil) } func hostnameHandler(w http.ResponseWriter, r *http.Request) { hostname, err := hostname() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Write([]byte(hostname)) } func timeHandler(w http.ResponseWriter, r *http.Request) { time, err := time() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Write([]byte(time)) } func issueHandler(w http.ResponseWriter, r *http.Request) { distro, kernel, err := issue() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Write([]byte(distro + " " + kernel)) }
package main import "net/http" func main() { http.HandleFunc("/hostname", hostnameHandler) http.HandleFunc("/time", timeHandler) http.HandleFunc("/issue", issueHandler) http.ListenAndServe(":3000", nil) } func hostnameHandler(w http.ResponseWriter, r *http.Request) { hostname, err := hostname() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Write([]byte(hostname)) } func timeHandler(w http.ResponseWriter, r *http.Request) { time, err := time() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Write([]byte(time)) } func issueHandler(w http.ResponseWriter, r *http.Request) { distro, kernel, err := issue() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Write([]byte(distro + " " + kernel)) }
Make main template really configurable again
"use strict"; angular.module( 'arethusa', [ 'mm.foundation', 'ngRoute', 'arethusa.core', 'arethusa.morph', 'arethusa.hist' ], function($routeProvider) { $routeProvider.when('/', { controller: 'MainCtrl', template: '<div ng-include="template"></div>', resolve: { loadConfiguration: function($q, $http, $route, configurator) { return $http({ method: 'GET', url: $route.current.params.conf || './static/configuration_default.json' }).then(function(result) { configurator.configuration = result.data; }); } } } ); });
"use strict"; angular.module( 'arethusa', [ 'mm.foundation', 'ngRoute', 'arethusa.core', 'arethusa.morph', 'arethusa.hist' ], function($routeProvider) { $routeProvider.when('/', { controller: 'MainCtrl', templateUrl: 'templates/main2.html', resolve: { loadConfiguration: function($q, $http, $route, configurator) { console.log($route.current.params.conf); return $http({ method: 'GET', url: $route.current.params.conf || './static/configuration_default.json' }).then(function(result) { configurator.configuration = result.data; }); } } } ); });
Add 'rb' to open() to support python 3
from distutils.extension import Extension from setuptools import setup, Extension from Cython.Distutils import build_ext import os.path here = os.path.dirname(os.path.abspath(__file__)) ext_modules = [Extension("sass", ["sass.pyx"], libraries=["sass", 'stdc++'] )] setup( name = 'sass', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules, version = '1.0', author = 'Sergey Kirilov', author_email = 'sergey.kirillov@gmail.com', url='https://github.com/pistolero/python-scss', install_requires=['Cython'], license="Apache License 2.0", keywords="sass scss libsass", description='Python bindings for libsass', long_description=open(os.path.join(here, 'README.rst'), 'rb').read().decode('utf-8') )
from distutils.extension import Extension from setuptools import setup, Extension from Cython.Distutils import build_ext import os.path here = os.path.dirname(os.path.abspath(__file__)) ext_modules = [Extension("sass", ["sass.pyx"], libraries=["sass", 'stdc++'] )] setup( name = 'sass', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules, version = '1.0', author = 'Sergey Kirilov', author_email = 'sergey.kirillov@gmail.com', url='https://github.com/pistolero/python-scss', install_requires=['Cython'], license="Apache License 2.0", keywords="sass scss libsass", description='Python bindings for libsass', long_description=open(os.path.join(here, 'README.rst')).read().decode('utf-8') )
Remove unneeded Mocha require statement
'use strict'; const gulpopen = require('../'); const os = require('os'); describe('gulp-open', function() { const browser = os.platform() === 'linux' ? 'google-chrome' : ( os.platform() === 'darwin' ? 'google chrome' : ( os.platform() === 'win32' ? 'chrome' : 'firefox')); describe('opening files', function() { it('should open a stream of files with the default application', function(done) { gulpopen('<%= file.path%>', {}, done()); }); it('should open a stream of files with a defined application', function(done) { gulpopen('<%= file.path%>', {app: browser}, done()); }); it('should open a stream of files with a browser using the options', function(done) { gulpopen({}, {uri: __dirname + '/../package.json', app: browser}, done()); }); }); describe('opening urls', function() { it('should open a website in a browser using the options', function(done) { gulpopen({}, {uri: 'http://localhost:3000'}, done()); }); it('should open a website in a browser using chrome or firefox', function(done) { gulpopen({}, {uri: 'https://www.google.com', app: browser}, done()); }); }); });
'use strict'; const gulpopen = require('../'); const os = require('os'); require('mocha'); describe('gulp-open', function() { const browser = os.platform() === 'linux' ? 'google-chrome' : ( os.platform() === 'darwin' ? 'google chrome' : ( os.platform() === 'win32' ? 'chrome' : 'firefox')); describe('opening files', function() { it('should open a stream of files with the default application', function(done) { gulpopen('<%= file.path%>', {}, done()); }); it('should open a stream of files with a defined application', function(done) { gulpopen('<%= file.path%>', {app: browser}, done()); }); it('should open a stream of files with a browser using the options', function(done) { gulpopen({}, {uri: __dirname + '/../package.json', app: browser}, done()); }); }); describe('opening urls', function() { it('should open a website in a browser using the options', function(done) { gulpopen({}, {uri: 'http://localhost:3000'}, done()); }); it('should open a website in a browser using chrome or firefox', function(done) { gulpopen({}, {uri: 'https://www.google.com', app: browser}, done()); }); }); });
Store actual target for actual rule in rule struct
package main import ( "github.com/aws/aws-sdk-go/service/cloudwatchevents" ) type Rules struct { Rules []Rule } type Rule struct { Description string `yaml:"description"` EventPattern string `yaml:"event_pattern"` Name string `yaml:"name"` ScheduleExpression string `yaml:"schedule_expression"` State string `yaml:"state"` LambdaFunctions []LambdaFunction `yaml:"lambda_functions"` ActualRule cloudwatchevents.Rule ActualTargets []cloudwatchevents.Target NeedUpdate bool } type LambdaFunction struct { Name string `yaml:"name"` Input string `yaml:"input"` InputPath string `yaml:"input_path"` }
package main import ( "github.com/aws/aws-sdk-go/service/cloudwatchevents" ) type Rules struct { Rules []Rule } type Rule struct { Description string `yaml:"description"` EventPattern string `yaml:"event_pattern"` Name string `yaml:"name"` ScheduleExpression string `yaml:"schedule_expression"` State string `yaml:"state"` LambdaFunctions []LambdaFunction `yaml:"lambda_functions"` ActualRule cloudwatchevents.Rule NeedUpdate bool } type LambdaFunction struct { Name string `yaml:"name"` Input string `yaml:"input"` InputPath string `yaml:"input_path"` }
Fix related box going over footer
$(function(){ function checkOverflow(){ var $related = $(".related-positioning"); if($related.length !== 0 && $related.css('position') == 'fixed') { var viewPort = $(window).height(); var relatedBox = $(".related").height(); var boxOffset = $related.position().top; if(relatedBox > (viewPort - boxOffset)){ $related.css("position", "absolute"); return true; } else { $related.css("position", "fixed"); return false; } } return false; } if(!checkOverflow()){ window.GOVUK.stopScrollingAtFooter.addEl($('.related-positioning'), $('#related').height()); } });
$(function(){ function checkOverflow(){ var $related = $(".related-positioning"); if($related.length !== 0 && $related.css('position') == 'fixed') { var viewPort = $(window).height(); var relatedBox = $(".related").height(); var boxOffset = $related.position().top; if(relatedBox > (viewPort - boxOffset)){ $related.css("position", "absolute"); return true; } else { $related.css("position", "fixed"); return false; } } return false; } if(!checkOverflow()){ window.GOVUK.stopScrollingAtFooter.addEl($('.related-positioning'), $('#related .inner').height()); } });
Rename menu pick that opens into Browser as VisBrowser. Changing JxBrowser menu pick to Visualizer to follow.
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.opensim.threejs; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.eclipse.jetty.JettyMain; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.NbBundle.Messages; import org.opensim.swingui.SwingWorker; import org.opensim.utils.BrowserLauncher; import org.opensim.view.pub.OpenSimDB; import org.opensim.view.pub.ViewDB; @ActionID( category = "Edit", id = "org.opensim.threejs.VisualizerWindow" ) @ActionRegistration( displayName = "#CTL_VisualizerWindow" ) @ActionReference(path = "Menu/Window", position = 3333) @Messages("CTL_VisualizerWindow=Vis Browser") public final class VisualizerWindowAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // launch server and open page in fixed location to be used as a view openVisualizerWindow(); } public static void openVisualizerWindow() { ViewDB.getInstance().startVisualizationServer(); BrowserLauncher.openURL("http://localhost:"+JettyMain.getServerPort()+JettyMain.getPathToStartPage()+"index.html"); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.opensim.threejs; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.eclipse.jetty.JettyMain; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.NbBundle.Messages; import org.opensim.swingui.SwingWorker; import org.opensim.utils.BrowserLauncher; import org.opensim.view.pub.OpenSimDB; import org.opensim.view.pub.ViewDB; @ActionID( category = "Edit", id = "org.opensim.threejs.VisualizerWindow" ) @ActionRegistration( displayName = "#CTL_VisualizerWindow" ) @ActionReference(path = "Menu/Window", position = 3333) @Messages("CTL_VisualizerWindow=Visualizer") public final class VisualizerWindowAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // launch server and open page in fixed location to be used as a view openVisualizerWindow(); } public static void openVisualizerWindow() { ViewDB.getInstance().startVisualizationServer(); BrowserLauncher.openURL("http://localhost:"+JettyMain.getServerPort()+JettyMain.getPathToStartPage()+"index.html"); } }
Fix ID handling of rst widget
// Copyright (c) 2012 gocept gmbh & co. kg // See also LICENSE.txt (function($) { zeit.cms.RestructuredTextWidget = gocept.Class.extend({ construct: function(widget_id) { var self = this; widget_id = widget_id.replace(/\./g, '\\.'); self.textarea = $('#' + widget_id); self.preview = $('#' + widget_id + '\\.preview'); self.textarea.hide(); // XXX This assumes knowlegde outside the widget about how the form is // rendered. Unfortunately there doesn't seem to be another way to // achieve a large enough click area. self.preview.closest('.field').bind('click', function(event) { if (event.target.nodeName == 'A') { return; } self.preview.hide(); self.textarea.show(); self.textarea.focus(); }); $('a', self.preview).each(function(i, elem) { $(elem).attr('target', '_blank'); }); if (! self.preview.text()) { self.preview.addClass('empty'); } } }); }(jQuery));
// Copyright (c) 2012 gocept gmbh & co. kg // See also LICENSE.txt (function($) { zeit.cms.RestructuredTextWidget = gocept.Class.extend({ construct: function(widget_id) { var self = this; widget_id = widget_id.replace('.', '\\.'); self.textarea = $('#' + widget_id); self.preview = $('#' + widget_id + '\\.preview'); self.textarea.hide(); // XXX This assumes knowlegde outside the widget about how the form is // rendered. Unfortunately there doesn't seem to be another way to // achieve a large enough click area. self.preview.closest('.field').bind('click', function(event) { if (event.target.nodeName == 'A') { return; } self.preview.hide(); self.textarea.show(); self.textarea.focus(); }); $('a', self.preview).each(function(i, elem) { $(elem).attr('target', '_blank'); }); if (! self.preview.text()) { self.preview.addClass('empty'); } } }); }(jQuery));
Add source title to messages
'use strict'; const config = require('./config'); const gooGl = require('goo.gl'); const moment = require('moment-timezone'); const removeUrlGarbage = require('link-cleaner'); if (config.shortenLinks) { gooGl.setKey(config.gooGlKey); } async function formatDocuments(data) { data.sort((a, b) => { const ap = a.published; const bp = b.published; if (ap > bp) { return 1; } if (ap < bp) { return -1; } return 0; }); const docs = []; for (let doc of data) { const link = config.shortenLinks ? await gooGl.shorten(doc.link) : removeUrlGarbage(doc.link); const date = moment.tz(doc.published, 'UTC'); const formattedDate = date.tz(config.tz).format('DD.MM.Y HH:mm'); docs.push(`${formattedDate} ${link}\n${doc.title}: ${doc.source_title}`); } return docs; } module.exports = { formatDocuments, };
'use strict'; const config = require('./config'); const gooGl = require('goo.gl'); const moment = require('moment-timezone'); const removeUrlGarbage = require('link-cleaner'); if (config.shortenLinks) { gooGl.setKey(config.gooGlKey); } async function formatDocuments(data) { data.sort((a, b) => { const ap = a.published; const bp = b.published; if (ap > bp) { return 1; } if (ap < bp) { return -1; } return 0; }); const docs = []; for (let doc of data) { const link = config.shortenLinks ? await gooGl.shorten(doc.link) : removeUrlGarbage(doc.link); const date = moment.tz(doc.published, 'UTC'); const formattedDate = date.tz(config.tz).format('DD.MM.Y HH:mm'); docs.push(`${formattedDate} ${link}\n${doc.title}`); } return docs; } module.exports = { formatDocuments, };
Update variables names in exam tests
# -*- coding: utf-8 -*- from django.test import TestCase from should_dsl import should from exam.dynamic_import import create_specific_exam from core.tests import FormatTest from sys import stderr class TestDynamicImport(FormatTest, TestCase): def setUp(self): self.my_type = '[Exam - Dynamic Import]' stderr.write(self.__str__()) def test_create_biopsy_exam(self): from biopsy.models import Biopsy biopsy_exam = create_specific_exam('Biopsy') biopsy_exam | should | be_kind_of(Biopsy) def test_create_necropsy_exam(self): from necropsy.models import Necropsy necropsy_exam = create_specific_exam('Necropsy') necropsy_exam | should | be_kind_of(Necropsy) def test_create_specific_exam_invalid_param(self): from exam.exceptions import InvalidParameter InvalidParameter | should | be_thrown_by(lambda: create_specific_exam( '')) def test_create_specific_exam_invalid_model(self): from exam.exceptions import ModelDoesNotExist ModelDoesNotExist | should | be_thrown_by(lambda: create_specific_exam( 'InvalidModel'))
# -*- coding: utf-8 -*- from django.test import TestCase from should_dsl import should from exam.dynamic_import import create_specific_exam from core.tests import FormatTest from sys import stderr class TestDynamicImport(FormatTest, TestCase): def setUp(self): self.my_type = '[Exam - Dynamic Import]' stderr.write(self.__str__()) def test_create_biopsy_exam(self): from biopsy.models import Biopsy specific_exam = create_specific_exam('Biopsy') specific_exam | should | be_kind_of(Biopsy) def test_create_necropsy_exam(self): from necropsy.models import Necropsy specific_exam = create_specific_exam('Necropsy') specific_exam | should | be_kind_of(Necropsy) def test_create_specific_exam_invalid_param(self): from exam.exceptions import InvalidParameter InvalidParameter | should | be_thrown_by(lambda: create_specific_exam( '')) def test_create_specific_exam_invalid_model(self): from exam.exceptions import ModelDoesNotExist ModelDoesNotExist | should | be_thrown_by(lambda: create_specific_exam( 'InvalidModel'))
Trim down defaults out of TimeoutDetector.
'use strict'; /*jslint node: true, es5: true, indent: 2 */ var util = require('util'); var stream = require('stream'); var TimeoutDetector = module.exports = function(opts) { if (!opts || !opts.timeout) throw new Error('TimeoutDetector({timeout: ...}) is a required parameter.'); stream.Transform.call(this, opts); this.timeout_ms = opts.timeout * 1000; setInterval(this._check.bind(this), this.timeout_ms); }; util.inherits(TimeoutDetector, stream.Transform); TimeoutDetector.prototype._check = function() { // silent_ms: milliseconds since we got some incoming data var silent_ms = Date.now() - this.last; if (silent_ms > this.timeout_ms) { // ensure we get something every x seconds. this.emit('error', new Error('TimeoutDetector timed out.')); } }; TimeoutDetector.prototype._transform = function(chunk, encoding, callback) { this.last = Date.now(); this.push(chunk); callback(); };
'use strict'; /*jslint node: true, es5: true, indent: 2 */ var util = require('util'); var stream = require('stream'); var TimeoutDetector = module.exports = function(opts) { if (opts === undefined) opts = {}; // opts = {[timeout: 60 (seconds)]} stream.Transform.call(this, opts); if (opts.timeout !== undefined) { // ensure we get something every x seconds. this.timeout_ms = opts.timeout * 1000; setInterval(this._check.bind(this), this.timeout_ms); } }; util.inherits(TimeoutDetector, stream.Transform); TimeoutDetector.prototype._check = function() { // silent_ms: milliseconds since we got some incoming data var silent_ms = Date.now() - this.last; if (silent_ms > this.timeout_ms) { this.emit('error', new Error('Timeout pipe timed out.')); } }; TimeoutDetector.prototype._transform = function(chunk, encoding, callback) { this.last = Date.now(); this.push(chunk); callback(); };
Fix once again nobody being allowed to connect
from txircd.channel import IRCChannel from txircd.modbase import Module class Autojoin(Module): def joinOnConnect(self, user): if "client_join_on_connect" in self.ircd.servconfig: for channel in self.ircd.servconfig["client_join_on_connect"]: user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel)) return True class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.conn_join = None def spawn(self): self.conn_join = Autojoin().hook(self.ircd) return { "actions": { "register": [self.conn_join.joinOnConnect] } } def cleanup(self): self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)
from txircd.channel import IRCChannel from txircd.modbase import Module class Autojoin(Module): def joinOnConnect(self, user): if "client_join_on_connect" in self.ircd.servconfig: for channel in self.ircd.servconfig["client_join_on_connect"]: user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel)) class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.conn_join = None def spawn(self): self.conn_join = Autojoin().hook(self.ircd) return { "actions": { "register": self.conn_join.joinOnConnect } } def cleanup(self): self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)
Fix another broken sc2reader.plugins reference.
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals, division import sc2reader from sc2reader.factories.plugins.replay import toJSON def main(): import argparse parser = argparse.ArgumentParser(description="Prints replay data to a json string.") parser.add_argument('--indent', '-i', type=int, default=None, help="The per-line indent to use when printing a human readable json string") parser.add_argument('--encoding', '-e', type=str, default='UTF-8', help="The character encoding use..") parser.add_argument('path', metavar='path', type=str, nargs=1, help="Path to the replay to serialize.") args = parser.parse_args() factory = sc2reader.factories.SC2Factory() factory.register_plugin("Replay", toJSON(encoding=args.encoding, indent=args.indent)) replay_json = factory.load_replay(args.path[0]) print(replay_json) if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals, division import sc2reader from sc2reader.plugins.replay import toJSON def main(): import argparse parser = argparse.ArgumentParser(description="Prints replay data to a json string.") parser.add_argument('--indent', '-i', type=int, default=None, help="The per-line indent to use when printing a human readable json string") parser.add_argument('--encoding', '-e', type=str, default='UTF-8', help="The character encoding use..") parser.add_argument('path', metavar='path', type=str, nargs=1, help="Path to the replay to serialize.") args = parser.parse_args() factory = sc2reader.factories.SC2Factory() factory.register_plugin("Replay", toJSON(encoding=args.encoding, indent=args.indent)) replay_json = factory.load_replay(args.path[0]) print(replay_json) if __name__ == '__main__': main()
Update dependencies to make it installable.
""" setup.py """ from setuptools import setup, find_packages setup( name='SATOSA', version='2.1.1', description='Protocol proxy (SAML/OIDC).', author='DIRG', author_email='dirg@its.umu.se', license='Apache 2.0', url='https://github.com/its-dirg/SATOSA', packages=find_packages('src/'), package_dir={'': 'src'}, install_requires=[ "oic>=0.8.4.0", "pyop==1.0.0", "pyjwkest==1.1.5", "pysaml2==4.0.3", "requests", "PyYAML", "gunicorn", "Werkzeug", "click" ], zip_safe=False, classifiers=[ "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.4", ], entry_points={ "console_scripts": ["satosa-saml-metadata=satosa.scripts.satosa_saml_metadata:construct_saml_metadata"] } )
""" setup.py """ from setuptools import setup, find_packages setup( name='SATOSA', version='2.1.1', description='Protocol proxy (SAML/OIDC).', author='DIRG', author_email='dirg@its.umu.se', license='Apache 2.0', url='https://github.com/its-dirg/SATOSA', packages=find_packages('src/'), package_dir={'': 'src'}, install_requires=[ "oic==0.8.4.0", "pyop==1.0.0", "pyjwkest==1.1.5", "pysaml2==4.0.3", "requests==2.9.1", "PyYAML==3.11", "gunicorn==19.4.1", "Werkzeug==0.11.2", "click==6.6" ], zip_safe=False, classifiers=[ "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.4", ], entry_points={ "console_scripts": ["satosa-saml-metadata=satosa.scripts.satosa_saml_metadata:construct_saml_metadata"] } )
Remove question mark as initial state on tabs
(function(){ 'use strict'; angular.module('cla.controllers') .controller('CaseEditDetailCtrl', ['$scope', 'AlternativeHelpService', function($scope, AlternativeHelpService){ // when viewing coming back to the details view // clear out the Alternative Help selections. AlternativeHelpService.clear(); $scope.diagnosisIcon = function () { return $scope.diagnosis.isInScopeTrue() ? 'Icon Icon--right Icon--solidTick Icon--green' : ($scope.diagnosis.isInScopeFalse() ? 'Icon Icon--right Icon--solidCross Icon--red' : ''); }; $scope.eligibilityIcon = function () { return $scope.eligibility_check.isEligibilityTrue() ? 'Icon Icon--right Icon--solidTick Icon--green' : ($scope.eligibility_check.isEligibilityFalse() ? 'Icon Icon--right Icon--solidCross Icon--red' : ''); }; } ] ); })();
(function(){ 'use strict'; angular.module('cla.controllers') .controller('CaseEditDetailCtrl', ['$scope', 'AlternativeHelpService', function($scope, AlternativeHelpService){ // when viewing coming back to the details view // clear out the Alternative Help selections. AlternativeHelpService.clear(); $scope.diagnosisIcon = function () { return $scope.diagnosis.isInScopeTrue() ? 'Icon Icon--right Icon--solidTick Icon--green' : ($scope.diagnosis.isInScopeFalse() ? 'Icon Icon--right Icon--solidCross Icon--red' : 'Icon Icon--right Icon--info'); }; $scope.eligibilityIcon = function () { return $scope.eligibility_check.isEligibilityTrue() ? 'Icon Icon--right Icon--solidTick Icon--green' : ($scope.eligibility_check.isEligibilityFalse() ? 'Icon Icon--right Icon--solidCross Icon--red' : 'Icon Icon--right Icon--info'); }; } ] ); })();
Use default value instead of operator 'or'
'use strict' const path = require('path') const {spawnSync} = require('child_process') const { env: { STANDARDJS_EXECUTABLE = 'standard', STANDARDJS_ARGV, SKIP_CODE_STYLE_CHECKING } } = require('process') const wdir = path.resolve(__dirname, '..') test('JavaScript Code Style: StandardJS', () => { if (SKIP_CODE_STYLE_CHECKING === 'true') return const argv = STANDARDJS_ARGV ? JSON.parse(STANDARDJS_ARGV) : [] expect(argv).toBeInstanceOf(Array) const { stdout, stderr, signal, error, status } = spawnSync(STANDARDJS_EXECUTABLE, argv, {cwd: wdir}) if (stdout === null) console.warn('standard.stdout is null') if (stderr === null) console.warn('standard.stderr is null') if (signal) console.warn(`standard.signal is ${JSON.stringify(signal)}`) if (error) throw error if (status) throw new Error(stderr + '\n' + stdout) })
'use strict' const path = require('path') const {spawnSync} = require('child_process') const { env: { STANDARDJS_EXECUTABLE, STANDARDJS_ARGV, SKIP_CODE_STYLE_CHECKING } } = require('process') const wdir = path.resolve(__dirname, '..') test('JavaScript Code Style: StandardJS', () => { if (SKIP_CODE_STYLE_CHECKING === 'true') return const argv = STANDARDJS_ARGV ? JSON.parse(STANDARDJS_ARGV) : [] expect(argv).toBeInstanceOf(Array) const { stdout, stderr, signal, error, status } = spawnSync(STANDARDJS_EXECUTABLE || 'standard', argv, {cwd: wdir}) if (stdout === null) console.warn('standard.stdout is null') if (stderr === null) console.warn('standard.stderr is null') if (signal) console.warn(`standard.signal is ${JSON.stringify(signal)}`) if (error) throw error if (status) throw new Error(stderr + '\n' + stdout) })
Set default log level to warn
var winston = require('winston'), path = require('path'); var logLevel = 'warn'; var sharedLogger = function(filename) { return new winston.Logger({ transports: [ new winston.transports.Console({ prettyPrint: true, timestamp: true, level: logLevel, label: path.basename(filename, '.js') }) ] }); }; sharedLogger.setLevel = function (val) { logLevel = val; } function failedPromiseHandler(logger) { logger = logger || sharedLogger; return function(err) { logger.error(err.stack); }; } function uuid() { return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } module.exports = { logger: sharedLogger, failedPromiseHandler: failedPromiseHandler, uuid: uuid }
var winston = require('winston'), path = require('path'); var logLevel = 'debug'; var sharedLogger = function(filename) { return new winston.Logger({ transports: [ new winston.transports.Console({ prettyPrint: true, timestamp: true, level: logLevel, label: path.basename(filename, '.js') }) ] }); }; sharedLogger.setLevel = function (val) { logLevel = val; } function failedPromiseHandler(logger) { logger = logger || sharedLogger; return function(err) { logger.error(err.stack); }; } function uuid() { return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } module.exports = { logger: sharedLogger, failedPromiseHandler: failedPromiseHandler, uuid: uuid }
Tweak to hard code values to make test pass
package hello; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController public class ArchivedCardController { @RequestMapping("/archivedCards") public List<ArchivedCard> archivedCard() { List<ArchivedCard> archivedCardList = new ArrayList<ArchivedCard>(); ArchivedCard card1 = new ArchivedCard(); card1.setText("Take Claritin"); card1.setDate("5/31/2105"); archivedCardList.add(card1); ArchivedCard card2 = new ArchivedCard(); card2.setText("Save the whales"); card2.setDate("5/31/2105"); archivedCardList.add(card2); return archivedCardList; } }
package hello; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController public class ArchivedCardController { @RequestMapping("/archivedCards") public List<ArchivedCard> archivedCard() { List<ArchivedCard> archivedCardList = new ArrayList<ArchivedCard>(); ArchivedCard card1 = new ArchivedCard(); card1.setText("Take Claritin"); card1.setDate("05/31/2105"); archivedCardList.add(card1); ArchivedCard card2 = new ArchivedCard(); card2.setText("Save the whales"); card2.setDate("05/31/2105"); archivedCardList.add(card2); return archivedCardList; } }
Fix empty first line in migration
<?php /** * Copyright (C) 2019 Xibo Signage Ltd * * Xibo - Digital Signage - http://www.xibo.org.uk * * This file is part of Xibo. * * Xibo 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 * any later version. * * Xibo 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 Xibo. If not, see <http://www.gnu.org/licenses/>. */ use Phinx\Migration\AbstractMigration; /** * Class AddNotificationAttachmentFilenameNonUsersMigration */ class AddNotificationAttachmentFilenameNonUsersMigration extends AbstractMigration { /** @inheritdoc */ public function change() { $table = $this->table('notification'); $table ->addColumn('filename', 'string', ['limit' => 1000, 'null' => true]) ->addColumn('nonusers', 'string', ['limit' => 1000, 'null' => true]) ->save(); } }
<?php /** * Copyright (C) 2019 Xibo Signage Ltd * * Xibo - Digital Signage - http://www.xibo.org.uk * * This file is part of Xibo. * * Xibo 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 * any later version. * * Xibo 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 Xibo. If not, see <http://www.gnu.org/licenses/>. */ use Phinx\Migration\AbstractMigration; /** * Class AddNotificationAttachmentFilenameNonUsersMigration */ class AddNotificationAttachmentFilenameNonUsersMigration extends AbstractMigration { /** @inheritdoc */ public function change() { $table = $this->table('notification'); $table ->addColumn('filename', 'string', ['limit' => 1000, 'null' => true]) ->addColumn('nonusers', 'string', ['limit' => 1000, 'null' => true]) ->save(); } }
Resolve circular reference during import
import boolean class Rule: """ Argument is an expression tree Returns a possibly modified expression tree """ def __call__(self, expr): return self.fire(expr) import algebra class CrossProduct2Join(Rule): """A rewrite rule for removing Cross Product""" def fire(self, expr): if isinstance(expr, algebra.CrossProduct): return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right) return expr def __str__(self): return "CrossProduct(left, right) => Join(1=1, left, right)" class removeProject(Rule): """A rewrite rule for removing Projections""" def fire(self, expr): if isinstance(expr, algebra.Project): return expr.input return expr def __str__(self): return "Project => ()" class OneToOne(Rule): def __init__(self, opfrom, opto): self.opfrom = opfrom self.opto = opto def fire(self, expr): if isinstance(expr, self.opfrom): newop = self.opto() newop.copy(expr) return newop return expr def __str__(self): return "%s => %s" % (self.opfrom.__name__,self.opto.__name__)
import algebra import boolean class Rule: """ Argument is an expression tree Returns a possibly modified expression tree """ def __call__(self, expr): return self.fire(expr) class CrossProduct2Join(Rule): """A rewrite rule for removing Cross Product""" def fire(self, expr): if isinstance(expr, algebra.CrossProduct): return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right) return expr def __str__(self): return "CrossProduct(left, right) => Join(1=1, left, right)" class removeProject(Rule): """A rewrite rule for removing Projections""" def fire(self, expr): if isinstance(expr, algebra.Project): return expr.input return expr def __str__(self): return "Project => ()" class OneToOne(Rule): def __init__(self, opfrom, opto): self.opfrom = opfrom self.opto = opto def fire(self, expr): if isinstance(expr, self.opfrom): newop = self.opto() newop.copy(expr) return newop return expr def __str__(self): return "%s => %s" % (self.opfrom.__name__,self.opto.__name__)
Fix hoem directory for windows
#!/usr/bin/env node 'use strict'; import path from 'path'; import pkg from '../package.json'; import hogan from 'hogan.js'; import app from 'commander'; import DataStore from './DataStore'; var home = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME']; var src = process.env.TSTORE_HOME || path.join(home, '.config/wpmanager'); var store = new DataStore(src); app.version(pkg.version); app.command('get <key>') .description('Print data directly to stdout') .action(key => { var data = store.get(key); console.log(JSON.stringify(data, 0, 2)); }); app.command('set <key> <json>') .description('Set data from json string') .action((key, json) => { store.set(key, json); }); app.command('template <key> <template>') .description('Compile data into provided handlebars template') .action((key, template) => { var data = store.get(key); var template = hogan.compile(template); console.log(template.render(data)); }); app.parse(process.argv);
#!/usr/bin/env node 'use strict'; import path from 'path'; import pkg from '../package.json'; import hogan from 'hogan.js'; import app from 'commander'; import DataStore from './DataStore'; var store = new DataStore(process.env.TSTORE_HOME || path.join(process.env.HOME, '.config/tstore')); app.version(pkg.version); app.command('get <key>') .description('Print data directly to stdout') .action(key => { var data = store.get(key); console.log(JSON.stringify(data, 0, 2)); }); app.command('set <key> <json>') .description('Set data from json string') .action((key, json) => { store.set(key, json); }); app.command('template <key> <template>') .description('Compile data into provided handlebars template') .action((key, template) => { var data = store.get(key); var template = hogan.compile(template); console.log(template.render(data)); }); app.parse(process.argv);
Fix no notification service client issue.
import os import traceback from django.utils import timezone from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer def no_action(msg): pass try: from iconizer.gui_client.notification_service_client import NotificationServiceClient notification_method = NotificationServiceClient().notify except: notification_method = no_action def pull_all_in_enumerable(enum_method): for repo in enum_method(): if os.path.exists(repo.full_path): p = GitSynchronizer(repo.full_path, notification_method()) success = False try: p.pull_all_branches() print "pull and push done", p.sync_msg success = True except: traceback.print_exc() print "Pull error for: %s" % repo.full_path repo.last_checked = timezone.now() repo.is_last_pull_success = success repo.save()
import os import traceback from django.utils import timezone from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer def no_action(msg): pass try: from iconizer.gui_client.notification_service_client import NotificationServiceClient notification_method = NotificationServiceClient().notify except: notification_method = no_action def pull_all_in_enumerable(enum_method): for repo in enum_method(): if os.path.exists(repo.full_path): p = GitSynchronizer(repo.full_path, NotificationServiceClient().notify) success = False try: p.pull_all_branches() print "pull and push done", p.sync_msg success = True except: traceback.print_exc() print "Pull error for: %s" % repo.full_path repo.last_checked = timezone.now() repo.is_last_pull_success = success repo.save()
Handle empty response inside Github monitor.
'use strict'; const assert = require('assert'); const github = require('github'); /** * @param {secret} ORGANIZATION - Github ORGANIZATION name * @param {secret} GITHUB_TOKEN - Github API Token with "org:read" permission * @return JSON ['john', 'mark'] */ module.exports = (ctx, cb) => { assert(ctx.secrets, 'Secrets not set!'); assert(ctx.secrets.GITHUB_TOKEN, 'GITHUB_TOKEN not set!'); assert(ctx.secrets.ORGANIZATION, 'ORGANIZATION not set!'); const client = new github({ version: '3.0.0', debug: false, protocol: 'https', host: 'api.github.com', timeout: 5000, headers: { 'user-agent': 'webtask-mfa-monitor (https://github.com/radekk/webtask-mfa-monitor/)' } }); client.authenticate({ type: 'token', token: ctx.secrets.GITHUB_TOKEN }); client.orgs.getMembers({ org: ctx.secrets.ORGANIZATION, per_page: 100, filter: '2fa_disabled' }, (err, res) => { if (err) return cb(err); if (!res) return cb(new Error('Empty response received from Github API!')); cb(null, res.map(data => data.login)); }); };
'use strict'; const GitHubApi = require('github'); const github = new GitHubApi({ version: '3.0.0', debug: false, protocol: 'https', host: 'api.github.com', timeout: 5000, headers: { 'user-agent': 'webtask-mfa-monitor (https://github.com/radekk/webtask-mfa-monitor/)' } }); /** * @param {secret} ORGANIZATION - Github ORGANIZATION name * @param {secret} GITHUB_TOKEN - Github API Token with "org:read" permission * @return JSON ['john', 'mark'] */ module.exports = (ctx, cb) => { github.authenticate({ type: 'token', token: ctx.secrets.GITHUB_TOKEN }); github.orgs.getMembers({ org: ctx.secrets.ORGANIZATION, per_page: 100, filter: '2fa_disabled' }, (err, res) => { if (err) return cb(err); if (res && res.length) return cb(null, res.map(data => data.login)); return []; }); };
Test against jQuery 3.2.0 and 3.2.1
QUnit.config.urlConfig.push({ id: "jquery", label: "jQuery version", value: ["3.2.1", "3.2.0", "3.1.1", "3.0.0", "2.2.4", "2.1.4", "2.0.3", "1.12.4", "1.11.3"], tooltip: "What jQuery Core version to test against" }); /* Hijacks normal form submit; lets it submit to an iframe to prevent * navigating away from the test suite */ $(document).on('submit', function(e) { if (!e.isDefaultPrevented()) { var form = $(e.target), action = form.attr('action'), name = 'form-frame' + jQuery.guid++, iframe = $('<iframe name="' + name + '" />'); if (action && action.indexOf('iframe') < 0) form.attr('action', action + '?iframe=true') form.attr('target', name); $('#qunit-fixture').append(iframe); form.trigger('iframe:loading'); } });
QUnit.config.urlConfig.push({ id: "jquery", label: "jQuery version", value: ["3.1.1", "3.0.0", "2.2.4", "2.1.4", "2.0.3", "1.12.4", "1.11.3"], tooltip: "What jQuery Core version to test against" }); /* Hijacks normal form submit; lets it submit to an iframe to prevent * navigating away from the test suite */ $(document).on('submit', function(e) { if (!e.isDefaultPrevented()) { var form = $(e.target), action = form.attr('action'), name = 'form-frame' + jQuery.guid++, iframe = $('<iframe name="' + name + '" />'); if (action && action.indexOf('iframe') < 0) form.attr('action', action + '?iframe=true') form.attr('target', name); $('#qunit-fixture').append(iframe); form.trigger('iframe:loading'); } });
Send all postures as array
function ddg_spice_yoga_asanas(apiResult) { if (!apiResult || !apiResult.response.numFound) { return Spice.failed('yoga_asanas'); } Spice.add({ id: 'yoga_asanas', name: 'Yoga Asanas', data: apiResult.response.docs, normalize: function(a){ var meta = eval("(" + a.meta + ")"); delete a.meta; return { image: meta.img, title: a.title, subtitle: a.paragraph, meta: { srcName: meta.srcName, srcUrl: meta.srcUrl, srcIcon: meta.favicon } }; }, templates: { group: 'media', }, }); }
function ddg_spice_yoga_asanas(apiResult) { if (!apiResult || !apiResult.response.numFound) { return Spice.failed('yoga_asanas'); } for(i = 0; i < apiResult.response.numFound; i++){ var a = apiResult.response.docs[i]; var meta = eval("(" + a.meta + ")"); delete a.meta; Spice.add({ id: 'yoga_asanas', name: 'Yoga Asanas', data: a, normalize: function(x){ return { image: meta.img, title: a.title, subtitle: a.paragraph }; }, meta: { srcName: meta.srcName, srcUrl: meta.srcUrl, srcIcon: meta.favicon }, templates: { group: 'media', }, }); } }
Fix the response adding the closing delimiter
package split import ( "bytes" "mime" "mime/multipart" "net/http" "net/textproto" ) // WriteResponses serialize the responses passed as argument into the ResponseWriter func WriteResponses(w http.ResponseWriter, responses []*http.Response) error { var buf bytes.Buffer multipartWriter := multipart.NewWriter(&buf) mimeHeaders := textproto.MIMEHeader(make(map[string][]string)) mimeHeaders.Set("Content-Type", "application/http") for _, resp := range responses { part, err := multipartWriter.CreatePart(mimeHeaders) if err != nil { return err } resp.Write(part) } multipartWriter.Close() w.Header().Set("Content-Type", mime.FormatMediaType("multipart/mixed", map[string]string{"boundary": multipartWriter.Boundary()})) w.WriteHeader(http.StatusOK) buf.WriteTo(w) return nil }
package split import ( "bytes" "mime" "mime/multipart" "net/http" "net/textproto" ) // WriteResponses serialize the responses passed as argument into the ResponseWriter func WriteResponses(w http.ResponseWriter, responses []*http.Response) error { var buf bytes.Buffer multipartWriter := multipart.NewWriter(&buf) mimeHeaders := textproto.MIMEHeader(make(map[string][]string)) mimeHeaders.Set("Content-Type", "application/http") for _, resp := range responses { part, err := multipartWriter.CreatePart(mimeHeaders) if err != nil { return err } resp.Write(part) } w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", mime.FormatMediaType("multipart/mixed", map[string]string{"boundary": multipartWriter.Boundary()})) w.WriteHeader(http.StatusOK) buf.WriteTo(w) return nil }
Make the form action redirect to the products.index page with the correct params
// Dependencies import Ember from 'ember'; import layout from '../templates/components/yebo-search'; /** The search form @class YeboDetails @namespace Component @extends Ember.Component */ export default Ember.Component.extend({ layout: layout, // The text that is going to be searched searchText: '', actions: { /** * Transition to the /products route with param search */ search: function() { // Search Text let searchText = this.get('searchText'); // Check if the searchText is higher than 2 // @todo Show some kind of error if( searchText.length < 3 ) return; // Get the current controller // @todo Check if _controller is the correct to use in this case let controller = this._controller; // Transition to the products page controller.transitionToRoute('yebo.products', { queryParams: { search: searchText } }); } } });
// Dependencies import Ember from 'ember'; import layout from '../templates/components/yebo-search'; /** The search form @class YeboDetails @namespace Component @extends Ember.Component */ export default Ember.Component.extend({ layout: layout, // The text that is going to be searched searchText: '', actions: { /** * Transition to the /products route with param search */ search: function() { // Search Text let searchText = this.get('searchText'); // Check if the searchText is higher than 2 // @todo Show some kind of error if( searchText.length < 3 ) return; // Transition to the products page // this.transitionTo('products', { queryParams: { search: searchText } }); } } });
Add esc key bind in editor
import React from 'react' import SimpleMDE from 'react-simplemde-editor' const PoemEditor = (props) => { const extraKeys = { // 'Ctrl-Enter': () => { props.handleEditorSubmit() }, 'Cmd-Enter': () => { props.handleEditorSubmit() }, 'Esc': () => { document.activeElement.blur() } } return ( <div className="poem-form"> <SimpleMDE onChange={props.handleEditorChange} value={props.value} options={{ autofocus: false, spellChecker: false, indentWithTabs: false, status: false, toolbar: false, }} addKeyMaps={extraKeys} /> <div className="post-button"> <a onClick={props.handleEditorSubmit} className="button is-dark">post</a> </div> </div> ) } export default PoemEditor
import React from 'react' import SimpleMDE from 'react-simplemde-editor' const PoemEditor = (props) => { const extraKeys = { // 'Ctrl-Enter': () => { props.handleEditorSubmit() }, 'Cmd-Enter': () => { props.handleEditorSubmit() }, } return ( <div className="poem-form"> <SimpleMDE onChange={props.handleEditorChange} value={props.value} options={{ autofocus: false, spellChecker: false, indentWithTabs: false, status: false, toolbar: false, }} addKeyMaps={extraKeys} /> <div className="post-button"> <a onClick={props.handleEditorSubmit} className="button is-dark">post</a> </div> </div> ) } export default PoemEditor
Update the permission helper functions.
def user_can_view_scans(user, moon): return ( user_can_delete_scans(user, moon) or user.has_perm('eve_sde.sys_can_view_scans', moon.planet.system) or user.has_perm('eve_sde.con_can_view_scans', moon.planet.system.constellation) or user.has_perm('eve_sde.reg_can_view_scans', moon.planet.system.constellation.region) ) def user_can_add_scans(user, moon): return ( user_can_delete_scans(user, moon) or user.has_perm('eve_sde.sys_can_add_scans', moon.planet.system) or user.has_perm('eve_sde.con_can_add_scans', moon.planet.system.constellation) or user.has_perm('eve_sde.reg_can_add_scans', moon.planet.system.constellation.region) ) def user_can_delete_scans(user, moon): return ( user.has_perm('eve_sde.sys_can_delete_scans', moon.planet.system) or user.has_perm('eve_sde.con_can_delete_scans', moon.planet.system.constellation) or user.has_perm('eve_sde.reg_can_delete_scans', moon.planet.system.constellation.region) )
def user_can_view_scans(user, moon): return ( user_can_delete_scans(user, moon) or user.has_perm('eve_sde.can_view_scans', moon.planet.system) or user.has_perm('eve_sde.can_view_scans', moon.planet.system.constellation) or user.has_perm('eve_sde.can_view_scans', moon.planet.system.constellation.region) ) def user_can_add_scans(user, moon): return ( user_can_delete_scans(user, moon) or user.has_perm('eve_sde.can_add_scans', moon.planet.system) or user.has_perm('eve_sde.can_add_scans', moon.planet.system.constellation) or user.has_perm('eve_sde.can_add_scans', moon.planet.system.constellation.region) ) def user_can_delete_scans(user, moon): return ( user.has_perm('eve_sde.can_delete_scans', moon.planet.system) or user.has_perm('eve_sde.can_delete_scans', moon.planet.system.constellation) or user.has_perm('eve_sde.can_delete_scans', moon.planet.system.constellation.region) )
docs: Add comment denoting change and why it's hard to test and when to revisit.
import props from './props'; function getValue (elem) { const type = elem.type; if (type === 'checkbox' || type === 'radio') { return elem.checked ? elem.value || true : false; } return elem.value; } export default function (elem, target) { return (e) => { // We fallback to checking the composed path. Unfortunately this behaviour // is difficult to impossible to reproduce as it seems to be a possible // quirk in the shadydom polyfill that incorrectly returns null for the // target but has the target as the first point in the path. // TODO revisit once all browsers have native support. const localTarget = target || e.target || e.composedPath()[0]; const value = getValue(localTarget); const localTargetName = e.target.name || 'value'; if (localTargetName.indexOf('.') > -1) { const parts = localTargetName.split('.'); const firstPart = parts[0]; const propName = parts.pop(); const obj = parts.reduce((prev, curr) => (prev && prev[curr]), elem); obj[propName || e.target.name] = value; props(elem, { [firstPart]: elem[firstPart] }); } else { props(elem, { [localTargetName]: value }); } }; }
import props from './props'; function getValue (elem) { const type = elem.type; if (type === 'checkbox' || type === 'radio') { return elem.checked ? elem.value || true : false; } return elem.value; } export default function (elem, target) { return (e) => { const localTarget = target || e.target || e.composedPath()[0]; const value = getValue(localTarget); const localTargetName = e.target.name || 'value'; if (localTargetName.indexOf('.') > -1) { const parts = localTargetName.split('.'); const firstPart = parts[0]; const propName = parts.pop(); const obj = parts.reduce((prev, curr) => (prev && prev[curr]), elem); obj[propName || e.target.name] = value; props(elem, { [firstPart]: elem[firstPart] }); } else { props(elem, { [localTargetName]: value }); } }; }
Restructure abstract calendar to use iterators.
<?php namespace Plummer\Calendar; abstract class CalendarAbstract implements CalendarInterface { protected $name; protected $events; protected $recurrenceTypes; public function __construct($name) { $this->name = $name; } public function addEvents($events) { if($events instanceof \Iterator) { $this->events->append($events); } elseif(is_array($events)) { foreach($events as $key => $event) { $this->events[$key] = $event; } } } public function addRecurrenceTypes($recurrenceTypes) { if($recurrenceTypes instanceof \Iterator) { $this->recurrenceTypes->append($recurrenceTypes); } elseif(is_array($recurrenceTypes)) { foreach($recurrenceTypes as $key => $recurrenceType) { $this->recurrenceTypes[$key] = $recurrenceType; } } } abstract public function addEvent(EventInterface $event); abstract public function addRecurrenceType(RecurrenceInterface $recurrenceType); abstract public function getEvents(); }
<?php namespace Plummer\Calendar; abstract class CalendarAbstract implements CalendarInterface { protected $events; protected $recurrenceTypes; protected function __construct(\Iterator $events, $recurrenceTypes) { $this->events = $events; $this->addRecurrenceTypes($recurrenceTypes); } public static function make(\Iterator $events, $recurrenceTypes = []) { return new static($events, $recurrenceTypes); } public function addEvents(array $events) { foreach($events as $event) { $this->addEvent($event); } } public function addRecurrenceTypes(array $recurrenceTypes) { foreach($recurrenceTypes as $recurrenceType) { $this->addRecurrenceType($recurrenceType); } } abstract public function addEvent(EventInterface $event); abstract public function addRecurrenceType(RecurrenceInterface $recurrenceType); abstract public function getEvents(); }
Switch over to loading .js file Gerrit no longer supports html plugins so we have to use the .js version. Bug: Issue 14335 Change-Id: I284647480d0cac76f3afde0aa566b47121ff9511
// Copyright (C) 2013 The Android Open Source Project // // 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.googlesource.gerrit.plugins.deleteproject; import com.google.gerrit.extensions.registration.DynamicSet; import com.google.gerrit.extensions.webui.JavaScriptPlugin; import com.google.gerrit.extensions.webui.WebUiPlugin; import com.google.inject.servlet.ServletModule; public class HttpModule extends ServletModule { @Override protected void configureServlets() { DynamicSet.bind(binder(), WebUiPlugin.class) .toInstance(new JavaScriptPlugin("delete-project.js")); } }
// Copyright (C) 2013 The Android Open Source Project // // 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.googlesource.gerrit.plugins.deleteproject; import com.google.gerrit.extensions.registration.DynamicSet; import com.google.gerrit.extensions.webui.JavaScriptPlugin; import com.google.gerrit.extensions.webui.WebUiPlugin; import com.google.inject.servlet.ServletModule; public class HttpModule extends ServletModule { @Override protected void configureServlets() { DynamicSet.bind(binder(), WebUiPlugin.class) .toInstance(new JavaScriptPlugin("delete-project.html")); } }
Handle unknown extensions with the html frontend
<?php namespace BNETDocs\Controllers; use \BNETDocs\Libraries\Controller; use \BNETDocs\Libraries\Exceptions\UnspecifiedViewException; use \BNETDocs\Libraries\Router; use \BNETDocs\Models\Maintenance as MaintenanceModel; use \BNETDocs\Views\MaintenanceHtml as MaintenanceHtmlView; use \BNETDocs\Views\MaintenanceJSON as MaintenanceJSONView; use \BNETDocs\Views\MaintenancePlain as MaintenancePlainView; class Maintenance extends Controller { protected $message; public function __construct($message) { parent::__construct(); $this->message = $message; } public function run(Router &$router) { switch ($router->getRequestPathExtension()) { case "htm": case "html": case "": $view = new MaintenanceHtmlView(); break; case "json": $view = new MaintenanceJSONView(); break; case "txt": $view = new MaintenancePlainView(); break; default: $view = new MaintenanceHtmlView(); } $model = new MaintenanceModel(); $model->message = $this->message; ob_start(); $view->render($model); $router->setResponseCode(503); $router->setResponseTTL(0); $router->setResponseHeader("Content-Type", $view->getMimeType()); $router->setResponseContent(ob_get_contents()); ob_end_clean(); } }
<?php namespace BNETDocs\Controllers; use \BNETDocs\Libraries\Controller; use \BNETDocs\Libraries\Exceptions\UnspecifiedViewException; use \BNETDocs\Libraries\Router; use \BNETDocs\Models\Maintenance as MaintenanceModel; use \BNETDocs\Views\MaintenanceHtml as MaintenanceHtmlView; use \BNETDocs\Views\MaintenanceJSON as MaintenanceJSONView; use \BNETDocs\Views\MaintenancePlain as MaintenancePlainView; class Maintenance extends Controller { protected $message; public function __construct($message) { parent::__construct(); $this->message = $message; } public function run(Router &$router) { switch ($router->getRequestPathExtension()) { case "htm": case "html": case "": $view = new MaintenanceHtmlView(); break; case "json": $view = new MaintenanceJSONView(); break; case "txt": $view = new MaintenancePlainView(); break; default: throw new UnspecifiedViewException(); } $model = new MaintenanceModel(); $model->message = $this->message; ob_start(); $view->render($model); $router->setResponseCode(503); $router->setResponseTTL(0); $router->setResponseHeader("Content-Type", $view->getMimeType()); $router->setResponseContent(ob_get_contents()); ob_end_clean(); } }
Fix annotation retention for reflect usage
package butterknife; import android.support.annotation.ArrayRes; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Bind a field to the specified array resource ID. The type of array will be inferred from the * annotated element. * * String array: * <pre><code> * {@literal @}BindArray(R.array.countries) String[] countries; * </code></pre> * * Int array: * <pre><code> * {@literal @}BindArray(R.array.phones) int[] phones; * </code></pre> * * Text array: * <pre><code> * {@literal @}BindArray(R.array.options) CharSequence[] options; * </code></pre> * * {@link android.content.res.TypedArray}: * <pre><code> * {@literal @}BindArray(R.array.icons) TypedArray icons; * </code></pre> */ @Retention(RUNTIME) @Target(FIELD) public @interface BindArray { /** Array resource ID to which the field will be bound. */ @ArrayRes int value(); }
package butterknife; import android.support.annotation.ArrayRes; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.CLASS; /** * Bind a field to the specified array resource ID. The type of array will be inferred from the * annotated element. * * String array: * <pre><code> * {@literal @}BindArray(R.array.countries) String[] countries; * </code></pre> * * Int array: * <pre><code> * {@literal @}BindArray(R.array.phones) int[] phones; * </code></pre> * * Text array: * <pre><code> * {@literal @}BindArray(R.array.options) CharSequence[] options; * </code></pre> * * {@link android.content.res.TypedArray}: * <pre><code> * {@literal @}BindArray(R.array.icons) TypedArray icons; * </code></pre> */ @Retention(CLASS) @Target(FIELD) public @interface BindArray { /** Array resource ID to which the field will be bound. */ @ArrayRes int value(); }
Remove the lert message of passing id info for Block creation git-svn-id: 6eed24e287f84bf0ab23ca377a3e397011128a6f@3438 fdecad78-55fc-0310-b1b2-d7d25cf747c9
//TODO:Javacsript can check if checked Ids hasv the same scale ID function extractSelectedItems(submitButton) { sourceForm = document.getElementById("modifyFormRows"); destinationForm = submitButton.form; var count = 0; //enforce at least 2 check box are checked if (sourceForm && destinationForm) { var idList = ""; // look for checkboxes which have IDs of the form "block-12-11" and keep track of the ones that are checked. for (var a=0; a < sourceForm.elements.length; a++) { if (sourceForm.elements[a].type=="checkbox" && sourceForm.elements[a].checked) { if (idList.length > 0) { idList += ","; } idList += sourceForm.elements[a].id.substr(sourceForm.elements[a].id.lastIndexOf('-')+1); count = count + 1; } } destinationForm.templateItemIds.value=idList; //alert("ids="+destinationForm.templateItemIds.value); if(count < 2){ alert("you must select at least 2 items to create a block"); return false; } else return true; } return false; }
//TODO:Javacsript can check if checked Ids hasv the same scale ID function extractSelectedItems(submitButton) { sourceForm = document.getElementById("modifyFormRows"); destinationForm = submitButton.form; var count = 0; //enforce at least 2 check box are checked if (sourceForm && destinationForm) { var idList = ""; // look for checkboxes which have IDs of the form "block-12-11" and keep track of the ones that are checked. for (var a=0; a < sourceForm.elements.length; a++) { if (sourceForm.elements[a].type=="checkbox" && sourceForm.elements[a].checked) { if (idList.length > 0) { idList += ","; } idList += sourceForm.elements[a].id.substr(sourceForm.elements[a].id.lastIndexOf('-')+1); count = count + 1; } } destinationForm.templateItemIds.value=idList; alert("ids="+destinationForm.templateItemIds.value); if(count < 2){ alert("you must select at least 2 items to create a block"); return false; } else return true; } return false; }
Remove single shard optimization, don't use sharding if you have one shard.
<?php namespace League\Flysystem\UrlGeneration; use InvalidArgumentException; use League\Flysystem\Config; use League\Flysystem\PathPrefixer; use function array_map; use function count; use function crc32; final class ShardedPrefixPublicUrlGenerator implements PublicUrlGenerator { /** @var PathPrefixer[] */ private array $prefixers; private int $count; /** * @param string[] $prefixes */ public function __construct(array $prefixes) { $this->count = count($prefixes); if ($this->count === 0) { throw new InvalidArgumentException('At least one prefix is required.'); } $this->prefixers = array_map(static fn (string $prefix) => new PathPrefixer($prefix, '/'), $prefixes); } public function publicUrl(string $path, Config $config): string { $index = crc32($path) % $this->count; return $this->prefixers[$index]->prefixPath($path); } }
<?php namespace League\Flysystem\UrlGeneration; use InvalidArgumentException; use League\Flysystem\Config; use League\Flysystem\PathPrefixer; use function array_map; use function count; use function crc32; final class ShardedPrefixPublicUrlGenerator implements PublicUrlGenerator { /** @var PathPrefixer[] */ private array $prefixers; private int $count; /** * @param string[] $prefixes */ public function __construct(array $prefixes) { $this->count = count($prefixes); if ($this->count === 0) { throw new InvalidArgumentException('At least one prefix is required.'); } $this->prefixers = array_map(static fn (string $prefix) => new PathPrefixer($prefix, '/'), $prefixes); } public function publicUrl(string $path, Config $config): string { if (1 === count($this->prefixers)) { return $this->prefixers[0]->prefixPath($path); } $index = crc32($path) % $this->count; return $this->prefixers[$index]->prefixPath($path); } }
Update source directory in coveralls configuration.
<?php use mageekguy\atoum\reports; $runner ->addTestsFromDirectory(__DIR__ . '/tests/units/classes') ->disallowUndefinedMethodInInterface() ; $travis = getenv('TRAVIS'); if ($travis) { $script->addDefaultReport(); $coverallsToken = getenv('COVERALLS_REPO_TOKEN'); if ($coverallsToken) { $coverallsReport = new reports\asynchronous\coveralls('classes', $coverallsToken); $defaultFinder = $coverallsReport->getBranchFinder(); $coverallsReport ->setBranchFinder(function() use ($defaultFinder) { if (($branch = getenv('TRAVIS_BRANCH')) === false) { $branch = $defaultFinder(); } return $branch; } ) ->setServiceName('travis-ci') ->setServiceJobId(getenv('TRAVIS_JOB_ID')) ->addDefaultWriter() ; $runner->addReport($coverallsReport); } }
<?php use mageekguy\atoum\reports; $runner ->addTestsFromDirectory(__DIR__ . '/tests/units/classes') ->disallowUndefinedMethodInInterface() ; $travis = getenv('TRAVIS'); if ($travis) { $script->addDefaultReport(); $coverallsToken = getenv('COVERALLS_REPO_TOKEN'); if ($coverallsToken) { $coverallsReport = new reports\asynchronous\coveralls(__DIR__ . '/classes', $coverallsToken); $defaultFinder = $coverallsReport->getBranchFinder(); $coverallsReport ->setBranchFinder(function() use ($defaultFinder) { if (($branch = getenv('TRAVIS_BRANCH')) === false) { $branch = $defaultFinder(); } return $branch; } ) ->setServiceName('travis-ci') ->setServiceJobId(getenv('TRAVIS_JOB_ID')) ->addDefaultWriter() ; $runner->addReport($coverallsReport); } }
Update to always run, and tune some of the selectors
var doc = window.document; function setup(container) { var inputs = container.getElementsByClassName('hours'); var arr = Array.prototype.slice.call(inputs); for (var i=0; i<arr.length; i++) { var element = arr[i]; if ( (" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf(" smart-processed ") > -1 ) { //Skip already processed fields continue; } element.addEventListener("blur", function (event) { var value = event.target.value; var parts = value.split(':'); if (parts.length === 2) { var element = event.target; element.value = parseInt(parts[0]) + parseFloat(parseInt(parts[1])/60); if ("createEvent" in doc) { var evt = doc.createEvent("HTMLEvents"); evt.initEvent("change", false, true); element.dispatchEvent(evt); } else { element.fireEvent("onchange"); } } var oldClasses = element.getAttribute('class'); element.setAttribute('class', oldClasses + ' smart-processed'); }, true); } } var interval = setInterval(function () { var container = doc.getElementById('ajaxContenthourListTable'); if (container) { setup(container); } }, 3000);
var doc = window.document; function setup(container) { var inputs = container.getElementsByTagName('input'); var arr = Array.prototype.slice.call(inputs); for (var i=0; i<arr.length; i++) { var element = arr[i]; if (element.id.indexOf('weeks[') !== -1) { element.addEventListener("blur", function (event) { var value = event.target.value; var parts = value.split(':'); if (parts.length === 2) { var element = event.target; element.value = parseInt(parts[0]) + parseFloat(parseInt(parts[1])/60); if ("createEvent" in doc) { var evt = doc.createEvent("HTMLEvents"); evt.initEvent("change", false, true); element.dispatchEvent(evt); } else { element.fireEvent("onchange"); } } }, true); } } } var interval = setInterval(function () { var container = doc.getElementById('ajaxContentDataForm'); if (container) { clearInterval(interval); setup(container); } }, 50);
Make more use-friendly constants for sort ascending, descending.
<?php namespace UWDOEM\Framework\FilterStatement; use Propel\Runtime\ActiveQuery\ModelCriteria; interface FilterStatementInterface { const COND_SORT_ASC = "ascending"; const COND_SORT_DESC = "descending"; const COND_LESS_THAN = 3; const COND_GREATER_THAN = 4; const COND_EQUAL_TO = 5; const COND_NOT_EQUAL_TO = 6; const COND_CONTAINS = 7; const COND_PAGINATE_BY = 8; /** * @return string */ public function getFieldName(); /** * @return string */ public function getCondition(); /** * @return mixed */ public function getCriterion(); /** * @return mixed */ public function getControl(); /** * @param ModelCriteria $query * @return ModelCriteria */ public function applyToQuery(ModelCriteria $query); /** * @param \UWDOEM\Framework\Row\Row[] $rows * @return \UWDOEM\Framework\Row\Row[] */ public function applyToRows(array $rows); }
<?php namespace UWDOEM\Framework\FilterStatement; use Propel\Runtime\ActiveQuery\ModelCriteria; interface FilterStatementInterface { const COND_SORT_ASC = 1; const COND_SORT_DESC = 2; const COND_LESS_THAN = 3; const COND_GREATER_THAN = 4; const COND_EQUAL_TO = 5; const COND_NOT_EQUAL_TO = 6; const COND_CONTAINS = 7; const COND_PAGINATE_BY = 8; /** * @return string */ public function getFieldName(); /** * @return string */ public function getCondition(); /** * @return mixed */ public function getCriterion(); /** * @return mixed */ public function getControl(); /** * @param ModelCriteria $query * @return ModelCriteria */ public function applyToQuery(ModelCriteria $query); /** * @param \UWDOEM\Framework\Row\Row[] $rows * @return \UWDOEM\Framework\Row\Row[] */ public function applyToRows(array $rows); }
Update description and long description [ci skip]
import os import sys from setuptools import setup __author__ = 'Ryan McGrath <ryan@venodesigns.net>' __version__ = '2.10.0' packages = [ 'twython', 'twython.streaming' ] if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() setup( # Basic package information. name='twython', version=__version__, packages=packages, # Packaging options. include_package_data=True, # Package dependencies. install_requires=['requests==1.2.2', 'requests_oauthlib==0.3.2'], # Metadata for PyPI. author='Ryan McGrath', author_email='ryan@venodesigns.net', license='MIT License', url='http://github.com/ryanmcgrath/twython/tree/master', keywords='twitter search api tweet twython stream', description='Actively maintained, pure Python wrapper for the Twitter API. Supports both normal and streaming Twitter APIs', long_description=open('README.rst').read() + '\n\n' + open('HISTORY.rst').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Communications :: Chat', 'Topic :: Internet' ] )
import os import sys from setuptools import setup __author__ = 'Ryan McGrath <ryan@venodesigns.net>' __version__ = '2.10.0' packages = [ 'twython', 'twython.streaming' ] if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() setup( # Basic package information. name='twython', version=__version__, packages=packages, # Packaging options. include_package_data=True, # Package dependencies. install_requires=['requests==1.2.2', 'requests_oauthlib==0.3.2'], # Metadata for PyPI. author='Ryan McGrath', author_email='ryan@venodesigns.net', license='MIT License', url='http://github.com/ryanmcgrath/twython/tree/master', keywords='twitter search api tweet twython', description='An easy (and up to date) way to access Twitter data with Python.', long_description=open('README.rst').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Communications :: Chat', 'Topic :: Internet' ] )
Remove autopopulation from User model
var modelProperties, mongoose, passportLocalMongoose, Rat, Schema, UserSchema; mongoose = require( 'mongoose' ); passportLocalMongoose = require( 'passport-local-mongoose' ); Rat = require( './rat' ); Schema = mongoose.Schema; modelProperties = { email: String, password: String, CMDRs: { default: [], type: [{ type: Schema.Types.ObjectId, ref: 'Rat' }] } }; UserSchema = new Schema( modelProperties ); UserSchema.methods.toJSON = function () { obj = this.toObject(); delete obj.hash; delete obj.salt; return obj; }; UserSchema.plugin( passportLocalMongoose, { usernameField: 'email' }); module.exports = mongoose.model( 'User', UserSchema );
var modelProperties, mongoose, passportLocalMongoose, Rat, Schema, UserSchema; mongoose = require( 'mongoose' ); passportLocalMongoose = require( 'passport-local-mongoose' ); Rat = require( './rat' ); Schema = mongoose.Schema; modelProperties = { email: String, password: String, CMDRs: { default: [], type: [{ autopopulate: true, type: Schema.Types.ObjectId, ref: 'Rat' }] } }; UserSchema = new Schema( modelProperties ); UserSchema.methods.toJSON = function () { obj = this.toObject(); delete obj.hash; delete obj.salt; return obj; }; //UserSchema.plugin( require( 'mongoose-autopopulate' ) ); UserSchema.plugin( passportLocalMongoose, { usernameField: 'email' }); module.exports = mongoose.model( 'User', UserSchema );
Make browserHistory routing actually work.
var path = require('path'); var webpack = require('webpack'); var babelSettings = JSON.stringify({ presets: ['es2015', 'react'] }); module.exports = { entry: [ 'webpack-dev-server/client?http://0.0.0.0:8080', // WebpackDevServer host and port 'webpack/hot/only-dev-server', // "only" prevents reload on syntax errors './main.js' // Your appʼs entry point ], output: { path: __dirname, filename: 'bundle.js', }, module: { loaders: [ { test: /\.json$/, loader: 'json' }, { test: /.jsx?$/, loaders: [ 'react-hot', 'babel-loader?' + babelSettings ], exclude: /node_modules/, } ] }, devServer: { historyApiFallback: true }, plugins: [ new webpack.HotModuleReplacementPlugin() ], };
var path = require('path'); var webpack = require('webpack'); var babelSettings = JSON.stringify({ presets: ['es2015', 'react'] }); module.exports = { entry: [ 'webpack-dev-server/client?http://0.0.0.0:8080', // WebpackDevServer host and port 'webpack/hot/only-dev-server', // "only" prevents reload on syntax errors './main.js' // Your appʼs entry point ], output: { path: __dirname, filename: 'bundle.js' }, module: { loaders: [ { test: /\.json$/, loader: 'json' }, { test: /.jsx?$/, loaders: [ 'react-hot', 'babel-loader?' + babelSettings ], exclude: /node_modules/, } ] }, plugins: [ new webpack.HotModuleReplacementPlugin() ], };
Python: Fix typo in test case
from django.db import connection, models from django.db.models.expressions import RawSQL def test_plain(): cursor = connection.cursor() cursor.execute("some sql") # $getSql="some sql" def test_context(): with connection.cursor() as cursor: cursor.execute("some sql") # $getSql="some sql" cursor.execute(sql="some sql") # $getSql="some sql" class User(models.Model): pass def test_model(): User.objects.raw("some sql") # $getSql="some sql" User.objects.annotate(RawSQL("some sql")) # $getSql="some sql" User.objects.annotate(val=RawSQL("some sql")) # $getSql="some sql" User.objects.extra("some sql") # $getSql="some sql" User.objects.extra(select="select", where="where", tables="tables", order_by="order_by") # $getSql="select" $getSql="where" $getSql="tables" $getSql="order_by" raw = RawSQL("so raw") User.objects.annotate(val=raw) # $f-:getSql="so raw"
from django.db import connection, models from django.db.models.expressions import RawSQL def test_plain(): cursor = connection.cursor() cursor.execute("some sql") # $getSql="some sql" def test_context(): with connection.cursor() as cursor: cursor.execute("some sql") # $getSql="some sql" cursor.execute(sql="some sql") # $getSql="some sql" class User(models.Model): pass def test_model(): User.objects.raw("some sql") # $getSql="some sql" User.objects.annotate(RawSQL("some sql")) # $getSql="some sql" User.objects.annotate(val=RawSQL("some sql")) # $getSql="some sql" User.objects.extra("some sql") # $getSql="some sql" User.objects.extra(select="select", where="where", tables="tables", order_by="order_by") # $getSql="select" $getSql="where" $getSql="tables" $getSql="order_by" raw = RawSQL("so raw") Users.objects.annotate(val=raw) # $f-:getSql="so raw"
Throw AuthorizationException if user doesn't have scope Should this not throw AuthorizationException when the user doesn't have the required scopes as the user is authenticated but doesn't have the scope to access the route?
<?php namespace Laravel\Passport\Http\Middleware; use Illuminate\Auth\AuthenticationException; use Illuminate\Auth\Access\AuthorizationException; class CheckScopes { /** * Handle the incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param array $scopes * @return \Illuminate\Http\Response */ public function handle($request, $next, ...$scopes) { if (! $request->user() || ! $request->user()->token()) { throw new AuthenticationException; } foreach ($scopes as $scope) { if (! $request->user()->tokenCan($scope)) { throw new AuthorizationException; } } return $next($request); } }
<?php namespace Laravel\Passport\Http\Middleware; use Illuminate\Auth\AuthenticationException; class CheckScopes { /** * Handle the incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param array $scopes * @return \Illuminate\Http\Response */ public function handle($request, $next, ...$scopes) { if (! $request->user() || ! $request->user()->token()) { throw new AuthenticationException; } foreach ($scopes as $scope) { if (! $request->user()->tokenCan($scope)) { throw new AuthenticationException; } } return $next($request); } }
Make label and field selector query strings versionable. Kubernetes-commit: 266234f3b9ccce6519c2bb500a2b102bf4b7fa16
/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package api // This file contains API types that are unversioned. // APIVersions lists the api versions that are available, to allow // version negotiation. APIVersions isn't just an unnamed array of // strings in order to allow for future evolution, though unversioned type APIVersions struct { Versions []string `json:"versions"` } // RootPaths lists the paths available at root. // For example: "/healthz", "/api". type RootPaths struct { Paths []string `json:"paths"` } // preV1Beta3 returns true if the provided API version is an API introduced before v1beta3. func PreV1Beta3(version string) bool { return version == "v1beta1" || version == "v1beta2" } func LabelSelectorQueryParam(version string) string { if PreV1Beta3(version) { return "labels" } return "label-selector" } func FieldSelectorQueryParam(version string) string { if PreV1Beta3(version) { return "fields" } return "field-selector" }
/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package api // This file contains API types that are unversioned. // APIVersions lists the api versions that are available, to allow // version negotiation. APIVersions isn't just an unnamed array of // strings in order to allow for future evolution, though unversioned type APIVersions struct { Versions []string `json:"versions"` } // RootPaths lists the paths available at root. // For example: "/healthz", "/api". type RootPaths struct { Paths []string `json:"paths"` }
Add throws to the javadoc
package co.paralleluniverse.firebase; //~--- non-JDK imports -------------------------------------------------------- import co.paralleluniverse.fibers.SuspendExecution; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.Query; /** * This class exposes Firebase functionality that builds on top of the fiber * model. */ public enum FirebaseUtil { INSTANCE; /** * Retrieves the Firebase server time based off of the local server time * offset. * * @param ref an authenticated Firebase reference. * * @return the Firebase server time. * * @throws SuspendExecution */ public long serverTime(Firebase ref) throws SuspendExecution { return System.currentTimeMillis() + serverTimeOffset(ref); } /** * Retrieves the local server time offset. * * @param ref an authenticated Firebase reference. * * @return the local server time offset. * * @throws SuspendExecution */ public long serverTimeOffset(Firebase ref) throws SuspendExecution { DataSnapshot snap = QuasarUtil.INSTANCE.run(new ValueEventListenerAsync() { @Override protected void requestAsync() { Query query = ref.getRoot().child(".info/serverTimeOffset"); query.addListenerForSingleValueEvent(this); } }); return (Long) snap.getValue(); } }
package co.paralleluniverse.firebase; //~--- non-JDK imports -------------------------------------------------------- import co.paralleluniverse.fibers.SuspendExecution; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.Query; /** * This class exposes Firebase functionality that builds on top of the fiber * model. */ public enum FirebaseUtil { INSTANCE; /** * Retrieves the Firebase server time based off of the local server time * offset. * * @param ref an authenticated Firebase reference. * * @return the Firebase server time. */ public long serverTime(Firebase ref) throws SuspendExecution { return System.currentTimeMillis() + serverTimeOffset(ref); } public long serverTimeOffset(Firebase ref) throws SuspendExecution { DataSnapshot snap = QuasarUtil.INSTANCE.run(new ValueEventListenerAsync() { @Override protected void requestAsync() { Query query = ref.getRoot().child(".info/serverTimeOffset"); query.addListenerForSingleValueEvent(this); } }); return (Long) snap.getValue(); } }
Add missing fields in view.state.values
package com.slack.api.model.view; import com.slack.api.model.block.composition.PlainTextObject; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; import java.util.Map; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ViewState { // block_id, action_id private Map<String, Map<String, Value>> values; @Data public static class Value { private String type; private String value; private String selectedDate; private String selectedConversation; private String selectedChannel; private String selectedUser; private SelectedOption selectedOption; private List<String> selectedConversations; private List<String> selectedChannels; private List<String> selectedUsers; private List<SelectedOption> selectedOptions; } @Data public static class SelectedOption { private PlainTextObject text; private String value; } }
package com.slack.api.model.view; import com.slack.api.model.block.composition.PlainTextObject; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; import java.util.Map; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ViewState { // block_id, action_id private Map<String, Map<String, Value>> values; /** * This class may miss some attributes. * If you find missing ones, let us know at https://github.com/seratch/jslack/issues */ @Data public static class Value { private String type; private String value; private String selectedDate; private String selectedConversation; private String selectedChannel; private String selectedUser; private SelectedOption selectedOption; private List<String> selectedUsers; } @Data public static class SelectedOption { private PlainTextObject text; private String value; } }
Fix glossary file location to relative
#! /usr/bin/python2.7 # -*- coding: utf-8 -*- from flask import Flask, render_template import os import re from settings import BABEL_SETTINGS, SERVER_SETTINGS from utils.i18n import PopongBabel from utils.glossary import load as load_glossary app = Flask(__name__) app.debug = SERVER_SETTINGS['debug'] p = os.path.join(app.root_path, 'static/data/crawlers/glossary/glossary.csv') terms = load_glossary(p) PopongBabel(app, **BABEL_SETTINGS) @app.route('/') def home(): return render_template('glossary.html', terms=terms) def cmd_args(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-l', dest='locale', choices=app.LOCALES + ['auto'], default='auto') args = parser.parse_args() return args def main(): args = cmd_args() if args.locale and args.locale != 'auto': app.babel.locale_selector_func = lambda: args.locale app.run(**SERVER_SETTINGS) if __name__ == '__main__': main()
#! /usr/bin/python2.7 # -*- coding: utf-8 -*- import re from flask import Flask, render_template from settings import BABEL_SETTINGS, SERVER_SETTINGS from utils.i18n import PopongBabel from utils.glossary import load as load_glossary app = Flask(__name__) app.debug = SERVER_SETTINGS['debug'] terms = load_glossary('static/data/crawlers/glossary/glossary.csv') PopongBabel(app, **BABEL_SETTINGS) @app.route('/') def home(): return render_template('glossary.html', terms=terms) def cmd_args(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-l', dest='locale', choices=app.LOCALES + ['auto'], default='auto') args = parser.parse_args() return args def main(): args = cmd_args() if args.locale and args.locale != 'auto': app.babel.locale_selector_func = lambda: args.locale app.run(**SERVER_SETTINGS) if __name__ == '__main__': main()
Add condition on scan of pci.ids to exclude sub-classes from being caught up as a device.
package pci import ( "bufio" "bytes" ) func isHex(b byte) bool { return ('a' <= b && b <= 'f') || ('A' <= b && b <= 'F') || ('0' <= b && b <= '9') } // scan searches for Vendor and Device lines from the input *bufio.Scanner based // on pci.ids format. Found Vendors and Devices are added to the input ids map. func scan(s *bufio.Scanner, ids map[string]Vendor) error { var currentVendor string var line string for s.Scan() { line = s.Text() switch { case isHex(line[0]) && isHex(line[1]): currentVendor = line[:4] ids[currentVendor] = Vendor{Name: line[6:], Devices: make(map[string]Device)} case currentVendor != "" && line[0] == '\t' && isHex(line[1]) && isHex(line[3]): ids[currentVendor].Devices[line[1:5]] = Device(line[7:]) } } return nil } func parse(input []byte) (map[string]Vendor, error) { ids := make(map[string]Vendor) s := bufio.NewScanner(bytes.NewReader(input)) err := scan(s, ids) return ids, err }
package pci import ( "bufio" "bytes" ) func isHex(b byte) bool { return ('a' <= b && b <= 'f') || ('A' <= b && b <= 'F') || ('0' <= b && b <= '9') } // scan searches for Vendor and Device lines from the input *bufio.Scanner based // on pci.ids format. Found Vendors and Devices are added to the input map. // This implimentation expects an input pci.ids to have comments, blank lines, // sub-devices, and classes already removed. func scan(s *bufio.Scanner, ids map[string]Vendor) error { var currentVendor string var line string for s.Scan() { line = s.Text() switch { case isHex(line[0]) && isHex(line[1]): currentVendor = line[:4] ids[currentVendor] = Vendor{Name: line[6:], Devices: make(map[string]Device)} case currentVendor != "" && line[0] == '\t' && isHex(line[1]): ids[currentVendor].Devices[line[1:5]] = Device(line[7:]) } } return nil } func parse(input []byte) (map[string]Vendor, error) { ids := make(map[string]Vendor) s := bufio.NewScanner(bytes.NewReader(input)) err := scan(s, ids) return ids, err }
Validate input using class, using return on if else condition
<input type="text" class="form-control input" placeholder="Nama.." id="nama"><br> <textarea rows="8" id="komentar" placeholder="Komentar anda.." class="form-control input"></textarea><br> <button class="btn btn-info" onclick="postComment()">Submit</button> <script type="text/javascript"> function postComment() { // Firebase var ref = new Firebase("https://tauduluan.firebaseio.com"); var comments = ref.child("comments"); // Get input value var nama = $('#nama').val(); var komentar = $('#komentar').val(); var input = $('.input').val(); if (input == '') { alert('Input is not filled') return false; } else { // Log input value console.log('Nama: ' + nama); console.log('Komentar: ' + komentar); // Post data to firebase comments.push().set({ nama: nama, komentar: komentar }); return true; } } </script> <script src="https://cdn.firebase.com/js/client/2.4.1/firebase.js" charset="utf-8"></script>
<input type="text" class="form-control" placeholder="Nama.." id="nama"><br> <textarea rows="8" id="komentar" placeholder="Komentar anda.." class="form-control"></textarea><br> <button class="btn btn-info" onclick="postComment()">Submit</button> <script type="text/javascript"> function postComment() { // Firebase var ref = new Firebase("https://tauduluan.firebaseio.com"); var comments = ref.child("comments"); // Get input value var nama = $('#nama').val(); var komentar = $('#komentar').val(); var input = $('.form-control').val(); if (input == '') { alert('Input is not filled') } else { // Log input value console.log('Nama: ' + nama); console.log('Komentar: ' + komentar); // Post data to firebase comments.push().set({ nama: nama, komentar: komentar }) } } </script> <script src="https://cdn.firebase.com/js/client/2.4.1/firebase.js" charset="utf-8"></script>
Make email and password have default values * which must be overriden
package com.fns.xlator.client.impl; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "app.frengly") public class FrenglyClientSettings { private String host = "frengly.com"; @NotEmpty private String email = "change@me.com"; @NotEmpty private String password = "changeme"; private int retries = 10; @Value("${app.defaults.locale}") private String defaultSource; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDefaultSource() { return defaultSource; } public int getRetries() { return retries; } }
package com.fns.xlator.client.impl; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "app.frengly") public class FrenglyClientSettings { private String host = "frengly.com"; @NotEmpty private String email; @NotEmpty private String password; private int retries = 10; @Value("${app.defaults.locale}") private String defaultSource; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDefaultSource() { return defaultSource; } public int getRetries() { return retries; } }
Add argument to print usernames
#!/usr/bin/env python3 """ A program to extract raw text from Telegram chat log """ import argparse from json import loads def main(): parser = argparse.ArgumentParser( description="Extract all raw text from a specific Telegram chat") parser.add_argument('filepath', help='the json chatlog file to analyse') parser.add_argument('-u','--usernames', help='Show usernames before messages',action='store_true') args=parser.parse_args() filepath = args.filepath with open(filepath, 'r') as jsonfile: events = (loads(line) for line in jsonfile) for event in events: #check the event is the sort we're looking for if "from" in event and "text" in event: if args.usernames: print(event['from']['username'],end=': ') #do i need the "from" here? print(event["text"]) if __name__ == "__main__": main()
#!/usr/bin/env python3 """ A program to extract raw text from Telegram chat log """ import argparse from json import loads def main(): parser = argparse.ArgumentParser( description="Extract all raw text from a specific Telegram chat") parser.add_argument('filepath', help='the json chatlog file to analyse') args=parser.parse_args() filepath = args.filepath with open(filepath, 'r') as jsonfile: events = (loads(line) for line in jsonfile) for event in events: #check the event is the sort we're looking for if "from" in event and "text" in event: #do i need the "from" here? print(event["text"]) if __name__ == "__main__": main()
Remove application flag, not an application
# -*- coding: utf-8 -*- # Copyright 2013-2017 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) {'name': 'Connector', 'version': '10.0.1.0.0', 'author': 'Camptocamp,Openerp Connector Core Editors,' 'Odoo Community Association (OCA)', 'website': 'http://odoo-connector.com', 'license': 'AGPL-3', 'category': 'Generic Modules', 'depends': ['mail', 'queue_job', ], 'data': ['security/connector_security.xml', 'security/ir.model.access.csv', 'checkpoint/checkpoint_view.xml', 'connector_menu.xml', 'setting_view.xml', 'res_partner_view.xml', ], 'installable': True, }
# -*- coding: utf-8 -*- # Copyright 2013-2017 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) {'name': 'Connector', 'version': '10.0.1.0.0', 'author': 'Camptocamp,Openerp Connector Core Editors,' 'Odoo Community Association (OCA)', 'website': 'http://odoo-connector.com', 'license': 'AGPL-3', 'category': 'Generic Modules', 'depends': ['mail', 'queue_job', ], 'data': ['security/connector_security.xml', 'security/ir.model.access.csv', 'checkpoint/checkpoint_view.xml', 'connector_menu.xml', 'setting_view.xml', 'res_partner_view.xml', ], 'installable': True, 'application': True, }
Rearrange methods to follow route setup
// global_config.js var Parse = require('parse/node').Parse, PromiseRouter = require('./PromiseRouter'); var router = new PromiseRouter(); function getGlobalConfig(req) { return req.config.database.rawCollection('_GlobalConfig') .then(coll => coll.findOne({'_id': 1})) .then(globalConfig => ({response: { params: globalConfig.params }})) .catch(() => ({ status: 404, response: { code: Parse.Error.INVALID_KEY_NAME, error: 'config does not exist', } })); } function updateGlobalConfig(req) { if (!req.auth.isMaster) { return Promise.resolve({ status: 401, response: {error: 'unauthorized'}, }); } return req.config.database.rawCollection('_GlobalConfig') .then(coll => coll.findOneAndUpdate({ _id: 1 }, { $set: req.body }, { returnOriginal: false })) .then(response => { return { response: { params: response.value.params } } }) .catch(() => ({ status: 404, response: { code: Parse.Error.INVALID_KEY_NAME, error: 'config cannot be updated', } })); } router.route('GET', '/config', getGlobalConfig); router.route('PUT', '/config', updateGlobalConfig); module.exports = router;
// global_config.js var Parse = require('parse/node').Parse, PromiseRouter = require('./PromiseRouter'); var router = new PromiseRouter(); function updateGlobalConfig(req) { if (!req.auth.isMaster) { return Promise.resolve({ status: 401, response: {error: 'unauthorized'}, }); } return req.config.database.rawCollection('_GlobalConfig') .then(coll => coll.findOneAndUpdate({ _id: 1 }, { $set: req.body }, { returnOriginal: false })) .then(response => { return { response: { params: response.value.params } } }) .catch(() => ({ status: 404, response: { code: Parse.Error.INVALID_KEY_NAME, error: 'config cannot be updated', } })); } function getGlobalConfig(req) { return req.config.database.rawCollection('_GlobalConfig') .then(coll => coll.findOne({'_id': 1})) .then(globalConfig => ({response: { params: globalConfig.params }})) .catch(() => ({ status: 404, response: { code: Parse.Error.INVALID_KEY_NAME, error: 'config does not exist', } })); } router.route('GET', '/config', getGlobalConfig); router.route('PUT', '/config', updateGlobalConfig); module.exports = router;
:bug: Fix a flow warning Flow does not support the unicode flag with RegExpes yet
'use babel' /* @flow */ import type { Message, MessageLegacy } from '../types' // Code Point 160 === &nbsp; const replacementRegex = new RegExp(String.fromCodePoint(160), 'g') export function visitMessage(message: Message | MessageLegacy) { const messageFile = message.version === 1 ? message.filePath : message.location.file const messageRange = message.version === 1 ? message.range : message.location.position atom.workspace.open(messageFile, { searchAllPanes: true }).then(function() { const textEditor = atom.workspace.getActiveTextEditor() if (textEditor && textEditor.getPath() === messageFile && messageRange) { textEditor.setCursorBufferPosition(messageRange.start) } }) } export function htmlToText(html: any) { const element = document.createElement('div') if (typeof html === 'string') { element.innerHTML = html } else { element.appendChild(html.cloneNode(true)) } // NOTE: Convert &nbsp; to regular whitespace return element.textContent.replace(replacementRegex, ' ') }
'use babel' /* @flow */ import type { Message, MessageLegacy } from '../types' export function visitMessage(message: Message | MessageLegacy) { const messageFile = message.version === 1 ? message.filePath : message.location.file const messageRange = message.version === 1 ? message.range : message.location.position atom.workspace.open(messageFile, { searchAllPanes: true }).then(function() { const textEditor = atom.workspace.getActiveTextEditor() if (textEditor && textEditor.getPath() === messageFile) { textEditor.setCursorBufferPosition(messageRange.start) } }) } export function htmlToText(html: any) { const element = document.createElement('div') if (typeof html === 'string') { element.innerHTML = html } else { element.appendChild(html.cloneNode(true)) } // NOTE: Convert &nbsp; to regular whitespace return element.textContent.replace(/\u00A0/gu, ' ') }
Use the .caller property to test tail-calls instead of trying to cause stackoverflow errors
/* * Copyright (c) 2012-2014 André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ const { assertSame } = Assert; // Invalid direct eval call and tail calls: // - direct eval fallback and 'wrong' eval function have both tail calls enabled // - chaining them should preserve the tail call property let realm = new Realm({ directEval: { fallback(thisArgument, callee, ...args) { "use strict"; return callee(...args); } } }); realm.eval(` function returnCaller() { return returnCaller.caller; } function tailCall() { "use strict"; return returnCaller(); } function testFunction() { return eval("123"); } eval = tailCall; `); assertSame(realm.global.testFunction, realm.eval(`testFunction()`));
/* * Copyright (c) 2012-2014 André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ const { assertSame } = Assert; // Invalid direct eval call and tail calls: // - direct eval fallback and 'wrong' eval function have both tail calls enabled // - chaining them should preserve the tail call property const stackLimit = (function() { let limit = 0; try { (function f(){ f(limit++) })(); } catch (e) { } return limit; })(); function gauss(n) { return (n * n + n) / 2; } let callCount; let realm = new Realm({ directEval: { fallback(thisArgument, callee, ...args) { "use strict"; callCount += 1; return callee(...args); } } }); realm.eval(` function sum(n, acc) { "use strict"; if (n === 0) return acc; return eval(n - 1, acc + n); } eval = sum; `); for (let v of [1, 10, 100, 1000, 10000, stackLimit * 10]) { callCount = 0; assertSame(gauss(v), realm.eval(`sum(${v}, 0)`)); assertSame(v, callCount); }
Return format to please the browser's graph.
import neo4j class SubTopics(neo4j.Traversal): """Traverser that yields all subcategories of a category.""" types = [neo4j.Incoming.is_a] returnable = neo4j.RETURN_ALL_BUT_START_NODE order = neo4j.BREADTH_FIRST stop = neo4j.STOP_AT_END_OF_GRAPH class Topics(neo4j.Traversal): types = [ neo4j.Outgoing.mentions_concept, neo4j.Outgoing.mentions, neo4j.Outgoing.is_a, ] order = neo4j.BREADTH_FIRST stop = neo4j.STOP_AT_END_OF_GRAPH def isReturnable(self, position): return not position.is_start and\ position.last_relationship.type == 'is_a' def run(graph, index, node): topics = {} for topic in Topics(node): # TODO need to give this '1' some meaning topics[topic["name"]] = [{sub["name"]: 1} for sub in SubTopics(topic)] return topics
import neo4j class SubTopics(neo4j.Traversal): """Traverser that yields all subcategories of a category.""" types = [neo4j.Incoming.is_a] returnable = neo4j.RETURN_ALL_BUT_START_NODE order = neo4j.BREADTH_FIRST stop = neo4j.STOP_AT_END_OF_GRAPH class Topics(neo4j.Traversal): types = [ neo4j.Outgoing.mentions_concept, neo4j.Outgoing.mentions, neo4j.Outgoing.is_a, ] order = neo4j.BREADTH_FIRST stop = neo4j.STOP_AT_END_OF_GRAPH def isReturnable(self, position): return not position.is_start and\ position.last_relationship.type == 'is_a' def run(graph, index, node): topics = {} for topic in Topics(node): topics[topic["name"]] = [sub["name"] for sub in SubTopics(topic)] return topics
Update the required vectormath version to 0.1.0
#!/usr/bin/env python """ properties: Fancy properties for Python. """ from distutils.core import setup from setuptools import find_packages CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Physics', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Operating System :: Unix', 'Operating System :: MacOS', 'Natural Language :: English', ] with open("README.rst") as f: LONG_DESCRIPTION = ''.join(f.readlines()) setup( name="properties", version="0.2.2", packages=find_packages(exclude=('tests',)), install_requires=[ 'future', 'numpy>=1.7', 'six', 'vectormath>=0.1.0', ], author="3point Science", author_email="info@3ptscience.com", description="properties", long_description=LONG_DESCRIPTION, keywords="property", url="http://steno3d.com/", download_url="http://github.com/3ptscience/properties", classifiers=CLASSIFIERS, platforms=["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"], use_2to3=False, )
#!/usr/bin/env python """ properties: Fancy properties for Python. """ from distutils.core import setup from setuptools import find_packages CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Physics', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Operating System :: Unix', 'Operating System :: MacOS', 'Natural Language :: English', ] with open("README.rst") as f: LONG_DESCRIPTION = ''.join(f.readlines()) setup( name="properties", version="0.2.2", packages=find_packages(exclude=('tests',)), install_requires=[ 'future', 'numpy>=1.7', 'six', 'vectormath', ], author="3point Science", author_email="info@3ptscience.com", description="properties", long_description=LONG_DESCRIPTION, keywords="property", url="http://steno3d.com/", download_url="http://github.com/3ptscience/properties", classifiers=CLASSIFIERS, platforms=["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"], use_2to3=False, )
Set default jakefile task to 'test' so it gets executed by travis-ci.org
/* globals desc:false, task: false, complete: fase, jake: false */ (function (desc, task, complete, jake) { "use strict"; desc('The default task. Runs tests.'); task('default', ['test'], function () { }); desc('Run tests'); task('test', [], function () { jake.exec(["./node_modules/.bin/vows test/debug.test.js", "./node_modules/.bin/vows test/launcher.test.js", "./node_modules/.bin/nodeunit test/site.test.js"], function () { console.log('All tests passed.'); complete(); }, {stdout: true}); }, true); })(desc, task, complete, jake);
/* globals desc:false, task: false, complete: fase, jake: false */ (function (desc, task, complete, jake) { "use strict"; desc('The default task. Runs tests.'); task('default', ['tests'], function () { }); desc('Run tests'); task('tests', [], function () { jake.exec(["./node_modules/.bin/vows test/debug.test.js", "./node_modules/.bin/vows test/launcher.test.js", "./node_modules/.bin/nodeunit test/site.test.js"], function () { console.log('All tests passed.'); complete(); }, {stdout: true}); }, true); })(desc, task, complete, jake);
Convert tags to a set on init and back to a list on writing.
"""Provide the class IdxItem which represents an item in the index. """ import hashlib def _md5file(fname): """Calculate the md5 hash for a file. """ m = hashlib.md5() chunksize = 8192 with open(fname, 'rb') as f: while True: chunk = f.read(chunksize) if not chunk: break m.update(chunk) return m.hexdigest() class IdxItem(object): def __init__(self, filename=None, data=None): self.filename = None self.tags = [] if data is not None: self.__dict__.update(data) elif filename is not None: self.filename = filename self.md5 = _md5file(filename) self.tags = set(self.tags) def as_dict(self): d = self.__dict__.copy() d['tags'] = list(d['tags']) return d
"""Provide the class IdxItem which represents an item in the index. """ import hashlib def _md5file(fname): """Calculate the md5 hash for a file. """ m = hashlib.md5() chunksize = 8192 with open(fname, 'rb') as f: while True: chunk = f.read(chunksize) if not chunk: break m.update(chunk) return m.hexdigest() class IdxItem(object): def __init__(self, filename=None, data=None): self.filename = None self.tags = [] if data is not None: self.__dict__.update(data) elif filename is not None: self.filename = filename self.md5 = _md5file(filename) def as_dict(self): return dict(self.__dict__)
Change the way text message egress initializes
import BaseWorker from '../../base' import twilio from 'twilio' import path from 'path' export class TextMessage extends BaseWorker { constructor (rsmq) { super('text_message', rsmq) this.client = new twilio.RestClient( process.env.TWILIO_SID, process.env.TWILIO_TOKEN ) } body (message) { return this.render( path.join(__dirname, '../templates', 'plain_text.ejs'), message ) } async process (message, next) { try { await this.client.sendMessage({ body: this.body(message), to: process.env.TWILIO_TO_NUMBER, from: process.env.TWILIO_FROM_NUMBER }) next(null) } catch (err) { next(err) } } } export default TextMessage
import BaseWorker from '../../base' import twilio from 'twilio' import path from 'path' const client = new twilio.RestClient( process.env.TWILIO_SID, process.env.TWILIO_TOKEN ) export class TextMessage extends BaseWorker { constructor (rsmq) { super('text_message', rsmq) } body (message) { return this.render( path.join(__dirname, '../templates', 'plain_text.ejs'), message ) } async process (message, next) { try { await client.sendMessage({ body: this.body(message), to: process.env.TWILIO_TO_NUMBER, from: process.env.TWILIO_FROM_NUMBER }) next() } catch (err) { next(err) } } } export default TextMessage
Update : uppercase every input commands
# -*- coding: utf-8 -*- # Copyright (c) 2012 theo crevon # # See the file LICENSE for copying permission. from clint.textui import puts, colored from elevator.utils.patterns import destructurate from .helpers import FAILURE_STATUS def prompt(*args, **kwargs): current_db = kwargs.pop('current_db', 'default') if current_db: pattern = '@ Elevator.{db} => '.format(db=current_db) else: pattern = '! Offline => ' input_str = raw_input(pattern) return input_str def parse_input(input_str, *args, **kwargs): input_str = input_str.strip().split() command, args = destructurate(input_str) return command.upper(), args def output_result(status, result, *args, **kwargs): if result: if status == FAILURE_STATUS: puts(colored.red(str(result))) else: puts(str(result))
# -*- coding: utf-8 -*- # Copyright (c) 2012 theo crevon # # See the file LICENSE for copying permission. from clint.textui import puts, colored from elevator.utils.patterns import destructurate from .helpers import FAILURE_STATUS def prompt(*args, **kwargs): current_db = kwargs.pop('current_db', 'default') if current_db: pattern = '@ Elevator.{db} => '.format(db=current_db) else: pattern = '! Offline => ' input_str = raw_input(pattern) return input_str def parse_input(input_str, *args, **kwargs): input_str = input_str.strip().split() command, args = destructurate(input_str) return command, args def output_result(status, result, *args, **kwargs): if result: if status == FAILURE_STATUS: puts(colored.red(str(result))) else: puts(str(result))
Test: Increase timeout duration for "scroll"
const { Tracker } = Sentinel; /* Constants */ const targetSize = 200; const container = document.getElementById('container'); const bounds = document.getElementById('bounds'); function createTarget(styles = {}, parent = container) { const element = document.createElement('div'); element.classList.add('target'); /* Set target's dimensions */ element.style.height = `${targetSize}px`; element.style.width = `${targetSize}px`; /* Append style rules dynamically */ Object.keys(styles).forEach(rule => element.style[rule] = styles[rule]); parent.appendChild(element); return element; } function scroll(nextX, nextY) { return new Promise((resolve) => { window.scrollTo(nextX, nextY); setTimeout(resolve, 25); }); } function beforeEachHook() { /* Restore scroll position before each test */ window.scrollTo(0, 0); } function afterEachHook() { /* Clean up the containers after each test */ container.innerHTML = ''; bounds.innerHTML = ''; } function animate(DOMElement) { DOMElement.classList.add('tracked'); } require([ 'test/basics.spec', 'test/edges.spec', 'test/thresholds.spec', 'test/once.spec', ], mocha.run);
const { Tracker } = Sentinel; /* Constants */ const targetSize = 200; const container = document.getElementById('container'); const bounds = document.getElementById('bounds'); function createTarget(styles = {}, parent = container) { const element = document.createElement('div'); element.classList.add('target'); /* Set target's dimensions */ element.style.height = `${targetSize}px`; element.style.width = `${targetSize}px`; /* Append style rules dynamically */ Object.keys(styles).forEach(rule => element.style[rule] = styles[rule]); parent.appendChild(element); return element; } function scroll(nextX, nextY) { return new Promise((resolve) => { window.scrollTo(nextX, nextY); setTimeout(resolve, 20); }); } function beforeEachHook() { /* Restore scroll position before each test */ window.scrollTo(0, 0); } function afterEachHook() { /* Clean up the containers after each test */ container.innerHTML = ''; bounds.innerHTML = ''; } function animate(DOMElement) { DOMElement.classList.add('tracked'); } require([ 'test/basics.spec', 'test/edges.spec', 'test/thresholds.spec', 'test/once.spec', ], mocha.run);
Improve download speed by using non-blocking. Also adding upper limit 365.
var cheerio = require('cheerio'), request = require('request'), fs = require('fs'); var savePath = process.argv[2]; if(typeof savePath === 'undefined') { console.log("Error: Save path not defined."); return; } var year = "2013"; var baseUri = 'http://www.facets.la/'; (function getImg(id) { var uri = baseUri + year + '/' + id + '/'; request({ uri: uri }, function(error, response, body) { if(id == 330) year = "2014"; var $ = cheerio.load(body); var imgDiv = $('#facet-image').children()['0']; if(typeof imgDiv !== 'undefined') { request(imgDiv.attribs.src).pipe(fs.createWriteStream(savePath + id + '.jpg')); } }); if(id <= 365) getImg(id+1); })(1);
var cheerio = require('cheerio'), request = require('request'), fs = require('fs'); var savePath = process.argv[2]; if(typeof savePath === 'undefined') { console.log("Error: Save path not defined."); return; } var year = "2013"; var baseUri = 'http://www.facets.la/'; (function getImg(id) { var uri = baseUri + year + '/' + id + '/'; request({ uri: uri }, function(error, response, body) { if(id == 330) year = "2014"; var $ = cheerio.load(body); var imgDiv = $('#facet-image').children()['0']; if(typeof imgDiv !== 'undefined') { request(imgDiv.attribs.src).pipe(fs.createWriteStream(savePath + id + '.jpg')); } getImg(id+1); }); })(1);
Add notification about gemini config overriding
'use strict'; var path = require('path'), opener = require('opener'), chalk = require('chalk'), pkg = require('../package.json'), server = require('./server'), program = require('commander'); exports.run = function() { program .version(pkg.version) .allowUnknownOption(true) .option('-p, --port <port>', 'Port to launch server on', 8000) .option('-h, --hostname <hostname>', 'Hostname to launch server on', 'localhost') .option('-c, --config <file>', 'Gemini config file', path.resolve) .parse(process.argv); program.on('--help', function() { console.log('Also you can override gemini config options.'); console.log('See all possible options in gemini documentation.'); }); program.testFiles = [].concat(program.args); server.start(program).then(function(result) { console.log('GUI is running at %s', chalk.cyan(result.url)); opener(result.url); }).done(); };
'use strict'; var path = require('path'), opener = require('opener'), chalk = require('chalk'), pkg = require('../package.json'), server = require('./server'), program = require('commander'); function getConfigPath(config) { return path.resolve(config); } exports.run = function() { program .version(pkg.version) .allowUnknownOption(true) .option('-p, --port <port>', 'Port to launch server on', 8000) .option('-h, --hostname <hostname>', 'Hostname to launch server on', 'localhost') .option('-c, --config <file>', 'Gemini config file', getConfigPath) .parse(process.argv); program.testFiles = [].concat(program.args); server.start(program).then(function(result) { console.log('GUI is running at %s', chalk.cyan(result.url)); opener(result.url); }).done(); };
Fix an issue where the unit test fails on PHP 5.3
<?php namespace Dakatsuka\MonologFluentHandler\Tests; use Dakatsuka\MonologFluentHandler\FluentHandler; use Monolog\Logger; class FluentHandlerTest extends \PHPUnit_Framework_TestCase { /** * @var array */ protected $record; protected function setUp() { $record = array(); $record['channel'] = 'debug'; $record['message'] = 'monolog.fluent'; $record['context'] = array('foo' => 'bar'); $record['formatted'] = 'formatted message'; $record['level'] = Logger::DEBUG; $this->record = $record; } public function testWrite() { $context = $this->record['context']; $context['level'] = Logger::getLevelName($this->record['level']); $loggerMock = $this->getMockBuilder('Fluent\Logger\FluentLogger') ->disableOriginalConstructor() ->getMock(); $loggerMock ->expects($this->once()) ->method('post') ->with('debug.monolog.fluent', $context); $handler = new FluentHandler($loggerMock); $handler->write($this->record); } }
<?php namespace Dakatsuka\MonologFluentHandler\Tests; use Dakatsuka\MonologFluentHandler\FluentHandler; use Monolog\Logger; class FluentHandlerTest extends \PHPUnit_Framework_TestCase { /** * @var array */ protected $record; protected function setUp() { $record = array(); $record['channel'] = 'debug'; $record['message'] = 'monolog.fluent'; $record['context'] = ['foo' => 'bar']; $record['formatted'] = 'formatted message'; $record['level'] = Logger::DEBUG; $this->record = $record; } public function testWrite() { $context = $this->record['context']; $context['level'] = Logger::getLevelName($this->record['level']); $loggerMock = $this->getMockBuilder('Fluent\Logger\FluentLogger') ->disableOriginalConstructor() ->getMock(); $loggerMock ->expects($this->once()) ->method('post') ->with('debug.monolog.fluent', $context); $handler = new FluentHandler($loggerMock); $handler->write($this->record); } }
Support IPv6 in random ip
#!/usr/bin/env python # -*- coding: utf-8 -*- import random from flask import Flask, request, render_template, url_for, redirect from pyhipku import encode app = Flask(__name__) @app.route('/<current_ip>') def index(current_ip): your_ip = request.remote_addr lines = encode(current_ip).split('\n') return render_template('cover.html', lines=lines, your_ip=your_ip, current_ip=current_ip) @app.route('/') def get_ip(): return redirect(url_for('index', current_ip=request.remote_addr)) @app.route('/random') def random_ip(): if random.random() < 0.5: random_ip = '.'.join(map(str, [random.randint(0, 255) for _ in range(4)])) else: random_ip = ':'.join('{0:x}'.format(random.randint(0,2**16-1)) for _ in range(8)) return redirect(url_for('index', current_ip=random_ip)) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
#!/usr/bin/env python # -*- coding: utf-8 -*- from random import randint from flask import Flask, request, render_template, url_for, redirect from pyhipku import encode app = Flask(__name__) @app.route('/<current_ip>') def index(current_ip): your_ip = request.remote_addr lines = encode(current_ip).split('\n') return render_template('cover.html', lines=lines, your_ip=your_ip, current_ip=current_ip) @app.route('/') def get_ip(): return redirect(url_for('index', current_ip=request.remote_addr)) @app.route('/random') def random_ip(): random_ip = '.'.join(map(str, [randint(0, 255) for _ in range(4)])) return redirect(url_for('index', current_ip=random_ip)) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
Fix Karma trying to compile files that should not be compiled Perhaps we need another strategy here. Basically only 'frontend' files need to be compiled.
module.exports = function(karma) { const rollupConfig = require("./rollup.config")[0]; karma.set({ frameworks: ["mocha", "chai", "chai-dom", "sinon-chai"], files: [ { pattern: "src/**/!(cli|webpack).js", included: false }, "spec/**/*.spec.js" ], preprocessors: { "src/**/!(cli|tasks|utils).js": ["rollup"], "spec/**/*.spec.js": ["rollup"] }, client: { captureConsole: true, mocha: { reporter: "html" // view on http://localhost:9876/debug.html } }, reporters: ["mocha"], browsers: ["ChromeHeadlessNoSandbox"], customLaunchers: { ChromeHeadlessNoSandbox: { base: "ChromeHeadless", flags: ["--no-sandbox"] } }, rollupPreprocessor: { output: rollupConfig.output, plugins: rollupConfig.plugins, external: undefined } }); };
module.exports = function(karma) { const rollupConfig = require("./rollup.config")[0]; karma.set({ frameworks: ["mocha", "chai", "chai-dom", "sinon-chai"], files: [ { pattern: "src/**/!(cli|webpack).js", included: false }, "spec/**/*.spec.js" ], preprocessors: { "src/**/!(cli).js": ["rollup"], "spec/**/*.spec.js": ["rollup"] }, client: { captureConsole: true, mocha: { reporter: "html" // view on http://localhost:9876/debug.html } }, reporters: ["mocha"], browsers: ["ChromeHeadlessNoSandbox"], customLaunchers: { ChromeHeadlessNoSandbox: { base: "ChromeHeadless", flags: ["--no-sandbox"] } }, rollupPreprocessor: { output: rollupConfig.output, plugins: rollupConfig.plugins, external: undefined } }); };
Make intro flashes more interesting
var Drawing = function (pulse, config) { pulse.framesLeft = 300; pulse.shade = 0; this.pulse = pulse; }; Drawing.prototype.draw = function (p) { var self = this; var pulse = self.pulse if (pulse.framesLeft > 255) { if (pulse.framesLeft % 10 === 0) { pulse.r = Math.random() * 255; pulse.g = Math.random() * 255; pulse.b = Math.random() * 255; } pulse.shade += 2; } else { pulse.shade = pulse.framesLeft; } p.fill(pulse.r, pulse.g, pulse.b, pulse.shade); p.textSize(100); p.textAlign(p.CENTER); p.textStyle(p.BOLD); p.text("PULSAR", p.windowWidth/2, p.windowHeight/2); p.fill(pulse.shade); p.textSize(15); p.textStyle(p.NORMAL); p.text("v" + pulse.version, p.windowWidth/2, p.windowHeight/2 + 20); pulse.framesLeft -= 2; }; Drawing.prototype.done = function () { if (this.pulse.framesLeft < 0) { return true; } else { return false; } } module.exports = Drawing;
var Drawing = function (pulse, config) { pulse.framesLeft = 255; this.pulse = pulse; }; Drawing.prototype.draw = function (p) { var self = this; var pulse = self.pulse var shade = 255; if (pulse.framesLeft > 230) { pulse.r = Math.random() * 255; pulse.g = Math.random() * 255; pulse.b = Math.random() * 255; shade = Math.random() * 50; } else { shade = pulse.framesLeft; } p.fill(pulse.r, pulse.g, pulse.b, shade); p.textSize(100); p.textAlign(p.CENTER); p.textStyle(p.BOLD); p.text("PULSAR", p.windowWidth/2, p.windowHeight/2); p.fill(shade); p.textSize(15); p.textStyle(p.NORMAL); p.text("v" + pulse.version, p.windowWidth/2, p.windowHeight/2 + 20); pulse.framesLeft -= 2; }; Drawing.prototype.done = function () { if (this.pulse.framesLeft < 0) { return true; } else { return false; } } module.exports = Drawing;
Update method signature to use interface instead of class Closes #303
<?php /* * This file is part of the Sonata package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\DoctrineORMAdminBundle\Guesser; use Sonata\AdminBundle\Guesser\TypeGuesserInterface; use Doctrine\ORM\Mapping\MappingException; use Sonata\AdminBundle\Model\ModelManagerInterface; abstract class AbstractTypeGuesser implements TypeGuesserInterface { /** * @param string $baseClass * @param string $propertyFullName * @param \Sonata\AdminBundle\Model\ModelManagerInterface $modelManager * * @return array|null */ protected function getParentMetadataForProperty($baseClass, $propertyFullName, ModelManagerInterface $modelManager) { try { return $modelManager->getParentMetadataForProperty($baseClass, $propertyFullName); } catch (MappingException $e) { // no metadata not found. return null; } } }
<?php /* * This file is part of the Sonata package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\DoctrineORMAdminBundle\Guesser; use Sonata\AdminBundle\Guesser\TypeGuesserInterface; use Doctrine\ORM\Mapping\MappingException; use Sonata\DoctrineORMAdminBundle\Model\ModelManager; abstract class AbstractTypeGuesser implements TypeGuesserInterface { /** * @param string $baseClass * @param string $propertyFullName * @param \Sonata\DoctrineORMAdminBundle\Model\ModelManager $modelManager * * @return array|null */ protected function getParentMetadataForProperty($baseClass, $propertyFullName, ModelManager $modelManager) { try { return $modelManager->getParentMetadataForProperty($baseClass, $propertyFullName); } catch (MappingException $e) { // no metadata not found. return null; } } }
Rename method setSliderManager to setSlider
/** Copyright 2017 John Kester (Jack Kester) 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.github.slidekb.api; /** * @author JackSec */ public interface SlideBarPlugin { /** * returns the priority for the plugin * not currently used for anything yet * * @return */ public int getPriority(); /** * name displayed in master configuration window/ main application. * * @return */ public String getLabelName(); /** * runs while exe current window or hotkey is being pressed */ public void run(); /** * runs on first .exe match or hotkeypress. used to set up run(); */ public void runFirst(); /** * sets the SlideBar manager * * @param sliderManager */ public void setSlider(Slider slider); }
/** Copyright 2017 John Kester (Jack Kester) 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.github.slidekb.api; /** * @author JackSec */ public interface SlideBarPlugin { /** * returns the priority for the plugin * not currently used for anything yet * * @return */ public int getPriority(); /** * name displayed in master configuration window/ main application. * * @return */ public String getLabelName(); /** * runs while exe current window or hotkey is being pressed */ public void run(); /** * runs on first .exe match or hotkeypress. used to set up run(); */ public void runFirst(); /** * sets the SlideBar manager * * @param sliderManager */ public void setSliderManager(Slider slider); }
Remove custom 1D lerp() function. THREE.Math.lerp() was added in three.js r82.
import * as THREE from 'three'; export function randomPointOnSphere( vector = new THREE.Vector3() ) { const theta = 2 * Math.PI * Math.random(); const u = 2 * Math.random() - 1; const v = Math.sqrt( 1 - u * u ); return vector.set( v * Math.cos( theta ), v * Math.sin( theta ), u ); } export function inverseLerp( a, b, x ) { return ( x - a ) / ( b - a ); } /* Returns a function that invokes the callback on a vector, passing in the position of the vector relative to the geometry bounding box, where [ 0, 0, 0 ] is the center and extrema are in [ -1, 1 ]. For example, [ -1, 0, 0 ] if the vector is on the left face of the bounding box, [ 0, 1, 0 ] if on the top face, etc. The callback is invoked with four arguments: (vector, xt, yt, zt). */ export function parametric( geometry, callback ) { geometry.computeBoundingBox(); const { min, max } = geometry.boundingBox; return vector => { callback( vector, 2 * inverseLerp( min.x, max.x, vector.x ) - 1, 2 * inverseLerp( min.y, max.y, vector.y ) - 1, 2 * inverseLerp( min.z, max.z, vector.z ) - 1 ); }; }
import * as THREE from 'three'; export function randomPointOnSphere( vector = new THREE.Vector3() ) { const theta = 2 * Math.PI * Math.random(); const u = 2 * Math.random() - 1; const v = Math.sqrt( 1 - u * u ); return vector.set( v * Math.cos( theta ), v * Math.sin( theta ), u ); } export function lerp( a, b, t ) { return a + t * ( b - a ); } export function inverseLerp( a, b, x ) { return ( x - a ) / ( b - a ); } /* Returns a function that invokes the callback on a vector, passing in the position of the vector relative to the geometry bounding box, where [ 0, 0, 0 ] is the center and extrema are in [ -1, 1 ]. For example, [ -1, 0, 0 ] if the vector is on the left face of the bounding box, [ 0, 1, 0 ] if on the top face, etc. The callback is invoked with four arguments: (vector, xt, yt, zt). */ export function parametric( geometry, callback ) { geometry.computeBoundingBox(); const { min, max } = geometry.boundingBox; return vector => { callback( vector, 2 * inverseLerp( min.x, max.x, vector.x ) - 1, 2 * inverseLerp( min.y, max.y, vector.y ) - 1, 2 * inverseLerp( min.z, max.z, vector.z ) - 1 ); }; }
Set password in user ini
from google.appengine.ext import db import bcrypt class User(db.Model): email = db.EmailProperty() first_name = db.StringProperty() last_name = db.StringProperty() password_hash = db.StringProperty() created = db.DateTimeProperty(auto_now_add=True) updated = db.DateTimeProperty(auto_now=True) def __init__(self, *args, **kwds): db.Model.__init__(self, *args, **kwds) password = kwds.pop('password', None) if password: self.set_password(password) def set_password(self, password): self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt(log_rounds=1)) def check_password(self, password): return bcrypt.hashpw(password, self.password_hash) == self.password_hash @classmethod def authenticate(cls, email, password): user = cls.all().filter('email =', email).get() if user is None: return None if user.check_password(password): return user return None
from google.appengine.ext import db import bcrypt class User(db.Model): email = db.EmailProperty() first_name = db.StringProperty() last_name = db.StringProperty() password_hash = db.StringProperty() created = db.DateTimeProperty(auto_now_add=True) updated = db.DateTimeProperty(auto_now=True) def set_password(self, password): self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt(log_rounds=1)) def check_password(self, password): return bcrypt.hashpw(password, self.password_hash) == self.password_hash @classmethod def authenticate(cls, email, password): user = cls.all().filter('email =', email).get() if user is None: return None if user.check_password(password): return user return None