text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Use statusCode instead of code
/** * Various HTTP helper functions and defaults. */ 'use strict'; /** * Module dependencies. */ var http = require('http'); /** * Default charset. */ var CHARSET = 'utf-8'; /** * Reply to options request */ function options(req, res, methods) { res.setHeader('Allow', methods.join(' ')); } /** * Reply to request */ function reply(req, res) { return function(statusCode, data) { if (data instanceof Error) { if (http.STATUS_CODES[data.statusCode]) { statusCode = data.statusCode; } data = { message: data.message }; } res.statusCode = statusCode; if (!data && data !== null) { data = { message: http.STATUS_CODES[statusCode] || 'unknown error' }; } data = data ? JSON.stringify(data, null, 4) + '\n' : ''; res.setHeader('Content-Length', Buffer.byteLength(data, CHARSET)); if (data) { res.setHeader('Content-Type', 'application/json; charset=' + CHARSET); if (req.method !== 'HEAD') { return res.end(data); } } res.end(); }; } /** * Expose http */ exports.CHARSET = CHARSET; exports.STATUS_CODES = http.STATUS_CODES; exports.options = options; exports.reply = reply;
/** * Various HTTP helper functions and defaults. */ 'use strict'; /** * Module dependencies. */ var http = require('http'); /** * Default charset. */ var CHARSET = 'utf-8'; /** * Reply to options request */ function options(req, res, methods) { res.setHeader('Allow', methods.join(' ')); } /** * Reply to request */ function reply(req, res) { return function(code, data) { if (data instanceof Error) { if (http.STATUS_CODES[data.code]) { code = data.code; } data = { message: data.message }; } res.statusCode = code; if (!data && data !== null) { data = { message: http.STATUS_CODES[code] || 'unknown error' }; } data = data ? JSON.stringify(data, null, 4) + '\n' : ''; res.setHeader('Content-Length', Buffer.byteLength(data, CHARSET)); if (data) { res.setHeader('Content-Type', 'application/json; charset=' + CHARSET); if (req.method !== 'HEAD') { return res.end(data); } } res.end(); }; } /** * Expose http */ exports.CHARSET = CHARSET; exports.STATUS_CODES = http.STATUS_CODES; exports.options = options; exports.reply = reply;
Move updating preview text to its own function
'use strict'; var GameDataCreator = require('../gamedata'); var PointView = require('../prefabs/pointview'); function Editor() {} Editor.prototype = { create: function() { this.game.data = new GameDataCreator.GameData(); var background = this.game.add.sprite(0, 0, 'background'); this.sprites = this.game.add.group(); background.inputEnabled = true; background.events.onInputDown.add(this.clickListener, this); }, update: function() { }, clickListener: function(sprite, pointer) { var newPoint = new GameDataCreator.GamePoint(Math.floor(pointer.x), Math.floor(pointer.y), 'unvisited'); this.game.data.points.push(newPoint); var pointSprite = new PointView(this.game, newPoint); this.game.add.existing(pointSprite); this.sprites.add(pointSprite); this.updatePreviewText(); }, updatePreviewText: function() { var textArea = window.document.getElementById('outputJSON'); textArea.value = JSON.stringify(this.game.data, null, 2); } }; module.exports = Editor;
'use strict'; var GameDataCreator = require('../gamedata'); var PointView = require('../prefabs/pointview'); function Editor() {} Editor.prototype = { create: function() { this.game.data = new GameDataCreator.GameData(); var background = this.game.add.sprite(0, 0, 'background'); this.sprites = this.game.add.group(); background.inputEnabled = true; background.events.onInputDown.add(this.clickListener, this); }, update: function() { }, clickListener: function(sprite, pointer) { var newPoint = new GameDataCreator.GamePoint(Math.floor(pointer.x), Math.floor(pointer.y), 'unvisited'); console.log(newPoint); this.game.data.points.push(newPoint); var pointSprite = new PointView(this.game, newPoint); this.game.add.existing(pointSprite); this.sprites.add(pointSprite); console.log(Math.floor(pointer.x) + ' ' + Math.floor(pointer.y)); console.log(this.game.data.points); var textArea = window.document.getElementById('outputJSON'); textArea.value = JSON.stringify(this.game.data, null, 2); } }; module.exports = Editor;
Add support to register body from struct data
package httpfake import ( "encoding/json" "fmt" "net/http" ) // Response stores the settings defined by the request handler // of how it will respond the request back type Response struct { StatusCode int BodyBuffer []byte Header http.Header } // NewResponse creates a new Response func NewResponse() *Response { return &Response{ Header: make(http.Header), } } // Status sets the response status func (r *Response) Status(status int) *Response { r.StatusCode = status return r } // SetHeader sets the a HTTP header to the response func (r *Response) SetHeader(key, value string) *Response { r.Header.Set(key, value) return r } // AddHeader adds a HTTP header into the response func (r *Response) AddHeader(key, value string) *Response { r.Header.Add(key, value) return r } // BodyString sets the response body func (r *Response) BodyString(body string) *Response { r.BodyBuffer = []byte(body) return r } // BodyStruct sets the response body from a struct func (r *Response) BodyStruct(body interface{}) *Response { b, err := json.Marshal(body) if err != nil { printError(fmt.Sprintf("marshalling body %#v failed with %v", body, err)) } r.BodyBuffer = b return r }
package httpfake import "net/http" // Response stores the settings defined by the request handler // of how it will respond the request back type Response struct { StatusCode int BodyBuffer []byte Header http.Header } // NewResponse creates a new Response func NewResponse() *Response { return &Response{ Header: make(http.Header), } } // Status sets the response status func (r *Response) Status(status int) *Response { r.StatusCode = status return r } // SetHeader sets the a HTTP header to the response func (r *Response) SetHeader(key, value string) *Response { r.Header.Set(key, value) return r } // AddHeader adds a HTTP header into the response func (r *Response) AddHeader(key, value string) *Response { r.Header.Add(key, value) return r } // BodyString sets the response body func (r *Response) BodyString(body string) *Response { r.BodyBuffer = []byte(body) return r }
Improve formatting of schema format exception messages
class SchemaFormatException(Exception): """Exception which encapsulates a problem found during the verification of a a schema.""" def __init__(self, message, path): self._message = message.format('\"{}\"'.format(path)) self._path = path @property def path(self): """The field path at which the format error was found.""" return self._path def __str__(self): return self._message class ValidationException(Exception): """Exception which is thrown in response to the failed validation of a document against it's associated schema.""" def __init__(self, errors): self._errors = errors @property def errors(self): """A dict containing the validation error(s) found at each field path.""" return self._errors def __str__(self): return repr(self._errors)
class SchemaFormatException(Exception): """Exception which encapsulates a problem found during the verification of a a schema.""" def __init__(self, message, path): self._message = message.format(path) self._path = path @property def path(self): """The field path at which the format error was found.""" return self._path def __str__(self): return self._message class ValidationException(Exception): """Exception which is thrown in response to the failed validation of a document against it's associated schema.""" def __init__(self, errors): self._errors = errors @property def errors(self): """A dict containing the validation error(s) found at each field path.""" return self._errors def __str__(self): return repr(self._errors)
Add variables to send to the view
<?php namespace RadDB\Http\Controllers; use Charts; use RadDB\GenData; use RadDB\HVLData; use RadDB\Machine; use RadDB\TestDates; use RadDB\RadSurveyData; use RadDB\RadiationOutput; use Illuminate\Http\Request; class QAController extends Controller { /** * Index page for QA/survey data section * * @return \Illuminate\Http\Response */ public function index() { // Show a table of machines with QA data in the database // Get a list of the survey IDs in the gendata table $surveys = GenData::select('survey_id')->distinct()->get(); $machines = TestDate::whereIn('id', $surveys->toArray())->get(); return view('qa.index', [ 'surveys' => $surveys, 'machines' => $machines, ]); } }
<?php namespace RadDB\Http\Controllers; use Charts; use RadDB\Machine; use RadDB\TestDates; use RadDB\GenData; use RadDB\HVLData; use RadDB\RadSurveyData; use RadDB\RadiationOutput; use Illuminate\Http\Request; class QAController extends Controller { /** * Index page for QA/survey data section * * @return \Illuminate\Http\Response */ public function index() { // Show a table of machines with QA data in the database // Get a list of the survey IDs in the gendata table $surveys = GenData::select('survey_id')->distinct()->get(); $machines = TestDate::whereIn('id', $surveys->toArray())->get(); return view('qa.index', [ ]); } }
Rename "Label" to "TextView" in jquery example Done to reflect eclipsesource/tabris-js@ca0f105e82a2d27067c9674ecf71a93af2c7b7bd Change-Id: I1c267e0130809077c1339ba0395da1a7e1c6b281
// jQuery built with "grunt custom:-ajax/script,-ajax/jsonp,-css,-deprecated,-dimensions,-effects,-event,-event/alias,-offset,-wrap,-ready,-deferred,-exports/amd,-sizzle" // https://github.com/jquery/jquery#how-to-build-your-own-jquery var $ = require("./lib/jquery.min.js"); var MARGIN = 12; var page = tabris.create("Page", { title: "XMLHttpRequest", topLevel: true }); var createTextView = function(text) { tabris.create("TextView", { text: text, markupEnabled: true, layoutData: {left: MARGIN, right: MARGIN, top: [page.children().last() || 0, MARGIN]} }).appendTo(page); }; $.getJSON("http://www.telize.com/geoip", function(json) { createTextView("The IP address is: " + json.ip); createTextView("Latitude: " + json.latitude); createTextView("Longitude: " + json.longitude); }); page.open();
// jQuery built with "grunt custom:-ajax/script,-ajax/jsonp,-css,-deprecated,-dimensions,-effects,-event,-event/alias,-offset,-wrap,-ready,-deferred,-exports/amd,-sizzle" // https://github.com/jquery/jquery#how-to-build-your-own-jquery var $ = require("./lib/jquery.min.js"); var MARGIN = 12; var page = tabris.create("Page", { title: "XMLHttpRequest", topLevel: true }); var createLabel = function(labelText) { tabris.create("Label", { text: labelText, markupEnabled: true, layoutData: {left: MARGIN, right: MARGIN, top: [page.children().last() || 0, MARGIN]} }).appendTo(page); }; $.getJSON("http://www.telize.com/geoip", function(json) { createLabel("The IP address is: " + json.ip); createLabel("Latitude: " + json.latitude); createLabel("Longitude: " + json.longitude); }); page.open();
Reduce bounds on generic: Java lacks most of the stuff to actually use it.
package to.etc.domui.component.ntbl; import to.etc.domui.component.meta.*; import to.etc.domui.component.tbl.*; import to.etc.domui.dom.html.*; /** * Event handler for row-based editors. * * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a> * Created on Dec 21, 2009 */ public interface IRowEditorEvent<T, E extends NodeContainer> { /** * Called after a row has been edited in an editable table component, when editing is (somehow) marked * as complete. When called the editor's contents has been moved to the model by using the bindings. This method * can be used to check the data for validity or to check for duplicates, for instance by using {@link MetaManager#hasDuplicates(java.util.List, Object, String)}. * * @param tablecomponent * @param editor * @param instance * @return false to refuse the change. * @throws Exception */ boolean onRowChanged(TableModelTableBase<T> tablecomponent, E editor, T instance) throws Exception; }
package to.etc.domui.component.ntbl; import to.etc.domui.component.meta.*; import to.etc.domui.component.tbl.*; import to.etc.domui.dom.html.*; /** * Event handler for row-based editors. * * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a> * Created on Dec 21, 2009 */ public interface IRowEditorEvent<T, E extends NodeContainer & IEditor> { /** * Called after a row has been edited in an editable table component, when editing is (somehow) marked * as complete. When called the editor's contents has been moved to the model by using the bindings. This method * can be used to check the data for validity or to check for duplicates, for instance by using {@link MetaManager#hasDuplicates(java.util.List, Object, String)}. * * @param tablecomponent * @param editor * @param instance * @return false to refuse the change. * @throws Exception */ boolean onRowChanged(TableModelTableBase<T> tablecomponent, E editor, T instance) throws Exception; }
Add a useful standard ACE shortcut.
var $ = document.getElementById.bind(document); var exampleTests = require('./example-tests'); var Main = require('../src/main/main-controller'); var providedByAceEditor = function() {/* noop() */}; var isMac = navigator.platform.indexOf('Mac') === 0; var metaKey = isMac ? 'Meta' : 'Control'; var shortcuts = [ [[metaKey, 'S'], executeTestCode, 'Save+Run'], [[metaKey, 'D'], providedByAceEditor(), 'Delete line'], [[metaKey, 'Shift', 'D'], providedByAceEditor(), 'Duplicate line'], [[metaKey, '/'], providedByAceEditor(), 'Comment in/out line'], [['Shift', 'F6'], refactoringRename, 'Rename (refactoring)'] ]; var main = new Main($('tddbin'), { initialContent: exampleTests.simplePassingTestCode, iframeSrcUrl: '../src/test-runner/mocha/spec-runner.html', shortcuts: shortcuts }); function executeTestCode() { main.runEditorContent(); } function refactoringRename() { main.placeCursorsForRenaming(); }
var $ = document.getElementById.bind(document); var exampleTests = require('./example-tests'); var Main = require('../src/main/main-controller'); var providedByAceEditor = function() {/* noop() */}; var isMac = navigator.platform.indexOf('Mac') === 0; var metaKey = isMac ? 'Meta' : 'Control'; var shortcuts = [ [[metaKey, 'S'], executeTestCode, 'Save+Run'], [[metaKey, 'D'], providedByAceEditor(), 'Delete line'], [[metaKey, 'Shift', 'D'], providedByAceEditor(), 'Duplicate line'], [['Shift', 'F6'], refactoringRename, 'Rename (refactoring)'] ]; var main = new Main($('tddbin'), { initialContent: exampleTests.simplePassingTestCode, iframeSrcUrl: '../src/test-runner/mocha/spec-runner.html', shortcuts: shortcuts }); function executeTestCode() { main.runEditorContent(); } function refactoringRename() { main.placeCursorsForRenaming(); }
Tag list now uses the simple table style Signed-off-by: Prashant P Shah <80f978b5ac27fb318171799f0fb6a277863f2bf5@gmail.com>
<?php $tags_q = $this->db->get("tags"); echo "<table border=0 cellpadding=5 class=\"simple-table tag-table\">"; echo "<thead><tr><th>Title</th><th>Color</th><th colspan=5></th></tr></thead>"; echo "<tbody>"; $odd_even = "odd"; foreach ($tags_q->result() as $row) { echo "<tr class=\"tr-" . $odd_even. "\">"; echo "<td>" . $row->title . "</td>"; echo "<td>" . $this->Tag_model->show_voucher_tag($row->id) . "</td>"; echo "<td>" . anchor('tag/edit/' . $row->id , "Edit", array('title' => 'Edit Tag', 'class' => 'red-link')); echo " &nbsp;"; echo anchor('tag/delete/' . $row->id , img(array('src' => asset_url() . "images/icons/delete.png", 'border' => '0', 'alt' => 'Delete Tag', 'class' => "confirmClick", 'title' => "Delete Tag")), array('title' => 'Delete Tag')) . "</td>"; echo "</tr>"; $odd_even = ($odd_even == "odd") ? "even" : "odd"; } echo "</tbody>"; echo "</table>"; echo "<br />"; echo anchor('setting', 'Back', array('title' => 'Back to Settings'));
<?php $tags_q = $this->db->get("tags"); echo "<table border=0 cellpadding=5 class=\"generaltable\">"; echo "<thead><tr><th>Title</th><th>Color</th><th colspan=5>Actions</th></tr></thead>"; echo "<tbody>"; $odd_even = "odd"; foreach ($tags_q->result() as $row) { echo "<tr class=\"tr-" . $odd_even. "\">"; echo "<td>" . $row->title . "</td>"; echo "<td>" . $this->Tag_model->show_voucher_tag($row->id) . "</td>"; echo "<td>" . anchor('tag/edit/' . $row->id , img(array('src' => asset_url() . "images/icons/edit.png", 'border' => '0', 'alt' => 'Edit Tag')), array('title' => 'Edit Tag')) . "</td>"; echo "<td>" . anchor('tag/delete/' . $row->id , img(array('src' => asset_url() . "images/icons/delete.png", 'border' => '0', 'alt' => 'Delete Tag', 'class' => "confirmClick", 'title' => "Delete Tag")), array('title' => 'Delete Tag')) . "</td>"; echo "</tr>"; $odd_even = ($odd_even == "odd") ? "even" : "odd"; } echo "</tbody>"; echo "</table>"; echo "<br />"; echo anchor('setting', 'Back', array('title' => 'Back to Settings'));
Correct class name of arduino nano
BOARDS = { 'arduino': { 'digital': tuple(x for x in range(14)), 'analog': tuple(x for x in range(6)), 'pwm': (3, 5, 6, 9, 10, 11), 'use_ports': True, 'disabled': (0, 1) # Rx, Tx, Crystal }, 'arduino_mega': { 'digital': tuple(x for x in range(54)), 'analog': tuple(x for x in range(16)), 'pwm': tuple(x for x in range(2, 14)), 'use_ports': True, 'disabled': (0, 1) # Rx, Tx, Crystal }, 'arduino_due': { 'digital': tuple(x for x in range(54)), 'analog': tuple(x for x in range(12)), 'pwm': tuple(x for x in range(2, 14)), 'use_ports': True, 'disabled': (0, 1) # Rx, Tx, Crystal }, 'arduino_nano': { 'digital': tuple(x for x in range(14)), 'analog': tuple(x for x in range(8)), 'pwm': (3, 5, 6, 9, 10, 11), 'use_ports': True, 'disabled': (0, 1) # Rx, Tx, Crystal } }
BOARDS = { 'arduino': { 'digital': tuple(x for x in range(14)), 'analog': tuple(x for x in range(6)), 'pwm': (3, 5, 6, 9, 10, 11), 'use_ports': True, 'disabled': (0, 1) # Rx, Tx, Crystal }, 'arduino_mega': { 'digital': tuple(x for x in range(54)), 'analog': tuple(x for x in range(16)), 'pwm': tuple(x for x in range(2, 14)), 'use_ports': True, 'disabled': (0, 1) # Rx, Tx, Crystal }, 'arduino_due': { 'digital': tuple(x for x in range(54)), 'analog': tuple(x for x in range(12)), 'pwm': tuple(x for x in range(2, 14)), 'use_ports': True, 'disabled': (0, 1) # Rx, Tx, Crystal }, 'nano': { 'digital': tuple(x for x in range(14)), 'analog': tuple(x for x in range(8)), 'pwm': (3, 5, 6, 9, 10, 11), 'use_ports': True, 'disabled': (0, 1) # Rx, Tx, Crystal } }
Add distutils for legacy pypi
#!/usr/bin/env python import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup __author__ = 'Mike Helmick <me@michaelhelmick.com>' __version__ = '1.1.1' if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() setup( name='python-tumblpy', version=__version__, install_requires=['requests>=1.2.2', 'requests_oauthlib>=0.3.2'], author='Mike Helmick', author_email='me@michaelhelmick.com', license=open('LICENSE').read(), url='https://github.com/michaelhelmick/python-tumblpy/', keywords='python tumblpy tumblr oauth api', description='A Python Library to interface with Tumblr v2 REST API & OAuth', long_description=open('README.rst').read() + '\n\n' + open('HISTORY.rst').read(), download_url='https://github.com/michaelhelmick/python-tumblpy/zipball/master', include_package_data=True, packages=['tumblpy'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Communications :: Chat', 'Topic :: Internet' ], )
#!/usr/bin/env python import os import sys from setuptools import setup __author__ = 'Mike Helmick <me@michaelhelmick.com>' __version__ = '1.1.1' if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() setup( name='python-tumblpy', version=__version__, install_requires=['requests>=1.2.2', 'requests_oauthlib>=0.3.2'], author='Mike Helmick', author_email='me@michaelhelmick.com', license=open('LICENSE').read(), url='https://github.com/michaelhelmick/python-tumblpy/', keywords='python tumblpy tumblr oauth api', description='A Python Library to interface with Tumblr v2 REST API & OAuth', long_description=open('README.rst').read() + '\n\n' + open('HISTORY.rst').read(), download_url='https://github.com/michaelhelmick/python-tumblpy/zipball/master', include_package_data=True, packages=['tumblpy'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Communications :: Chat', 'Topic :: Internet' ], )
Add redirect from / to /polls
"""vote URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from django.http.response import HttpResponseRedirect urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), url(r'^$', lambda r: HttpResponseRedirect('polls/')), ]
"""vote URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ]
Allow slashes and backslashes in the code's content.
<?php /* * (c) Jeroen van den Enden <info@endroid.nl> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Endroid\Bundle\QrCodeBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Endroid\QrCode\QrCode; /** * QR code controller. */ class QrCodeController extends Controller { /** * * @Route("/{text}.{extension}", name="endroid_qrcode", requirements={"text"="[\w\W]+", "extension"="jpg|png|gif"}) * */ public function generateAction($text, $extension) { $qrCode = new QrCode(); $qrCode->setText($text); $qrCode = $qrCode->get($extension); $mime_type = 'image/'.$extension; if ($extension == 'jpg') { $mime_type = 'image/jpeg'; } return new Response($qrCode, 200, array('Content-Type' => $mime_type)); } }
<?php /* * (c) Jeroen van den Enden <info@endroid.nl> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Endroid\Bundle\QrCodeBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Endroid\QrCode\QrCode; /** * QR code controller. */ class QrCodeController extends Controller { /** * * @Route("/{text}.{extension}", name="endroid_qrcode", requirements={"text"="[^/\\]+", "extension"="jpg|png|gif"}) * */ public function generateAction($text, $extension) { $qrCode = new QrCode(); $qrCode->setText($text); $qrCode = $qrCode->get($extension); $mime_type = 'image/'.$extension; if ($extension == 'jpg') { $mime_type = 'image/jpeg'; } return new Response($qrCode, 200, array('Content-Type' => $mime_type)); } }
Exclude counter from chart form
from collections import defaultdict from django.http import QueryDict from google.appengine.ext import db from google.appengine.ext.db import djangoforms from charter.models import Chart, ChartDataSet, DataRow from charter.form_utils import BaseFormSet class ChartForm(djangoforms.ModelForm): class Meta: model = Chart exclude = ('data', 'user', 'hash','counter',) class DataSetForm(djangoforms.ModelForm): class Meta: model = ChartDataSet exclude = ('previous_version',) def __init__(self, *args, **kwargs): foo = kwargs['instance'].data_rows super(DataSetForm, self).__init__(*args, **kwargs) class DataRowForm(djangoforms.ModelForm): class Meta: model = DataRow class DataRowFormSet(BaseFormSet): base_form = DataRowForm
from collections import defaultdict from django.http import QueryDict from google.appengine.ext import db from google.appengine.ext.db import djangoforms from charter.models import Chart, ChartDataSet, DataRow from charter.form_utils import BaseFormSet class ChartForm(djangoforms.ModelForm): class Meta: model = Chart exclude = ('data', 'user', 'hash',) class DataSetForm(djangoforms.ModelForm): class Meta: model = ChartDataSet exclude = ('previous_version',) def __init__(self, *args, **kwargs): foo = kwargs['instance'].data_rows super(DataSetForm, self).__init__(*args, **kwargs) class DataRowForm(djangoforms.ModelForm): class Meta: model = DataRow class DataRowFormSet(BaseFormSet): base_form = DataRowForm
Make migration rerunable (just for simplicity's sake)
<?php // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); /** * Migration script for adding mail preference option to incremental registration **/ class Migration20130715111246ModIncrementalRegistration extends Hubzero_Migration { /** * Up **/ protected static function up($db) { if (!$db->tableHasField('#__profile_completion_awards', 'mailpreferenceoption')) { $query = "ALTER TABLE `#__profile_completion_awards` ADD COLUMN mailpreferenceoption int not null default 0;"; $db->setQuery($query); $db->query(); } $query = "SELECT * FROM `#__incremental_registration_labels` WHERE `field` = 'mailPreferenceOption';"; $db->setQuery($query); if (!$db->loadResult()) { $query = "INSERT INTO `#__incremental_registration_labels` (field, label) VALUES ('mailPreferenceOption', 'E-Mail Updates');"; $db->setQuery($query); $db->query(); } } /** * Down **/ protected static function down($db) { if ($db->tableHasField('#__profile_completion_awards', 'mailpreferenceoption')) { $query = "ALTER TABLE `#__profile_completion_awards` DROP COLUMN mailpreferenceoption;"; $db->setQuery($query); $db->query(); } $query = "DELETE FROM `#__incremental_registration_labels` WHERE `field` = 'mailPreferenceOption';"; $db->setQuery($query); $db->query(); } }
<?php // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); /** * Migration script for ... **/ class Migration20130715111246ModIncrementalRegistration extends Hubzero_Migration { /** * Up **/ protected static function up($db) { $queries = array( 'alter table #__profile_completion_awards add column mailpreferenceoption int not null default 0', 'insert into #__incremental_registration_labels(field, label) values (\'mailPreferenceOption\', \'E-Mail Updates\')' ); foreach ($queries as $query) { $db->setQuery($query); $db->query(); } } /** * Down **/ protected static function down($db) { $queries = array( 'alter table #__profile_completion_awards drop column mailpreferenceoption', 'delete from #__incremental_registration_labels where field = \'mailPreferenceOption\'' ); foreach ($queries as $query) { $db->setQuery($query); $db->query(); } } }
Remove auto generated code by Intellj
package com.sailthru.client; import com.google.gson.JsonSerializer; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonPrimitive; import com.google.gson.JsonNull; import java.lang.reflect.Type; import java.util.Map; public class NullSerializingMapSerializer implements JsonSerializer<Map> { private static final Gson gson = (new GsonBuilder()).serializeNulls().create(); public JsonElement serialize(Map map, Type typeOfSrc, JsonSerializationContext context) { if(map == null) { return new JsonNull(); } return new JsonPrimitive(gson.toJson(map)); } }
package com.sailthru.client; import com.google.gson.JsonSerializer; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonPrimitive; import com.google.gson.JsonNull; import java.lang.reflect.Type; import java.util.Map; /** * Created with IntelliJ IDEA. * User: dennisyu * Date: 8/5/13 * Time: 4:41 PM * To change this template use File | Settings | File Templates. */ public class NullSerializingMapSerializer implements JsonSerializer<Map> { private static final Gson gson = (new GsonBuilder()).serializeNulls().create(); public JsonElement serialize(Map map, Type typeOfSrc, JsonSerializationContext context) { if(map == null) { return new JsonNull(); } return new JsonPrimitive(gson.toJson(map)); } }
Add support for per Argument help data
class Argument(object): def __init__(self, name=None, names=(), kind=str, default=None, help=None): if name and names: msg = "Cannot give both 'name' and 'names' arguments! Pick one." raise TypeError(msg) if not (name or names): raise TypeError("An Argument must have at least one name.") self.names = names if names else (name,) self.kind = kind self.raw_value = self._value = None self.default = default self.help = help def __str__(self): return "Arg: %r (%s)" % (self.names, self.kind) @property def takes_value(self): return self.kind is not bool @property def value(self): return self._value if self._value is not None else self.default @value.setter def value(self, arg): self.raw_value = arg self._value = self.kind(arg)
class Argument(object): def __init__(self, name=None, names=(), kind=str, default=None): if name and names: msg = "Cannot give both 'name' and 'names' arguments! Pick one." raise TypeError(msg) if not (name or names): raise TypeError("An Argument must have at least one name.") self.names = names if names else (name,) self.kind = kind self.raw_value = self._value = None self.default = default def __str__(self): return "Arg: %r (%s)" % (self.names, self.kind) @property def takes_value(self): return self.kind is not bool @property def value(self): return self._value if self._value is not None else self.default @value.setter def value(self, arg): self.raw_value = arg self._value = self.kind(arg)
Change time frequency to publish message
'use strict' const express = require('express') const bodyParser = require('body-parser') const config = require('./config') const app = express() const publisher = require('./publisher') var cronJob = require('cron').CronJob app.set('port', (process.env.PORT || config.PORT)) app.use(bodyParser.urlencoded({extended: false})) app.use(bodyParser.json()) app.get('/', function (req, res) { res.send('Meeaaww') }) app.get('/meaw', function (req, res) { res.status(200).send('Meaaawww 200') }) app.listen(app.get('port'), () => { console.log(`Running Crypty on port : ${app.get('port')}`) var cryptoJob = new cronJob({ cronTime: '0 */60 * * * *', onTick: function () { // Publish every 60 min publisher.publish() }, start: false, timeZone: 'Asia/Bangkok' }) cryptoJob.start() })
'use strict' const express = require('express') const bodyParser = require('body-parser') const config = require('./config') const app = express() const publisher = require('./publisher') var cronJob = require('cron').CronJob app.set('port', (process.env.PORT || config.PORT)) app.use(bodyParser.urlencoded({extended: false})) app.use(bodyParser.json()) app.get('/', function (req, res) { res.send('Meeaaww') }) app.get('/meaw', function (req, res) { res.status(200).send('Meaaawww 200') }) app.listen(app.get('port'), () => { console.log(`Running Crypty on port : ${app.get('port')}`) var cryptoJob = new cronJob({ cronTime: '0 */20 * * * *', onTick: function () { // Publish every 20 min publisher.publish() }, start: false, timeZone: 'Asia/Bangkok' }) cryptoJob.start() })
proxy: Reduce SO_LINGER timeout to 10 seconds The existing value of 1 minute can put a lot of stress on the proxymap table in an environment with many concurrent, short lived connections. Signed-off-by: Thomas Graf <5f50a84c1fa3bcff146405017f36aec1a10a9e38@cilium.io>
// Copyright 2017 Authors of Cilium // // 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 proxy import ( "time" ) const ( // Size of channel (number of requests/messages) which buffers messages // enqueued onto proxy sockets socketQueueSize = 100 // proxyConnectionCloseTimeout is the time to wait before closing both // connections of a proxied connection after one side has initiated the // closing and the other side is not being closed. proxyConnectionCloseTimeout = 10 * time.Second )
// Copyright 2017 Authors of Cilium // // 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 proxy import ( "time" ) const ( // Size of channel (number of requests/messages) which buffers messages // enqueued onto proxy sockets socketQueueSize = 100 // proxyConnectionCloseTimeout is the time to wait before closing both // connections of a proxied connection after one side has initiated the // closing and the other side is not being closed. proxyConnectionCloseTimeout = 1 * time.Minute )
Include correct Paweł's email :camel:
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Shipping\Model; use Doctrine\Common\Collections\Collection; /** * @author Paweł Jędrzejewski <pawel@sylius.org> */ interface ShippingMethodsAwareInterface { /** * @return Collection|ShippingMethodInterface[] */ public function getShippingMethods(); /** * @param ShippingMethodInterface $shippingMethod * * @return bool */ public function hasShippingMethod(ShippingMethodInterface $shippingMethod); /** * @param ShippingMethodInterface $shippingMethod */ public function addShippingMethod(ShippingMethodInterface $shippingMethod); /** * @param ShippingMethodInterface $shippingMethod */ public function removeShippingMethod(ShippingMethodInterface $shippingMethod); }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Shipping\Model; use Doctrine\Common\Collections\Collection; /** * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl> */ interface ShippingMethodsAwareInterface { /** * @return Collection|ShippingMethodInterface[] */ public function getShippingMethods(); /** * @param ShippingMethodInterface $shippingMethod * * @return bool */ public function hasShippingMethod(ShippingMethodInterface $shippingMethod); /** * @param ShippingMethodInterface $shippingMethod */ public function addShippingMethod(ShippingMethodInterface $shippingMethod); /** * @param ShippingMethodInterface $shippingMethod */ public function removeShippingMethod(ShippingMethodInterface $shippingMethod); }
Correct typo in documentation of crop_corners
import logging logger = logging.getLogger(__name__) def crop_corners(image, box=None, **kwargs): """ Crop corners to the selection defined by image_cropping `box` is a string of the format 'x1,y1,x2,y2' or a four-tuple of integers. """ if not box: return image if not isinstance(box, (list, tuple)): # convert cropping string to a list of integers if necessary try: box = map(int, box.split(',')) except ValueError: # there's garbage in the cropping field, ignore logger.warning( 'Unable to parse "box" parameter "%s". Ignoring.' % box) except AttributeError: pass if len(box) == 4: if box[0] < 0: # a negative first box value indicates that cropping is disabled return image width = abs(box[2] - box[0]) height = abs(box[3] - box[1]) if width and height and (width, height) != image.size: image = image.crop(box) else: logger.warning( '"box" parameter requires four values. Ignoring "%r".' % box) return image
import logging logger = logging.getLogger(__name__) def crop_corners(image, box=None, **kwargs): """ Crop corners to the selection defined by image_cropping `box` is a string of the format 'x1,y1,x2,y1' or a four-tuple of integers. """ if not box: return image if not isinstance(box, (list, tuple)): # convert cropping string to a list of integers if necessary try: box = map(int, box.split(',')) except ValueError: # there's garbage in the cropping field, ignore logger.warning( 'Unable to parse "box" parameter "%s". Ignoring.' % box) except AttributeError: pass if len(box) == 4: if box[0] < 0: # a negative first box value indicates that cropping is disabled return image width = abs(box[2] - box[0]) height = abs(box[3] - box[1]) if width and height and (width, height) != image.size: image = image.crop(box) else: logger.warning( '"box" parameter requires four values. Ignoring "%r".' % box) return image
Add real author to author key too.
# -*- coding: utf-8 -*- # © <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Module name", "summary": "Module summary", "version": "8.0.1.0.0", "category": "Uncategorized", "license": "AGPL-3", "website": "https://odoo-community.org/", "author": "<AUTHOR(S)>, Odoo Community Association (OCA)", "application": False, "installable": True, "external_dependencies": { "python": [], "bin": [], }, "depends": [ ], "data": [ ], "demo": [ ], }
# -*- coding: utf-8 -*- # © <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Module name", "summary": "Module summary", "version": "8.0.1.0.0", "category": "Uncategorized", "license": "AGPL-3", "website": "https://odoo-community.org/", "author": "Odoo Community Association (OCA)", "application": False, "installable": True, "external_dependencies": { "python": [], "bin": [], }, "depends": [ ], "data": [ ], "demo": [ ], }
Implement method to search group for clients
/** * 24.05.2017 * TCP Chat using NodeJS * https://github.com/PatrikValkovic/TCPChat * Created by patri */ 'use strict' let counter = 0 /** * Represent connected client * @type {Client} */ module.exports = class Client { constructor(socket) { this.socket = socket this.name = 'anonymous' this.id = counter++ this.groups = {} } /** * Disconnect client from server */ disconnect() { this.socket.destroy() } /** * Check, if is user in specific group * @param {string} name Name of group to check * @returns {boolean} True if is user in group, false otherwise */ isInGroup(name) { return this.groupByName(name) !== null } joinedGroups(){ return Object.assign({},this.groups) } groupByName(name){ for(const i of this.groups) if(this.groups[i].name === name) return this.groups[i] return null } groupById(id){ return this.groups[id.toString()] || null } }
/** * 24.05.2017 * TCP Chat using NodeJS * https://github.com/PatrikValkovic/TCPChat * Created by patri */ 'use strict' let counter = 0 /** * Represent connected client * @type {Client} */ module.exports = class Client { constructor(socket) { this.socket = socket this.name = 'anonymous' this.id = counter++ this.groups = {} } /** * Disconnect client from server */ disconnect() { this.socket.destroy() } /** * Check, if is user in specific group * @param {string} name Name of group to check * @returns {boolean} True if is user in group, false otherwise */ isInGroup(name) { for(const i of this.groups) if(this.groups[i].name === name) return true return false } joinedGroups(){ return Object.assign({},this.groups) } }
Fix caching time dependant MNT provider query (api)
const db = require('../db.js'); async function getTrips(id, coachOnly) { return (await db.query(` SELECT TIME_TO_SEC(time) AS time, TIME_TO_SEC(time) - TIME_TO_SEC(NOW()) as countdown, route.name, trip.destination, route.type, 'mnt' AS provider FROM stops AS stop JOIN stop_times ON stop_id = id JOIN trips AS trip ON trip.id = trip_id JOIN routes AS route ON route.id = route_id JOIN services AS service ON service.id = trip.service_id WHERE stop.id = ? AND route.type IS NOT NULL AND time > CURTIME() AND ( ( CURDATE() BETWEEN start AND end AND SUBSTR(days, WEEKDAY(CURDATE()) + 1, 1) = 1 AND service_id NOT IN ( SELECT service_id FROM service_exceptions WHERE type = 0 AND date = CURDATE() ) ) OR service_id IN ( SELECT service_id FROM service_exceptions WHERE type = 1 AND date = CURDATE() ) ) ${coachOnly ? "AND route.type LIKE 'coach%'" : ''} ORDER BY time LIMIT ${coachOnly ? '5' : '15'} `, [ id ])).map((trip) => ({ ...trip, live: false })); } module.exports = { getTrips };
const db = require('../db.js'); const cache = require('../utils/cache.js'); async function getTrips(id, coachOnly) { return await cache.use('mnt-trips', id, async () => (await db.query(` SELECT TIME_TO_SEC(time) AS time, TIME_TO_SEC(time) - TIME_TO_SEC(NOW()) as countdown, route.name, trip.destination, route.type, 'mnt' AS provider FROM stops AS stop JOIN stop_times ON stop_id = id JOIN trips AS trip ON trip.id = trip_id JOIN routes AS route ON route.id = route_id JOIN services AS service ON service.id = trip.service_id WHERE stop.id = ? AND route.type IS NOT NULL AND time > CURTIME() AND ( ( CURDATE() BETWEEN start AND end AND SUBSTR(days, WEEKDAY(CURDATE()) + 1, 1) = 1 AND service_id NOT IN ( SELECT service_id FROM service_exceptions WHERE type = 0 AND date = CURDATE() ) ) OR service_id IN ( SELECT service_id FROM service_exceptions WHERE type = 1 AND date = CURDATE() ) ) ${coachOnly ? "AND route.type LIKE 'coach%'" : ''} ORDER BY time LIMIT ${coachOnly ? '5' : '15'} `, [ id ])).map((trip) => ({ ...trip, live: false }))); } module.exports = { getTrips };
Fix webpack context path on windows
/* global __dirname */ 'use strict'; var webpack = require('webpack'); var path = require('path'); var commonsPlugin = new webpack.optimize.CommonsChunkPlugin('common.js'); module.exports = { context: path.resolve(__dirname, 'client'), entry: { index: './js/index', embed: './js/embed' }, output: { filename: '[name].bundle.js', chunkFilename: '[id].bundle.js', path: __dirname + '/public/js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['es2015'] } }, { test: /\.sass$/, loaders: ['style', 'css', 'sass'] }, { test: /\.jade$/, loaders: ['jade'] } ] }, sassLoader: { indentedSyntax: true }, plugins: [commonsPlugin], node: { fs: 'empty' // needed for term.js } };
/* global __dirname */ 'use strict'; var webpack = require('webpack'); var commonsPlugin = new webpack.optimize.CommonsChunkPlugin('common.js'); module.exports = { context: __dirname + '/client', entry: { index: './js/index', embed: './js/embed' }, output: { filename: '[name].bundle.js', chunkFilename: '[id].bundle.js', path: __dirname + '/public/js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['es2015'] } }, { test: /\.sass$/, loaders: ['style', 'css', 'sass'] }, { test: /\.jade$/, loaders: ['jade'] } ] }, sassLoader: { indentedSyntax: true }, plugins: [commonsPlugin], node: { fs: 'empty' // needed for term.js } };
Mark all of these tests too.
import pytest from components.people.models import Group, Idol, Membership, Staff from components.people.factories import (GroupFactory, IdolFactory, MembershipFactory, StaffFactory) pytestmark = pytest.mark.django_db def test_group_factory(): factory = GroupFactory() assert isinstance(factory, Group) assert 'group' in factory.romanized_name def test_group_get_absolute_url(client): factory = GroupFactory() response = client.get(factory.get_absolute_url()) assert response.status_code == 200 def test_idol_factory(): factory = IdolFactory() assert isinstance(factory, Idol) assert 'family' in factory.romanized_family_name assert 'given' in factory.romanized_given_name def test_idol_get_absolute_url(client): factory = IdolFactory() response = client.get(factory.get_absolute_url()) assert response.status_code == 200 def test_staff_factory(): factory = StaffFactory() assert isinstance(factory, Staff) assert 'family' in factory.romanized_family_name assert 'given' in factory.romanized_given_name def test_membership_factory(): factory = MembershipFactory() assert isinstance(factory, Membership) assert isinstance(factory.group, Group) assert isinstance(factory.idol, Idol)
import pytest from components.people.models import Group, Idol, Membership, Staff from components.people.factories import (GroupFactory, IdolFactory, MembershipFactory, StaffFactory) @pytest.mark.django_db def test_group_factory(): factory = GroupFactory() assert isinstance(factory, Group) assert 'group' in factory.romanized_name @pytest.mark.django_db def test_group_get_absolute_url(client): factory = GroupFactory() response = client.get(factory.get_absolute_url()) assert response.status_code == 200 @pytest.mark.django_db def test_idol_factory(): factory = IdolFactory() assert isinstance(factory, Idol) assert 'family' in factory.romanized_family_name assert 'given' in factory.romanized_given_name @pytest.mark.django_db def test_idol_get_absolute_url(client): factory = IdolFactory() response = client.get(factory.get_absolute_url()) assert response.status_code == 200 @pytest.mark.django_db def test_staff_factory(): factory = StaffFactory() assert isinstance(factory, Staff) assert 'family' in factory.romanized_family_name assert 'given' in factory.romanized_given_name @pytest.mark.django_db def test_membership_factory(): factory = MembershipFactory() assert isinstance(factory, Membership) assert isinstance(factory.group, Group) assert isinstance(factory.idol, Idol)
Test validator can now be used as a module
#! /usr/bin/python import jsonschema import json import sys import os import glob vm_schema = None jsons = [] valid_vms = [] def load_schema(filename): global vm_schema vm_schema = json.loads(open(filename).read()); def validate_vm_spec(filename): global valid_vms vm_spec = None # Load and parse as JSON try: vm_spec = json.loads(open(filename).read()) except: raise Exception("JSON load / parse Error for " + filename) # Validate JSON according to schema try: jsonschema.validate(vm_spec, vm_schema) except Exception as err: raise Exception("JSON schema validation failed: " + err.message) valid_vms.append(vm_spec) def has_required_stuff(path): global jsons # Certain files are mandatory required_files = [ "Makefile", "test.py", "README.md", "*.cpp" ] for file in required_files: if not glob.glob(file): raise Exception("missing " + file) # JSON-files must conform to VM-schema jsons = glob.glob("*.json") for json in jsons: validate_vm_spec(json) if __name__ == "__main__": path = sys.argv[1] if len(sys.argv) > 1 else "." load_schema("vm.schema.json") os.chdir(path) try: has_required_stuff(path) print "<validate_test> \tPASS: ",os.getcwd() except Exception as err: print "<validate_test> \tFAIL: unmet requirements in " + path, ": " , err.message
#! /usr/bin/python import jsonschema import json import sys import os import glob vm_schema = json.loads(open("vm.schema.json").read()); def validate_vm_spec(filename): # Load and parse as JSON try: vm_spec = json.loads(open(filename).read()) except: raise Exception("JSON load / parse Error for " + filename) # Validate JSON according to schema try: jsonschema.validate(vm_spec, vm_schema) except Exception as err: raise Exception("JSON schema validation failed: " + err.message) def has_required_stuff(path): # Certain files are mandatory required_files = [ "Makefile", "test.py", "README.md", "*.cpp" ] for file in required_files: if not glob.glob(file): raise Exception("missing " + file) # JSON-files must conform to VM-schema for json in glob.glob("*.json"): validate_vm_spec(json) path = sys.argv[1] if len(sys.argv) > 1 else "." os.chdir(path) try: has_required_stuff(path) print "\tPASS: ",os.getcwd() except Exception as err: print "\tFAIL: unmet requirements in " + path, ": " , err.message
Remove another reference to DeferredResult.
#!/usr/bin/python """ A flask web application that downloads a page in the background. """ import logging from flask import Flask, session, escape from crochet import setup, run_in_reactor, retrieve_result, TimeoutError # Can be called multiple times with no ill-effect: setup() app = Flask(__name__) @run_in_reactor def download_page(url): """ Download a page. """ from twisted.web.client import getPage return getPage(url) @app.route('/') def index(): if 'download' not in session: # Calling an @run_in_reactor function returns an EventualResult: result = download_page('http://www.google.com') session['download'] = result.stash() return "Starting download, refresh to track progress." # retrieval is a one-time operation, so session value cannot be reused: result = retrieve_result(session.pop('download')) try: download = result.wait(timeout=0.1) return "Downloaded: " + escape(download) except TimeoutError: session['download'] = result.stash() return "Download in progress..." if __name__ == '__main__': import os, sys logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) app.secret_key = os.urandom(24) app.run()
#!/usr/bin/python """ A flask web application that downloads a page in the background. """ import logging from flask import Flask, session, escape from crochet import setup, run_in_reactor, retrieve_result, TimeoutError # Can be called multiple times with no ill-effect: setup() app = Flask(__name__) @run_in_reactor def download_page(url): """ Download a page. """ from twisted.web.client import getPage return getPage(url) @app.route('/') def index(): if 'download' not in session: # Calling an @run_in_reactor function returns a DefererdResult: result = download_page('http://www.google.com') session['download'] = result.stash() return "Starting download, refresh to track progress." # retrieval is a one-time operation, so session value cannot be reused: result = retrieve_result(session.pop('download')) try: download = result.wait(timeout=0.1) return "Downloaded: " + escape(download) except TimeoutError: session['download'] = result.stash() return "Download in progress..." if __name__ == '__main__': import os, sys logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) app.secret_key = os.urandom(24) app.run()
Fix purchase confirmation decimal points
import React, { PropTypes } from 'react'; import { FormattedTime } from 'react-intl'; import { epochToDate } from '../_utils/DateUtils'; import { M, NumberPlain } from '../_common'; const PurchaseConfirmation = ({ receipt }) => ( <div> <table> <thead> <th colSpan="2">{`Contract Ref. ${receipt.contract_id}`}</th> </thead> <tbody> <tr> <td colSpan="2"> {receipt.longcode} </td> </tr> <tr> <td><M m="Purchase Price" /></td> <td>{receipt.buy_price}</td> </tr> <tr> <td><M m="Purchase Time" /></td> <td> <FormattedTime value={epochToDate(receipt.purchase_time)} format="full" /> </td> </tr> <tr> <td><M m="Balance" /></td> <td> <NumberPlain value={receipt.balance_after} /> </td> </tr> </tbody> </table> <br/> <button><M m="Back" /></button> </div> ); PurchaseConfirmation.propTypes = { proposal: PropTypes.object, }; export default PurchaseConfirmation;
import React, { PropTypes } from 'react'; import { FormattedTime } from 'react-intl'; import { epochToDate } from '../_utils/DateUtils'; import { M } from '../_common'; const PurchaseConfirmation = ({ receipt }) => ( <div> <table> <tbody> <tr> <td colSpan="2"> {receipt.longcode} </td> </tr> <tr> <td><M m="Purchase Price" /></td> <td>{receipt.buy_price}</td> </tr> <tr> <td><M m="Purchase Time" /></td> <td> <FormattedTime value={epochToDate(receipt.purchase_time)} format="full" /> </td> </tr> <tr> <td><M m="Balance" /></td> <td>{receipt.balance_after}</td> </tr> </tbody> </table> <br/> <button><M m="Back" /></button> </div> ); PurchaseConfirmation.propTypes = { proposal: PropTypes.object, }; export default PurchaseConfirmation;
Add missing properties to SNS::Subscription
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty try: from awacs.aws import Policy policytypes = (dict, Policy) except ImportError: policytypes = dict, class Subscription(AWSProperty): props = { 'Endpoint': (basestring, True), 'Protocol': (basestring, True), } class SubscriptionResource(AWSObject): resource_type = "AWS::SNS::Subscription" props = { 'DeliveryPolicy': (dict, False), 'Endpoint': (basestring, False), 'FilterPolicy': (dict, False), 'Protocol': (basestring, True), 'RawMessageDelivery': (boolean, False), 'Region': (basestring, False), 'TopicArn': (basestring, True), } class TopicPolicy(AWSObject): resource_type = "AWS::SNS::TopicPolicy" props = { 'PolicyDocument': (policytypes, True), 'Topics': (list, True), } class Topic(AWSObject): resource_type = "AWS::SNS::Topic" props = { 'DisplayName': (basestring, False), 'Subscription': ([Subscription], False), 'TopicName': (basestring, False), }
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty try: from awacs.aws import Policy policytypes = (dict, Policy) except ImportError: policytypes = dict, class Subscription(AWSProperty): props = { 'Endpoint': (basestring, True), 'Protocol': (basestring, True), } class SubscriptionResource(AWSObject): resource_type = "AWS::SNS::Subscription" props = { 'Endpoint': (basestring, True), 'Protocol': (basestring, True), 'TopicArn': (basestring, True), 'FilterPolicy': (dict, False), } class TopicPolicy(AWSObject): resource_type = "AWS::SNS::TopicPolicy" props = { 'PolicyDocument': (policytypes, True), 'Topics': (list, True), } class Topic(AWSObject): resource_type = "AWS::SNS::Topic" props = { 'DisplayName': (basestring, False), 'Subscription': ([Subscription], False), 'TopicName': (basestring, False), }
Add minimal compatibility with changes in DBAL 2.11 RunSqlCommand Proper fix would be more involved, relying on interfaces in DBAL to not change, which we cannot assume won't happen at this point. Full, proper fix needs to be done once DBAL 2.11 API is stable. Such fix will probably involve deprecating our current command class as well, since DBAL one has everything our command added on top in past.
<?php namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Doctrine\DBAL\Tools\Console\Command\RunSqlCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * Execute a SQL query and output the results. */ class RunSqlDoctrineCommand extends RunSqlCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this ->setName('doctrine:query:sql') ->setHelp(<<<EOT The <info>%command.name%</info> command executes the given SQL query and outputs the results: <info>php %command.full_name% "SELECT * FROM users"</info> EOT ); if ($this->getDefinition()->hasOption('connection')) { return; } $this->addOption('connection', null, InputOption::VALUE_OPTIONAL, 'The connection to use for this command'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationConnection($this->getApplication(), $input->getOption('connection')); return parent::execute($input, $output); } }
<?php namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Doctrine\DBAL\Tools\Console\Command\RunSqlCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * Execute a SQL query and output the results. */ class RunSqlDoctrineCommand extends RunSqlCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this ->setName('doctrine:query:sql') ->addOption('connection', null, InputOption::VALUE_OPTIONAL, 'The connection to use for this command') ->setHelp(<<<EOT The <info>%command.name%</info> command executes the given SQL query and outputs the results: <info>php %command.full_name% "SELECT * FROM users"</info> EOT ); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationConnection($this->getApplication(), $input->getOption('connection')); return parent::execute($input, $output); } }
Use System.import instead of require
import React from 'react'; import {render} from 'react-dom'; import {AppContainer} from 'react-hot-loader'; import store from './store'; import Root from './Root'; render( <AppContainer> <Root store={store} /> </AppContainer>, document.getElementById('content') ); if (module.hot) { module.hot.accept('./Root', () => { System.import('./Root').then((root) => { render( <AppContainer> <root.default store={store} /> </AppContainer>, document.getElementById('content') ); }); }); }
import React from 'react'; import {render} from 'react-dom'; import {AppContainer} from 'react-hot-loader'; import store from './store'; import Root from './Root'; render( <AppContainer> <Root store={store} /> </AppContainer>, document.getElementById('content') ); if (module.hot) { module.hot.accept('./Root', () => { const ReloadedRoot = require('./Root').default; // eslint-disable-line global-require, #scaffolding render( <AppContainer> <ReloadedRoot store={store} /> </AppContainer>, document.getElementById('content') ); }); }
Set small modal for catch all
import React from 'react'; import PropTypes from 'prop-types'; import { c } from 'ttag'; import { Modal, ContentModal, FooterModal, ResetButton } from 'react-components'; import AddressesTable from './AddressesTable'; const CatchAllModal = ({ domain, show, onClose }) => { return ( <Modal modalClassName="pm-modal--smaller" show={show} onClose={onClose} title={c('Title').t`Catch all address`}> <ContentModal onReset={onClose}> <AddressesTable domain={domain} /> <FooterModal> <ResetButton>{c('Action').t`Close`}</ResetButton> </FooterModal> </ContentModal> </Modal> ); }; CatchAllModal.propTypes = { show: PropTypes.bool.isRequired, onClose: PropTypes.func.isRequired, domain: PropTypes.object.isRequired }; export default CatchAllModal;
import React from 'react'; import PropTypes from 'prop-types'; import { c } from 'ttag'; import { Modal, ContentModal, FooterModal, ResetButton } from 'react-components'; import AddressesTable from './AddressesTable'; const CatchAllModal = ({ domain, show, onClose }) => { return ( <Modal modalClassName="pm-modal--small" show={show} onClose={onClose} title={c('Title').t`Catch all address`}> <ContentModal onReset={onClose}> <AddressesTable domain={domain} /> <FooterModal> <ResetButton>{c('Action').t`Close`}</ResetButton> </FooterModal> </ContentModal> </Modal> ); }; CatchAllModal.propTypes = { show: PropTypes.bool.isRequired, onClose: PropTypes.func.isRequired, domain: PropTypes.object.isRequired }; export default CatchAllModal;
Bump version numbers of ppp_datamodel and ppp_core.
#!/usr/bin/env python3 from setuptools import setup, find_packages setup( name='ppp_nlp_ml_standalone', version='0.1', description='Compute triplets from a question, with an ML approach', url='https://github.com/ProjetPP', author='Quentin Cormier', author_email='quentin.cormier@ens-lyon.fr', license='MIT', classifiers=[ 'Environment :: No Input/Output (Daemon)', 'Development Status :: 1 - Planning', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application', 'Topic :: Software Development :: Libraries', ], install_requires=[ 'ppp_datamodel>=0.5', 'ppp_core>=0.5', ], packages=[ 'ppp_nlp_ml_standalone', ], )
#!/usr/bin/env python3 from setuptools import setup, find_packages setup( name='ppp_nlp_ml_standalone', version='0.1', description='Compute triplets from a question, with an ML approach', url='https://github.com/ProjetPP', author='Quentin Cormier', author_email='quentin.cormier@ens-lyon.fr', license='MIT', classifiers=[ 'Environment :: No Input/Output (Daemon)', 'Development Status :: 1 - Planning', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application', 'Topic :: Software Development :: Libraries', ], install_requires=[ 'ppp_datamodel>=0.2', 'ppp_core>=0.2', ], packages=[ 'ppp_nlp_ml_standalone', ], )
Drop FK before dropping instance_id column.
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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.from sqlalchemy import * from sqlalchemy import Column, Integer, String, MetaData, Table meta = MetaData() # # Tables to alter # # instance_id = Column('instance_id', Integer()) instance_uuid = Column('instance_uuid', String(255)) def upgrade(migrate_engine): meta.bind = migrate_engine migrations = Table('migrations', meta, autoload=True) migrations.create_column(instance_uuid) if migrate_engine.name == "mysql": migrate_engine.execute("ALTER TABLE migrations DROP FOREIGN KEY " \ "`migrations_ibfk_1`;") migrations.c.instance_id.drop() def downgrade(migrate_engine): meta.bind = migrate_engine migrations = Table('migrations', meta, autoload=True) migrations.c.instance_uuid.drop() migrations.create_column(instance_id)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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.from sqlalchemy import * from sqlalchemy import Column, Integer, String, MetaData, Table meta = MetaData() # # Tables to alter # # instance_id = Column('instance_id', Integer()) instance_uuid = Column('instance_uuid', String(255)) def upgrade(migrate_engine): meta.bind = migrate_engine migrations = Table('migrations', meta, autoload=True) migrations.create_column(instance_uuid) migrations.c.instance_id.drop() def downgrade(migrate_engine): meta.bind = migrate_engine migrations = Table('migrations', meta, autoload=True) migrations.c.instance_uuid.drop() migrations.create_column(instance_id)
Fix potential issue when parsing text content charset
package com.vtence.molecule.testing.http; import com.vtence.molecule.http.ContentType; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; public class TextContent implements HttpContent { private final String text; private final String contentType; public TextContent(String text, String contentType) { this.text = text; this.contentType = contentType; } @Override public long contentLength() { return content().length; } public String contentType() { return contentType; } private byte[] content() { return text.getBytes(charset()); } @Override public void writeTo(OutputStream out) throws IOException { out.write(content()); } private Charset charset() { if (contentType() == null) return StandardCharsets.ISO_8859_1; ContentType contentType = ContentType.parse(contentType()); if (contentType.charset() == null) return StandardCharsets.ISO_8859_1; return contentType.charset(); } }
package com.vtence.molecule.testing.http; import com.vtence.molecule.http.ContentType; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; public class TextContent implements HttpContent { private final String text; private final String contentType; public TextContent(String text, String contentType) { this.text = text; this.contentType = contentType; } @Override public long contentLength() { return content().length; } public String contentType() { return contentType; } private byte[] content() { return text.getBytes(charset()); } @Override public void writeTo(OutputStream out) throws IOException { out.write(content()); } private Charset charset() { ContentType contentType = ContentType.parse(contentType()); if (contentType == null || contentType.charset() == null) return StandardCharsets.ISO_8859_1; return contentType.charset(); } }
[Google] Add the possibility to get more details on an api error
<?php /** * This file is part of the CalendArt package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace CalendArt\Adapter\Google\Exception; use ErrorException; use GuzzleHttp\Message\Response, GuzzleHttp\Exception\ParseException; /** * Whenever the Api returns an unexpected result * * @author Baptiste Clavié <baptiste@wisembly.com> */ class ApiErrorException extends ErrorException { public function __construct(Response $response) { try { $this->details = $response->json(); $message = $this->details['error']['message']; } catch (ParseException $e) { $message = $response->getReasonPhrase(); } parent::__construct(sprintf('The request failed and returned an invalid status code ("%d") : %s', $response->getStatusCode(), $message), $response->getStatusCode()); } public function getDetails() { return $this->details; } }
<?php /** * This file is part of the CalendArt package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace CalendArt\Adapter\Google\Exception; use ErrorException; use GuzzleHttp\Message\Response, GuzzleHttp\Exception\ParseException; /** * Whenever the Api returns an unexpected result * * @author Baptiste Clavié <baptiste@wisembly.com> */ class ApiErrorException extends ErrorException { public function __construct(Response $response) { try { $json = $response->json(); $message = $json['error']['message']; } catch (ParseException $e) { $message = $response->getReasonPhrase(); } parent::__construct(sprintf('The request failed and returned an invalid status code ("%d") : %s', $response->getStatusCode(), $message), $response->getStatusCode()); } }
fix: Use different import for better testing
"""AWS Spinnaker Application.""" from pprint import pformat from foremast.app import base from foremast.utils import wait_for_task class SpinnakerApp(base.BaseApp): """Create AWS Spinnaker Application.""" def create(self): """Send a POST to spinnaker to create a new application with class variables. Raises: AssertionError: Application creation failed. """ self.appinfo['accounts'] = self.get_accounts() self.log.debug('Pipeline Config\n%s', pformat(self.pipeline_config)) self.log.debug('App info:\n%s', pformat(self.appinfo)) jsondata = self.retrieve_template() wait_for_task(jsondata) self.log.info("Successfully created %s application", self.appname) return def delete(self): """Delete AWS Spinnaker Application.""" return False def update(self): """Update AWS Spinnaker Application.""" return False
"""AWS Spinnaker Application.""" from pprint import pformat from foremast.app.base import BaseApp from foremast.utils import wait_for_task class SpinnakerApp(BaseApp): """Create AWS Spinnaker Application.""" def create(self): """Send a POST to spinnaker to create a new application with class variables. Raises: AssertionError: Application creation failed. """ self.appinfo['accounts'] = self.get_accounts() self.log.debug('Pipeline Config\n%s', pformat(self.pipeline_config)) self.log.debug('App info:\n%s', pformat(self.appinfo)) jsondata = self.retrieve_template() wait_for_task(jsondata) self.log.info("Successfully created %s application", self.appname) return def delete(self): """Delete AWS Spinnaker Application.""" return False def update(self): """Update AWS Spinnaker Application.""" return False
Add missing keepalive on TCP connection
package livestatus import ( "net" ) const bufferSize = 1024 // Client represents a Livestatus client instance. type Client struct { network string address string dialer *net.Dialer conn net.Conn } // NewClient creates a new Livestatus client instance. func NewClient(network, address string) *Client { return NewClientWithDialer(network, address, new(net.Dialer)) } // NewClientWithDialer creates a new Livestatus client instance using a provided network dialer. func NewClientWithDialer(network, address string, dialer *net.Dialer) *Client { return &Client{ network: network, address: address, dialer: dialer, } } // Close closes any remaining connection. func (c *Client) Close() { if c.conn != nil { c.conn.Close() c.conn = nil } } // Exec executes a given Livestatus query. func (c *Client) Exec(r Request) (*Response, error) { var err error // Initialize connection if none available if c.conn == nil { c.conn, err = c.dialer.Dial(c.network, c.address) if err != nil { return nil, err } if r.keepAlive() { c.conn.(*net.TCPConn).SetKeepAlive(true) } else { defer c.Close() } } return r.handle(c.conn) }
package livestatus import ( "net" ) const bufferSize = 1024 // Client represents a Livestatus client instance. type Client struct { network string address string dialer *net.Dialer conn net.Conn } // NewClient creates a new Livestatus client instance. func NewClient(network, address string) *Client { return NewClientWithDialer(network, address, new(net.Dialer)) } // NewClientWithDialer creates a new Livestatus client instance using a provided network dialer. func NewClientWithDialer(network, address string, dialer *net.Dialer) *Client { return &Client{ network: network, address: address, dialer: dialer, } } // Close closes any remaining connection. func (c *Client) Close() { if c.conn != nil { c.conn.Close() c.conn = nil } } // Exec executes a given Livestatus query. func (c *Client) Exec(r Request) (*Response, error) { var err error // Initialize connection if none available if c.conn == nil { c.conn, err = c.dialer.Dial(c.network, c.address) if err != nil { return nil, err } if !r.keepAlive() { defer c.Close() } } return r.handle(c.conn) }
Add code box utils file.
import React from "react"; import CSSModules from 'react-css-modules'; import styles from "../../../scss/_code-box.scss"; import _ from "lodash"; import {compare} from '../../utils/code-box-utils'; class CSSView extends React.Component { constructor(){ super(); } render() { const{dispatch, cssView, pixelCount, rectData} = this.props; let sortedRectData = rectData.sort(compare); let cssCode = []; if(cssView){ rectData.map(function(value, idx, arr){ if(idx === arr.length - 1){ cssCode.push( `${sortedRectData[idx][0]}px ${sortedRectData[idx][1]}px ${sortedRectData[idx][2]};` ) } else{ cssCode.push( `${sortedRectData[idx][0]}px ${sortedRectData[idx][1]}px ${sortedRectData[idx][2]}, ` ) } }); return( <p id="inner_code_box"> box-shadow:<br/> {cssCode}</p> ); } return( <div></div> ); } } export default CSSView;
import React from "react"; import CSSModules from 'react-css-modules'; import styles from "../../../scss/_code-box.scss"; import _ from "lodash"; import {compare} from '../../utils/code-box-utils'; class CSSView extends React.Component { constructor(){ super(); } render() { const{dispatch, cssView, pixelCount, rectData} = this.props; let sortedRectData = rectData.sort(compare); if(cssView){ let cssCode = []; rectData.map(function(value, idx, arr){ if(idx === arr.length - 1){ cssCode.push( `${sortedRectData[idx][0]}px ${sortedRectData[idx][1]}px ${sortedRectData[idx][2]};` ) } else{ cssCode.push( `${sortedRectData[idx][0]}px ${sortedRectData[idx][1]}px ${sortedRectData[idx][2]}, ` ) } }); return( <p id="inner_code_box"> box-shadow:<br/> {cssCode}</p> ); } return( <div></div> ); } } export default CSSView;
Improve subprocess call during deployment
import subprocess from django.conf import settings from django.contrib.sites.models import Site from django.http import JsonResponse, HttpResponseBadRequest from django.shortcuts import redirect from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token @csrf_exempt def deploy(request): deploy_secret_key = request.POST.get('DEPLOY_SECRET_KEY') # branch = request.POST.get('BRANCH') commit = request.POST.get('COMMIT') if deploy_secret_key != settings.SECRET_KEY: return HttpResponseBadRequest('Incorrect key.') subprocess.run(['scripts/deploy.sh', commit], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) return JsonResponse({'result': 'deploy started'}) def social_redirect(request): token, _ = Token.objects.get_or_create(user=request.user) return_url = '{protocol}://{domain}/finish-steam/{token}'.format( protocol='http' if settings.DEBUG else 'https', domain=Site.objects.get_current().domain, token=token.key ) return redirect(return_url)
import subprocess from django.conf import settings from django.contrib.sites.models import Site from django.http import JsonResponse, HttpResponseBadRequest from django.shortcuts import redirect from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token @csrf_exempt def deploy(request): deploy_secret_key = request.POST.get('DEPLOY_SECRET_KEY') # branch = request.POST.get('BRANCH') commit = request.POST.get('COMMIT') if deploy_secret_key != settings.SECRET_KEY: return HttpResponseBadRequest('Incorrect key.') subprocess.Popen(['scripts/deploy.sh', commit], stdout=subprocess.PIPE) return JsonResponse({'result': 'deploy started'}) def social_redirect(request): token, _ = Token.objects.get_or_create(user=request.user) return_url = '{protocol}://{domain}/finish-steam/{token}'.format( protocol='http' if settings.DEBUG else 'https', domain=Site.objects.get_current().domain, token=token.key ) return redirect(return_url)
TabBarIcon: Use platformPrefixIcon to smartly prefix the icon Signed-off-by: Kristofer Rye <1ed31cfd0b53bc3d1689a6fee6dbfc9507dffd22@gmail.com> Tested-by: Kristofer Rye <1ed31cfd0b53bc3d1689a6fee6dbfc9507dffd22@gmail.com>
// @flow import * as React from 'react' import {StyleSheet, Platform} from 'react-native' import Icon from 'react-native-vector-icons/Ionicons' const styles = StyleSheet.create({ icon: { fontSize: Platform.select({ ios: 30, android: 24, }), }, }) type Props = { tintColor: string, focused: boolean, } export const platformPrefixIcon = (name: string) => { let isAvailable = Icon.hasIcon(name) let isAvailableOnBothPlatforms = Icon.hasIcon(`ios-${name}`) && Icon.hasIcon(`md-${name}`) if (isAvailable && !isAvailableOnBothPlatforms) { return name } return Platform.OS === 'ios' ? `ios-${name}` : `md-${name}` } export const TabBarIcon = (icon: string) => ({tintColor}: Props) => ( <Icon name={platformPrefixIcon(icon)} style={[styles.icon, {color: tintColor}]} /> )
// @flow import * as React from 'react' import {StyleSheet, Platform} from 'react-native' import Icon from 'react-native-vector-icons/Ionicons' const styles = StyleSheet.create({ icon: { fontSize: Platform.select({ ios: 30, android: 24, }), }, }) type Props = { tintColor: string, focused: boolean, } export const platformPrefixIcon = (name: string) => { let isAvailable = Icon.hasIcon(name) let isAvailableOnBothPlatforms = Icon.hasIcon(`ios-${name}`) && Icon.hasIcon(`md-${name}`) if (isAvailable && !isAvailableOnBothPlatforms) { return name } return Platform.OS === 'ios' ? `ios-${name}` : `md-${name}` } export const TabBarIcon = (icon: string) => ({tintColor}: Props) => ( <Icon name={`ios-${icon}`} style={[styles.icon, {color: tintColor}]} /> )
Use .some instead of ES6 .find
import Ui from "./Ui"; import Generator from "./Generator"; Ui.initializeDefaults(); $.getJSON("/features.json").done(displayFeatures); $.getJSON("/formats.json").done(displayFormats); function displayFeatures(features) { features.forEach(function (feature) { var checkbox = createFeatureCheckbox(feature); var container = $("<div>").addClass("item").append(checkbox); container.appendTo("#feature-list"); }); } function createFeatureCheckbox(feature) { let id = feature.token + "-feature"; let container = $("<div>").data(feature).addClass("ui checkbox"); $("<input type='checkbox' id='" + id + "'>").appendTo(container); $("<label>").attr("for", id).text(feature.name).appendTo(container); return container; } function displayFormats(formats) { formats.forEach(function (format) { let option = $("<div class='item' data-value='" + format.extension + "'>"); option.data(format).text(format.name); option.appendTo("#format-list"); }); formats.some(value => { if (value.default) { Ui.initializeFormats(value); return true; } }); }
import Ui from "./Ui"; import Generator from "./Generator"; Ui.initializeDefaults(); $.getJSON("/features.json").done(displayFeatures); $.getJSON("/formats.json").done(displayFormats); function displayFeatures(features) { features.forEach(function (feature) { var checkbox = createFeatureCheckbox(feature); var container = $("<div>").addClass("item").append(checkbox); container.appendTo("#feature-list"); }); } function createFeatureCheckbox(feature) { let id = feature.token + "-feature"; let container = $("<div>").data(feature).addClass("ui checkbox"); $("<input type='checkbox' id='" + id + "'>").appendTo(container); $("<label>").attr("for", id).text(feature.name).appendTo(container); return container; } function displayFormats(formats) { formats.forEach(function (format) { let option = $("<div class='item' data-value='" + format.extension + "'>"); option.data(format).text(format.name); option.appendTo("#format-list"); }); Ui.initializeFormats(formats.find(format => format.default)); }
Set age groups to match paper registration.
calculateAgeGroup = function (age) { /* * Calculate the age group * based on an age input * return the age group string * 0-5: child * 6-12: youth * 13-17: teen * 18-25: yaf * 26+: adult */ // Make sure age is an integer try { parseInt(age); } catch (error) { console.log(error.message); return; } // determine the age group as described above if (age >= 0 && age <= 5) { return 'child'; } else if (age >= 6 && age <= 12) { return 'youth'; } else if (age >= 13 && age <= 17) { return 'teen'; } else if (age >= 18 && age <= 25) { return 'youngAdult'; } else if (age >= 26 ) { return 'adult'; } else { return undefined; } };
calculateAgeGroup = function (age) { /* * Calculate the age group * based on an age input * return the age group string * 0-5: child * 6-10: youth * 11-17: teen * 18-25: yaf * 26+: adult */ // Make sure age is an integer try { parseInt(age); } catch (error) { console.log(error.message); return; } // determine the age group as described above if (age >= 0 && age <= 5) { return 'child'; } else if (age >= 6 && age <= 10) { return 'youth'; } else if (age >= 11 && age <= 17) { return 'teen'; } else if (age >= 18 && age <= 25) { return 'youngAdult'; } else if (age >= 26 ) { return 'adult'; } else { return undefined; } };
Read the config file only from /etc/autocloud/autocloud.cfg file.
# -*- coding: utf-8 -*- import ConfigParser import os PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__)) name = '/etc/autocloud/autocloud.cfg' if not os.path.exists(name): raise Exception('Please add a proper cofig file under /etc/autocloud/') config.read(name) KOJI_SERVER_URL = config.get('autocloud', 'koji_server_url') BASE_KOJI_TASK_URL = config.get('autocloud', 'base_koji_task_url') HOST = config.get('autocloud', 'host') or '127.0.0.1' PORT = int(config.get('autocloud', 'port')) or 5000 DEBUG = config.getboolean('autocloud', 'debug') SQLALCHEMY_URI = config.get('sqlalchemy', 'uri') VIRTUALBOX = config.getboolean('autocloud', 'virtualbox')
# -*- coding: utf-8 -*- import ConfigParser import os PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__)) config = ConfigParser.RawConfigParser() name = "{PROJECT_ROOT}/config/autocloud.cfg".format( PROJECT_ROOT=PROJECT_ROOT) if not os.path.exists(name): name = '/etc/autocloud/autocloud.cfg' config.read(name) KOJI_SERVER_URL = config.get('autocloud', 'koji_server_url') BASE_KOJI_TASK_URL = config.get('autocloud', 'base_koji_task_url') HOST = config.get('autocloud', 'host') or '127.0.0.1' PORT = int(config.get('autocloud', 'port')) or 5000 DEBUG = config.getboolean('autocloud', 'debug') SQLALCHEMY_URI = config.get('sqlalchemy', 'uri') VIRTUALBOX = config.getboolean('autocloud', 'virtualbox')
Clean up the description for PyPI
import sys import re if sys.version < '3.4': print('Sorry, this is not a compatible version of Python. Use 3.4 or later.') exit(1) from setuptools import setup, find_packages with open('README.md') as f: description = f.read() description = re.sub(r'\[!\[.+\].+\]\(.+\)', '', description) description = '\n'.join(description.splitlines()[2:]) description = re.sub('\n{2,}', '\n\n', description).strip() from circle_asset.version import VERSION, SHORT_DESCRIPTION setup(name='circle-asset', version=VERSION, description=SHORT_DESCRIPTION, author='Alistair Lynn', author_email='arplynn@gmail.com', license="MIT", long_description=description, url='https://github.com/prophile/circle-asset', zip_safe=True, setup_requires=['nose >=1, <2'], install_requires=[ 'requests >=2.5, <3' ], entry_points={'console_scripts': [ 'circle-asset=circle_asset.cli:main' ]}, packages=find_packages(), test_suite='nose.collector')
import sys if sys.version < '3.4': print('Sorry, this is not a compatible version of Python. Use 3.4 or later.') exit(1) from setuptools import setup, find_packages with open('README.md') as f: description = f.read() from circle_asset.version import VERSION, SHORT_DESCRIPTION setup(name='circle-asset', version=VERSION, description=SHORT_DESCRIPTION, author='Alistair Lynn', author_email='arplynn@gmail.com', license="MIT", long_description=description, url='https://github.com/prophile/circle-asset', zip_safe=True, setup_requires=['nose >=1, <2'], install_requires=[ 'requests >=2.5, <3' ], entry_points={'console_scripts': [ 'circle-asset=circle_asset.cli:main' ]}, packages=find_packages(), test_suite='nose.collector')
Create a transaction ID from a string UUID
<?php declare(strict_types=1); namespace PerFi\Domain\Transaction; use Ramsey\Uuid\Uuid; class TransactionId { /** * @var Uuid */ private $id; /** * Create an transaction ID * * @param Uuid $id */ private function __construct(Uuid $id) { $this->id = $id; } /** * Create an transaction ID from an UUID * * @param Uuid $id * @return TransactionId */ public static function fromUuid(Uuid $id) : self { return new self($id); } /** * Create a transaction ID from a string UUID * * @param string $id * @return AccountId */ public static function fromString(string $id) : self { return new self( Uuid::fromString($id) ); } /** * String representation of the transaction ID * * @return string */ public function __toString() : string { return (string) $this->id; } }
<?php declare(strict_types=1); namespace PerFi\Domain\Transaction; use Ramsey\Uuid\Uuid; class TransactionId { /** * @var Uuid */ private $id; /** * Create an transaction ID * * @param Uuid $id */ private function __construct(Uuid $id) { $this->id = $id; } /** * Create an transaction ID from an UUID * * @param Uuid $id * @return TransactionId */ public static function fromUuid(Uuid $id) : self { return new self($id); } /** * String representation of the transaction ID * * @return string */ public function __toString() : string { return (string) $this->id; } }
Add second constructor for already formed string Summary: When catching an exception that has formatting chars in it, we can run into issues if we try to format again Reviewed By: cjhopman shipit-source-id: 1929d59f1795cfbdefd0c86688b6c852f4438205
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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.facebook.buck.core.rules.analysis; import com.facebook.buck.core.exceptions.HumanReadableException; import javax.annotation.Nullable; /** * Represents the failure of an analysis phase implementation function * * <p>This exception should result in a {@link com.facebook.buck.util.ExitCode.BUILD_ERROR} */ public class RuleAnalysisException extends HumanReadableException { public RuleAnalysisException( @Nullable Throwable cause, String humanReadableFormatString, Object... args) { super(cause, humanReadableFormatString, args); } public RuleAnalysisException(@Nullable Throwable cause, String message) { super(cause, message); } }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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.facebook.buck.core.rules.analysis; import com.facebook.buck.core.exceptions.HumanReadableException; import javax.annotation.Nullable; /** * Represents the failure of an analysis phase implementation function * * <p>This exception should result in a {@link com.facebook.buck.util.ExitCode.BUILD_ERROR} */ public class RuleAnalysisException extends HumanReadableException { public RuleAnalysisException( @Nullable Throwable cause, String humanReadableFormatString, Object... args) { super(cause, humanReadableFormatString, args); } }
Fix the initial factionId bug
import { List } from 'immutable'; import { Reducer } from 'flux-reducer'; import factions from '../models/faction'; export default class ShipInputReducer extends Reducer({ shipName: '', factionId: '', factions: new List, }) { static create() { var allFactions = factions.getAll(); return new ShipInputReducer({ factions: new List(allFactions), factionId: allFactions.length > 0 ? allFactions[0].id : '', }); } constructor(values) { super(values || factions.getAll()); this.addDisposable(factions.onAdd(this.onAdd.bind(this))); } onAdd(factionList) { if (!Array.isArray(factionList)) { factionList = [factionList]; } this.trigger(this.set('factions', this.factions.push(...factionList))); } changeShipName(name) { this.trigger(this.set('shipName', name)); } changeFactionId(id) { this.trigger(this.set('factionId', id)); } addShip(ship) { let faction = factions.getById(ship.factionId); faction && faction.addShip({name: ship.shipName}); } }
import { List } from 'immutable'; import { Reducer } from 'flux-reducer'; import factions from '../models/faction'; export default class ShipInputReducer extends Reducer({ shipName: '', factionId: '', factions: new List, }) { static create() { return new ShipInputReducer({ factions: new List(factions.getAll()), }); } constructor(values) { super(values || factions.getAll()); this.addDisposable(factions.onAdd(this.onAdd.bind(this))); } onAdd(factionList) { if (!Array.isArray(factionList)) { factionList = [factionList]; } this.trigger(this.set('factions', this.factions.push(...factionList))); } changeShipName(name) { this.trigger(this.set('shipName', name)); } changeFactionId(id) { this.trigger(this.set('factionId', id)); } addShip(ship) { let faction = factions.getById(ship.factionId); faction && faction.addShip({name: ship.shipName}); } }
Enable Node 16 and NPM 7/8 support on generation Signed-off-by: Derrick Mehaffy <d3de28f82f22c58e03cd756b0176b069ba189978@gmail.com>
'use strict'; /** * Expose main package JSON of the application * with basic info, dependencies, etc. */ module.exports = opts => { const { strapiDependencies, additionalsDependencies, strapiVersion, projectName, uuid, packageJsonStrapi, } = opts; // Finally, return the JSON. return { name: projectName, private: true, version: '0.1.0', description: 'A Strapi application', scripts: { develop: 'strapi develop', start: 'strapi start', build: 'strapi build', strapi: 'strapi', }, devDependencies: {}, dependencies: Object.assign( {}, strapiDependencies.reduce((acc, key) => { acc[key] = strapiVersion; return acc; }, {}), additionalsDependencies ), author: { name: 'A Strapi developer', }, strapi: { uuid, ...packageJsonStrapi, }, engines: { node: '>=12.x.x <=16.x.x', npm: '>=6.0.0', }, license: 'MIT', }; };
'use strict'; /** * Expose main package JSON of the application * with basic info, dependencies, etc. */ module.exports = opts => { const { strapiDependencies, additionalsDependencies, strapiVersion, projectName, uuid, packageJsonStrapi, } = opts; // Finally, return the JSON. return { name: projectName, private: true, version: '0.1.0', description: 'A Strapi application', scripts: { develop: 'strapi develop', start: 'strapi start', build: 'strapi build', strapi: 'strapi', }, devDependencies: {}, dependencies: Object.assign( {}, strapiDependencies.reduce((acc, key) => { acc[key] = strapiVersion; return acc; }, {}), additionalsDependencies ), author: { name: 'A Strapi developer', }, strapi: { uuid, ...packageJsonStrapi, }, engines: { node: '>=12.x.x <=14.x.x', npm: '^6.0.0', }, license: 'MIT', }; };
Apply golang opts, and give an example
package main import ( "fmt" "os" "time" "github.com/voxelbrain/goptions" ) func main() { options := struct { Servers []string `goptions:"-s, --server, obligatory, description='Servers to connect to'"` Password string `goptions:"-p, --password, description='Don\\'t prompt for password'"` Timeout time.Duration `goptions:"-t, --timeout, description='Connection timeout in seconds'"` Help goptions.Help `goptions:"-h, --help, description='Show this help'"` goptions.Verbs Execute struct { Command string `goptions:"--command, mutexgroup='input', description='Command to exectute', obligatory"` Script *os.File `goptions:"--script, mutexgroup='input', description='Script to exectute', rdonly"` } `goptions:"execute"` Delete struct { Path string `goptions:"-n, --name, obligatory, description='Name of the entity to be deleted'"` Force bool `goptions:"-f, --force, description='Force removal'"` } `goptions:"delete"` }{ // Default values goes here Timeout: 10 * time.Second, } goptions.ParseAndFail(&options) fmt.Println(options.Servers, len(options.Servers)) } //Example: go run main.go -s localhost -s 127.0.0.1
package main import ( "github.com/voxelbrain/goptions" "os" "time" ) func main() { options := struct { Servers []string `goptions:"-s, --server, obligatory, description='Servers to connect to'"` Password string `goptions:"-p, --password, description='Don\\'t prompt for password'"` Timeout time.Duration `goptions:"-t, --timeout, description='Connection timeout in seconds'"` Help goptions.Help `goptions:"-h, --help, description='Show this help'"` goptions.Verbs Execute struct { Command string `goptions:"--command, mutexgroup='input', description='Command to exectute', obligatory"` Script *os.File `goptions:"--script, mutexgroup='input', description='Script to exectute', rdonly"` } `goptions:"execute"` Delete struct { Path string `goptions:"-n, --name, obligatory, description='Name of the entity to be deleted'"` Force bool `goptions:"-f, --force, description='Force removal'"` } `goptions:"delete"` }{ // Default values goes here Timeout: 10 * time.Second, } goptions.ParseAndFail(&options) }
Fix bug where domains were valid entries.
/* Returns a clever domain for the given text, if one exists. */ function checkDomains() { /* Get the input string */ var userString = document.getElementById("domainInput").value; /* Sample list of domain suffixes */ var data = [ 'io', 'biz', 'im', 'info' ]; /* Try to find a matching domain ending. */ for(var ending = 0; ending < data.length; ++ending) { var domain = data[ending]; if(userString.slice(userString.length - domain.length, userString.length) === domain && userString.length > 2) { var domainPrefix = userString.slice(0, userString.lastIndexOf(domain[0]) ); var pickedDomain = domainPrefix + '.' + domain; break; }; }; /* Check if a domain was found. */ if (typeof domainPrefix === 'undefined') { message = 'No clever domains were found for \'' + userString + '\' :('; } else { message = 'Congrats! We\'ve found a domain for you: ' + pickedDomain; } setDivMessage(message); return; }; /* Set the message to the output div. */ function setDivMessage(message) { var outputDiv = document.getElementById("domainOutput"); outputDiv.textContent = message; outputDiv.style.display = "block"; };
/* Returns a clever domain for the given text, if one exists. */ function checkDomains() { /* Get the input string */ var userString = document.getElementById("domainInput").value; /* Sample list of domain suffixes */ var data = [ 'io', 'biz', 'im', 'info' ]; /* Try to find a matching domain ending. */ for(var ending = 0; ending < data.length; ++ending) { var domain = data[ending]; if(userString.slice(userString.length - domain.length, userString.length) === domain) { var domainPrefix = userString.slice(0, userString.lastIndexOf(domain[0]) ); var pickedDomain = domainPrefix + '.' + domain; break; }; }; /* Check if a domain was found. */ if (typeof domainPrefix === 'undefined') { message = 'No clever domains were found for \'' + userString + '\' :('; } else { message = 'Congrats! We\'ve found a domain for you: ' + pickedDomain; } setDivMessage(message); return; }; /* Set the message to the output div. */ function setDivMessage(message) { var outputDiv = document.getElementById("domainOutput"); outputDiv.textContent = message; outputDiv.style.display = "block"; };
Fix typo in jsbox URLs.
from django.conf.urls.defaults import patterns, url, include urlpatterns = patterns('', url(r'^survey/', include('go.apps.surveys.urls', namespace='survey')), url(r'^multi_survey/', include('go.apps.multi_surveys.urls', namespace='multi_survey')), url(r'^bulk_message/', include('go.apps.bulk_message.urls', namespace='bulk_message')), url(r'^opt_out/', include('go.apps.opt_out.urls', namespace='opt_out')), url(r'^sequential_send/', include('go.apps.sequential_send.urls', namespace='sequential_send')), url(r'^subscription/', include('go.apps.subscription.urls', namespace='subscription')), url(r'^wikipedia_ussd/', include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')), url(r'^wikipedia_sms/', include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')), url(r'^jsbox/', include('go.apps.jsbox.urls', namespace='jsbox')), )
from django.conf.urls.defaults import patterns, url, include urlpatterns = patterns('', url(r'^survey/', include('go.apps.surveys.urls', namespace='survey')), url(r'^multi_survey/', include('go.apps.multi_surveys.urls', namespace='multi_survey')), url(r'^bulk_message/', include('go.apps.bulk_message.urls', namespace='bulk_message')), url(r'^opt_out/', include('go.apps.opt_out.urls', namespace='opt_out')), url(r'^sequential_send/', include('go.apps.sequential_send.urls', namespace='sequential_send')), url(r'^subscription/', include('go.apps.subscription.urls', namespace='subscription')), url(r'^wikipedia_ussd/', include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')), url(r'^wikipedia_sms/', include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')), url(r'^jsbox/', include('go.apps.jsbos.urls', namespace='jsbox')), )
Use logrus.FieldLogger instead of *logrus.Logger This allows supplying a logrus logger that already has fields configured
// Package logrusadapter provides a logger that writes to a github.com/sirupsen/logrus.Logger // log. package logrusadapter import ( "github.com/jackc/pgx" "github.com/sirupsen/logrus" ) type Logger struct { l logrus.FieldLogger } func NewLogger(l logrus.FieldLogger) *Logger { return &Logger{l: l} } func (l *Logger) Log(level pgx.LogLevel, msg string, data map[string]interface{}) { var logger logrus.FieldLogger if data != nil { logger = l.l.WithFields(data) } else { logger = l.l } switch level { case pgx.LogLevelTrace: logger.WithField("PGX_LOG_LEVEL", level).Debug(msg) case pgx.LogLevelDebug: logger.Debug(msg) case pgx.LogLevelInfo: logger.Info(msg) case pgx.LogLevelWarn: logger.Warn(msg) case pgx.LogLevelError: logger.Error(msg) default: logger.WithField("INVALID_PGX_LOG_LEVEL", level).Error(msg) } }
// Package logrusadapter provides a logger that writes to a github.com/sirupsen/logrus.Logger // log. package logrusadapter import ( "github.com/jackc/pgx" "github.com/sirupsen/logrus" ) type Logger struct { l *logrus.Logger } func NewLogger(l *logrus.Logger) *Logger { return &Logger{l: l} } func (l *Logger) Log(level pgx.LogLevel, msg string, data map[string]interface{}) { var logger logrus.FieldLogger if data != nil { logger = l.l.WithFields(data) } else { logger = l.l } switch level { case pgx.LogLevelTrace: logger.WithField("PGX_LOG_LEVEL", level).Debug(msg) case pgx.LogLevelDebug: logger.Debug(msg) case pgx.LogLevelInfo: logger.Info(msg) case pgx.LogLevelWarn: logger.Warn(msg) case pgx.LogLevelError: logger.Error(msg) default: logger.WithField("INVALID_PGX_LOG_LEVEL", level).Error(msg) } }
STYLE: Fix missing line at end of file Fix missing line Remove whitespace
""" Tests corresponding to sandbox.stats.runs """ from numpy.testing import assert_almost_equal from statsmodels.sandbox.stats.runs import runstest_1samp def test_mean_cutoff(): x = [1] * 5 + [2] * 6 + [3] * 8 cutoff = "mean" expected = (-4.007095978613213, 6.146988816717466e-05) results = runstest_1samp(x, cutoff=cutoff, correction=False) assert_almost_equal(expected, results) def test_median_cutoff(): x = [1] * 5 + [2] * 6 + [3] * 8 cutoff = "median" expected = (-3.944254410803499, 8.004864125547193e-05) results = runstest_1samp(x, cutoff=cutoff, correction=False) assert_almost_equal(expected, results) def test_numeric_cutoff(): x = [1] * 5 + [2] * 6 + [3] * 8 cutoff = 2 expected = (-3.944254410803499, 8.004864125547193e-05) results = runstest_1samp(x, cutoff=cutoff, correction=False) assert_almost_equal(expected, results)
""" Tests corresponding to sandbox.stats.runs """ from numpy.testing import assert_almost_equal from statsmodels.sandbox.stats.runs import runstest_1samp def test_mean_cutoff(): x = [1] * 5 + [2] * 6 + [3] * 8 cutoff = "mean" expected = (-4.007095978613213, 6.146988816717466e-05) results = runstest_1samp(x, cutoff=cutoff, correction=False) assert_almost_equal(expected, results) def test_median_cutoff(): x = [1] * 5 + [2] * 6 + [3] * 8 cutoff = "median" expected = (-3.944254410803499, 8.004864125547193e-05) results = runstest_1samp(x, cutoff=cutoff, correction=False) assert_almost_equal(expected, results) def test_numeric_cutoff(): x = [1] * 5 + [2] * 6 + [3] * 8 cutoff = 2 expected = (-3.944254410803499, 8.004864125547193e-05) results = runstest_1samp(x, cutoff=cutoff, correction=False) assert_almost_equal(expected, results)
Store yang store snapshot cache using soft reference. Change-Id: I9b159db83ba204b4a636f2314fd4fc2e7b6f654c Signed-off-by: Tomas Olvecky <15c0b3ba77d9541ebd8ccf1bd003ebd96c682ed7@cisco.com>
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.netconf.confignetconfconnector.osgi; import java.lang.ref.SoftReference; import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; import javax.annotation.concurrent.GuardedBy; public class YangStoreServiceImpl implements YangStoreService { private final SchemaContextProvider service; @GuardedBy("this") private SoftReference<YangStoreSnapshotImpl> cache = new SoftReference<>(null); public YangStoreServiceImpl(SchemaContextProvider service) { this.service = service; } @Override public synchronized YangStoreSnapshotImpl getYangStoreSnapshot() throws YangStoreException { YangStoreSnapshotImpl yangStoreSnapshot = cache.get(); if (yangStoreSnapshot == null) { yangStoreSnapshot = new YangStoreSnapshotImpl(service.getSchemaContext()); cache = new SoftReference<>(yangStoreSnapshot); } return yangStoreSnapshot; } /** * Called when schema context changes, invalidates cache. */ public synchronized void refresh() { cache.clear(); } }
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.netconf.confignetconfconnector.osgi; import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; import javax.annotation.concurrent.GuardedBy; public class YangStoreServiceImpl implements YangStoreService { private final SchemaContextProvider service; @GuardedBy("this") private YangStoreSnapshotImpl cache = null; public YangStoreServiceImpl(SchemaContextProvider service) { this.service = service; } @Override public synchronized YangStoreSnapshotImpl getYangStoreSnapshot() throws YangStoreException { if (cache == null) { cache = new YangStoreSnapshotImpl(service.getSchemaContext()); } return cache; } /** * Called when schema context changes, invalidates cache. */ public synchronized void refresh() { cache = null; } }
Refactor to avoid export expression assignment
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Boolean indicating if the runtime is a web browser. * * @module @stdlib/assert/is-browser * * @example * var IS_BROWSER = require( '@stdlib/assert/is-browser' ); * * var bool = IS_BROWSER; * // returns <boolean> */ // MODULES // var isBrowser = require( './main.js' ); // VARIABLES // var bool = isBrowser(); // EXPORTS // module.exports = bool;
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Boolean indicating if the runtime is a web browser. * * @module @stdlib/assert/is-browser * * @example * var IS_BROWSER = require( '@stdlib/assert/is-browser' ); * * var bool = IS_BROWSER; * // returns <boolean> */ // MODULES // var isBrowser = require( './main.js' ); // EXPORTS // module.exports = isBrowser();
Use `make_admin_app`, document why `admin_app` is still needed
""" :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. API-specific fixtures """ import pytest from tests.base import create_admin_app from tests.conftest import CONFIG_PATH_DATA_KEY from .helpers import assemble_authorization_header API_TOKEN = 'just-say-PLEASE!' @pytest.fixture(scope='session') # `admin_app` fixture is required because it sets up the database. def app(admin_app, make_admin_app): config_overrides = { 'API_TOKEN': API_TOKEN, 'SERVER_NAME': 'api.acmecon.test', } app = make_admin_app(**config_overrides) with app.app_context(): yield app @pytest.fixture(scope='session') def api_client(app): """Provide a test HTTP client against the API.""" return app.test_client() @pytest.fixture(scope='session') def api_client_authz_header(): """Provide a test HTTP client against the API.""" return assemble_authorization_header(API_TOKEN)
""" :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. API-specific fixtures """ import pytest from tests.base import create_admin_app from tests.conftest import CONFIG_PATH_DATA_KEY from .helpers import assemble_authorization_header API_TOKEN = 'just-say-PLEASE!' @pytest.fixture(scope='session') def app(admin_app, data_path): config_overrides = { 'API_TOKEN': API_TOKEN, CONFIG_PATH_DATA_KEY: data_path, 'SERVER_NAME': 'api.acmecon.test', } app = create_admin_app(config_overrides) with app.app_context(): yield app @pytest.fixture(scope='session') def api_client(app): """Provide a test HTTP client against the API.""" return app.test_client() @pytest.fixture(scope='session') def api_client_authz_header(): """Provide a test HTTP client against the API.""" return assemble_authorization_header(API_TOKEN)
Increase TAC maxteamsize to 3 (from 1) - Fixes #343 - Opens #346, since the user cannot select the teamsize
/** * TAC Presets: TAC rankings, followed by wins and numgames * * @return Presets * @author Erik E. Lorenz <erik@tuvero.de> * @license MIT License * @see LICENSE */ define(function () { var Presets; Presets = { target: 'tac', systems: { swiss: { ranking: ['tac', 'numgames', 'wins', 'headtohead'], mode: 'ranks' }, ko: { mode: 'matched' }, round: { ranking: ['tac', 'numgames', 'wins', 'headtohead'] }, placement: { } }, ranking: { components: ['tac', 'numgames', 'wins', 'headtohead', 'saldo'] }, registration: { minteamsize: 1, maxteamsize: 3, teamsizeicon: false }, taboptions: { namemaxwidth: false, showmatchtables: true }, names: { playernameurl: '', dbplayername: 'tacplayers', apitoken: 'apitoken', teamsfile: 'tuvero-anmeldungen.txt' } }; return Presets; });
/** * TAC Presets: TAC rankings, followed by wins and numgames * * @return Presets * @author Erik E. Lorenz <erik@tuvero.de> * @license MIT License * @see LICENSE */ define(function () { var Presets; Presets = { target: 'tac', systems: { swiss: { ranking: ['tac', 'numgames', 'wins', 'headtohead'], mode: 'ranks' }, ko: { mode: 'matched' }, round: { ranking: ['tac', 'numgames', 'wins', 'headtohead'] }, placement: { } }, ranking: { components: ['tac', 'numgames', 'wins', 'headtohead', 'saldo'] }, registration: { minteamsize: 1, maxteamsize: 1, teamsizeicon: false }, taboptions: { namemaxwidth: false, showmatchtables: true }, names: { playernameurl: '', dbplayername: 'tacplayers', apitoken: 'apitoken', teamsfile: 'tuvero-anmeldungen.txt' } }; return Presets; });
[BugFix] Disable remember me on auto login
<?php namespace Wells\L4LdapNtlm; use Illuminate\Auth\Guard; /** * An LDAP/NTLM authentication driver for Laravel 4. * * @author Brian Wells (https://github.com/wells/) * */ class L4LdapNtlmGuard extends Guard { public function admin() { // Check if user is logged in if ($this->check() && $this->user()) { // User type is admin = 0 return $this->user()->type == 0; } return FALSE; } public function auto() { if ($this->check()) return TRUE; // Should return FALSE if libapache2-mod-auth-ntlm-winbind is not installed if (! isset($_SERVER['REMOTE_USER'])) return FALSE; $ntlm = explode('\\', $_SERVER['REMOTE_USER']); if (count($ntlm) != 2) return FALSE; $credentials = array( 'username' => strtolower($ntlm[1]), 'NTLM' => TRUE ); return $this->attempt($credentials, FALSE); } }
<?php namespace Wells\L4LdapNtlm; use Illuminate\Auth\Guard; /** * An LDAP/NTLM authentication driver for Laravel 4. * * @author Brian Wells (https://github.com/wells/) * */ class L4LdapNtlmGuard extends Guard { public function admin() { // Check if user is logged in if ($this->check() && $this->user()) { // User type is admin = 0 return $this->user()->type == 0; } return FALSE; } public function auto() { if ($this->check()) return TRUE; // Should return FALSE if libapache2-mod-auth-ntlm-winbind is not installed if (! isset($_SERVER['REMOTE_USER'])) return FALSE; $ntlm = explode('\\', $_SERVER['REMOTE_USER']); if (count($ntlm) != 2) return FALSE; $credentials = array( 'username' => strtolower($ntlm[1]), 'NTLM' => TRUE ); return $this->attempt($credentials, TRUE); } }
Fix static url path error.
""" hello/__init__.py ------------------ Initializes Flask application and brings all components together. """ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_misaka import Misaka # Create application object app = Flask(__name__, instance_relative_config=True, static_url_path='/static', static_folder='staticfiles') # Load default configuration settings app.config.from_object('config.default') # Load non-VC configuration variables from instance folder app.config.from_pyfile('instance.cfg', silent=True) # Load settings specified by APP_CONFIG_FILE environment variable # (such as 'config.development' or 'config.production') # Variables defined here will override default configurations #app.config.from_envvar('APP_CONFIG_FILE', silent=True) # Disable Flask-SQLAlchemy event notification system. app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # Explicitly add debugger middleware if app.debug: from werkzeug.debug import DebuggedApplication app.wsgi_app = DebuggedApplication(app.wsgi_app, True) # Create SQLAlchemy object (database) db = SQLAlchemy(app) # Use Misaka for markdown templates Misaka(app) # Import main views module (main pages) from homepage import views # Import admin views from homepage import admin
""" hello/__init__.py ------------------ Initializes Flask application and brings all components together. """ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_misaka import Misaka # Create application object app = Flask(__name__, instance_relative_config=True, static_url_path='static', static_folder='staticfiles') # Load default configuration settings app.config.from_object('config.default') # Load non-VC configuration variables from instance folder app.config.from_pyfile('instance.cfg', silent=True) # Load settings specified by APP_CONFIG_FILE environment variable # (such as 'config.development' or 'config.production') # Variables defined here will override default configurations #app.config.from_envvar('APP_CONFIG_FILE', silent=True) # Disable Flask-SQLAlchemy event notification system. app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # Explicitly add debugger middleware if app.debug: from werkzeug.debug import DebuggedApplication app.wsgi_app = DebuggedApplication(app.wsgi_app, True) # Create SQLAlchemy object (database) db = SQLAlchemy(app) # Use Misaka for markdown templates Misaka(app) # Import main views module (main pages) from homepage import views # Import admin views from homepage import admin
Add queries.rate to the 'autoscaling' consumer.
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.admin.monitoring; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; /** * Metrics used for autoscaling * * @author bratseth */ public class AutoscalingMetrics { public static final MetricSet autoscalingMetricSet = create(); private static MetricSet create() { return new MetricSet("autoscaling", metrics("cpu.util", "mem.util", "disk.util", "application_generation", "in_service", "queries.rate")); } private static Set<Metric> metrics(String ... metrics) { return Arrays.stream(metrics).map(Metric::new).collect(Collectors.toSet()); } }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.admin.monitoring; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; /** * Metrics used for autoscaling * * @author bratseth */ public class AutoscalingMetrics { public static final MetricSet autoscalingMetricSet = create(); private static MetricSet create() { return new MetricSet("autoscaling", metrics("cpu.util", "mem.util", "disk.util", "application_generation", "in_service")); } private static Set<Metric> metrics(String ... metrics) { return Arrays.stream(metrics).map(Metric::new).collect(Collectors.toSet()); } }
:art: Throw TypeError instead of Error
import find from 'lodash.find'; import composedFetch from '../composedFetch.js'; export const sourcePostalPoint = id => composedFetch(id) .then(data => { const result = find(data.events, { key: `received.domestic-corner` }); return result.location.en; }) .catch(e => console.error(e)); export const destinationPostalPoint = id => composedFetch(id) .then(data => data.deliveryPoint.name.en) .catch(e => console.error(e)); export const destinationAsAddress = id => composedFetch(id) .then(data => { const obj = data.deliveryPoint; return `${obj.street.en} ${obj.streetNumber.en}, ${obj.postcode.en} ${obj.municipality.en}`; }) .catch(e => console.error(e)); export const openingHours = (id, day) => { if (!day) throw new TypeError(`Please specify a day`); return composedFetch(id) .then(data => { const obj = find( data.deliveryPoint.openingSchedules, { dayOfTheWeek: day.toUpperCase() } ); return obj.openingHours[0]; }) .catch(e => console.error(e)); }; export const destinationCoordinate = id => composedFetch(id) .then(data => { return { latitude: data.deliveryPoint.latitude, longitude: data.deliveryPoint.longitude, }; }) .catch(e => console.error(e));
import find from 'lodash.find'; import composedFetch from '../composedFetch.js'; export const sourcePostalPoint = id => composedFetch(id) .then(data => { const result = find(data.events, { key: `received.domestic-corner` }); return result.location.en; }) .catch(e => console.error(e)); export const destinationPostalPoint = id => composedFetch(id) .then(data => data.deliveryPoint.name.en) .catch(e => console.error(e)); export const destinationAsAddress = id => composedFetch(id) .then(data => { const obj = data.deliveryPoint; return `${obj.street.en} ${obj.streetNumber.en}, ${obj.postcode.en} ${obj.municipality.en}`; }) .catch(e => console.error(e)); export const openingHours = (id, day) => { if (!day) throw new Error(`Please specify a day`); return composedFetch(id) .then(data => { const obj = find( data.deliveryPoint.openingSchedules, { dayOfTheWeek: day.toUpperCase() } ); return obj.openingHours[0]; }) .catch(e => console.error(e)); }; export const destinationCoordinate = id => composedFetch(id) .then(data => { return { latitude: data.deliveryPoint.latitude, longitude: data.deliveryPoint.longitude, }; }) .catch(e => console.error(e));
Add fields to Special model
from django.db import models MAX_PRICE_FORMAT = { 'max_digits': 5, 'decimal_places': 2 } SPECIAL_TYPES = ( ('LU', 'Lunch'), ('BR', 'Breakfast'), ('DI', 'Dinner'), ) MAX_RESTAURANT_NAME_LENGTH = 50 MAX_DESCRIPTION_LENGTH = 500 class Restaurant(models.Model): name = models.CharField(max_length=MAX_RESTAURANT_NAME_LENGTH) description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH) def __unicode__(self): return self.name class Special(models.Model): restaurant = models.ForeignKey(Restaurant) description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH) special_type = models.CharField(max_length=2, choices=SPECIAL_TYPES) special_price = models.DecimalField(**MAX_PRICE_FORMAT) normal_price = models.DecimalField(**MAX_PRICE_FORMAT) valid_from = models.DateField() valid_until = models.DateField() def __unicode__(self): return "%s: %s" % (self.restaurant.name, self.description)
from django.db import models MAX_PRICE_FORMAT = { 'max_digits': 5, 'decimal_places': 2 } SPECIAL_TYPES = ( ('LU', 'Lunch'), ('BR', 'Breakfast'), ('DI', 'Dinner'), ) MAX_RESTAURANT_NAME_LENGTH = 50 MAX_DESCRIPTION_LENGTH = 500 class Restaurant(models.Model): name = models.CharField(max_length=MAX_RESTAURANT_NAME_LENGTH) description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH) class Special(models.Model): restaurant = models.ForeignKey(Restaurant) description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH) special_type = models.CharField(max_length=2, choices=SPECIAL_TYPES) special_price = models.DecimalField(**MAX_PRICE_FORMAT) normal_price = models.DecimalField(**MAX_PRICE_FORMAT)
Switch phone number to Environment Variable (instead of const)
// Sample Lambda Function to send notifications via text when an AWS Health event happens var AWS = require('aws-sdk'); var sns = new AWS.SNS(); //main function which gets AWS Health data from Cloudwatch event exports.handler = (event, context, callback) => { //get phone number from Env Variable var phoneNumber = process.env.PHONE_NUMBER; //extract details from Cloudwatch event eventName = event.detail.eventTypeCode healthMessage = 'The following AWS Health event type has occured: ' + eventName + ' For more details, please see https://phd.aws.amazon.com/phd/home?region=us-east-1#/dashboard/open-issues'; //prepare message for SNS to publish var snsPublishParams = { Message: healthMessage, PhoneNumber: phoneNumber, }; sns.publish(snsPublishParams, function(err, data) { if (err) { const snsPublishErrorMessage = `Error publishing AWS Health event to SNS`; console.log(snsPublishErrorMessage, err); callback(snsPublishErrorMessage); } else { const snsPublishSuccessMessage = `Successfully got details from AWS Health event, ${eventName} and sent SMS via SNS.`; console.log(snsPublishSuccessMessage, data); callback(null, snsPublishSuccessMessage); //return success } }); };
// Sample Lambda Function to send notifications via text when an AWS Health event happens var AWS = require('aws-sdk'); var sns = new AWS.SNS(); // define configuration const phoneNumber =''; // Insert phone number here. For example, a U.S. phone number in E.164 format would appear as +1XXX5550100 //main function which gets AWS Health data from Cloudwatch event exports.handler = (event, context, callback) => { //extract details from Cloudwatch event eventName = event.detail.eventTypeCode healthMessage = 'The following AWS Health event type has occured: ' + eventName + ' For more details, please see https://phd.aws.amazon.com/phd/home?region=us-east-1#/dashboard/open-issues'; //prepare message for SNS to publish var snsPublishParams = { Message: healthMessage, PhoneNumber: phoneNumber, }; sns.publish(snsPublishParams, function(err, data) { if (err) { const snsPublishErrorMessage = `Error publishing AWS Health event to SNS`; console.log(snsPublishErrorMessage, err); callback(snsPublishErrorMessage); } else { const snsPublishSuccessMessage = `Successfully got details from AWS Health event, ${eventName} and sent SMS via SNS.`; console.log(snsPublishSuccessMessage, data); callback(null, snsPublishSuccessMessage); //return success } }); };
Remove unique_together on the model; the key length was too long on wide-character MySQL installs.
from django.db import models class MigrationHistory(models.Model): app_name = models.CharField(max_length=255) migration = models.CharField(max_length=255) applied = models.DateTimeField(blank=True) @classmethod def for_migration(cls, migration): try: return cls.objects.get(app_name=migration.app_label(), migration=migration.name()) except cls.DoesNotExist: return cls(app_name=migration.app_label(), migration=migration.name()) def get_migrations(self): from south.migration.base import Migrations return Migrations(self.app_name) def get_migration(self): return self.get_migrations().migration(self.migration)
from django.db import models class MigrationHistory(models.Model): app_name = models.CharField(max_length=255) migration = models.CharField(max_length=255) applied = models.DateTimeField(blank=True) class Meta: unique_together = (('app_name', 'migration'),) @classmethod def for_migration(cls, migration): try: return cls.objects.get(app_name=migration.app_label(), migration=migration.name()) except cls.DoesNotExist: return cls(app_name=migration.app_label(), migration=migration.name()) def get_migrations(self): from south.migration.base import Migrations return Migrations(self.app_name) def get_migration(self): return self.get_migrations().migration(self.migration)
Update "A Plea for Colour Analysis Tools in DCC Applications" blog post div height.
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/html"> <head> <meta charset="utf-8"> <title>A Plea for Colour Analysis Tools in DCC Applications</title> <?php include ("common_header_attributes.php"); ?> </head> <body> <?php include_once("analytics_tracking.php") ?> <?php include ("navigation.php"); ?> <!-- >>> Content --> <div class="container"> <div class="row"> <!-- >>> Center --> <div class="col-md-9"> <div class="embed-responsive" style="height: 9550px;"> <iframe class="embed-responsive-item" src="ipython/a_plea_for_colour_analysis_tools_in_dcc_applications.html"></iframe> </div> <?php include("disqus.php") ?> </div> <!-- <<< Center --> <?php include ("sidebar.php"); ?> </div> </div> <!-- <<< Content --> <?php include ("footer.php"); ?> <?php include ("common_body_attributes.php"); ?> </body> </html>
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/html"> <head> <meta charset="utf-8"> <title>A Plea for Colour Analysis Tools in DCC Applications</title> <?php include ("common_header_attributes.php"); ?> </head> <body> <?php include_once("analytics_tracking.php") ?> <?php include ("navigation.php"); ?> <!-- >>> Content --> <div class="container"> <div class="row"> <!-- >>> Center --> <div class="col-md-9"> <div class="embed-responsive" style="height: 9600px;"> <iframe class="embed-responsive-item" src="ipython/a_plea_for_colour_analysis_tools_in_dcc_applications.html"></iframe> </div> <?php include("disqus.php") ?> </div> <!-- <<< Center --> <?php include ("sidebar.php"); ?> </div> </div> <!-- <<< Content --> <?php include ("footer.php"); ?> <?php include ("common_body_attributes.php"); ?> </body> </html>
Move oparl api from /api/v1/ to /api/oparl/v1
<?php /* @var Illuminate\Routing\Router $router */ $router->get('/', ['uses' => 'RootController@index', 'as' => 'api.index']); $router->group([ 'as' => 'api.v1.', 'domain' => 'dev.'.config('app.url'), 'prefix' => 'api/oparl/v1/', 'middleware' => ['track', 'bindings'], ], function () use ($router) { $apiOnlyIndexAndShow = ['only' => ['index', 'show']]; $router->resource('system', 'SystemController', $apiOnlyIndexAndShow); $router->resource('body', 'BodyController', $apiOnlyIndexAndShow); $router->resource('legislativeterm', 'LegislativeTermController', $apiOnlyIndexAndShow); $router->resource('agendaitem', 'AgendaItemController', $apiOnlyIndexAndShow); $router->resource('person', 'PersonController', $apiOnlyIndexAndShow); $router->resource('meeting', 'MeetingController', $apiOnlyIndexAndShow); $router->resource('organization', 'OrganizationController', $apiOnlyIndexAndShow); $router->resource('membership', 'MembershipController', $apiOnlyIndexAndShow); $router->resource('paper', 'PaperController', $apiOnlyIndexAndShow); $router->resource('consultation', 'ConsultationController', $apiOnlyIndexAndShow); $router->resource('location', 'LocationController', $apiOnlyIndexAndShow); $router->resource('file', 'FileController', $apiOnlyIndexAndShow); });
<?php /* @var Illuminate\Routing\Router $router */ $router->get('/', ['uses' => 'RootController@index', 'as' => 'api.index']); $router->group([ 'as' => 'api.v1.', 'domain' => 'dev.'.config('app.url'), 'prefix' => 'api/v1/', 'middleware' => ['track', 'bindings'], ], function () use ($router) { $apiOnlyIndexAndShow = ['only' => ['index', 'show']]; $router->resource('system', 'SystemController', $apiOnlyIndexAndShow); $router->resource('body', 'BodyController', $apiOnlyIndexAndShow); $router->resource('legislativeterm', 'LegislativeTermController', $apiOnlyIndexAndShow); $router->resource('agendaitem', 'AgendaItemController', $apiOnlyIndexAndShow); $router->resource('person', 'PersonController', $apiOnlyIndexAndShow); $router->resource('meeting', 'MeetingController', $apiOnlyIndexAndShow); $router->resource('organization', 'OrganizationController', $apiOnlyIndexAndShow); $router->resource('membership', 'MembershipController', $apiOnlyIndexAndShow); $router->resource('paper', 'PaperController', $apiOnlyIndexAndShow); $router->resource('consultation', 'ConsultationController', $apiOnlyIndexAndShow); $router->resource('location', 'LocationController', $apiOnlyIndexAndShow); $router->resource('file', 'FileController', $apiOnlyIndexAndShow); });
Allow servers command to work without a password.
from BaseController import BaseController from api.util import settings class ServerListController(BaseController): def get(self): servers = {"servers": self.read_server_config()} self.write(servers) def read_server_config(self): """Returns a list of servers with the 'id' field added. """ # TODO: Move this into the settings module so everything benefits. server_list = [] redis_servers = settings.get_redis_servers() for server in redis_servers: if 'password' not in server: server['password'] = None server_id = "%(server)s:%(port)s" % server s = dict(server=server['server'], port=server['port'], password=server['password'], id=server_id) server_list.append(s) return server_list
from BaseController import BaseController from api.util import settings class ServerListController(BaseController): def get(self): servers = {"servers": self.read_server_config()} self.write(servers) def read_server_config(self): """Returns a list of servers with the 'id' field added. """ # TODO: Move this into the settings module so everything benefits. server_list = [] redis_servers = settings.get_redis_servers() for server in redis_servers: server_id = "%(server)s:%(port)s" % server s = dict(server=server['server'], port=server['port'], password=server['password'], id=server_id) server_list.append(s) return server_list
Update exmple for node position in new RGG interface.
import networkx as nx import matplotlib.pyplot as plt G=nx.random_geometric_graph(200,0.125) # position is stored as node attribute data for random_geometric_graph pos=nx.get_node_attributes(G,'pos') # find node near center (0.5,0.5) dmin=1 ncenter=0 for n in pos: x,y=pos[n] d=(x-0.5)**2+(y-0.5)**2 if d<dmin: ncenter=n dmin=d # color by path length from node near center p=nx.single_source_shortest_path_length(G,ncenter) plt.figure(figsize=(8,8)) nx.draw_networkx_edges(G,pos,nodelist=[ncenter],alpha=0.4) nx.draw_networkx_nodes(G,pos,nodelist=p.keys(), node_size=80, node_color=p.values(), cmap=plt.cm.Reds_r) plt.xlim(-0.05,1.05) plt.ylim(-0.05,1.05) plt.axis('off') plt.savefig('random_geometric_graph.png') plt.show()
import networkx as nx import matplotlib.pyplot as plt G=nx.random_geometric_graph(200,0.125) pos=G.pos # position is stored as member data for random_geometric_graph # find node near center (0.5,0.5) dmin=1 ncenter=0 for n in pos: x,y=pos[n] d=(x-0.5)**2+(y-0.5)**2 if d<dmin: ncenter=n dmin=d # color by path length from node near center p=nx.single_source_shortest_path_length(G,ncenter) plt.figure(figsize=(8,8)) nx.draw_networkx_edges(G,pos,nodelist=[ncenter],alpha=0.4) nx.draw_networkx_nodes(G,pos,nodelist=p.keys(), node_size=80, node_color=p.values(), cmap=plt.cm.Reds_r) plt.xlim(-0.05,1.05) plt.ylim(-0.05,1.05) plt.axis('off') plt.savefig('random_geometric_graph.png') plt.show()
Change ConcreteCard test class params.
""" Created on Dec 04, 2016 @author: john papa Copyright 2016 John Papa. All rights reserved. This work is licensed under the MIT License. """ import unittest from cards.card import Card class Test_Card(unittest.TestCase): def setUp(self): self._suit = "clubs" self._rank = "10" self._card = ConcreteCard(suit=self._suit, rank=self._rank) def tearDown(self): pass def test_card_is_abstract_class(self): """ Test that the Card class is an abstract base class """ with self.assertRaises(TypeError): Card() def test_rank(self): """ Test 'rank' property returns correct rank. """ card = self._card self.assertEqual(card.rank, self._rank) def test_suit(self): """ Test 'suit' property returns correct suit. """ card = self._card self.assertEqual(card.suit, self._suit) class ConcreteCard(Card): def __init__(self, suit, rank): super().__init__(suit, rank) @property def value(self): pass if __name__ == "__main__": # import sys;sys.argv = ['', 'Test.testName'] unittest.main()
""" Created on Dec 04, 2016 @author: john papa Copyright 2016 John Papa. All rights reserved. This work is licensed under the MIT License. """ import unittest from cards.card import Card class Test_Card(unittest.TestCase): def setUp(self): self._suit = "clubs" self._rank = "10" self._card = ConcreteCard(suit=self._suit, rank=self._rank) def tearDown(self): pass def test_card_is_abstract_class(self): """ Test that the Card class is an abstract base class """ with self.assertRaises(TypeError): Card() def test_rank(self): """ Test 'rank' property returns correct rank. """ card = self._card self.assertEqual(card.rank, self._rank) def test_suit(self): """ Test 'suit' property returns correct suit. """ card = self._card self.assertEqual(card.suit, self._suit) class ConcreteCard(Card): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @property def value(self): pass if __name__ == "__main__": # import sys;sys.argv = ['', 'Test.testName'] unittest.main()
Change managerarea header app name to tenant name
<header class="main-header"> <!-- Logo --> <a href="#" class="logo" data-toggle="push-menu" role="button"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><i class="fa fa-home"></i></span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b>{{ $currentTenant->name }}</b></span> </a> <!-- Header Navbar: style can be found in header.less --> <nav class="navbar navbar-static-top"> <div class="navbar-custom-menu pull-left"> <ul class="nav navbar-nav"> <li><a href="{{ route('managerarea.home') }}"><i class="fa fa-home"></i> {{ trans('cortex/foundation::common.home') }}</a></li> </ul> </div> <div class="navbar-custom-menu"> {!! Menu::render('managerarea.header') !!} </div> </nav> </header>
<header class="main-header"> <!-- Logo --> <a href="#" class="logo" data-toggle="push-menu" role="button"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><i class="fa fa-home"></i></span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b>{{ config('app.name') }}</b></span> </a> <!-- Header Navbar: style can be found in header.less --> <nav class="navbar navbar-static-top"> <div class="navbar-custom-menu pull-left"> <ul class="nav navbar-nav"> <li><a href="{{ route('managerarea.home') }}"><i class="fa fa-home"></i> {{ trans('cortex/foundation::common.home') }}</a></li> </ul> </div> <div class="navbar-custom-menu"> {!! Menu::render('managerarea.header') !!} </div> </nav> </header>
Add auto detedt url from model scenario
<?php /* * X-editable extension for Yii2 * * @link https://github.com/hiqdev/yii2-x-editable * @package yii2-x-editable * @license BSD-3-Clause * @copyright Copyright (c) 2015, HiQDev (https://hiqdev.com/) */ namespace hiqdev\xeditable\widgets; use hiqdev\xeditable\traits\XEditableTrait; use yii\base\Widget; class XEditable extends Widget { use XEditableTrait; public $value; public $model; public $attribute; public function init() { parent::init(); $this->registerAssets(); $this->pluginOptions['url'] = (isset($this->pluginOptions['url']) && mb_strlen($this->pluginOptions['url']) > 0) ? : $this->model->getScenario(); } public function run() { return $this->prepareHtml([ 'value' => $this->value, 'model' => $this->model, 'attribute' => $this->attribute, 'pluginOptions' => $this->pluginOptions, ]); } }
<?php /* * X-editable extension for Yii2 * * @link https://github.com/hiqdev/yii2-x-editable * @package yii2-x-editable * @license BSD-3-Clause * @copyright Copyright (c) 2015, HiQDev (https://hiqdev.com/) */ namespace hiqdev\xeditable\widgets; use hiqdev\xeditable\traits\XEditableTrait; use yii\base\Widget; class XEditable extends Widget { use XEditableTrait; public $value; public $model; public $attribute; public function run() { return $this->prepareHtml([ 'value' => $this->value, 'model' => $this->model, 'attribute' => $this->attribute, 'pluginOptions' => $this->pluginOptions, ]); } }
Check for the existence of the resource cache key before attempting to make dirty
import { SET_RESOURCE, MARK_DASHBOARD_DIRTY, RESET_RESOURCE_CACHE } from './actions'; const markAllDirty = (keys, state) => { const dirty = {}; keys.forEach((key) => { if (state[key]) { dirty[key] = { ...state[key], dirty: true }; } }); return dirty; }; const resourceReducer = (state = {}, action) => { switch (action.type) { case MARK_DASHBOARD_DIRTY: return { ...state, ...markAllDirty(action.payload, state), }; case SET_RESOURCE: return { ...state, [action.payload.key]: action.payload.resource, }; case RESET_RESOURCE_CACHE: return {}; default: return state; } }; export default resourceReducer;
import { SET_RESOURCE, MARK_DASHBOARD_DIRTY, RESET_RESOURCE_CACHE } from './actions'; const markAllDirty = (keys, state) => { const dirty = {}; keys.forEach((key) => { dirty[key] = { ...state[key], dirty: true }; }); return dirty; }; const resourceReducer = (state = {}, action) => { switch (action.type) { case MARK_DASHBOARD_DIRTY: return { ...state, ...markAllDirty(action.payload, state), }; case SET_RESOURCE: return { ...state, [action.payload.key]: action.payload.resource, }; case RESET_RESOURCE_CACHE: return {}; default: return state; } }; export default resourceReducer;
Update typo references in table name var
<?php /** * Feed * * Class for handle feed operations. * * @author Ángel Guzmán Maeso <shakaran@gmail.com> * @since 0.1 */ class Feed { private static $table_name = 'ttrss_feeds'; public function __construct() { } /** * Check if the feeds table exist and it is available. * * It uses a legacy method with SHOW TABLES or a simple * select (limited) if the first method is not available. * * @param string $database_driver The driverdatabase type for queries * * @author Ángel Guzmán Maeso <shakaran@gmail.com> * * @return boolean TRUE if the table exists, or FALSE on error */ public static function existLegacyTable($database_driver = NULL) { global $link; // Try to search the table with first legacy detection method $result = db_query($link, "SHOW TABLES LIKE '" . self::$table_name . "'", $database_driver, FALSE); if(db_num_rows($result) == 1) { return TRUE; } else { // If there are restrictions or some problem, try a simple select method (with limited rows for avoid overhead) $result = db_query($link, "SELECT TRUE FROM " . self::$table_name . " LIMIT 1", $database_driver, FALSE); return db_num_rows($result) == 1; } } }
<?php /** * Feed * * Class for handle feed operations. * * @author Ángel Guzmán Maeso <shakaran@gmail.com> * @since 0.1 */ class Feed { private static $table_name = 'ttrss_feeds'; public function __construct() { } /** * Check if the feeds table exist and it is available. * * It uses a legacy method with SHOW TABLES or a simple * select (limited) if the first method is not available. * * @param string $database_driver The driverdatabase type for queries * @return boolean TRUE if the table exists, or FALSE on error */ public static function existLegacyTable($database_driver = NULL) { global $link; // Try to search the table with first legacy detection method $result = db_query($link, "SHOW TABLES LIKE '" . self::table_name . "'", $database_driver, FALSE); if(db_num_rows($result) == 1) { return TRUE; } else { // If there are restrictions or some problem, try a simple select method (with limited rows for avoid overhead) $result = db_query($link, "SELECT TRUE FROM " . self::table_name . " LIMIT 1", $database_driver, FALSE); return db_num_rows($result) == 1; } } }
Update build.gradle and fix compilation Signed-off-by: Steven Downer <e51bce9123e792aec8a98724fb48684dc936521f@outlook.com>
/** * This file is part of AlmuraSDK, All Rights Reserved. * * Copyright (c) 2015 AlmuraDev <http://github.com/AlmuraDev/> */ package com.almuradev.almurasdk.permissions; import java.util.HashSet; import java.util.Set; public class PermissibleAllMods implements Permissible { private Set<Permissible> permissibles = new HashSet<>(); public void addPermissible(Permissible permissible) { this.permissibles.add(permissible); } @Override public String getPermissibleModName() { return "all"; } @Override public float getPermissibleModVersion() { return 0.0F; } @Override public void registerPermissions(PermissionsManager permissionsManager) { } @Override public void onPermissionsCleared(PermissionsManager manager) { for (Permissible permissible : this.permissibles) { permissible.onPermissionsCleared(manager); } } @Override public void onPermissionsChanged(PermissionsManager manager) { for (Permissible permissible : this.permissibles) { permissible.onPermissionsChanged(manager); } } }
/** * This file is part of AlmuraSDK, All Rights Reserved. * * Copyright (c) 2015 AlmuraDev <http://github.com/AlmuraDev/> */ package com.almuradev.almurasdk.permissions; import java.util.HashSet; import java.util.Set; public class PermissibleAllMods implements Permissible { private Set<Permissible> permissibles = new HashSet<>(); public void addPermissible(Permissible permissible) { this.permissibles.add(permissible); } @Override public String getPermissibleModName() { return "all"; } @Override public float getPermissibleModVersion() { return 0.0F; } @Override public void registerPermissions(PermissionsManagerClient permissionsManager) { } @Override public void onPermissionsCleared(PermissionsManager manager) { for (Permissible permissible : this.permissibles) { permissible.onPermissionsCleared(manager); } } @Override public void onPermissionsChanged(PermissionsManager manager) { for (Permissible permissible : this.permissibles) { permissible.onPermissionsChanged(manager); } } }
BUG: Remove call of unimplemented method.
# Enthought library imports. from traits.api import Instance, on_trait_change from enaml.components.constraints_widget import ConstraintsWidget # local imports from pyface.tasks.editor import Editor class EnamlEditor(Editor): """ Create an Editor for Enaml Components. """ #### EnamlEditor interface ############################################## component = Instance(ConstraintsWidget) def create_component(self): raise NotImplementedError ########################################################################### # 'IEditor' interface. ########################################################################### def create(self, parent): self.component = self.create_component() self.component.setup(parent=parent) self.control = self.component.toolkit_widget def destroy(self): self.control = None self.component.destroy()
# Enthought library imports. from traits.api import Instance, on_trait_change from enaml.components.constraints_widget import ConstraintsWidget # local imports from pyface.tasks.editor import Editor class EnamlEditor(Editor): """ Create an Editor for Enaml Components. """ #### EnamlEditor interface ############################################## component = Instance(ConstraintsWidget) def create_component(self): raise NotImplementedError ########################################################################### # 'IEditor' interface. ########################################################################### def create(self, parent): self.component = self.create_component() self.component.setup(parent=parent) self.control = self.component.toolkit_widget self.component.on_trait_change(self.size_hint_changed, 'size_hint_updated') def destroy(self): self.control = None self.component.destroy()
Change port to 8080 to match with clevercloud requirement
require('zone.js/dist/zone-node'); require('reflect-metadata'); const express = require('express'); const fs = require('fs'); const { platformServer, renderModuleFactory } = require('@angular/platform-server'); const { ngExpressEngine } = require('@nguniversal/express-engine'); // Import module map for lazy loading const { provideModuleMap } = require('@nguniversal/module-map-ngfactory-loader'); // Import the AOT compiled factory for your AppServerModule. // This import will change with the hash of your built server bundle. const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require(`./dist-server/main.bundle`); const app = express(); const port = 8080; const baseUrl = `http://localhost:${port}`; // Set the engine app.engine('html', ngExpressEngine({ bootstrap: AppServerModuleNgFactory, providers: [ provideModuleMap(LAZY_MODULE_MAP) ] })); app.set('view engine', 'html'); app.set('views', './'); app.use('/', express.static('./', {index: false})); app.get('*', (req, res) => { res.render('index', { req, res }); }); app.listen(port, () => { console.log(`Listening at ${baseUrl}`); });
require('zone.js/dist/zone-node'); require('reflect-metadata'); const express = require('express'); const fs = require('fs'); const { platformServer, renderModuleFactory } = require('@angular/platform-server'); const { ngExpressEngine } = require('@nguniversal/express-engine'); // Import module map for lazy loading const { provideModuleMap } = require('@nguniversal/module-map-ngfactory-loader'); // Import the AOT compiled factory for your AppServerModule. // This import will change with the hash of your built server bundle. const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require(`./dist-server/main.bundle`); const app = express(); const port = 8000; const baseUrl = `http://localhost:${port}`; // Set the engine app.engine('html', ngExpressEngine({ bootstrap: AppServerModuleNgFactory, providers: [ provideModuleMap(LAZY_MODULE_MAP) ] })); app.set('view engine', 'html'); app.set('views', './'); app.use('/', express.static('./', {index: false})); app.get('*', (req, res) => { res.render('index', { req, res }); }); app.listen(port, () => { console.log(`Listening at ${baseUrl}`); });
Mark middleware class as nullsafe Reviewed By: defHLT Differential Revision: D24256184 fbshipit-source-id: cf0342d0ed800576ce0cad9a37bcd96d8483ae4a
package com.facebook.fresco.middleware; import android.graphics.PointF; import android.graphics.Rect; import android.net.Uri; import com.facebook.fresco.ui.common.ControllerListener2.Extras; import com.facebook.infer.annotation.Nullsafe; import java.util.Map; import javax.annotation.Nullable; @Nullsafe(Nullsafe.Mode.STRICT) public class MiddlewareUtils { public static Extras obtainExtras( Map<String, Object> componentAttribution, Map<String, Object> shortcutAttribution, @Nullable Map<String, Object> dataSourceExtras, @Nullable Rect viewportDimensions, @Nullable String scaleType, @Nullable PointF focusPoint, @Nullable Map<String, Object> imageExtras, @Nullable Object callerContext, @Nullable Uri mainUri) { final Extras extras = new Extras(); if (viewportDimensions != null) { extras.viewportWidth = viewportDimensions.width(); extras.viewportHeight = viewportDimensions.height(); } extras.scaleType = scaleType; if (focusPoint != null) { extras.focusX = focusPoint.x; extras.focusY = focusPoint.y; } extras.callerContext = callerContext; extras.mainUri = mainUri; extras.datasourceExtras = dataSourceExtras; extras.imageExtras = imageExtras; extras.shortcutExtras = shortcutAttribution; extras.componentExtras = componentAttribution; return extras; } }
package com.facebook.fresco.middleware; import android.graphics.PointF; import android.graphics.Rect; import android.net.Uri; import com.facebook.fresco.ui.common.ControllerListener2.Extras; import java.util.Map; import javax.annotation.Nullable; public class MiddlewareUtils { public static Extras obtainExtras( Map<String, Object> componentAttribution, Map<String, Object> shortcutAttribution, @Nullable Map<String, Object> dataSourceExtras, @Nullable Rect viewportDimensions, @Nullable String scaleType, @Nullable PointF focusPoint, @Nullable Map<String, Object> imageExtras, @Nullable Object callerContext, @Nullable Uri mainUri) { final Extras extras = new Extras(); if (viewportDimensions != null) { extras.viewportWidth = viewportDimensions.width(); extras.viewportHeight = viewportDimensions.height(); } extras.scaleType = scaleType; if (focusPoint != null) { extras.focusX = focusPoint.x; extras.focusY = focusPoint.y; } extras.callerContext = callerContext; extras.mainUri = mainUri; extras.datasourceExtras = dataSourceExtras; extras.imageExtras = imageExtras; extras.shortcutExtras = shortcutAttribution; extras.componentExtras = componentAttribution; return extras; } }
Use bedrock instead of polished andesite
const Vec3 = require('vec3').Vec3 const rand = require('random-seed') function generation ({ version, seed, level = 50 } = {}) { const Chunk = require('prismarine-chunk')(version) const mcData = require('minecraft-data')(version) function generateChunk (chunkX, chunkZ) { const seedRand = rand.create(seed + ':' + chunkX + ':' + chunkZ) const chunk = new Chunk() for (let x = 0; x < 16; x++) { for (let z = 0; z < 16; z++) { const bedrockheighttop = 1 + seedRand(4) const bedrockheightbottom = 1 + seedRand(4) for (let y = 0; y < 128; y++) { // Nether only goes up to 128 let block let data if (y < bedrockheightbottom) block = mcData.blocksByName.bedrock.id else if (y < level) block = seedRand(50) === 0 ? mcData.blocksByName.glowstone.id : mcData.blocksByName.netherrack.id else if (y > 127 - bedrockheighttop) block = mcData.blocksByName.bedrock.id const pos = new Vec3(x, y, z) if (block) chunk.setBlockType(pos, block) if (data) chunk.setBlockData(pos, data) // Don't need to set light data in nether } } } return chunk } return generateChunk } module.exports = generation
const Vec3 = require('vec3').Vec3 const rand = require('random-seed') function generation ({ version, seed, level = 50 } = {}) { const Chunk = require('prismarine-chunk')(version) const mcData = require('minecraft-data')(version) function generateChunk (chunkX, chunkZ) { const seedRand = rand.create(seed + ':' + chunkX + ':' + chunkZ) const chunk = new Chunk() for (let x = 0; x < 16; x++) { for (let z = 0; z < 16; z++) { const bedrockheighttop = 1 + seedRand(4) const bedrockheightbottom = 1 + seedRand(4) for (let y = 0; y < 128; y++) { // Nether only goes up to 128 let block let data if (y < bedrockheightbottom) block = 7 else if (y < level) block = seedRand(50) === 0 ? mcData.blocksByName.glowstone.id : mcData.blocksByName.netherrack.id else if (y > 127 - bedrockheighttop) block = mcData.blocksByName.bedrock.id const pos = new Vec3(x, y, z) if (block) chunk.setBlockType(pos, block) if (data) chunk.setBlockData(pos, data) // Don't need to set light data in nether } } } return chunk } return generateChunk } module.exports = generation
Update comments on the built-in file types
import build_inputs from path import Path class SourceFile(build_inputs.File): def __init__(self, name, source=Path.srcdir, lang=None): build_inputs.File.__init__(self, name, source=source) self.lang = lang class HeaderFile(build_inputs.File): install_kind = 'data' install_root = Path.includedir class HeaderDirectory(build_inputs.Directory): install_root = Path.includedir class ObjectFile(build_inputs.File): def __init__(self, name, source=Path.builddir, lang=None): build_inputs.File.__init__(self, name, source) self.lang = lang class Binary(build_inputs.File): install_kind = 'program' class Executable(Binary): install_root = Path.bindir class Library(Binary): install_root = Path.libdir def __init__(self, lib_name, name, source=Path.builddir): Binary.__init__(self, name, source) self.lib_name = lib_name class StaticLibrary(Library): pass class SharedLibrary(Library): pass # Used for Windows DLL files, which aren't linked to directly. Import libraries # are handled via SharedLibrary above. class DynamicLibrary(Library): pass class ExternalLibrary(Library): def __init__(self, name): # TODO: Keep track of the external lib's actual location on the # filesystem? Library.__init__(self, name, name)
import build_inputs from path import Path class SourceFile(build_inputs.File): def __init__(self, name, source=Path.srcdir, lang=None): build_inputs.File.__init__(self, name, source=source) self.lang = lang class HeaderFile(build_inputs.File): install_kind = 'data' install_root = Path.includedir class HeaderDirectory(build_inputs.Directory): install_root = Path.includedir class ObjectFile(build_inputs.File): def __init__(self, name, source=Path.builddir, lang=None): build_inputs.File.__init__(self, name, source) self.lang = lang class Binary(build_inputs.File): install_kind = 'program' class Executable(Binary): install_root = Path.bindir class Library(Binary): install_root = Path.libdir def __init__(self, lib_name, name, source=Path.builddir): Binary.__init__(self, name, source) self.lib_name = lib_name class StaticLibrary(Library): pass class SharedLibrary(Library): pass # Used for Windows DLL files, which aren't linked to directly. class DynamicLibrary(Library): pass class ExternalLibrary(Library): def __init__(self, name): # TODO: Handle import libraries specifically? Library.__init__(self, name, name)
Use suggestedType instead of value.getClass()
package com.github.ferstl.depgraph.graph.style; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import com.fasterxml.jackson.databind.DatabindContext; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase; import com.fasterxml.jackson.databind.type.SimpleType; class NodeTypeResolver extends TypeIdResolverBase { @Override public JavaType typeFromId(DatabindContext context, String id) { try { return SimpleType.constructUnsafe(Class.forName(getClass().getPackage().getName() + "." + id.substring(0, 1).toUpperCase() + id.substring(1))); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } @Override public String idFromValue(Object value) { return idFromValueAndType(value, value != null ? value.getClass() : Box.class); } @Override public String idFromValueAndType(Object value, Class<?> suggestedType) { return suggestedType.getSimpleName().toLowerCase(); } @Override public Id getMechanism() { return Id.CUSTOM; } }
package com.github.ferstl.depgraph.graph.style; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import com.fasterxml.jackson.databind.DatabindContext; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase; import com.fasterxml.jackson.databind.type.SimpleType; class NodeTypeResolver extends TypeIdResolverBase { @Override public JavaType typeFromId(DatabindContext context, String id) { try { return SimpleType.constructUnsafe(Class.forName(getClass().getPackage().getName() + "." + id.substring(0, 1).toUpperCase() + id.substring(1))); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } @Override public String idFromValue(Object value) { return idFromValueAndType(value, value.getClass()); } @Override public String idFromValueAndType(Object value, Class<?> suggestedType) { return value.getClass().getSimpleName().toLowerCase(); } @Override public Id getMechanism() { return Id.CUSTOM; } }
Remove incorrect remark about Postgres 9.5
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0005_instance_xml_hash'), ] # Because some servers already have these modifications applied by Django South migration, # we need to delete old indexes to let django recreate them according to Django migration requirements. # # see old migration in onadata/apps/logger/south_migrations/0032_index_uuid.py operations = [ migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_xform_uuid_idx;" ), migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_instance_uuid_idx;" ), migrations.AlterField( model_name='instance', name='uuid', field=models.CharField(default='', max_length=249, db_index=True), ), migrations.AlterField( model_name='xform', name='uuid', field=models.CharField(default='', max_length=32, db_index=True), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0005_instance_xml_hash'), ] # This custom migration must be run on Postgres 9.5+. # Because some servers already have these modifications applied by Django South migration, # we need to delete old indexes to let django recreate them according to Django migration requirements. # # see old migration in onadata/apps/logger/south_migrations/0032_index_uuid.py operations = [ migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_xform_uuid_idx;" ), migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_instance_uuid_idx;" ), migrations.AlterField( model_name='instance', name='uuid', field=models.CharField(default='', max_length=249, db_index=True), ), migrations.AlterField( model_name='xform', name='uuid', field=models.CharField(default='', max_length=32, db_index=True), ), ]
Clone repository to playbooks directory
from django.db import models from django.conf import settings import git, os class Github (models.Model): username = models.CharField(max_length=39) repository = models.CharField(max_length=100) def __str__(self): return self.repository def clone_repository(self): DIR_NAME = os.path.join(settings.PLAYBOOK_DIR, self.repository) REMOTE_URL = "https://github.com/{0}/{1}.git".format(self.username, self.repository) os.mkdir(os.path.join(DIR_NAME)) repo = git.Repo.init(DIR_NAME) origin = repo.create_remote('origin', REMOTE_URL) origin.fetch() origin.pull(origin.refs[0].remote_head) def save(self, *args, **kwargs): self.clone_repository() super(Github, self).save(*args, **kwargs) class Meta: verbose_name_plural = "projects"
from django.db import models import git, os class Github (models.Model): username = models.CharField(max_length=39) repository = models.CharField(max_length=100) def __str__(self): return self.repository def clone_repository(self): DIR_NAME = self.repository REMOTE_URL = "https://github.com/{0}/{1}.git".format(self.username, self.repository) os.mkdir(DIR_NAME) repo = git.Repo.init(DIR_NAME) origin = repo.create_remote('origin', REMOTE_URL) origin.fetch() origin.pull(origin.refs[0].remote_head) def save(self, *args, **kwargs): self.clone_repository() super(Github, self).save(*args, **kwargs) class Meta: verbose_name_plural = "projects"
Set the coutdown min and sec values to 00 when the deadline time has been reached.
$(document).ready(function(){ $('.log-btn').click(function(){ $('.log-status').addClass('wrong-entry'); $('.alert').fadeIn(500); setTimeout( "$('.alert').fadeOut(1500);",3000 ); }); $('.form-control').keypress(function(){ $('.log-status').removeClass('wrong-entry'); }); }); function getTimeRemaining(endtime) { var t = Date.parse(endtime) - Date.parse(new Date()); var seconds = Math.floor((t / 1000) % 60); var minutes = Math.floor((t / 1000 / 60) % 60); return { 'total': t, 'minutes': minutes, 'seconds': seconds }; } function initializeClock(id, endtime) { var clock = document.getElementById(id); var minutesSpan = clock.querySelector('.minutes'); var secondsSpan = clock.querySelector('.seconds'); function updateClock() { var t = getTimeRemaining(endtime); minutesSpan.innerHTML = ('0' + t.minutes).slice(-2); secondsSpan.innerHTML = ('0' + t.seconds).slice(-2); if (t.total <= 0) { minutesSpan.innerHTML = ('00'); secondsSpan.innerHTML = ('00'); clearInterval(timeinterval); } } updateClock(); var timeinterval = setInterval(updateClock, 1000); } var deadline = new Date(Date.parse(time)); initializeClock('clockdiv', deadline)
$(document).ready(function(){ $('.log-btn').click(function(){ $('.log-status').addClass('wrong-entry'); $('.alert').fadeIn(500); setTimeout( "$('.alert').fadeOut(1500);",3000 ); }); $('.form-control').keypress(function(){ $('.log-status').removeClass('wrong-entry'); }); }); function getTimeRemaining(endtime) { var t = Date.parse(endtime) - Date.parse(new Date()); var seconds = Math.floor((t / 1000) % 60); var minutes = Math.floor((t / 1000 / 60) % 60); return { 'total': t, 'minutes': minutes, 'seconds': seconds }; } function initializeClock(id, endtime) { var clock = document.getElementById(id); var minutesSpan = clock.querySelector('.minutes'); var secondsSpan = clock.querySelector('.seconds'); function updateClock() { var t = getTimeRemaining(endtime); minutesSpan.innerHTML = ('0' + t.minutes).slice(-2); secondsSpan.innerHTML = ('0' + t.seconds).slice(-2); if (t.total <= 0) { clearInterval(timeinterval); } } updateClock(); var timeinterval = setInterval(updateClock, 1000); } var deadline = new Date(Date.parse(time)); initializeClock('clockdiv', deadline)
Fix spelling of my name
# 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 __future__ import absolute_import, division, print_function __all__ = [ "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ] __title__ = "cryptography" __summary__ = ("cryptography is a package designed to expose cryptographic " "primitives and recipes to Python developers.") __uri__ = "https://github.com/alex/cryptography" __version__ = "0.1.dev1" __author__ = ("Alex Gaynor, Donald Stufft, Laurens van Houvten, " "Jean-Paul Calderone, Christian Heimes, and Indivdual " "Contributors") __email__ = "cryptography-dev@python.org" __license__ = "Apache License, Version 2.0" __copyright__ = "Copyright 2013 Donald Stufft"
# 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 __future__ import absolute_import, division, print_function __all__ = [ "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ] __title__ = "cryptography" __summary__ = ("cryptography is a package designed to expose cryptographic " "primitives and recipes to Python developers.") __uri__ = "https://github.com/alex/cryptography" __version__ = "0.1.dev1" __author__ = ("Alex Gaynor, Donald Stufft, Laurens van Houvten, " "Jean-Paul Calderone, Chris Heime, and Indivdual Contributors") __email__ = "cryptography-dev@python.org" __license__ = "Apache License, Version 2.0" __copyright__ = "Copyright 2013 Donald Stufft"
Add log for force option in buildAddons task
var fs = require('fs'); var path = require('path'); var _ = require('underscore'); var addonsManager = require('../core/cb.addons/manager'); module.exports = function(grunt) { grunt.registerMultiTask('buildAddons', 'Build default add-ons', function() { var done = this.async(); _.defaults(this.data, { force: true }); var folder = this.data.addonsFolder; var force = this.data.force; grunt.log.writeln("Building addons in "+folder+" (force="+force+")"); addonsManager.loadAddonsInfos({}, folder) .then(addonsManager.runAddonsOperation(function(addon) { return addon.optimizeClient(force); }, { failOnError: false })) .then(function() { done(); }, function(err) { grunt.log.error(err); done(false); }); }); };
var fs = require('fs'); var path = require('path'); var _ = require('underscore'); var addonsManager = require('../core/cb.addons/manager'); module.exports = function(grunt) { grunt.registerMultiTask('buildAddons', 'Build default add-ons', function() { var done = this.async(); _.defaults(this.data, { force: true }); var folder = this.data.addonsFolder; var force = this.data.force; grunt.log.writeln("Building addons in "+folder); addonsManager.loadAddonsInfos({}, folder) .then(addonsManager.runAddonsOperation(function(addon) { return addon.optimizeClient(force); }, { failOnError: false })) .then(function() { done(); }, function(err) { grunt.log.error(err); done(false); }); }); };
Use analytics name for subreddits if available. This allows a catch-all for multis to be used.
from urllib import quote from pylons import c, g from r2.lib.pages import Ads as BaseAds class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) adzerk_all_the_things = g.live_config.get("adzerk_all_the_things") adzerk_srs = g.live_config.get("adzerk_srs") in_adzerk_sr = adzerk_srs and c.site.name.lower() in adzerk_srs if adzerk_all_the_things or in_adzerk_sr: url_key = "adzerk_https_url" if c.secure else "adzerk_url" site_name = getattr(c.site, "analytics_name", c.site.name) self.ad_url = g.config[url_key].format( subreddit=quote(site_name.lower()), origin=c.request_origin, ) self.frame_id = "ad_main"
from urllib import quote from pylons import c, g from r2.lib.pages import Ads as BaseAds class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) adzerk_all_the_things = g.live_config.get("adzerk_all_the_things") adzerk_srs = g.live_config.get("adzerk_srs") in_adzerk_sr = adzerk_srs and c.site.name.lower() in adzerk_srs if adzerk_all_the_things or in_adzerk_sr: url_key = "adzerk_https_url" if c.secure else "adzerk_url" self.ad_url = g.config[url_key].format( subreddit=quote(c.site.name.lower()), origin=c.request_origin, ) self.frame_id = "ad_main"
Make it more robust - don't error if setting is not present.
var config = require('../../util/config').config; /** * Return true if key starts with a prefixed defined in prefixes. * * @param {String} key Key name. * @param {Array} prefixes Prefixes. * @return {Boolean} true if the key starts with a prefix, false otherwise. */ function startsWithPrefix(key, prefixes) { var i, prefix; for (i = 0; i < prefixes.length; i++) { prefix = prefixes[i]; if (key.indexOf(prefix) === 0) { return true; } } return false; } exports.processResponse = function(req, res, callback) { var settings = config.middleware.header_remover, prefixes = settings.prefixes || [], key; if (prefixes.length === 0) { callback(); return; } for (key in res.headers) { if (res.headers.hasOwnProperty(key) && startsWithPrefix(key, prefixes)) { delete res.headers[key]; } } callback(); };
var config = require('../../util/config').config; /** * Return true if key starts with a prefixed defined in prefixes. * * @param {String} key Key name. * @param {Array} prefixes Prefixes. * @return {Boolean} true if the key starts with a prefix, false otherwise. */ function startsWithPrefix(key, prefixes) { var i, prefix; for (i = 0; i < prefixes.length; i++) { prefix = prefixes[i]; if (key.indexOf(prefix) === 0) { return true; } } return false; } exports.processResponse = function(req, res, callback) { var settings = config.middleware.header_remover, key; if (settings.prefixes.length === 0) { callback(); return; } for (key in res.headers) { if (res.headers.hasOwnProperty(key) && startsWithPrefix(key, settings.prefixes)) { delete res.headers[key]; } } callback(); };
Handle the case where the bucket already exists
from boto.s3.connection import S3Connection from boto.s3.bucket import Bucket from boto.exception import S3ResponseError, S3CreateError from django.conf import settings def upload(user, passwd, bucket, metadata, key, fd): conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False) while bucket.endswith('-'): bucket = bucket[:-1] try: bucket = conn.get_bucket(bucket) except S3ResponseError: try: bucket = conn.create_bucket(bucket, headers=metadata) except (S3ResponseError, UnicodeDecodeError): bucket = conn.create_bucket(bucket) except S3CreateError as e: if e.status == 409: bucket = Bucket(conn, bucket) key = bucket.new_key(key) try: key.set_contents_from_file(fd) except S3ResponseError: key.set_contents_from_file(fd) return key.generate_url(0).split('?')[0]
from boto.s3.connection import S3Connection from boto.exception import S3ResponseError from django.conf import settings def upload(user, passwd, bucket, metadata, key, fd): conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False) while bucket.endswith('-'): bucket = bucket[:-1] try: bucket = conn.get_bucket(bucket) except S3ResponseError: try: bucket = conn.create_bucket(bucket, headers=metadata) except (S3ResponseError, UnicodeDecodeError): bucket = conn.create_bucket(bucket) key = bucket.new_key(key) try: key.set_contents_from_file(fd) except S3ResponseError: key.set_contents_from_file(fd) return key.generate_url(0).split('?')[0]
Fix typo in setting up dropbox api
import dropboxFs from 'dropbox-fs' import fs from 'fs' import { promisify } from 'util' import { dropboxApiKey } from '../config' export const readFile = (...options) => { return dropboxApiKey ? dropboxReadFile(...options) : fsReadFile(...options) } export const writeFile = (...options) => { return dropboxApiKey ? dropboxWriteFile(...options) : fsWriteFile(...options) } const dfs = (dropboxApiKey) => { return dropboxFs({ apiKey: dropboxApiKey, }) } const dropboxReadFile = (path) => { return dfs(dropboxApiKey).readFile(`/${path}`, { encoding: 'utf8' }) } const dropboxWriteFile = (path, content) => { return dfs(dropboxApiKey).writeFile(`/${path}`, content, { encoding: 'utf8' }) } const fsReadFile = (path) => { const readFile = promisify(fs.readFile) return readFile(path, { encoding: 'utf8' }).catch((error) => { if (error.status === 409 && error.error.indexOf('not_found') !== -1) { error.code = 'ENOENT' } throw error }) } const fsWriteFile = (path, content) => { const writeFile = promisify(fs.writeFile) return writeFile(path, content, { encoding: 'utf8' }) }
import dropboxFs from 'dropbox-fs' import fs from 'fs' import { promisify } from 'util' import { dropboxApiKey } from '../config' export const readFile = (...options) => { return dropboxApiKey ? dropboxReadFile(...options) : fsReadFile(...options) } export const writeFile = (...options) => { return dropboxApiKey ? dropboxWriteFile(...options) : fsWriteFile(...options) } const dfs = (dropboxApiKey) => { return dropboxFs({ apikey: dropboxApiKey, }) } const dropboxReadFile = (path) => { return dfs(dropboxApiKey).readFile(`/${path}`, { encoding: 'utf8' }) } const dropboxWriteFile = (path, content) => { return dfs(dropboxApiKey).writeFile(`/${path}`, content, { encoding: 'utf8' }) } const fsReadFile = (path) => { const readFile = promisify(fs.readFile) return readFile(path, { encoding: 'utf8' }).catch((error) => { if (error.status === 409 && error.error.indexOf('not_found') !== -1) { error.code = 'ENOENT' } throw error }) } const fsWriteFile = (path, content) => { const writeFile = promisify(fs.writeFile) return writeFile(path, content, { encoding: 'utf8' }) }
Add required "navigation" module dependency (for ClientIdentifier).
/* * Copyright (C) 2015 Glyptodon LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Module which augments Guacamole's existing URL routing, adding support for * legacy-style client URLs (the format used in 0.9.7 and older). */ angular.module('legacyUrl', [ 'auth', 'navigation' ]); // Include legacyUrl module in index module dependencies, such that the // existing routing can be modified angular.module('index').requires.push('legacyUrl');
/* * Copyright (C) 2015 Glyptodon LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Module which augments Guacamole's existing URL routing, adding support for * legacy-style client URLs (the format used in 0.9.7 and older). */ angular.module('legacyUrl', [ 'auth' ]); // Include legacyUrl module in index module dependencies, such that the // existing routing can be modified angular.module('index').requires.push('legacyUrl');
Add stress test for wrapping stdout
import sys import time import logging log = logging.getLogger(__name__) # test cases def test_test(): for i in range(200): print "Mu! {0}".format(i) print 'WHEE' * 100 assert False def test_test2(): assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHER_IS_A_NICE_LADY def test(): assert True def test_test_test_test_test_test_test_test_test_test_test_test_test_test_test(): assert False def test_test3(): assert False def test_test4(): time.sleep(1) assert False def test_test5(): assert False def test_test6(): assert False def test_test7(): assert False def test_test8(): assert False def test_test9(): assert False def test_test10(): assert False def mu_test(): print "BANG BANG" sys.stderr.write("MU\n") log.debug('DANG') assert aoeu
import sys import time import logging log = logging.getLogger(__name__) # test cases def test_test(): for i in range(200): print "Mu! {0}".format(i) assert False def test_test2(): assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHER_IS_A_NICE_LADY def test(): assert True def test_test_test_test_test_test_test_test_test_test_test_test_test_test_test(): assert False def test_test3(): assert False def test_test4(): time.sleep(1) assert False def test_test5(): assert False def test_test6(): assert False def test_test7(): assert False def test_test8(): assert False def test_test9(): assert False def test_test10(): assert False def mu_test(): print "BANG BANG" sys.stderr.write("MU\n") log.debug('DANG') assert aoeu
Remove unnecessary redirect in NotesController.
(function() { angular.module('notely.notes', [ 'ui.router' ]) .controller('NotesController', NotesController) .config(notesConfig); notesConfig['$inject'] = ['$stateProvider']; function notesConfig($stateProvider) { $stateProvider .state('notes', { url: '/notes', abstract: true, templateUrl: '/notes/notes.html', controller: NotesController }) .state('notes.form', { url: '/{noteId}', templateUrl: '/notes/notes-form.html' }); } NotesController['$inject'] = ['$scope', '$state', 'notes']; function NotesController($scope, $state, notesService) { notesService.fetchNotes(function(notes) { $scope.notes = notes; }); } })();
(function() { angular.module('notely.notes', [ 'ui.router' ]) .controller('NotesController', NotesController) .config(notesConfig); notesConfig['$inject'] = ['$stateProvider']; function notesConfig($stateProvider) { $stateProvider .state('notes', { url: '/notes', abstract: true, templateUrl: '/notes/notes.html', controller: NotesController }) .state('notes.form', { url: '/{noteId}', templateUrl: '/notes/notes-form.html' }); } NotesController['$inject'] = ['$scope', '$state', 'notes']; function NotesController($scope, $state, notesService) { notesService.fetchNotes(function(notes) { $scope.notes = notes; }); $state.go('notes.form'); } })();
Check if hierarchySeparator presents in the options object
import addons from '@storybook/addons'; import { EVENT_ID } from '../shared'; // init function will be executed once when the storybook loads for the // first time. This is a good place to add global listeners on channel. export function init() { // NOTE nothing to do here } function regExpStringify(exp) { if (typeof exp === 'string') return exp; if (Object.prototype.toString.call(exp) === '[object RegExp]') return exp.source; return null; } // setOptions function will send Storybook UI options when the channel is // ready. If called before, options will be cached until it can be sent. export function setOptions(newOptions) { const channel = addons.getChannel(); if (!channel) { throw new Error( 'Failed to find addon channel. This may be due to https://github.com/storybooks/storybook/issues/1192.' ); } let options = newOptions; // since 'undefined' and 'null' are the valid values we don't want to // override the hierarchySeparator if the prop is missing if (Object.prototype.hasOwnProperty.call(newOptions, 'hierarchySeparator')) { options = { ...newOptions, hierarchySeparator: regExpStringify(newOptions.hierarchySeparator), }; } channel.emit(EVENT_ID, { options }); }
import addons from '@storybook/addons'; import { EVENT_ID } from '../shared'; // init function will be executed once when the storybook loads for the // first time. This is a good place to add global listeners on channel. export function init() { // NOTE nothing to do here } function regExpStringify(exp) { if (typeof exp === 'string') return exp; if (Object.prototype.toString.call(exp) === '[object RegExp]') return exp.source; return null; } // setOptions function will send Storybook UI options when the channel is // ready. If called before, options will be cached until it can be sent. export function setOptions(newOptions) { const channel = addons.getChannel(); if (!channel) { throw new Error( 'Failed to find addon channel. This may be due to https://github.com/storybooks/storybook/issues/1192.' ); } const options = { ...newOptions, hierarchySeparator: regExpStringify(newOptions.hierarchySeparator), }; channel.emit(EVENT_ID, { options }); }
Migrate from Folly Format to fmt Summary: Migrate from Folly Format to fmt which provides smaller compile times and per-call binary code size. Reviewed By: alandau Differential Revision: D14954926 fbshipit-source-id: 9d2c39e74a5d11e0f90c8ad0d71b79424c56747f
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import specs.folly as folly import specs.fizz as fizz import specs.fmt as fmt import specs.rsocket as rsocket import specs.sodium as sodium import specs.wangle as wangle import specs.zstd as zstd from shell_quoting import ShellQuoted def fbcode_builder_spec(builder): # This API should change rarely, so build the latest tag instead of master. builder.add_option( 'no1msd/mstch:git_hash', ShellQuoted('$(git describe --abbrev=0 --tags)') ) return { 'depends_on': [folly, fizz, fmt, sodium, rsocket, wangle, zstd], 'steps': [ # This isn't a separete spec, since only fbthrift uses mstch. builder.github_project_workdir('no1msd/mstch', 'build'), builder.cmake_install('no1msd/mstch'), builder.fb_github_cmake_install('fbthrift/thrift'), ], }
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import specs.folly as folly import specs.fizz as fizz import specs.rsocket as rsocket import specs.sodium as sodium import specs.wangle as wangle import specs.zstd as zstd from shell_quoting import ShellQuoted def fbcode_builder_spec(builder): # This API should change rarely, so build the latest tag instead of master. builder.add_option( 'no1msd/mstch:git_hash', ShellQuoted('$(git describe --abbrev=0 --tags)') ) return { 'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd], 'steps': [ # This isn't a separete spec, since only fbthrift uses mstch. builder.github_project_workdir('no1msd/mstch', 'build'), builder.cmake_install('no1msd/mstch'), builder.fb_github_cmake_install('fbthrift/thrift'), ], }
Fix flake8 issue and fix up documentation
#! /usr/bin/env python # -*- mode: python; coding: utf-8 -*- # Copyright 2017 the HERA Collaboration # Licensed under the 2-clause BSD license. import numpy as np from astropy.time import Time from pyuvdata import UVData from hera_mc import mc a = mc.get_mc_argument_parser() a.description = """Read the obsid from a file and create a record in M&C.""" a.add_argument('files', metavar='file', type=str, nargs='*', default=[], help='*.uvh5 files to add') args = a.parse_args() db = mc.connect_to_mc_db(args) for uvfile in args.files: # assume our data file is uvh5 uv = UVData() uv.read_uvh5(uvfile, read_data=False) times = np.unique(uv.time_array) starttime = Time(times[0], scale='utc', format='jd') stoptime = Time(times[-1], scale='utc', format='jd') obsid = int(np.floor(starttime.gps)) with db.sessionmaker() as session: obs = session.get_obs(obsid) if len(obs) > 0: print("observation {obs} already in M&C, skipping".format(obs=obsid)) continue print("Inserting obsid into M&C:" + str(obsid)) session.add_obs(starttime, stoptime, obsid) session.commit()
#! /usr/bin/env python # -*- mode: python; coding: utf-8 -*- # Copyright 2017 the HERA Collaboration # Licensed under the 2-clause BSD license. import os import numpy as np from astropy.time import Time from pyuvdata import UVData from hera_mc import mc a = mc.get_mc_argument_parser() a.description = """Read the obsid from a file and create a record in M&C.""" a.add_argument('files', metavar='file', type=str, nargs='*', default=[], help='*.uv files to extract') args = a.parse_args() db = mc.connect_to_mc_db(args) for uvfile in args.files: # assume our data file is uvh5 uv = UVData() uv.read_uvh5(uvfile, read_data=False) times = np.unique(uv.time_array) starttime = Time(times[0], scale='utc', format='jd') stoptime = Time(times[-1], scale='utc', format='jd') obsid = int(np.floor(starttime.gps)) with db.sessionmaker() as session: obs = session.get_obs(obsid) if len(obs) > 0: print("observation {obs} already in M&C, skipping".format(obs=obsid)) continue print("Inserting obsid into M&C:" + str(obsid)) session.add_obs(starttime, stoptime, obsid) session.commit()
Revert change 00342e052b17 to fix sshlibrary on standalone jar. Update issue 1311 Status: Done Revert change 00342e052b17 to fix sshlibrary on standalone jar.
/* Copyright 2008-2012 Nokia Siemens Networks Oyj * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.robotframework; import org.python.core.PyObject; import org.python.util.PythonInterpreter; /** * * Helper class to create an Jython object and coerce it so that it can be used * from Java. * */ public class RunnerFactory { private PyObject runnerClass; public RunnerFactory() { runnerClass = importRunnerClass(); } private PyObject importRunnerClass() { PythonInterpreter interpreter = new PythonInterpreter(); interpreter.exec("import robot; from robot.jarrunner import JarRunner"); return interpreter.get("JarRunner"); } /** * Creates and returns an instance of the robot.JarRunner (implemented in * Python), which can be used to execute tests. */ public RobotRunner createRunner() { PyObject runnerObject = runnerClass.__call__(); return (RobotRunner) runnerObject.__tojava__(RobotRunner.class); } }
/* Copyright 2008-2012 Nokia Siemens Networks Oyj * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.robotframework; import org.python.core.PyObject; import org.python.core.PySystemState; import org.python.util.PythonInterpreter; /** * * Helper class to create an Jython object and coerce it so that it can be used * from Java. * */ public class RunnerFactory { private PyObject runnerClass; public RunnerFactory() { runnerClass = importRunnerClass(); } private PyObject importRunnerClass() { PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState()); interpreter.exec("import robot; from robot.jarrunner import JarRunner"); return interpreter.get("JarRunner"); } /** * Creates and returns an instance of the robot.JarRunner (implemented in * Python), which can be used to execute tests. */ public RobotRunner createRunner() { PyObject runnerObject = runnerClass.__call__(); return (RobotRunner) runnerObject.__tojava__(RobotRunner.class); } }
Allow the live test wait to be skipped
<?php require __DIR__ . "/../vendor/autoload.php"; if (in_array("--live-tests", $_SERVER["argv"])) { echo "\nWARNING: These tests will make changes to the Sonos devices on the network:\n"; $warnings = [ "Queue contents will be changed", "Music will play", "Volume will be changed", "Playlists will be created", "Alarms will be created", ]; foreach ($warnings as $warning) { echo " * {$warning}\n"; } if (!in_array("--skip-wait", $_SERVER["argv"])) { $sleep = 5; echo "\nTests will run in " . $sleep . " seconds"; for ($i = 0; $i < $sleep; $i++) { echo "."; sleep(1); } echo "\n"; } echo "\n"; }
<?php require __DIR__ . "/../vendor/autoload.php"; if (in_array("--live-tests", $_SERVER["argv"])) { echo "\nWARNING: These tests will make changes to the Sonos devices on the network:\n"; $warnings = [ "Queue contents will be changed", "Music will play", "Volume will be changed", "Playlists will be created", "Alarms will be created", ]; foreach ($warnings as $warning) { echo " * {$warning}\n"; } $sleep = 5; echo "\nTests will run in " . $sleep . " seconds"; for ($i = 0; $i < $sleep; $i++) { echo "."; sleep(1); } echo "\n\n"; }
Fix for intel routing changes
// ==UserScript== // @id iitc-plugin-drawtools-sync@hansolo669 // @name IITC plugin: drawtools sync // @category Tweaks // @version 0.1.1 // @namespace https://github.com/hansolo669/iitc-tweaks // @updateURL https://iitc.reallyawesomedomain.com/drawtools-sync.meta.js // @downloadURL https://iitc.reallyawesomedomain.com/drawtools-sync.user.js // @description Uses the 'sync' plugin to sync drawtools data via the google realtime API. // @include https://*.ingress.com/intel* // @include http://*.ingress.com/intel* // @match https://*.ingress.com/intel* // @match http://*.ingress.com/intel* // @include https://*.ingress.com/mission/* // @include http://*.ingress.com/mission/* // @match https://*.ingress.com/mission/* // @match http://*.ingress.com/mission/* // @grant none // ==/UserScript==
// ==UserScript== // @id iitc-plugin-drawtools-sync@hansolo669 // @name IITC plugin: drawtools sync // @category Tweaks // @version 0.1.0 // @namespace https://github.com/hansolo669/iitc-tweaks // @updateURL https://iitc.reallyawesomedomain.com/drawtools-sync.meta.js // @downloadURL https://iitc.reallyawesomedomain.com/drawtools-sync.user.js // @description Uses the 'sync' plugin to sync drawtools data via the google realtime API. // @include https://www.ingress.com/intel* // @include http://www.ingress.com/intel* // @match https://www.ingress.com/intel* // @match http://www.ingress.com/intel* // @include https://www.ingress.com/mission/* // @include http://www.ingress.com/mission/* // @match https://www.ingress.com/mission/* // @match http://www.ingress.com/mission/* // @grant none // ==/UserScript==