content
stringlengths
128
6.74k
<commit_msg>Add tests for valid email converter <commit_before>import nose from datetime import datetime, timedelta from ckanext.requestdata import helpers as h import ckan.plugins as p from ckan.tests import helpers, factories from ckan import logic ok_ = nose.tools.ok_ eq_ = nose.tools.eq_ raises = nose.tools.raises class ActionBase(object): @classmethod def setup_class(self): self.app = helpers._get_test_app() if not p.plugin_loaded('requestdata'): p.load('requestdata') def setup(self): helpers.reset_db() @classmethod def teardown_class(self): if p.plugin_loaded('requestdata'): p.unload('requestdata') class TestHelpers(ActionBase): def test_time_ago_from_datetime_valid(self): d = datetime.today() - timedelta(days=1) eq_(h.time_ago_from_datetime(d), '1 day ago') def test_time_ago_from_datetime_valid_string_result(self): d = datetime.today() - timedelta(days=2) assert isinstance(h.time_ago_from_datetime(d), str) <commit_after>import nose from datetime import datetime, timedelta from ckanext.requestdata import helpers as h import ckan.plugins as p from ckan.tests import helpers, factories from ckan import logic ok_ = nose.tools.ok_ eq_ = nose.tools.eq_ raises = nose.tools.raises class ActionBase(object): @classmethod def setup_class(self): self.app = helpers._get_test_app() if not p.plugin_loaded('requestdata'): p.load('requestdata') def setup(self): helpers.reset_db() @classmethod def teardown_class(self): if p.plugin_loaded('requestdata'): p.unload('requestdata') class TestHelpers(ActionBase): def test_time_ago_from_datetime_valid(self): d = datetime.today() - timedelta(days=1) eq_(h.time_ago_from_datetime(d), '1 day ago') def test_time_ago_from_datetime_valid_string_result(self): d = datetime.today() - timedelta(days=2) assert isinstance(h.time_ago_from_datetime(d), str) def test_convert_id_to_emails_valid(self): user = factories.User() users = [{'name': user['name']}] ids = user['id'] response = h.convert_id_to_email(ids) email = 'test_user_05@ckan.org' assert email == response
<commit_msg>Add readonly text to form <commit_before>from django.shortcuts import get_object_or_404, render from django import forms class ExampleForm(forms.Form): text = forms.CharField() disabled_text = forms.CharField(disabled=True) readonly_text = forms.CharField( widget=forms.TextInput(attrs={'readonly':'readonly'}) ) checkbox1 = forms.BooleanField() checkbox2 = forms.BooleanField() select = forms.ChoiceField(choices=[('', "Select an Option"), (1, 'one'), (2, 'two'), (3, 'three')]) radio = forms.ChoiceField(choices=[(1, 'one'), (2, 'two'), (3, 'three')], widget=forms.RadioSelect()) form_initial = { "text": "", "disabled_text": "This field can't be changed", } def styleguide(request): return render(request, "styleguide/styleguide.html", { }) def styleguide_page(request, name): return render(request, "styleguide/styleguide-%s.html" % name, { "example_form": ExampleForm(initial=form_initial), }) def styleguide_sub_page(request, name, sub_page): return render(request, "styleguide/styleguide-%s-%s.html" % (name, sub_page), { "example_form": ExampleForm(initial=form_initial), }) <commit_after>from django.shortcuts import get_object_or_404, render from django import forms class ExampleForm(forms.Form): text = forms.CharField() disabled_text = forms.CharField(disabled=True) readonly_text = forms.CharField( widget=forms.TextInput(attrs={'readonly':'readonly'}) ) checkbox1 = forms.BooleanField() checkbox2 = forms.BooleanField() select = forms.ChoiceField(choices=[('', "Select an Option"), (1, 'one'), (2, 'two'), (3, 'three')]) radio = forms.ChoiceField(choices=[(1, 'one'), (2, 'two'), (3, 'three')], widget=forms.RadioSelect()) form_initial = { "text": "", "disabled_text": "This field can't be changed", "readonly_text": "This field is read only", } def styleguide(request): return render(request, "styleguide/styleguide.html", { }) def styleguide_page(request, name): return render(request, "styleguide/styleguide-%s.html" % name, { "example_form": ExampleForm(initial=form_initial), }) def styleguide_sub_page(request, name, sub_page): return render(request, "styleguide/styleguide-%s-%s.html" % (name, sub_page), { "example_form": ExampleForm(initial=form_initial), })
<commit_msg>Configure library and test space for build Bach itself <commit_before>import com.github.sormuras.bach.ProjectInfo; import com.github.sormuras.bach.ProjectInfo.Main; import com.github.sormuras.bach.ProjectInfo.Tweak; @ProjectInfo( name = "bach", main = @Main( modules = "com.github.sormuras.bach", release = 16, generateApiDocumentation = true, tweaks = { @Tweak( tool = "javac", args = {"-encoding", "UTF-8", "-g", "-parameters", "-Werror", "-Xlint"}), @Tweak( tool = "javadoc", args = { "-encoding", "UTF-8", "-windowtitle", "\uD83C\uDFBC Bach", "-header", "\uD83C\uDFBC Bach", "-use", "-linksource", "-notimestamp", "-Werror", "-Xdoclint", "-quiet" }) })) module build { requires com.github.sormuras.bach; provides com.github.sormuras.bach.BuildProgram with build.BachBuildProgram; } <commit_after>import com.github.sormuras.bach.ProjectInfo; import com.github.sormuras.bach.ProjectInfo.Library; import com.github.sormuras.bach.ProjectInfo.Library.Link; import com.github.sormuras.bach.ProjectInfo.Main; import com.github.sormuras.bach.ProjectInfo.Test; import com.github.sormuras.bach.ProjectInfo.Tweak; @ProjectInfo( name = "bach", library = @Library( requires = {"org.junit.platform.console", "junit"}, links = @Link(module = "junit", target = "junit:junit:4.13.1")), main = @Main( release = 16, generateApiDocumentation = true, tweaks = { @Tweak( tool = "javac", args = {"-encoding", "UTF-8", "-g", "-parameters", "-Werror", "-Xlint"}), @Tweak( tool = "javadoc", args = { "-encoding", "UTF-8", "-windowtitle", "\uD83C\uDFBC Bach", "-header", "\uD83C\uDFBC Bach", "-use", "-linksource", "-notimestamp", "-Werror", "-Xdoclint", "-quiet" }) }), test = @Test( tweaks = @Tweak( tool = "javac", args = { "--patch-module", "com.github.sormuras.bach=com.github.sormuras.bach/main/java" }))) module build { requires com.github.sormuras.bach; provides com.github.sormuras.bach.BuildProgram with build.BachBuildProgram; }
<commit_msg>Update the comment for VcapPassword <commit_before>package common import ( bosherr "github.com/cloudfoundry/bosh-utils/errors" ) type AgentOptions struct { // e.g. "https://user:password@127.0.0.1:4321/agent" Mbus string // e.g. ["0.us.pool.ntp.org"]. Ok to be empty NTP []string Blobstore BlobstoreOptions //vcap password VcapPassword string } type RegistryOptions struct { Host string Port int Username string Password string } type BlobstoreOptions struct { Provider string `json:"provider"` Options map[string]interface{} `json:"options"` } func (o AgentOptions) Validate() error { if o.Mbus == "" { return bosherr.Error("Must provide non-empty Mbus") } err := o.Blobstore.Validate() if err != nil { return bosherr.WrapError(err, "Validating Blobstore configuration") } return nil } func (o BlobstoreOptions) Validate() error { if o.Provider == "" { return bosherr.Error("Must provide non-empty provider") } return nil } <commit_after>package common import ( bosherr "github.com/cloudfoundry/bosh-utils/errors" ) type AgentOptions struct { // e.g. "https://user:password@127.0.0.1:4321/agent" Mbus string // e.g. ["0.us.pool.ntp.org"]. Ok to be empty NTP []string Blobstore BlobstoreOptions //The SHA-512 encrypted vcap password VcapPassword string } type RegistryOptions struct { Host string Port int Username string Password string } type BlobstoreOptions struct { Provider string `json:"provider"` Options map[string]interface{} `json:"options"` } func (o AgentOptions) Validate() error { if o.Mbus == "" { return bosherr.Error("Must provide non-empty Mbus") } err := o.Blobstore.Validate() if err != nil { return bosherr.WrapError(err, "Validating Blobstore configuration") } return nil } func (o BlobstoreOptions) Validate() error { if o.Provider == "" { return bosherr.Error("Must provide non-empty provider") } return nil }
<commit_msg>Make UInt safe on Transaction Params by not using pointer <commit_before>// // PSTCKTransactionParams.h // Paystack // #import <Foundation/Foundation.h> #import "PSTCKFormEncodable.h" /** * Representation of a user's credit card details. You can assemble these with information that your user enters and * then create Paystack tokens with them using an PSTCKAPIClient. @see https://paystack.com/docs/api#cards */ @interface PSTCKTransactionParams : NSObject<PSTCKFormEncodable> @property (nonatomic, copy, nonnull) NSString *email; @property (nonatomic, nonnull) NSUInteger *amount; @property (nonatomic, copy, nullable) NSString *reference; @property (nonatomic, copy, nullable) NSString *subaccount; @property (nonatomic, nullable) NSUInteger *transactionCharge; @property (nonatomic, copy, nullable) NSString *bearer; @property (nonatomic, copy, nullable) NSString *metadata; @end <commit_after>// // PSTCKTransactionParams.h // Paystack // #import <Foundation/Foundation.h> #import "PSTCKFormEncodable.h" /** * Representation of a user's credit card details. You can assemble these with information that your user enters and * then create Paystack tokens with them using an PSTCKAPIClient. @see https://paystack.com/docs/api#cards */ @interface PSTCKTransactionParams : NSObject<PSTCKFormEncodable> @property (nonatomic, copy, nonnull) NSString *email; @property (nonatomic) NSUInteger amount; @property (nonatomic, copy, nullable) NSString *reference; @property (nonatomic, copy, nullable) NSString *subaccount; @property (nonatomic) NSUInteger transactionCharge; @property (nonatomic, copy, nullable) NSString *bearer; @property (nonatomic, copy, nullable) NSString *metadata; @end
<commit_msg>Make the Future transient so not serialized <commit_before>package co.phoenixlab.discord.commands.tempstorage; import java.time.Duration; import java.time.Instant; import java.util.concurrent.Future; public class ServerTimeout { private final String serverId; private final String userId; private final Instant startTime; private final Duration duration; private final Instant endTime; private final String issuedByUserId; private final Future<Void> timerFuture; public ServerTimeout(Duration duration, Instant startTime, String userId, String serverId, String issuedByUserId, Future<Void> timerFuture) { this.duration = duration; this.startTime = startTime; this.userId = userId; this.serverId = serverId; this.timerFuture = timerFuture; this.endTime = startTime.plus(duration); this.issuedByUserId = issuedByUserId; } public String getServerId() { return serverId; } public String getUserId() { return userId; } public Instant getStartTime() { return startTime; } public Duration getDuration() { return duration; } public Instant getEndTime() { return endTime; } public String getIssuedByUserId() { return issuedByUserId; } public Future<Void> getTimerFuture() { return timerFuture; } } <commit_after>package co.phoenixlab.discord.commands.tempstorage; import java.time.Duration; import java.time.Instant; import java.util.concurrent.Future; public class ServerTimeout { private final String serverId; private final String userId; private final Instant startTime; private final Duration duration; private final Instant endTime; private final String issuedByUserId; private final transient Future<Void> timerFuture; public ServerTimeout(Duration duration, Instant startTime, String userId, String serverId, String issuedByUserId, Future<Void> timerFuture) { this.duration = duration; this.startTime = startTime; this.userId = userId; this.serverId = serverId; this.timerFuture = timerFuture; this.endTime = startTime.plus(duration); this.issuedByUserId = issuedByUserId; } public String getServerId() { return serverId; } public String getUserId() { return userId; } public Instant getStartTime() { return startTime; } public Duration getDuration() { return duration; } public Instant getEndTime() { return endTime; } public String getIssuedByUserId() { return issuedByUserId; } public Future<Void> getTimerFuture() { return timerFuture; } }
<commit_msg>Fix bug in unit test (ignore header row in output csv file) <commit_before>import os import numpy as np import crepe def test_sweep(): # this data contains a sine sweep file = os.path.join(os.path.dirname(__file__), 'sweep.wav') model = crepe.build_and_load_model() crepe.process_file(model, file) f0_file = os.path.join(os.path.dirname(__file__), 'sweep.f0.csv') result = np.loadtxt(f0_file, delimiter=',') # the result should be confident enough about the presence of pitch in every # frame assert np.mean(result[:, 2] > 0.5) > 0.99 # the frequencies should be linear assert np.corrcoef(result[:, 1]) > 0.99 <commit_after>import os import numpy as np import crepe def test_sweep(): # this data contains a sine sweep file = os.path.join(os.path.dirname(__file__), 'sweep.wav') model = crepe.build_and_load_model() crepe.process_file(model, file) f0_file = os.path.join(os.path.dirname(__file__), 'sweep.f0.csv') result = np.loadtxt(f0_file, delimiter=',', skiprows=1) # the result should be confident enough about the presence of pitch in every # frame assert np.mean(result[:, 2] > 0.5) > 0.99 # the frequencies should be linear assert np.corrcoef(result[:, 1]) > 0.99
<commit_msg>Make the PIL warning a little more noticeable. The warning has been fleshed out just a bit, and has a border above and below it to make it more obvious. <commit_before>import sys try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages import pkg_resources NAME = 'pillowfight' VERSION = '0.1' SUMMARY = 'Eases the transition from PIL to Pillow for projects.' fp = open('README.rst', 'r') DESCRIPTION = fp.read().strip() fp.close() # If PIL is installed, use that. Otherwise prefer the newer Pillow library. pil_req = pkg_resources.Requirement.parse('PIL') try: pkg_resources.get_provider(pil_req) # We found PIL. So, guess we have to use that. image_lib = 'PIL' sys.stderr.write('The "PIL" library is deprecated and support will be ' 'removed in a future release.\n' 'To switch to "Pillow", you must first uninstall ' '"PIL".\n\n') except pkg_resources.DistributionNotFound: image_lib = 'Pillow' setup(name=NAME, version=VERSION, license='MIT', description=SUMMARY, long_description=DESCRIPTION, install_requires=[image_lib], zip_safe=True, url='https://github.com/beanbaginc/pillowfight', maintainer='Beanbag, Inc.', maintainer_email='support@beanbaginc.com') <commit_after>import sys try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages import pkg_resources NAME = 'pillowfight' VERSION = '0.1' SUMMARY = 'Eases the transition from PIL to Pillow for projects.' fp = open('README.rst', 'r') DESCRIPTION = fp.read().strip() fp.close() PIL_WARNING = ''' *************************************************************************** The "PIL" library is deprecated in favor of "Pillow", and may not be supported in a future release. To switch to "Pillow", you must first uninstall "PIL". *************************************************************************** ''' # If PIL is installed, use that. Otherwise prefer the newer Pillow library. pil_req = pkg_resources.Requirement.parse('PIL') try: pkg_resources.get_provider(pil_req) # We found PIL. So, guess we have to use that. sys.stderr.write('\n%s\n' % PIL_WARNING.strip()) image_lib = 'PIL' except pkg_resources.DistributionNotFound: image_lib = 'Pillow' setup(name=NAME, version=VERSION, license='MIT', description=SUMMARY, long_description=DESCRIPTION, install_requires=[image_lib], zip_safe=True, url='https://github.com/beanbaginc/pillowfight', maintainer='Beanbag, Inc.', maintainer_email='support@beanbaginc.com')
<commit_msg>Switch to more optimal non-generator solution <commit_before>def sieve(n): return list(primes(n)) def primes(n): if n < 2: raise StopIteration yield 2 not_prime = set() for i in range(3, n+1, 2): if i not in not_prime: yield i not_prime.update(range(i*i, n, i)) <commit_after>def sieve(n): if n < 2: return [] not_prime = set() prime = [2] for i in range(3, n+1, 2): if i not in not_prime: prime.append(i) not_prime.update(range(i*i, n, i)) return prime
<commit_msg>Use napms method from curses rather than sleep method from time <commit_before> import curses import os import time from box import Box from utils import load_yaml def main(screen): """ Draws and redraws the screen. """ # Hide the cursor. curses.curs_set(0) # Load config from file. config = load_yaml(os.path.expanduser('~/.suave/config.yml')) # Create boxes from config. boxes = [] for box in config: boxes.append( Box( screen=screen, rows=box['rows'], columns=box['columns'], rows_offset=box['rows-offset'], columns_offset=box['columns-offset'], command=box['command'], interval=box['interval'], ) ) while True: # Redraw the screen only when it changes. if screen.is_wintouched(): screen.clear() screen.refresh() # Give every box an opportunity to redraw if it has changed. [box.redraw_if_changed() for box in boxes] # Wait before redrawing again. time.sleep(1) curses.wrapper(main) <commit_after> import curses import os from box import Box from utils import load_yaml def main(screen): """ Draws and redraws the screen. """ # Hide the cursor. curses.curs_set(0) # Load config from file. config = load_yaml(os.path.expanduser('~/.suave/config.yml')) # Create boxes from config. boxes = [] for box in config: boxes.append( Box( screen=screen, rows=box['rows'], columns=box['columns'], rows_offset=box['rows-offset'], columns_offset=box['columns-offset'], command=box['command'], interval=box['interval'], ) ) while True: # Redraw the screen only when it changes. if screen.is_wintouched(): screen.clear() screen.refresh() # Give every box an opportunity to redraw if it has changed. [box.redraw_if_changed() for box in boxes] # Wait before redrawing again. curses.napms(1000) curses.wrapper(main)
<commit_msg>Use Chrome's user agent string for content_shell, since some sites (i.e. Gmail) give a degraded experience otherwise. BUG=90445 Review URL: http://codereview.chromium.org/7980044 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@102172 0039d316-1c4b-4281-b951-d872f2087c98 <commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/shell/shell_content_client.h" #include "base/string_piece.h" namespace content { ShellContentClient::~ShellContentClient() { } void ShellContentClient::SetActiveURL(const GURL& url) { } void ShellContentClient::SetGpuInfo(const GPUInfo& gpu_info) { } void ShellContentClient::AddPepperPlugins( std::vector<PepperPluginInfo>* plugins) { } bool ShellContentClient::CanSendWhileSwappedOut(const IPC::Message* msg) { return false; } bool ShellContentClient::CanHandleWhileSwappedOut(const IPC::Message& msg) { return false; } std::string ShellContentClient::GetUserAgent(bool mimic_windows) const { return std::string(); } string16 ShellContentClient::GetLocalizedString(int message_id) const { return string16(); } base::StringPiece ShellContentClient::GetDataResource(int resource_id) const { return base::StringPiece(); } #if defined(OS_WIN) bool ShellContentClient::SandboxPlugin(CommandLine* command_line, sandbox::TargetPolicy* policy) { return false; } #endif } // namespace content <commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/shell/shell_content_client.h" #include "base/string_piece.h" #include "webkit/glue/user_agent.h" namespace content { ShellContentClient::~ShellContentClient() { } void ShellContentClient::SetActiveURL(const GURL& url) { } void ShellContentClient::SetGpuInfo(const GPUInfo& gpu_info) { } void ShellContentClient::AddPepperPlugins( std::vector<PepperPluginInfo>* plugins) { } bool ShellContentClient::CanSendWhileSwappedOut(const IPC::Message* msg) { return false; } bool ShellContentClient::CanHandleWhileSwappedOut(const IPC::Message& msg) { return false; } std::string ShellContentClient::GetUserAgent(bool mimic_windows) const { return webkit_glue::BuildUserAgentHelper(mimic_windows, "Chrome/15.16.17.18"); } string16 ShellContentClient::GetLocalizedString(int message_id) const { return string16(); } base::StringPiece ShellContentClient::GetDataResource(int resource_id) const { return base::StringPiece(); } #if defined(OS_WIN) bool ShellContentClient::SandboxPlugin(CommandLine* command_line, sandbox::TargetPolicy* policy) { return false; } #endif } // namespace content
<commit_msg>Make colored tree panel clearable <commit_before>package signature.display; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JPanel; import signature.ColoredTree; public class ColoredTreePanel extends JPanel { public int maxDepth; private DisplayableColoredTree displayTree; private boolean drawKey; public ColoredTreePanel(int width, int height) { this.setPreferredSize(new Dimension(width, height)); this.drawKey = false; this.displayTree = new DisplayableColoredTree(width, height); } public ColoredTreePanel(ColoredTree tree, int width, int height) { displayTree = new DisplayableColoredTree(tree, width, height); this.drawKey = false; this.setPreferredSize(new Dimension(width, height)); } public void setDrawKey(boolean drawKey) { this.drawKey = drawKey; } public void setTree(ColoredTree tree) { System.out.println("setting tree " + tree); this.displayTree.makeFromColoredTree(tree); this.displayTree.setDrawKey(drawKey); this.maxDepth = tree.getHeight(); } public void paint(Graphics g) { this.displayTree.paint(g); } } <commit_after>package signature.display; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JPanel; import signature.ColoredTree; public class ColoredTreePanel extends JPanel { public int maxDepth; private DisplayableColoredTree displayTree; private boolean drawKey; public ColoredTreePanel(int width, int height) { this.setPreferredSize(new Dimension(width, height)); this.drawKey = false; this.displayTree = new DisplayableColoredTree(width, height); } public ColoredTreePanel(ColoredTree tree, int width, int height) { displayTree = new DisplayableColoredTree(tree, width, height); this.drawKey = false; this.setPreferredSize(new Dimension(width, height)); } public void setDrawKey(boolean drawKey) { this.drawKey = drawKey; } public void setTree(ColoredTree tree) { System.out.println("setting tree " + tree); this.displayTree.makeFromColoredTree(tree); this.displayTree.setDrawKey(drawKey); this.maxDepth = tree.getHeight(); } public void paint(Graphics g) { if (displayTree != null) { this.displayTree.paint(g); } } public void clear() { this.displayTree = null; } }
<commit_msg>Send data using jqaram in registration controller <commit_before>export class RegisterComponent implements ng.IComponentOptions { static NAME:string = 'appRegister'; template: any; controllerAs:string; controller; constructor() { this.template = require('./register.component.html'); this.controllerAs = '$ctrl'; this.controller = RegisterController; } } class RegisterController implements ng.IComponentController { static $inject = ['$http', '$state']; title: string; user; emailUsed = false; constructor(private http: ng.IHttpService, private $state: ng.ui.IStateService) { this.title = "Register Page"; this.user = {}; } register() { this.http.post('http://localhost:8080/api/register', this.user, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(response => { console.log(response.data); if (response.data === 'email already used') { this.emailUsed = true; return; } this.$state.go('app.dashboard.student'); }) } }<commit_after>export class RegisterComponent implements ng.IComponentOptions { static NAME:string = 'appRegister'; template: any; controllerAs:string; controller; constructor() { this.template = require('./register.component.html'); this.controllerAs = '$ctrl'; this.controller = RegisterController; } } class RegisterController implements ng.IComponentController { static $inject = ['$http', '$state', '$httpParamSerializerJQLike']; title: string; user; emailUsed = false; constructor( private http: ng.IHttpService, private $state: ng.ui.IStateService, private httpParamSerializerJQLike: ng.IHttpParamSerializer ) { this.title = "Register Page"; this.user = {}; } register() { this.http.post( 'http://localhost:8080/api/register', this.httpParamSerializerJQLike(this.user), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } ).then(response => { console.log(response.data); if (response.data === 'email already used') { this.emailUsed = true; return; } this.$state.go('app.dashboard.student'); }) } }
<commit_msg>Make morse parser not assume that the current working directory is common/ <commit_before>f = open("morse_table.txt") morse_table = f.read() morse_table = dict([(morse[0:1], morse[2:len(morse)]) for morse in morse_table.split("\n")]) f.close() <commit_after>import inspect, os common_dir = os.path.dirname(inspect.getfile(inspect.currentframe())) # script directory f = open(os.path.join(common_dir, "morse_table.txt")) morse_table = f.read() morse_table = dict([(morse[0:1], morse[2:len(morse)]) for morse in morse_table.split("\n")]) f.close()
<commit_msg>Add unit test for decay method <commit_before>import pytest import pandas as pd from tardis.io.decay import IsotopeAbundances @pytest.fixture def simple_abundance_model(): index = pd.MultiIndex.from_tuples([(28, 56)], names=['atomic_number', 'mass_number']) return IsotopeAbundances([[1.0, 1.0]], index=index) def test_simple_decay(simple_abundance_model): 1/0 <commit_after>import pytest import pandas as pd from tardis.io.decay import IsotopeAbundances from numpy.testing import assert_almost_equal @pytest.fixture def simple_abundance_model(): index = pd.MultiIndex.from_tuples([(28, 56)], names=['atomic_number', 'mass_number']) return IsotopeAbundances([[1.0, 1.0]], index=index) def test_simple_decay(simple_abundance_model): decayed_abundance = simple_abundance_model.decay(100) assert_almost_equal(decayed_abundance.ix[26, 56][0], 0.55752) assert_almost_equal(decayed_abundance.ix[26, 56][1], 0.55752) assert_almost_equal(decayed_abundance.ix[27, 56][0], 0.4423791) assert_almost_equal(decayed_abundance.ix[27, 56][1], 0.4423791) assert_almost_equal(decayed_abundance.ix[28, 56][0], 1.1086e-05) assert_almost_equal(decayed_abundance.ix[28, 56][1], 1.1086e-05)
<commit_msg>Raise TypeError instead of returning <commit_before> class RequiresType(object): """ Checks that the first (or position given by the keyword argument 'position' argument to the function is an instance of one of the types given in the positional decorator arguments """ def __init__(self, *types, **kwargs): self.types = types self.position = 0 self.returnvalue = False if 'position' in kwargs: self.position = int(kwargs['position']) - 1 if 'returnvalue' in kwargs: self.returnvalue = kwargs['returnvalue'] def __call__(self, f): def wrapped_f(*args, **kwargs): if type(args[self.position]) not in self.types: return self.returnvalue return f(*args, **kwargs) return wrapped_f <commit_after> class RequiresType(object): """ Checks that the first (or position given by the keyword argument 'position' argument to the function is an instance of one of the types given in the positional decorator arguments """ def __init__(self, *types, **kwargs): self.types = types self.position = 0 if 'position' in kwargs: self.position = int(kwargs['position']) - 1 def __call__(self, f): def wrapped_f(*args, **kwargs): if type(args[self.position]) not in self.types: raise TypeError("Invalid argument type '%s' at position %d. " + "Expected one of (%s)" % ( type(args[self.position]).__name__, self.position, ", ".join([t.__name__ for t in self.types]))) return f(*args, **kwargs) return wrapped_f
<commit_msg>Change location of temporary file from /tmp to /var/tmp. This is a repeat of an earlier commit which apparently got lost with the last import. It helps solve the frequently reported problem pid 4032 (mail.local), uid 0 on /: file system full (though there appears to be a lot of space) caused by idiots sending 30 MB mail messages. Most-recently-reported-by: jahanur <jahanur@jjsoft.com> Add $FreeBSD$ so that I can check the file back in. Rejected-by: CVS <commit_before>/*- * Copyright (c) 1998 Sendmail, Inc. All rights reserved. * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * * * @(#)pathnames.h 8.5 (Berkeley) 5/19/1998 */ #include <paths.h> #define _PATH_LOCTMP "/tmp/local.XXXXXX" <commit_after>/*- * Copyright (c) 1998 Sendmail, Inc. All rights reserved. * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * * * @(#)pathnames.h 8.5 (Berkeley) 5/19/1998 * $FreeBSD$ */ #include <paths.h> #define _PATH_LOCTMP "/var/tmp/local.XXXXXX"
<commit_msg>Use the full commit hash so that we can download from github.com. <commit_before> class FsharpPackage(GitHubTarballPackage): def __init__(self): GitHubTarballPackage.__init__(self, 'fsharp', 'fsharp', '3.0.13', '3.0.13', configure = '') def build(self): self.sh ('autoreconf') self.sh ('./configure --prefix="%{prefix}"') self.sh ('make') FsharpPackage() <commit_after> class FsharpPackage(GitHubTarballPackage): def __init__(self): GitHubTarballPackage.__init__(self, 'fsharp', 'fsharp', '3.0.13', '893b8a3a9326b0a2008b5f7322dd8002b8065a69', configure = '') def build(self): self.sh ('autoreconf') self.sh ('./configure --prefix="%{prefix}"') self.sh ('make') FsharpPackage()
<commit_msg>Use get_or_create to avoid duplicate objects <commit_before>from __future__ import unicode_literals from django.db import migrations import uuid from cla_common.constants import RESEARCH_CONTACT_VIA def create_default_contact_for_research_methods(apps, schema_editor): ContactResearchMethods = apps.get_model("legalaid", "ContactResearchMethod") for value, name in RESEARCH_CONTACT_VIA: ContactResearchMethods.objects.create(method=value, reference=uuid.uuid4()).save() def rollback_default_contact_for_research_methods(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [("legalaid", "0021_auto_20190515_1042")] operations = [ migrations.RunPython( create_default_contact_for_research_methods, rollback_default_contact_for_research_methods ) ] <commit_after>from __future__ import unicode_literals from django.db import migrations import uuid from cla_common.constants import RESEARCH_CONTACT_VIA def create_default_contact_for_research_methods(apps, schema_editor): ContactResearchMethods = apps.get_model("legalaid", "ContactResearchMethod") for value, name in RESEARCH_CONTACT_VIA: ContactResearchMethods.objects.get_or_create(method=value, defaults={"reference": uuid.uuid4()}) def rollback_default_contact_for_research_methods(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [("legalaid", "0021_auto_20190515_1042")] operations = [ migrations.RunPython( create_default_contact_for_research_methods, rollback_default_contact_for_research_methods ) ]
<commit_msg>Make lua autoconfig work better. <commit_before>from .base_executor import ScriptExecutor class Executor(ScriptExecutor): ext = '.lua' name = 'LUA' command = 'lua' address_grace = 131072 test_program = "io.write(io.read('*all'))" @classmethod def get_version_flags(cls, command): return ['-v'] <commit_after>from .base_executor import ScriptExecutor class Executor(ScriptExecutor): ext = '.lua' name = 'LUA' command = 'lua' command_paths = ['lua', 'lua5.3', 'lua5.2', 'lua5.1'] address_grace = 131072 test_program = "io.write(io.read('*all'))" @classmethod def get_version_flags(cls, command): return ['-v']
<commit_msg>Add comments in ivi-test package <commit_before>import { VNode, render, update } from "ivi"; import { triggerNextTick, triggerNextFrame } from "./scheduler"; import { reset } from "./reset"; import { VNodeWrapper } from "./vdom"; let _container: HTMLDivElement | null = null; export class DOMRenderer { private container: HTMLDivElement; constructor(container: HTMLDivElement) { this.container = container; } render(vnode: VNode<any>): VNodeWrapper { render(vnode, this.container); return new VNodeWrapper(vnode, null, {}); } update(): void { update(); } nextTick(): void { triggerNextTick(); } nextFrame(time?: number): void { triggerNextFrame(time); } } export function initDOMRenderer(): DOMRenderer { if (_container === null) { _container = document.createElement("div"); _container.className = "ivi-dom-test-container"; document.body.appendChild(_container); } else { _container.innerText = ""; } reset(); return new DOMRenderer(_container); } <commit_after>import { VNode, render, update } from "ivi"; import { triggerNextTick, triggerNextFrame } from "./scheduler"; import { reset } from "./reset"; import { VNodeWrapper } from "./vdom"; let _container: HTMLDivElement | null = null; /** * DOMRenderer is a helper object for testing Virtual DOM in a real DOM. */ export class DOMRenderer { private container: HTMLDivElement; constructor(container: HTMLDivElement) { this.container = container; } /** * render renders a VNode in a test container and returns a VNodeWrapper object. * * @param vnode VNode. * @returns VNodeWrapper object. */ render(vnode: VNode<any>): VNodeWrapper { render(vnode, this.container); return new VNodeWrapper(vnode, null, {}); } /** * update triggers update in a scheduler. */ update(): void { update(); } /** * nextTick triggers next tick in a scheduler and execute all microtasks, tasks and frame updates. */ nextTick(): void { triggerNextTick(); } /** * nextFrame triggers next frame in a scheduler and executal all frame updates. * * @param time Current time. */ nextFrame(time?: number): void { triggerNextFrame(time); } } /** * initDOMRenderer instantiates and initializes DOMRenderer object. * * @returns DOMRenderer. */ export function initDOMRenderer(): DOMRenderer { if (_container === null) { _container = document.createElement("div"); _container.className = "ivi-dom-test-container"; document.body.appendChild(_container); } else { _container.innerText = ""; } reset(); return new DOMRenderer(_container); }