text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix up some bugs in ecenter_network.
Drupal.behaviors.jqPlot = function(context) { if (Drupal.settings.jqPlot) { var replace = ['renderer', 'markerRenderer', 'labelRenderer', 'parseX', 'parseY', 'scrapeSingle', 'scrapeMultiple', 'processSeries']; /*$.each(Drupal.settings.jqPlot, function(selector, settings) { settings = Drupal.jqPlot.replaceFunctions(settings, replace); $(selector).tablechart(settings); });*/ } } Drupal.jqPlot = {}; Drupal.jqPlot.replaceFunctions = function(obj, replace) { $.each(obj, function(key, val) { if (typeof val == 'object') { obj[key] = Drupal.jqPlot.replaceFunctions(val, replace); } else if (typeof val == 'string' && $.inArray(key, replace) > -1) { namespaces = val.split("."); func = namespaces.pop(); context = window; for (var i = 0; i < namespaces.length; i++) { context = context[namespaces[i]]; } obj[key] = context[func]; } }); return obj; }
Drupal.behaviors.jqPlot = function(context) { if (Drupal.settings.jqPlot) { var replace = ['renderer', 'markerRenderer', 'labelRenderer', 'parseX', 'parseY', 'scrapeSingle', 'scrapeMultiple', 'processSeries']; $.each(Drupal.settings.jqPlot, function(selector, settings) { settings = Drupal.jqPlot.replaceFunctions(settings, replace); $(selector).tablechart(settings); }); } } Drupal.jqPlot = {}; Drupal.jqPlot.replaceFunctions = function(obj, replace) { $.each(obj, function(key, val) { if (typeof val == 'object') { obj[key] = Drupal.jqPlot.replaceFunctions(val, replace); } else if (typeof val == 'string' && $.inArray(key, replace) > -1) { namespaces = val.split("."); func = namespaces.pop(); context = window; for (var i = 0; i < namespaces.length; i++) { context = context[namespaces[i]]; } obj[key] = context[func]; } }); return obj; }
Test coverage on added function
<?php namespace Omnipay\Elavon\Message; use Omnipay\Tests\TestCase; class ConvergeGenerateTokenRequestTest extends TestCase { public function setUp() { $this->request = new ConvergeGenerateTokenRequest($this->getHttpClient(), $this->getHttpRequest()); $this->request->initialize( array( 'card' => $this->getValidCard(), 'ssl_show_form' => 'false', 'ssl_result_format' => 'ASCII', ) ); } public function testCreateCardSuccess() { $this->setMockHttpResponse('ConvergeCreateCardResponse.txt'); $response = $this->request->send(); $this->assertTrue($response->isSuccessful()); $this->assertSame('7595301425001111', $response->getCardReference()); } }
<?php namespace Omnipay\Elavon\Message; use Omnipay\Tests\TestCase; class ConvergeGenerateTokenRequestTest extends TestCase { public function setUp() { $this->request = new ConvergeGenerateTokenRequest($this->getHttpClient(), $this->getHttpRequest()); $this->request->initialize( array( 'card' => $this->getValidCard(), 'ssl_show_form' => 'false', 'ssl_result_format' => 'ASCII', ) ); } public function testCreateCardSuccess() { $this->setMockHttpResponse('ConvergeCreateCardResponse.txt'); $response = $this->request->send(); $this->assertTrue($response->isSuccessful()); $this->assertSame('7595301425001111', $response->getCardToken()); } }
Remove print of terminal output for debugging
#!/usr/bin/python3 import pyqrcode # sudo pip install pyqrcode def getQRArray(text, errorCorrection): """ Takes in text and errorCorrection (letter), returns 2D array of the QR code""" # White is True (1) # Black is False (0) # ECC: L7, M15, Q25, H30 # Create the object qr = pyqrcode.create(text, error=errorCorrection) # Get the terminal representation and split by lines (get rid of top and bottom white spaces) plainOut = qr.terminal().split("\n")[5:-5] # Initialize the output 2D list out = [] for line in plainOut: thisOut = [] for char in line: if char == u'7': # This is white thisOut.append(1) elif char == u'4': # This is black, it's part of the u'49' thisOut.append(0) # Finally add everything to the output, stipping whitespaces at start and end out.append(thisOut[4:-4]) # Everything is done, return the qr code list return out
#!/usr/bin/python3 import pyqrcode # sudo pip install pyqrcode def getQRArray(text, errorCorrection): """ Takes in text and errorCorrection (letter), returns 2D array of the QR code""" # White is True (1) # Black is False (0) # ECC: L7, M15, Q25, H30 # Create the object qr = pyqrcode.create(text, error=errorCorrection) # Get the terminal representation and split by lines (get rid of top and bottom white spaces) plainOut = qr.terminal().split("\n")[5:-5] print(qr.terminal()) # Initialize the output 2D list out = [] for line in plainOut: thisOut = [] for char in line: if char == u'7': # This is white thisOut.append(1) elif char == u'4': # This is black, it's part of the u'49' thisOut.append(0) # Finally add everything to the output, stipping whitespaces at start and end out.append(thisOut[4:-4]) # Everything is done, return the qr code list return out
examples: Modify the examples to avoid reading the whole input at once. This will let the map job operate on the inputs that are larger than the physical memory.
package main import ( "bufio" "fmt" "github.com/discoproject/goworker/jobutil" "github.com/discoproject/goworker/worker" "io" "log" "strings" ) func Map(reader io.Reader, writer io.Writer) { scanner := bufio.NewScanner(reader) for scanner.Scan() { text := scanner.Text() words := strings.Fields(text) for _, word := range words { _, err := writer.Write([]byte(word + "\n")) jobutil.Check(err) } } if err := scanner.Err(); err != nil { log.Fatal("reading standard input:", err) } } func Reduce(reader io.Reader, writer io.Writer) { sreader := jobutil.Sorted(reader) grouper := jobutil.Grouper(sreader) for grouper.Scan() { word, count := grouper.Text() _, err := writer.Write([]byte(fmt.Sprintf("%d %s\n", count, word))) jobutil.Check(err) } if err := grouper.Err(); err != nil { jobutil.Check(err) } sreader.Close() } func main() { worker.Run(Map, Reduce) }
package main import ( "fmt" "github.com/discoproject/goworker/jobutil" "github.com/discoproject/goworker/worker" "io" "io/ioutil" "strings" ) func Map(reader io.Reader, writer io.Writer) { body, err := ioutil.ReadAll(reader) jobutil.Check(err) strBody := string(body) words := strings.Fields(strBody) for _, word := range words { _, err := writer.Write([]byte(word + "\n")) jobutil.Check(err) } } func Reduce(reader io.Reader, writer io.Writer) { sreader := jobutil.Sorted(reader) grouper := jobutil.Grouper(sreader) for grouper.Scan() { word, count := grouper.Text() _, err := writer.Write([]byte(fmt.Sprintf("%d %s\n", count, word))) jobutil.Check(err) } if err := grouper.Err(); err != nil { jobutil.Check(err) } sreader.Close() } func main() { worker.Run(Map, Reduce) }
Fix an error causing the css not being generated
module.exports = function () { var outputPath = "./<%= outFolder %>/"; var src = "./<%= srcFolder %>/"; var config = { vendor: { destPath: outputPath + "js", src: [] }, templates: src + "**/*.tpl.html", scss: { entry: src + "styles/<%= hAppName %>.scss", src: [src + "**/*.scss"], destPath: outputPath + "css" }, ts: { src: [src + "**/*.ts"], dest: outputPath + "js" }, html: { src: [src + "**/**.html"], dest: outputPath + "js" } }; return config; };
module.exports = function () { var outputPath = "./<%= outFolder %>/"; var src = "./<%= srcFolder %>/"; var config = { vendor: { destPath: outputPath + "js", src: [] }, templates: src + "**/*.tpl.html", scss: { entry: src + "styles/<%= appName %>.scss", src: [src + "**/*.scss"], destPath: outputPath + "css" }, ts: { src: [src + "**/*.ts"], dest: outputPath + "js" }, html: { src: [src + "**/**.html"], dest: outputPath + "js" } }; return config; };
Implement lcfirst for PHP < 5.3
<?php if (!function_exists('curl_init')) { throw new Exception('Userbin needs the CURL PHP extension.'); } if (!function_exists('json_decode')) { throw new Exception('Userbin needs the JSON PHP extension.'); } if (!function_exists('lcfirst')) { function lcfirst( $str ) { $str[0] = strtolower($str[0]); return (string)$str; } } require(dirname(__FILE__) . '/Userbin/Userbin.php'); require(dirname(__FILE__) . '/Userbin/Errors.php'); require(dirname(__FILE__) . '/Userbin/SessionToken.php'); require(dirname(__FILE__) . '/Userbin/SessionStore.php'); require(dirname(__FILE__) . '/Userbin/Resource.php'); require(dirname(__FILE__) . '/Userbin/Model.php'); require(dirname(__FILE__) . '/Userbin/Models/Challenge.php'); require(dirname(__FILE__) . '/Userbin/Models/Session.php'); require(dirname(__FILE__) . '/Userbin/Models/User.php'); require(dirname(__FILE__) . '/Userbin/JWT.php'); require(dirname(__FILE__) . '/Userbin/CurlTransport.php'); require(dirname(__FILE__) . '/Userbin/Request.php');
<?php if (!function_exists('curl_init')) { throw new Exception('Userbin needs the CURL PHP extension.'); } if (!function_exists('json_decode')) { throw new Exception('Userbin needs the JSON PHP extension.'); } require(dirname(__FILE__) . '/Userbin/Userbin.php'); require(dirname(__FILE__) . '/Userbin/Errors.php'); require(dirname(__FILE__) . '/Userbin/SessionToken.php'); require(dirname(__FILE__) . '/Userbin/SessionStore.php'); require(dirname(__FILE__) . '/Userbin/Resource.php'); require(dirname(__FILE__) . '/Userbin/Model.php'); require(dirname(__FILE__) . '/Userbin/Models/Challenge.php'); require(dirname(__FILE__) . '/Userbin/Models/Session.php'); require(dirname(__FILE__) . '/Userbin/Models/User.php'); require(dirname(__FILE__) . '/Userbin/JWT.php'); require(dirname(__FILE__) . '/Userbin/CurlTransport.php'); require(dirname(__FILE__) . '/Userbin/Request.php');
Fix incorrect date format in urlencoded parameter parser.
package ru.fitgraph.rest.elements; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by melges on 19.01.15. */ public class DateParameter { private static final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); private Date date; public DateParameter() { this.date = new Date(); } public DateParameter(String date) { try { this.date = dateTimeFormat.parse(date); } catch (ParseException e) { throw new WebApplicationException(Response .status(Response.Status.BAD_REQUEST) .entity(new ErrorResponse("InvalidParameterException", e.getLocalizedMessage())).build()); } } public Date getDate() { return date; } }
package ru.fitgraph.rest.elements; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by melges on 19.01.15. */ public class DateParameter { private static final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd.MM.yyyy-HH:mm:ss"); private Date date; public DateParameter() { this.date = new Date(); } public DateParameter(String date) { try { this.date = dateTimeFormat.parse(date); } catch (ParseException e) { throw new WebApplicationException(Response .status(Response.Status.BAD_REQUEST) .entity(new ErrorResponse("InvalidParameterException", e.getLocalizedMessage())).build()); } } public Date getDate() { return date; } }
Add wildcard condition to handle navigation to non-root url
const path = require('path'); const morgan = require('morgan'); const bodyParser = require('body-parser'); const webpack = require('webpack'); const webpackConfig = require(process.env.WEBPACK_CONFIG ? process.env.WEBPACK_CONFIG : '../../webpack.config'); const compiler = webpack(webpackConfig); module.exports = (app, express) => { app.use(morgan('dev')); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(require('webpack-dev-middleware')(compiler, { inline: true, hot: true, noInfo: true, publicPath: webpackConfig.output.publicPath, })); app.use(require('webpack-hot-middleware')(compiler, { path: '/__webpack_hmr', heartbeat: 10 * 1000, })); app.use(express.static(path.resolve(__dirname, '../../public'))); app.get('*', (req, res) => { res.sendFile(path.resolve(__dirname, '../../public', 'index.html')); }); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); };
const path = require('path'); const morgan = require('morgan'); const bodyParser = require('body-parser'); const webpack = require('webpack'); const webpackConfig = require(process.env.WEBPACK_CONFIG ? process.env.WEBPACK_CONFIG : '../../webpack.config'); const compiler = webpack(webpackConfig); module.exports = (app, express) => { app.use(morgan('dev')); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(require('webpack-dev-middleware')(compiler, { inline: true, hot: true, noInfo: true, publicPath: webpackConfig.output.publicPath, })); app.use(require('webpack-hot-middleware')(compiler, { path: '/__webpack_hmr', heartbeat: 10 * 1000, })); app.use(express.static(path.resolve(__dirname, '../../public'))); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); };
Revert "Revert "Ignore test that causes CI to fail on Java 7 - works locally."" This reverts commit 5d60bef3afd33f35a9789015a761f16e58c5cc4e.
package io.hawt.git; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import static io.hawt.git.GitFacadeTest.assertConfigDirectoryExists; import static io.hawt.git.GitFacadeTest.assertFileContents; import static io.hawt.git.GitFacadeTest.createTestGitFacade; /** * Tests we can clone a remote repo */ @Ignore("Fails on CircleCI with Java 7") public class GitCloneTest { GitFacade git = createTestGitFacade(); @Before public void init() throws Exception { git.init(); } @After public void destroy() throws Exception { git.destroy(); } @Test public void clonedRemoteRepo() throws Exception { assertConfigDirectoryExists(git); String contents = assertFileContents(git, "master", "/ReadMe.md"); System.out.println("Read me is: " + contents.trim()); } }
package io.hawt.git; import org.junit.After; import org.junit.Before; import org.junit.Test; import static io.hawt.git.GitFacadeTest.assertConfigDirectoryExists; import static io.hawt.git.GitFacadeTest.assertFileContents; import static io.hawt.git.GitFacadeTest.createTestGitFacade; /** * Tests we can clone a remote repo */ public class GitCloneTest { GitFacade git = createTestGitFacade(); @Before public void init() throws Exception { git.init(); } @After public void destroy() throws Exception { git.destroy(); } @Test public void clonedRemoteRepo() throws Exception { assertConfigDirectoryExists(git); String contents = assertFileContents(git, "master", "/ReadMe.md"); System.out.println("Read me is: " + contents.trim()); } }
Add getter for futures positions for BitVc
package org.knowm.xchange.huobi.service; import org.knowm.xchange.Exchange; import org.knowm.xchange.huobi.BitVc; import org.knowm.xchange.huobi.BitVcFutures; import org.knowm.xchange.huobi.dto.trade.BitVcFuturesPosition; import org.knowm.xchange.huobi.dto.trade.BitVcFuturesPositionByContract; import si.mazi.rescu.RestProxyFactory; public class BitVcFuturesServiceRaw { protected final BitVcFutures bitvc; protected final String accessKey; protected HuobiDigest digest; public BitVcFuturesServiceRaw(Exchange exchange) { this.bitvc = RestProxyFactory.createProxy(BitVcFutures.class, "https://api.bitvc.com/futures"); this.accessKey = exchange.getExchangeSpecification().getApiKey(); /** BitVc Futures expect a different secret key digest name from BitVc spot and Huobi */ this.digest = new HuobiDigest(exchange.getExchangeSpecification().getSecretKey(), "secretKey"); } public BitVcFuturesPositionByContract getFuturesPositions() { final BitVcFuturesPositionByContract positions = bitvc.positions(accessKey, 1, requestTimestamp(), digest); return positions; } protected long requestTimestamp() { return System.currentTimeMillis() / 1000; } }
package org.knowm.xchange.huobi.service; import org.knowm.xchange.Exchange; import org.knowm.xchange.huobi.BitVc; import org.knowm.xchange.huobi.BitVcFutures; import si.mazi.rescu.RestProxyFactory; public class BitVcFuturesServiceRaw { protected final BitVcFutures bitvc; protected final String accessKey; protected HuobiDigest digest; public BitVcFuturesServiceRaw(Exchange exchange) { this.bitvc = RestProxyFactory.createProxy(BitVcFutures.class, "https://api.bitvc.com/futures"); this.accessKey = exchange.getExchangeSpecification().getApiKey(); /** BitVc Futures expect a different secret key digest name from BitVc spot and Huobi */ this.digest = new HuobiDigest(exchange.getExchangeSpecification().getSecretKey(), "secretKey"); } protected long requestTimestamp() { return System.currentTimeMillis() / 1000; } }
Make listeners to show & hide description more consistent
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. // You can use CoffeeScript in this file: http://coffeescript.org/ ListenFor = (function() { var displaySection = function(section) { $(section).on('click', '.interest', function(event) { $('.main-content').hide('slow'); $(this).siblings('.main-content').show('slow'); }); } var description = function() { $('.description').on('click', function(event) { event.preventDefault(); $(this).parent().siblings('.hidden').show('slow'); }) } var less = function() { $('.hidden').on('click', '.less', function(event) { event.preventDefault(); $(this).parent().hide('slow'); }); } return { section: displaySection, description: description, less: less } })(); $(document).ready(function() { ListenFor.section('#projects'); ListenFor.section('#blog'); ListenFor.section('#resume'); ListenFor.section('#about'); ListenFor.section('#contact'); ListenFor.description(); ListenFor.less(); });
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. // You can use CoffeeScript in this file: http://coffeescript.org/ ListenFor = (function() { var displaySection = function(section) { $(section).on('click', '.interest', function(event) { $('.main-content').hide('slow'); $(this).siblings('.main-content').show('slow'); }); } var description = function() { $('.description').on('click', function(event) { event.preventDefault(); $(this).parent().siblings().removeClass('hidden'); }) } var less = function() { $('.hidden').on('click', '.less', function(event) { event.preventDefault(); $(this).parent().addClass('hidden'); }); } return { section: displaySection, description: description, less: less } })(); $(document).ready(function() { ListenFor.section('#projects'); ListenFor.section('#blog'); ListenFor.section('#resume'); ListenFor.section('#about'); ListenFor.section('#contact'); ListenFor.description(); ListenFor.less(); });
Set sample server to test it's working
$(function () { 'use strict'; var peer = new Peer({ host: 'api.tandembox.co', port: 80, path: '/peer' }); peer.on('open', function (id) { $('h1').html('Hi ' + id + ' :)'); peer.connect('defaultId'); }); peer.on('call', function (call) { call.on('stream', function (stream) { var streamUrl = URL.createObjectURL(stream); var audio = new Audio(); audio.src = streamUrl; audio.play(); console.log('Playing %s', streamUrl); }); call.answer(); }); peer.on('error', function (err) { console.error(err); }); });
$(function () { 'use strict'; var peer = new Peer({ key: 'evycxpu0zuissjor' }); peer.on('open', function (id) { $('h1').html('Hi ' + id + ' :)'); peer.connect('defaultId'); }); peer.on('call', function (call) { call.on('stream', function (stream) { var streamUrl = URL.createObjectURL(stream); var audio = new Audio(); audio.src = streamUrl; audio.play(); }); call.answer(); }); peer.on('error', function (err) { console.error(err); }); });
Change database in test because Travis was failing
package com.mijecu25.sqlplus.compiler.core.statement; import java.sql.SQLException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * Test StatementUseDatabase * * @author Miguel Velez - miguelvelezmj25 * @version 0.1.0.2 */ public class TestStatementUseDatabase extends TestStatement { protected static StatementUseDatabase statement; @BeforeClass public static void initialize() throws SQLException { TestStatement.initialize(); // TODO this might not work in all computers since they might not have this database TestStatementUseDatabase.statement = new StatementUseDatabase("information_schema"); } @AfterClass public static void terminate() throws SQLException { TestStatement.terminate(); } @Test public void testStatementUseDatabase() { StatementUseDatabase statement = new StatementUseDatabase("information_schema"); Assert.assertNotNull(statement); } @Test public void testExecute() throws SQLException { TestStatementUseDatabase.statement.execute(TestStatementUseDatabase.connection); } }
package com.mijecu25.sqlplus.compiler.core.statement; import java.sql.SQLException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * Test StatementUseDatabase * * @author Miguel Velez - miguelvelezmj25 * @version 0.1.0.1 */ public class TestStatementUseDatabase extends TestStatement { protected static StatementUseDatabase statement; @BeforeClass public static void initialize() throws SQLException { TestStatement.initialize(); // TODO this might not work in all computers since they might not have this database TestStatementUseDatabase.statement = new StatementUseDatabase("sys"); } @AfterClass public static void terminate() throws SQLException { TestStatement.terminate(); } @Test public void testStatementUseDatabase() { StatementUseDatabase statement = new StatementUseDatabase("sys"); Assert.assertNotNull(statement); } @Test public void testExecute() throws SQLException { TestStatementUseDatabase.statement.execute(TestStatementUseDatabase.connection); } }
Add health update packet code
module.exports = { // Packet constants PLAYER_START: "1", PLAYER_ADD: "2", PLAYER_ANGLE: "2", PLAYER_UPDATE: "3", PLAYER_ATTACK :"4", LEADERBOAD: "5", PLAYER_MOVE: "3", PLAYER_REMOVE: "4", LEADERS_UPDATE: "5", LOAD_GAME_OBJ: "6", GATHER_ANIM: "7", AUTO_ATK: "7", WIGGLE: "8", CLAN_CREATE: "8", PLAYER_LEAVE_CLAN: "9", STAT_UPDATE: "9", CLAN_REQ_JOIN: "10", UPDATE_HEALTH: "10", CLAN_ACC_JOIN: "11", CLAN_KICK: "12", UPDATE_AGE: "15", CHAT: "ch", CLAN_DEL: "ad", PLAYER_SET_CLAN: "st", SET_CLAN_PLAYERS: "sa", CLAN_ADD: "ac", CLAN_NOTIFY: "an", MINIMAP: "mm", DISCONN: "d" }
module.exports = { // Packet constants PLAYER_START: "1", PLAYER_ADD: "2", PLAYER_ANGLE: "2", PLAYER_UPDATE: "3", PLAYER_ATTACK :"4", LEADERBOAD: "5", PLAYER_MOVE: "3", PLAYER_REMOVE: "4", LEADERS_UPDATE: "5", LOAD_GAME_OBJ: "6", GATHER_ANIM: "7", AUTO_ATK: "7", WIGGLE: "8", CLAN_CREATE: "8", PLAYER_LEAVE_CLAN: "9", STAT_UPDATE: "9", CLAN_REQ_JOIN: "10", CLAN_ACC_JOIN: "11", CLAN_KICK: "12", UPDATE_AGE: "15", CHAT: "ch", CLAN_DEL: "ad", PLAYER_SET_CLAN: "st", SET_CLAN_PLAYERS: "sa", CLAN_ADD: "ac", CLAN_NOTIFY: "an", MINIMAP: "mm", DISCONN: "d" }
Add a way to fetch the calendar used in the EventApi
<?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; use Doctrine\Common\Collections\Collection; use CalendArt\AbstractEvent, CalendArt\AbstractCalendar; /** * Handle the dialog with the adapter's api for its events * * @author Baptiste Clavié <baptiste@wisembly.com> */ interface EventApiInterface { /** * Get all the events available on the selected calendar * * @return Collection<AbstractEvent> */ public function getList(AbstractCriterion $criterion = null); /** * Returns the specific information for a given event * * @param mixed $identifier Identifier of the event to fetch * * @return AbstractEvent */ public function get($identifier, AbstractCriterion $criterion = null); /** * Get the associated calendar for this api * * @return AbstractCalendar */ public function getCalendar(); }
<?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; use Doctrine\Common\Collections\Collection; use CalendArt\AbstractEvent; /** * Handle the dialog with the adapter's api for its events * * @author Baptiste Clavié <baptiste@wisembly.com> */ interface EventApiInterface { /** * Get all the events available on the selected calendar * * @return Collection<AbstractEvent> */ public function getList(AbstractCriterion $criterion = null); /** * Returns the specific information for a given event * * @param mixed $identifier Identifier of the event to fetch * * @return AbstractEvent */ public function get($identifier, AbstractCriterion $criterion = null); }
Add js resize script to header. git-svn-id: 245d8f85226f8eeeaacc1269b037bb4851d63c96@901 54a900ba-8191-11dd-a5c9-f1483cedc3eb
<?php session_start(); ?> <!DOCTYPE html> <head> <title>ClinicCases - Online Case Management Software for Law School Clinics</title> <meta name="robots" content="noindex"> <link rel="stylesheet" href="html/css/cm.css" type="text/css"> <link rel="stylesheet" href="html/css/cm_tabs.css" type="text/css"> <link rel="stylesheet" href="lib/jqueryui/css/custom-theme/jquery-ui-1.8.9.custom.css" type="text/css"> <link rel="shortcut icon" type="image/x-icon" href="html/images/favicon.ico"> <script src="lib/jqueryui/js/jquery-1.4.4.min.js" type="text/javascript"></script> <script src="lib/jqueryui/js/jquery-ui-1.8.9.custom.min.js" type="text/javascript"></script> <script src="lib/javascripts/jquery.idletimer.js" type="text/javascript"></script> <script src="lib/javascripts/jquery.idletimeout.js" type="text/javascript"></script> <script src="html/js/sizeContentWindow.js" type="text/javascript"></script>
<?php session_start(); ?> <!DOCTYPE html> <head> <title>ClinicCases - Online Case Management Software for Law School Clinics</title> <meta name="robots" content="noindex"> <link rel="stylesheet" href="html/css/cm.css" type="text/css"> <link rel="stylesheet" href="html/css/cm_tabs.css" type="text/css"> <link rel="stylesheet" href="lib/jqueryui/css/custom-theme/jquery-ui-1.8.9.custom.css" type="text/css"> <link rel="shortcut icon" type="image/x-icon" href="html/images/favicon.ico"> <script src="lib/jqueryui/js/jquery-1.4.4.min.js" type="text/javascript"></script> <script src="lib/jqueryui/js/jquery-ui-1.8.9.custom.min.js" type="text/javascript"></script> <script src="lib/javascripts/jquery.idletimer.js" type="text/javascript"></script> <script src="lib/javascripts/jquery.idletimeout.js" type="text/javascript"></script>
Return response instead of print on client side
import socket import sys def client(msg): client_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) client_socket.connect(('127.0.0.1', 50000)) # sends command line message to server, closes socket to writing client_socket.sendall(msg) client_socket.shutdown(socket.SHUT_WR) buffsize = 32 response_msg = '' done = False while not done: msg_part = client_socket.recv(buffsize) if len(msg_part) < buffsize: done = True client_socket.close() response_msg += msg_part return response_msg if __name__ == '__main__': client(sys.argv[1])
import socket import sys def client(msg): client_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) client_socket.connect(('127.0.0.1', 50000)) # sends command line message to server, closes socket to writing client_socket.sendall(msg) client_socket.shutdown(socket.SHUT_WR) buffsize = 32 response_msg = '' done = False while not done: msg_part = client_socket.recv(buffsize) if len(msg_part) < buffsize: done = True client_socket.close() response_msg += msg_part print response_msg if __name__ == '__main__': client(sys.argv[1])
Add user table to module init
import os from flask import Flask from flask.ext.assets import Bundle, Environment from flask.ext.login import LoginManager from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # Load the app config app.config.from_object("config.Config") assets = Environment(app) db= SQLAlchemy(app) login = LoginManager() login.init_app(app) assets.load_path = [ os.path.join(os.path.dirname(__file__), 'static'), os.path.join(os.path.dirname(__file__), 'static', 'bower_components') ] assets.register( 'js_all', Bundle( 'jquery/dist/jquery.min.js', 'bootstrap/dist/js/bootstrap.min.js', output='js_all.js' ) ) assets.register( 'css_all', Bundle( 'bootswatch/sandstone/bootstrap.css', 'css/ignition.css', output='css_all.css' ) ) from manager.views import core from manager.models import users
import os from flask import Flask from flask.ext.assets import Bundle, Environment from flask.ext.login import LoginManager from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # Load the app config app.config.from_object("config.Config") assets = Environment(app) db= SQLAlchemy(app) login = LoginManager() login.init_app(app) assets.load_path = [ os.path.join(os.path.dirname(__file__), 'static'), os.path.join(os.path.dirname(__file__), 'static', 'bower_components') ] assets.register( 'js_all', Bundle( 'jquery/dist/jquery.min.js', 'bootstrap/dist/js/bootstrap.min.js', output='js_all.js' ) ) assets.register( 'css_all', Bundle( 'bootswatch/sandstone/bootstrap.css', 'css/ignition.css', output='css_all.css' ) ) from manager.views import core
Fix settings modal button position and size
import EtherscanProxy from '@/wallets/web3-provider/etherscan-proxy'; const SERVERURL = 'https://api.etherscan.io/api'; const API_KEY = 'DSH5B24BQYKD1AD8KUCDY3SAQSS6ZAU175'; describe('EtherScan Proxy', () => { xit('[Problem] should respond correct json rpc', async () => { expect.assertions(3); const ethProxy = new EtherscanProxy(SERVERURL, API_KEY); await ethProxy .request({ method: 'eth_blockNumber', id: 5, jsonrpc: '2.0' }) .then(resp => { expect(resp.id).toEqual(5); expect(resp.jsonrpc).toEqual('2.0'); expect(resp.result.substr(0, 2)).toEqual('0x'); }); }); });
import EtherscanProxy from '@/wallets/web3-provider/etherscan-proxy'; const SERVERURL = 'https://api.etherscan.io/api'; const API_KEY = 'DSH5B24BQYKD1AD8KUCDY3SAQSS6ZAU175'; describe('EtherScan Proxy', () => { it('should respond correct json rpc', async () => { expect.assertions(3); const ethProxy = new EtherscanProxy(SERVERURL, API_KEY); await ethProxy .request({ method: 'eth_blockNumber', id: 5, jsonrpc: '2.0' }) .then(resp => { expect(resp.id).toEqual(5); expect(resp.jsonrpc).toEqual('2.0'); expect(resp.result.substr(0, 2)).toEqual('0x'); }); }); });
Fix for gulp config file
var gulp = require('gulp'); // include plug-ins var jshint = require('gulp-jshint'); var mocha = require('gulp-mocha'); // JS hint task gulp.task('jshint', function() { gulp.src('./src/*.js') .pipe(jshint()) .pipe(jshint.reporter('default')); }); gulp.task('mocha_test', function() { return gulp.src(['test/test-*.js'], { read: false }) .pipe(mocha({ reporter: 'spec', globals: { should: require('should') } })); }); gulp.task('default', function(){ gulp.run('jshint', 'mocha_test'); /*gulp.watch(scriptFiles, function(){ gulp.run('jshint', 'mocha_test'); });*/ });
var gulp = require('gulp'); // include plug-ins var jshint = require('gulp-jshint'); var mocha = require('gulp-mocha'); // JS hint task gulp.task('jshint', function() { gulp.src('./src/*.js') .pipe(jshint()) .pipe(jshint.reporter('default')); }); gulp.task('mocha_test', function() { return gulp.src(['test/test-*.js'], { read: false }) .pipe(mocha({ reporter: 'spec', globals: { should: require('should') } })); }); gulp.task('default', function(){ gulp.run('jshint', 'mocha_test'); gulp.watch(scriptFiles, function(){ gulp.run('jshint', 'mocha_test'); }); });
Move dependencies from removed 'jquery.ui.…' modules to 'jquery.ui' This increases the extension's MediaWiki dependency to version 1.34. Bug: T219604 Change-Id: Ic0bbb86ec93fff32731d84a7919f4951a9111d5f
<?php /* QuickResponse Extension for MediaWiki. @license MIT License */ $wgExtensionCredits[ 'other' ][] = array( 'path' => __FILE__, 'name' => 'QuickResponse', 'version' => '0.3.0', 'url' => '', 'author' => 'Konarak Ratnakar', 'descriptionmsg' => 'quickresponse-desc' ); $wgMessagesDirs['QuickResponse'] = __DIR__ . '/i18n'; $wgResourceModules[ 'QuickResponse' ] = array( 'scripts' => array('resources/qrcode.js', 'resources/jquery.qrcode.js', 'resources/quickresponse.js' ), 'dependencies' => 'jquery.ui', 'messages' => array('quickresponse-desc', 'quickresponse-text', 'quickresponse-title', 'quickresponse-tooltip' ), 'localBasePath' => __DIR__, 'remoteExtPath' => 'QuickResponse', ); $wgHooks[ 'BeforePageDisplay' ][] = function ( $out ) { $out->addModules( 'QuickResponse' ); return true; };
<?php /* QuickResponse Extension for MediaWiki. @license MIT License */ $wgExtensionCredits[ 'other' ][] = array( 'path' => __FILE__, 'name' => 'QuickResponse', 'version' => '0.3.0', 'url' => '', 'author' => 'Konarak Ratnakar', 'descriptionmsg' => 'quickresponse-desc' ); $wgMessagesDirs['QuickResponse'] = __DIR__ . '/i18n'; $wgResourceModules[ 'QuickResponse' ] = array( 'scripts' => array('resources/qrcode.js', 'resources/jquery.qrcode.js', 'resources/quickresponse.js' ), 'dependencies' => 'jquery.ui.dialog', 'messages' => array('quickresponse-desc', 'quickresponse-text', 'quickresponse-title', 'quickresponse-tooltip' ), 'localBasePath' => __DIR__, 'remoteExtPath' => 'QuickResponse', ); $wgHooks[ 'BeforePageDisplay' ][] = function ( $out ) { $out->addModules( 'QuickResponse' ); return true; };
Use newline instead of carriage return for import of buildings from XLS
<?php require_once('../../../config.gen.inc.php'); require_once "MDB2.php"; require_once $install_path."lib/db.php"; $db = new db; $stmtd =& $db->connection->prepare("DELETE FROM Buildings"); $stmtd->execute(); $filename = "buildings.txt"; $fd = fopen ($filename, "r"); $contents = fread ($fd,filesize ($filename)); fclose ($fd); $lines = explode("\n", $contents); echo("Starting import of ".count($lines)." building records..."); foreach ($lines as $line) { $fields = explode("\t", $line); echo("\nImporting '".$fields[0]."'..."); $types = array('text','text','text','text','text','text','text','integer','text','text','text','text','text'); $stmt =& $db->connection->prepare("INSERT INTO Buildings (name,latitude,longitude,physical_address,type,subtype,code,parent,wifi,phone,website,hours,campus,uid) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",$types); $stmt->execute(array($fields[0], $fields[1], $fields[2], $fields[3], $fields[4], $fields[5], $fields[6], $fields[7], $fields[8], $fields[9], $fields[10],$fields[11],$fields[12],$fields[13])); } echo("\nCompleted importing building data...\n"); ?>
<?php require_once('../../../config.gen.inc.php'); require_once "MDB2.php"; require_once $install_path."lib/db.php"; $db = new db; $stmtd =& $db->connection->prepare("DELETE FROM Buildings"); $stmtd->execute(); $filename = "buildings.txt"; $fd = fopen ($filename, "r"); $contents = fread ($fd,filesize ($filename)); fclose ($fd); $lines = explode("\r", $contents); echo("Starting import of ".count($lines)." building records..."); foreach ($lines as $line) { $fields = explode("\t", $line); echo("\nImporting '".$fields[0]."'..."); $types = array('text','text','text','text','text','text','text','integer','text','text','text','text','text'); $stmt =& $db->connection->prepare("INSERT INTO Buildings (name,latitude,longitude,physical_address,type,subtype,code,parent,wifi,phone,website,hours,campus,uid) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",$types); $stmt->execute(array($fields[0], $fields[1], $fields[2], $fields[3], $fields[4], $fields[5], $fields[6], $fields[7], $fields[8], $fields[9], $fields[10],$fields[11],$fields[12],$fields[13])); } echo("\nCompleted importing building data...\n"); ?>
Change update value to produce less thrash on embedded side
import blinkycolor import serial class BlinkyTape(object): def __init__(self, port, baud_rate = 115200, pixel_count = 60): self._serial = serial.Serial(port, baud_rate) self._pixel_count = pixel_count self._pixels = [blinkycolor.BLACK] * self._pixel_count @property def pixel_count(self): return self._pixel_count def set_pixel(self, index, color): if index >= self._pixel_count: raise IndexError self._pixels[index] = color def set_pixels(self, pixels): if len(pixels) != self._pixel_count: raise ValueError self._pixels = pixels def update(self): UPDATE_VALUE = [0, 0, 255] for pixel in self._pixels: self._serial.write(pixel.raw) self._serial.write(UPDATE_VALUE) self._serial.flush()
import blinkycolor import serial class BlinkyTape(object): def __init__(self, port, baud_rate = 115200, pixel_count = 60): self._serial = serial.Serial(port, baud_rate) self._pixel_count = pixel_count self._pixels = [blinkycolor.BLACK] * self._pixel_count @property def pixel_count(self): return self._pixel_count def set_pixel(self, index, color): if index >= self._pixel_count: raise IndexError self._pixels[index] = color def set_pixels(self, pixels): if len(pixels) != self._pixel_count: raise ValueError self._pixels = pixels def update(self): UPDATE_VALUE = [255, 255, 255] for pixel in self._pixels: self._serial.write(pixel.raw) self._serial.write(UPDATE_VALUE) self._serial.flush()
Add log emit for initial connect
var util = require('../util'); var log = require('../log'); var logger = log.logger('websocket'); var clients_limit = 5; var nb_clients=0; var updater = require('../updater'); function setupBroadcasts(clients_sockets){ log.on('any',function(msg){ clients_sockets.emit('log',msg); }); updater.on('status', function(status) { clients_sockets.emit('status', status); }); } var onConnect = function(socket) { var client = util.getClientAddress(socket.client.request) logger.info("Client " + client + " connected."); socket.on('disconnect', function() { logger.debug("Client disconnected"); }); socket.on('status', function(data) { socket.emit('status', machine.status); }); socket.on('ping', function(data) { socket.emit('pong'); }); socket.emit('status', updater.status); socket.emit('log', log.getLogBuffer()) }; module.exports = function(server) { server.io.on('connection', onConnect); setupBroadcasts(server.io.sockets); };
var util = require('../util'); var log = require('../log'); var logger = log.logger('websocket'); var clients_limit = 5; var nb_clients=0; var updater = require('../updater'); function setupBroadcasts(clients_sockets){ log.on('any',function(msg){ clients_sockets.emit('log',msg); }); updater.on('status', function(status) { clients_sockets.emit('status', status); }); } var onConnect = function(socket) { var client = util.getClientAddress(socket.client.request) logger.info("Client " + client + " connected."); socket.on('disconnect', function() { logger.debug("Client disconnected"); }); socket.on('status', function(data) { socket.emit('status', machine.status); }); socket.on('ping', function(data) { socket.emit('pong'); }); socket.emit('status', updater.status); }; module.exports = function(server) { server.io.on('connection', onConnect); setupBroadcasts(server.io.sockets); };
Include oauth2-provider's tests module in the installed package
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='edx-oauth2-provider', version='0.5.5', description='Provide OAuth2 access to edX installations', author='edX', url='https://github.com/edx/edx-oauth2-provider', license='AGPL', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], packages=find_packages(exclude=['tests']), dependency_links=[ 'git+https://github.com/edx/django-oauth2-provider@0.2.7-fork-edx-5#egg=django-oauth2-provider-0.2.7-fork-edx-5', ], install_requires=[ 'django-oauth2-provider==0.2.7-fork-edx-5', 'PyJWT==1.0.1' ] )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='edx-oauth2-provider', version='0.5.4', description='Provide OAuth2 access to edX installations', author='edX', url='https://github.com/edx/edx-oauth2-provider', license='AGPL', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], packages=find_packages(exclude=['tests', '*.tests']), dependency_links=[ 'git+https://github.com/edx/django-oauth2-provider@0.2.7-fork-edx-5#egg=django-oauth2-provider-0.2.7-fork-edx-5', ], install_requires=[ 'django-oauth2-provider==0.2.7-fork-edx-5', 'PyJWT==1.0.1' ] )
Add "prise de note" subject fixture
<?php namespace Ifensl\Bundle\PadManagerBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Ifensl\Bundle\PadManagerBundle\Entity\Subject; class LoadSubjectData implements FixtureInterface { /** * {@inheritDoc} */ public function load(ObjectManager $manager) { $algo = new Subject(); $algo->setName("Algorithmique"); $manager->persist($algo); $gestion = new Subject(); $gestion->setName("Gestion"); $manager->persist($gestion); $algebre = new Subject(); $algebre->setName("Algèbre"); $manager->persist($algebre); $prisDeNote = new Subject(); $prisDeNote->setName("Prise de notes"); $manager->persist($prisDeNote); $manager->flush(); } }
<?php namespace Ifensl\Bundle\PadManagerBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Ifensl\Bundle\PadManagerBundle\Entity\Subject; class LoadSubjectData implements FixtureInterface { /** * {@inheritDoc} */ public function load(ObjectManager $manager) { $algo = new Subject(); $algo->setName("Algorithmique"); $manager->persist($algo); $gestion = new Subject(); $gestion->setName("Gestion"); $manager->persist($gestion); $algebre = new Subject(); $algebre->setName("Algèbre"); $manager->persist($algebre); $manager->flush(); } }
Remove progress bar if element if not loading anymore git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@4260 b4e469a2-07ce-4b26-9273-4d7d95a670c7
package org.helioviewer.plugins.eveplugin.view.linedataselector.cellrenderer; import java.awt.Component; import javax.swing.JProgressBar; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import org.helioviewer.base.logging.Log; import org.helioviewer.plugins.eveplugin.view.linedataselector.LineDataSelectorElement; public class LoadingCellRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 2173458369966852891L; private final JProgressBar downloadProgressBar = new JProgressBar(); @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { LineDataSelectorElement element = (LineDataSelectorElement) value; Log.debug("element is downloading : " + element.isDownloading()); if (element.isDownloading()) { downloadProgressBar.setIndeterminate(true); downloadProgressBar.setVisible(element.isDownloading()); return downloadProgressBar; } else { return null; } } }
package org.helioviewer.plugins.eveplugin.view.linedataselector.cellrenderer; import java.awt.Component; import javax.swing.JProgressBar; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import org.helioviewer.plugins.eveplugin.view.linedataselector.LineDataSelectorElement; public class LoadingCellRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 2173458369966852891L; private final JProgressBar downloadProgressBar = new JProgressBar(); @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { LineDataSelectorElement element = (LineDataSelectorElement) value; downloadProgressBar.setIndeterminate(true); downloadProgressBar.setVisible(element.isDownloading()); return downloadProgressBar; } }
Remove ul class from search form
<header> <div class="top-bar"> <div class="top-bar-title"> <span data-responsive-toggle="responsive-menu" data-hide-for="medium"> <!-- <button class="menu-icon dark" type="button" data-toggle></button> --> <button class="menu-icon dark" type="button" data-open="offCanvasLeft"></button> </span> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo('name'); ?></a> </div><!-- .top-bar-title --> <div id="responsive-menu"> <div class="top-bar-left"> <?php if (has_nav_menu('primary_navigation')) :?> <?php sage_top_nav();?> <?php endif;?> </div><!-- .top-bar-left --> <div class="top-bar-right"> <?php get_search_form(); ?> </div><!-- .top-bar-right --> </div><!-- .responsive-menu --> </div><!-- .top-bar --> </header>
<header> <div class="top-bar"> <div class="top-bar-title"> <span data-responsive-toggle="responsive-menu" data-hide-for="medium"> <!-- <button class="menu-icon dark" type="button" data-toggle></button> --> <button class="menu-icon dark" type="button" data-open="offCanvasLeft"></button> </span> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo('name'); ?></a> </div><!-- .top-bar-title --> <div id="responsive-menu"> <div class="top-bar-left"> <?php if (has_nav_menu('primary_navigation')) :?> <?php sage_top_nav();?> <?php endif;?> </div><!-- .top-bar-left --> <div class="top-bar-right"> <ul class="menu"> <li><?php get_search_form(); ?></li> </ul> </div><!-- .top-bar-right --> </div><!-- .responsive-menu --> </div><!-- .top-bar --> </header>
Add dummy routes for API calls from organism search
<?php namespace AppBundle\Controller; use AppBundle\AppBundle; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\HttpFoundation\Request; class APIController extends Controller { /** * @param Request $request * @return \Symfony\Component\HttpFoundation\JsonResponse * @Route("/api/listing/overview", name="listing_overview") */ public function overviewAction(Request $request) { $overview = $this->get('app.api.listing.overview'); $db_version = $request->query->get('dbversion'); $result = $overview->execute($db_version, $request->getSession()); return $this->json($result); } /** * @Route("/api/listing/organism", name="organism_listing") */ public function organismListingAction(){ } /** * @Route("/api/result/organism", name="organism_result") */ public function organismResultAction(){ } }
<?php namespace AppBundle\Controller; use AppBundle\AppBundle; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\HttpFoundation\Request; class APIController extends Controller { /** * @param Request $request * @return \Symfony\Component\HttpFoundation\JsonResponse * @Route("/api/listing/overview", name="listing_overview") */ public function overviewAction(Request $request) { $overview = $this->get('app.api.listing.overview'); $db_version = $request->query->get('dbversion'); $result = $overview->execute($db_version, $request->getSession()); return $this->json($result); } }
Return a fresh collection every time - leave caching to calling application. This allows lists to be called for different languages and avoids hard-to-reason-about issues if the application applies transformations to the returned collection.
<?php namespace PeterColes\Countries; class Maker { public function lookup($locale = 'en', $flip = false) { $this->prep($locale); if ($flip) { return $this->countries->flip(); } return $this->countries; } public function keyValue($locale = 'en', $key = 'key', $value = 'value') { $this->prep($locale); $key = $key ?: 'key'; $value = $value ?: 'value'; return $this->countries->transform(function($item, $index) use ($key, $value) { return (object) [ $key => $index, $value =>$item ]; })->values(); } protected function prep($locale) { $locale = $locale ?: 'en'; $this->countries = collect(require realpath(__DIR__."/../data/$locale.php")); } }
<?php namespace PeterColes\Countries; class Maker { protected $countries = null; public function lookup($locale = 'en', $flip = false) { $this->prep($locale); if ($flip) { return $this->countries->flip(); } return $this->countries; } public function keyValue($locale = 'en', $key = 'key', $value = 'value') { $this->prep($locale); $key = $key ?: 'key'; $value = $value ?: 'value'; return $this->countries->transform(function($item, $index) use ($key, $value) { return (object) [ $key => $index, $value =>$item ]; })->values(); } protected function prep($locale) { if (!$this->countries) { $locale = $locale ?: 'en'; $this->countries = collect(require realpath(__DIR__."/../data/$locale.php")); } } }
Allow ember-power-select to be invoked transitively from another addon Also, the included hook is idempotent. The second time that is called is a noop
/* jshint node: true */ 'use strict'; // var path = require('path'); module.exports = { name: 'ember-power-select', included: function(appOrAddon) { let app = appOrAddon.app || appOrAddon; if (!app.__emberPowerSelectIncludedInvoked) { app.__emberPowerSelectIncludedInvoked = true; this._super.included.apply(this, arguments); // Don't include the precompiled css file if the user uses ember-cli-sass if (!app.registry.availablePlugins['ember-cli-sass']) { var addonConfig = app.options['ember-power-select']; if (!addonConfig || !addonConfig.theme) { app.import('vendor/ember-power-select.css'); } else { app.import('vendor/ember-power-select-'+addonConfig.theme+'.css'); } } } }, contentFor: function(type, config) { var emberBasicDropdown = this.addons.filter(function(addon) { return addon.name === 'ember-basic-dropdown'; })[0] return emberBasicDropdown.contentFor(type, config); } };  
/* jshint node: true */ 'use strict'; // var path = require('path'); module.exports = { name: 'ember-power-select', included: function(app) { this._super.included.apply(this, arguments); // Don't include the precompiled css file if the user uses ember-cli-sass if (!app.registry.availablePlugins['ember-cli-sass']) { var addonConfig = app.options['ember-power-select']; if (!addonConfig || !addonConfig.theme) { app.import('vendor/ember-power-select.css'); } else { app.import('vendor/ember-power-select-'+addonConfig.theme+'.css'); } } }, contentFor: function(type, config) { var emberBasicDropdown = this.addons.filter(function(addon) { return addon.name === 'ember-basic-dropdown'; })[0] return emberBasicDropdown.contentFor(type, config); } };  
:bug: Fix potential null reference callback invokation Fixes #11328
var childProcess = require('child_process'); // Exit the process if the command failed and only call the callback if the // command succeed, output of the command would also be piped. exports.safeExec = function(command, options, callback) { if (!callback) { callback = options; options = {}; } if (!options) options = {}; // This needed to be increased for `apm test` runs that generate many failures // The default is 200KB. options.maxBuffer = 1024 * 1024; var child = childProcess.exec(command, options, function(error, stdout, stderr) { if (error) process.exit(error.code || 1); else if (callback) callback(null); }); child.stderr.pipe(process.stderr); if (!options.ignoreStdout) child.stdout.pipe(process.stdout); } // Same with safeExec but call child_process.spawn instead. exports.safeSpawn = function(command, args, options, callback) { if (!callback) { callback = options; options = {}; } var child = childProcess.spawn(command, args, options); child.stderr.pipe(process.stderr); child.stdout.pipe(process.stdout); child.on('error', function(error) { console.error('Command \'' + command + '\' failed: ' + error.message); }); child.on('exit', function(code) { if (code != 0) process.exit(code); else callback(null); }); }
var childProcess = require('child_process'); // Exit the process if the command failed and only call the callback if the // command succeed, output of the command would also be piped. exports.safeExec = function(command, options, callback) { if (!callback) { callback = options; options = {}; } if (!options) options = {}; // This needed to be increased for `apm test` runs that generate many failures // The default is 200KB. options.maxBuffer = 1024 * 1024; var child = childProcess.exec(command, options, function(error, stdout, stderr) { if (error) process.exit(error.code || 1); else callback(null); }); child.stderr.pipe(process.stderr); if (!options.ignoreStdout) child.stdout.pipe(process.stdout); } // Same with safeExec but call child_process.spawn instead. exports.safeSpawn = function(command, args, options, callback) { if (!callback) { callback = options; options = {}; } var child = childProcess.spawn(command, args, options); child.stderr.pipe(process.stderr); child.stdout.pipe(process.stdout); child.on('error', function(error) { console.error('Command \'' + command + '\' failed: ' + error.message); }); child.on('exit', function(code) { if (code != 0) process.exit(code); else callback(null); }); }
Check if editor has parent
var _ = require('underscore'); var backbone = require('backbone'); var backboneBase = require('backbone-base'); var deepEmpty = require('deep-empty'); var outfile = require('datapackage-outfile'); var validator = require('datapackage-validate'); // Download validated datapackage module.exports = backbone.BaseView.extend({ reset: function(descriptor, schema) { var form = window.APP.layout.descriptorEdit.layout.form; this.$el.addClass('disabled'); // Drop errors of empty fields which are actually not required validator.validate(descriptor, schema).then((function(R) { var errors = _.filter(R.errors, function(E) { var editor = form.getEditor('root' + E.dataPath.replace(/\//g, '.')); var isRequired = editor.parent && _.contains(editor.parent.schema.required, editor.key); var value = editor.getValue(); return isRequired || !isRequired && editor.getValue() && !_.isEmpty(deepEmpty(editor.getValue())); }); if(!errors.length) this.$el .removeClass('disabled') .attr('href', outfile(descriptor, { IE9: window.APP.browser.name == 'ie' && parseInt(window.APP.browser.version.split('.')[0]) <= 9 })); }).bind(this)); return this; } });
var _ = require('underscore'); var backbone = require('backbone'); var backboneBase = require('backbone-base'); var deepEmpty = require('deep-empty'); var outfile = require('datapackage-outfile'); var validator = require('datapackage-validate'); // Download validated datapackage module.exports = backbone.BaseView.extend({ reset: function(descriptor, schema) { var form = window.APP.layout.descriptorEdit.layout.form; this.$el.addClass('disabled'); // Drop errors of empty fields which are actually not required validator.validate(descriptor, schema).then((function(R) { var errors = _.filter(R.errors, function(E) { var editor = form.getEditor('root' + E.dataPath.replace(/\//g, '.')); var isRequired = _.contains(editor.parent.schema.required, editor.key); var value = editor.getValue(); return isRequired || !isRequired && editor.getValue() && !_.isEmpty(deepEmpty(editor.getValue())); }); if(!errors.length) this.$el .removeClass('disabled') .attr('href', outfile(descriptor, { IE9: window.APP.browser.name == 'ie' && parseInt(window.APP.browser.version.split('.')[0]) <= 9 })); }).bind(this)); return this; } });
Fix URL to be HTTPS. random.org now redirects to HTTPS and we don't handle the redirect correctly, but if we start on HTTPS there is no redirect.
// // TrueRandom.java -- Java class TrueRandom // Project OrcSites // // $Id$ // // Copyright (c) 2009 The University of Texas at Austin. All rights reserved. // // Use and redistribution of this file is governed by the license terms in // the LICENSE file found in the project's top-level directory and also found at // URL: http://orc.csres.utexas.edu/license.shtml . // package orc.lib.net; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import orc.error.runtime.JavaException; import orc.error.runtime.TokenException; import orc.values.sites.compatibility.Args; import orc.values.sites.compatibility.EvalSite; public class TrueRandom extends EvalSite { private static String baseURL = "https://www.random.org/integers/?num=1&col=1&base=10&format=plain&rnd=new"; @Override public Object evaluate(final Args args) throws TokenException { try { final String number = HTTPUtils.getURL(new URL(baseURL + "&min=" + args.longArg(0) + "&max=" + (args.longArg(1) - 1))); return new Long(number.trim()); } catch (final MalformedURLException e) { throw new JavaException(e); } catch (final IOException e) { throw new JavaException(e); } } }
// // TrueRandom.java -- Java class TrueRandom // Project OrcSites // // $Id$ // // Copyright (c) 2009 The University of Texas at Austin. All rights reserved. // // Use and redistribution of this file is governed by the license terms in // the LICENSE file found in the project's top-level directory and also found at // URL: http://orc.csres.utexas.edu/license.shtml . // package orc.lib.net; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import orc.error.runtime.JavaException; import orc.error.runtime.TokenException; import orc.values.sites.compatibility.Args; import orc.values.sites.compatibility.EvalSite; public class TrueRandom extends EvalSite { private static String baseURL = "http://www.random.org/integers/?num=1&col=1&base=10&format=plain&rnd=new"; @Override public Object evaluate(final Args args) throws TokenException { try { final String number = HTTPUtils.getURL(new URL(baseURL + "&min=" + args.longArg(0) + "&max=" + (args.longArg(1) - 1))); return new Long(number.trim()); } catch (final MalformedURLException e) { throw new JavaException(e); } catch (final IOException e) { throw new JavaException(e); } } }
Add key prop for SongItem
import React, { PropTypes } from 'react' import SongItem from '../SongItem' class SongList extends React.Component { static propTypes = { fetchSongs: PropTypes.func.isRequired, songs: PropTypes.object, isFetching: PropTypes.bool.isRequired } render () { if (!this.props.songs || this.props.isFetching) return null let songs = this.props.songs.map(song => { return ( <SongItem title={song.title} plays={song.plays} onSelectSong={this.handleSongClick.bind(this, song.uid)} key={song.uid} /> ) }) return ( <div> {songs} </div> ) } handleSongClick(uid){ console.log('select', uid) } } export default SongList
import React, { PropTypes } from 'react' import SongItem from '../SongItem' class SongList extends React.Component { static propTypes = { fetchSongs: PropTypes.func.isRequired, songs: PropTypes.object, isFetching: PropTypes.bool.isRequired } render () { if (!this.props.songs || this.props.isFetching) return null let songs = this.props.songs.map(song => { return ( <SongItem title={song.title} plays={song.plays} onSelectSong={this.handleSongClick.bind(this, song.uid)} /> ) }) return ( <div> {songs} </div> ) } handleSongClick(uid){ console.log('select', uid) } } export default SongList
Use valid fromlist parameter when calling __import__ This was working before, but it wasn't what I had intended to write. It doesn't really matter what is passed in here as long as it isn't an empty list.
# import_string was appropriated from django and then rewritten for broader # python support. The version of this method can't be imported from Django # directly because it didn't exist until 1.7. def import_string(dotted_path): """ Import a dotted module path. Returns the attribute/class designated by the last name in the path. Raises ImportError if the import fails. """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: raise ImportError('%s doesn\'t look like a valid path' % dotted_path) module = __import__(module_path, fromlist=[class_name]) try: return getattr(module, class_name) except AttributeError: msg = 'Module "%s" does not define a "%s" attribute/class' % ( dotted_path, class_name) raise ImportError(msg)
# import_string was appropriated from django and then rewritten for broader # python support. The version of this method can't be imported from Django # directly because it didn't exist until 1.7. def import_string(dotted_path): """ Import a dotted module path. Returns the attribute/class designated by the last name in the path. Raises ImportError if the import fails. """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: raise ImportError('%s doesn\'t look like a valid path' % dotted_path) module = __import__(module_path, fromlist=['class_name']) try: return getattr(module, class_name) except AttributeError: msg = 'Module "%s" does not define a "%s" attribute/class' % ( dotted_path, class_name) raise ImportError(msg)
Comment out @override in createJSModules
package com.allthatseries.RNAudioPlayer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import com.facebook.react.bridge.JavaScriptModule; public class RNAudioPlayerPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new RNAudioPlayerModule(reactContext)); return modules; } // @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers( ReactApplicationContext reactContext) { return Collections.emptyList(); } }
package com.allthatseries.RNAudioPlayer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import com.facebook.react.bridge.JavaScriptModule; public class RNAudioPlayerPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new RNAudioPlayerModule(reactContext)); return modules; } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers( ReactApplicationContext reactContext) { return Collections.emptyList(); } }
Update Dates library, fix hour format and rename 'monthDayYear' to 'dayMonthYear'
import moment from 'moment'; import 'moment/locale/fr'; import 'moment-timezone'; moment.locale('fr'); export const dayMonthYear = (timestamp, timezone) => ( !timezone ? moment(timestamp).format('Do MMMM YYYY') : moment(timestamp).tz(timezone).format('Do MMMM YYYY') ); export const dayMonthYearAtTime = (timestamp, timezone) => ( !timezone ? moment(timestamp).format('Do MMMM YYYY [à] HH:mm') : moment(timestamp).tz(timezone).format('Do MMMM YYYY [à] HH:mm') ); export const timeago = (timestamp, timezone) => ( !timezone ? moment(timestamp).fromNow() : moment(timestamp).tz(timezone).fromNow() ); export const add = (timestamp, amount, range, timezone) => ( !timezone ? moment(timestamp).add(amount, range).format() : moment(timestamp).tz(timezone).add(amount, range).format() ); export const year = (timestamp, timezone) => ( !timezone ? moment(timestamp).format('YYYY') : moment(timestamp).tz(timezone).format('YYYY') );
import moment from 'moment'; import 'moment/locale/fr'; import 'moment-timezone'; moment.locale('fr'); export const monthDayYear = (timestamp, timezone) => ( !timezone ? moment(timestamp).format('MMMM Do, YYYY') : moment(timestamp).tz(timezone).format('MMMM Do, YYYY') ); export const dayMonthYearAtTime = (timestamp, timezone) => ( !timezone ? moment(timestamp).format('Do MMMM YYYY [à] hh:mm') : moment(timestamp).tz(timezone).format('Do MMMM YYYY [à] hh:mm') ); export const timeago = (timestamp, timezone) => ( !timezone ? moment(timestamp).fromNow() : moment(timestamp).tz(timezone).fromNow() ); export const add = (timestamp, amount, range, timezone) => ( !timezone ? moment(timestamp).add(amount, range).format() : moment(timestamp).tz(timezone).add(amount, range).format() ); export const year = (timestamp, timezone) => ( !timezone ? moment(timestamp).format('YYYY') : moment(timestamp).tz(timezone).format('YYYY') );
Add compatibility for Python 2
# coding: utf-8 from __future__ import unicode_literals import io import six from setuptools.command import setopt from setuptools.extern.six.moves import configparser class TestEdit: @staticmethod def parse_config(filename): parser = configparser.ConfigParser() with io.open(filename, encoding='utf-8') as reader: (parser.read_file if six.PY3 else parser.readfp)(reader) return parser @staticmethod def write_text(file, content): with io.open(file, 'wb') as strm: strm.write(content.encode('utf-8')) def test_utf8_encoding_retained(self, tmpdir): """ When editing a file, non-ASCII characters encoded in UTF-8 should be retained. """ config = tmpdir.join('setup.cfg') self.write_text(str(config), '[names]\njaraco=йарацо') setopt.edit_config(str(config), dict(names=dict(other='yes'))) parser = self.parse_config(str(config)) assert parser.get('names', 'jaraco') == 'йарацо' assert parser.get('names', 'other') == 'yes'
# coding: utf-8 from __future__ import unicode_literals import io import six from setuptools.command import setopt from setuptools.extern.six.moves import configparser class TestEdit: @staticmethod def parse_config(filename): parser = configparser.ConfigParser() with io.open(filename, encoding='utf-8') as reader: (parser.read_file if six.PY3 else parser.readfp)(reader) return parser @staticmethod def write_text(file, content): with io.open(file, 'wb') as strm: strm.write(content.encode('utf-8')) def test_utf8_encoding_retained(self, tmpdir): """ When editing a file, non-ASCII characters encoded in UTF-8 should be retained. """ config = tmpdir.join('setup.cfg') self.write_text(config, '[names]\njaraco=йарацо') setopt.edit_config(str(config), dict(names=dict(other='yes'))) parser = self.parse_config(str(config)) assert parser['names']['jaraco'] == 'йарацо' assert parser['names']['other'] == 'yes'
[TASK] Set the 'findNestedDependencies' flag for the r.js optimizer to true
/** * Grunt-Contrib-RequireJS * @description Optimize RequireJS projects using r.js. * @docs https://github.com/gruntjs/grunt-contrib-requirejs */ var config = require("../Config"); module.exports = { deploy: { options: { mainConfigFile: config.JavaScripts.paths.devDir + "/" + config.JavaScripts.requireJS.config + ".js", include: [config.JavaScripts.requireJS.libSourceFile, config.JavaScripts.requireJS.config], out: config.JavaScripts.requireJS.compileDistFile, // Include all require files in nested files. findNestedDependencies: true, // Wrap in an IIFE wrap: true, // Generate source maps for the build. generateSourceMaps: true, // Do not preserve license comments when working with source maps, incompatible. preserveLicenseComments: false, // Uglify the build with 'uglify2'. optimize: "uglify2", // Remove 'console.log(...)' statements if set to true in the grunt config. onBuildRead: function (moduleName, path, contents) { "use strict"; if(config.JavaScripts.requireJS.removeLoggingStatements) { return contents.replace(/console.log(.*);/g, ''); } else { return contents; } } } } };
/** * Grunt-Contrib-RequireJS * @description Optimize RequireJS projects using r.js. * @docs https://github.com/gruntjs/grunt-contrib-requirejs */ var config = require("../Config"); module.exports = { deploy: { options: { mainConfigFile: config.JavaScripts.paths.devDir + "/" + config.JavaScripts.requireJS.config + ".js", include: [config.JavaScripts.requireJS.libSourceFile, config.JavaScripts.requireJS.config], out: config.JavaScripts.requireJS.compileDistFile, // Wrap in an IIFE wrap: true, // Generate source maps for the build. generateSourceMaps: true, // Do not preserve license comments when working with source maps, incompatible. preserveLicenseComments: false, // Uglify the build with 'uglify2'. optimize: "uglify2", // Remove 'console.log(...)' statements if set to true in the grunt config. onBuildRead: function (moduleName, path, contents) { "use strict"; if(config.JavaScripts.requireJS.removeLoggingStatements) { return contents.replace(/console.log(.*);/g, ''); } else { return contents; } } } } };
Send data using jsonp instead of cors
Kadira = {}; Kadira.options = __meteor_runtime_config__.kadira; if(Kadira.options && Kadira.options.endpoint) { Kadira.syncedDate = new Ntp(Kadira.options.endpoint); Kadira.syncedDate.sync(); } /** * Send error metrics/traces to kadira server * @param {Object} payload Contains browser info and error traces */ Kadira.sendErrors = function (errors) { var retryCount = 0; var endpoint = Kadira.options.endpoint + '/errors'; var retry = new Retry({ minCount: 0, baseTimeout: 1000*5, maxTimeout: 1000*60, }); var payload = { errors: JSON.stringify(errors) }; tryToSend(); function tryToSend() { if(retryCount < 5) { retry.retryLater(retryCount++, sendPayload); } else { console.warn('Error sending error traces to kadira server'); } } function sendPayload () { $.ajax({ url: endpoint, data: payload, jsonp: 'callback', dataType: 'jsonp', error: tryToSend }); } } Kadira.getBrowserInfo = function () { return { browser: window.navigator.userAgent, userId: Meteor.userId, url: location.href }; }
Kadira = {}; Kadira.options = __meteor_runtime_config__.kadira; if(Kadira.options && Kadira.options.endpoint) { Kadira.syncedDate = new Ntp(Kadira.options.endpoint); Kadira.syncedDate.sync(); } /** * Send error metrics/traces to kadira server * @param {Object} payload Contains browser info and error traces */ Kadira.sendErrors = function (errors) { var retryCount = 0; var endpoint = Kadira.options.endpoint + '/errors'; var retry = new Retry({ minCount: 0, baseTimeout: 1000*5, maxTimeout: 1000*60, }); var payload = { errors: JSON.stringify(errors) }; tryToSend(); function tryToSend() { if(retryCount < 5) { retry.retryLater(retryCount++, sendPayload); } else { console.warn('Error sending error traces to kadira server'); } } function sendPayload () { $.ajax({ url: endpoint, data: payload, crossDomain: true, error: tryToSend }); } } Kadira.getBrowserInfo = function () { return { browser: window.navigator.userAgent, userId: Meteor.userId, url: location.href }; }
:sparkles: Add base and hasBase method to interface.
<?php namespace Risan\OAuth1\Config; interface UriConfigInterface { /** * Get the base URI. * * @return \Psr\Http\Message\UriInterface|null */ public function base(); /** * Check if base URI is set. * * @return boolean */ public function hasBase(); /** * Get the URI for obtaining temporary credentials. Also known as request * token URI. * * @return \Psr\Http\Message\UriInterface */ public function temporaryCredentials(); /** * Get the URI for asking user to authorize the request. * * @return \Psr\Http\Message\UriInterface */ public function authorization(); /** * Get the URI for obtaining token credentials. Also known as access token * URI. * * @return \Psr\Http\Message\UriInterface */ public function tokenCredentials(); /** * Get the callback URI. * * @return \Psr\Http\Message\UriInterface|null */ public function callback(); /** * Check if callback URI is set. * * @return boolean */ public function hasCallback(); }
<?php namespace Risan\OAuth1\Config; interface UriConfigInterface { /** * Get the URI for obtaining temporary credentials. Also known as request * token URI. * * @return \Psr\Http\Message\UriInterface */ public function temporaryCredentials(); /** * Get the URI for asking user to authorize the request. * * @return \Psr\Http\Message\UriInterface */ public function authorization(); /** * Get the URI for obtaining token credentials. Also known as access token * URI. * * @return \Psr\Http\Message\UriInterface */ public function tokenCredentials(); /** * Get the callback URI. * * @return \Psr\Http\Message\UriInterface|null */ public function callback(); /** * Check if callback URI is set. * * @return boolean */ public function hasCallback(); }
Add AJAX call to delete an entry on a user's dashboard page
$(document).ready(function() { $('#login-link').on('click', function(event) { event.preventDefault(); var $target = $(event.target); $.ajax({ type: 'GET', url: $target.attr('href'), dataType: 'html' }).done(function(response){ $resp = $(response).children('.auth-container'); $target.closest('#content').children('#pop-in').html($resp); }); $('#content').css("backgroundColor","#888877"); }); $('#signup-link').on('click', function(event) { event.preventDefault(); var $target = $(event.target); $.ajax({ type: 'GET', url: $target.attr('href'), dataType: 'html' }).done(function(response){ $resp = $(response).children('.auth-container'); $target.closest('#content').children('#pop-in').html($resp); }); $('#content').css("backgroundColor","#888877"); }); $('#delete-button').on('submit', function(event) { event.preventDefault(); var $target = $(event.target); $.ajax({ type: 'DELETE', url: $target.attr('action') }).done(function(response) { $target.closest('tr').remove(); }); }); });
$(document).ready(function() { $('#login-link').on('click', function(event) { event.preventDefault(); var $target = $(event.target); $.ajax({ type: 'GET', url: $target.attr('href'), dataType: 'html' }).done(function(response){ $resp = $(response).children('.auth-container') $target.closest('#content').children('#pop-in').html($resp); debugger }); $('#content').css("backgroundColor","#888877") }); $('#signup-link').on('click', function(event) { event.preventDefault(); var $target = $(event.target); $.ajax({ type: 'GET', url: $target.attr('href'), dataType: 'html' }).done(function(response){ $resp = $(response).children('.auth-container') $target.closest('#content').children('#pop-in').html($resp); debugger }); $('#content').css("backgroundColor","#888877") }); });
Use PDO in the local cellid script With 13ae949 the `mysql` calls have been changed to calls using the `PDO` classes. This updates `cellid_local.php` to use `PDO` as well. It also uses the proper capitalisation of the columns because at least the SQLite driver is case sensitive.
<?php require_once("database.php"); $db = connect_save(); if ($db === null) { echo "Result:4"; die(); } if ($_REQUEST["myl"] != "") { $temp = split(":", $_REQUEST["myl"]); $mcc = $temp[0]; $mnc = $temp[1]; $lac = $temp[2]; $cid = $temp[3]; } else { $mcc = $_REQUEST["mcc"]; $mnc = $_REQUEST["mnc"]; $lac = $_REQUEST["lac"]; $cid = $_REQUEST["cid"]; } if ( $mcc == "" || $mnc == "" || $lac == "" || $cid == "" ) { echo "Result:7"; // CellID not specified die(); } $result = $db->exec_sql("SELECT Latitude, Longitude FROM cellids WHERE CellID=? ORDER BY DateAdded DESC LIMIT 0,1", "$mcc-$mnc-$lac-$cid"); if ( $row=$result->fetch() ) echo "Result:0|$row[Latitude]|$row[Longitude]"; else echo "Result:6"; // No lat/long for specified CellID die(); ?>
<?php require_once("config.php"); if(!@mysql_connect("$DBIP","$DBUSER","$DBPASS")) { echo "Result:4"; die(); } mysql_select_db("$DBNAME"); if ($_REQUEST["myl"] != "") { $temp = split(":", $_REQUEST["myl"]); $mcc = $temp[0]; $mnc = $temp[1]; $lac = $temp[2]; $cid = $temp[3]; } else { $mcc = $_REQUEST["mcc"]; $mnc = $_REQUEST["mnc"]; $lac = $_REQUEST["lac"]; $cid = $_REQUEST["cid"]; } if ( $mcc == "" || $mnc == "" || $lac == "" || $cid == "" ) { echo "Result:7"; // CellID not specified die(); } $result=mysql_query("Select latitude,longitude FROM cellids WHERE cellid='$mcc-$mnc-$lac-$cid' order by dateadded desc limit 0,1"); if ( $row=mysql_fetch_array($result) ) echo "Result:0|".$row['latitude']."|".$row['longitude']; else echo "Result:6"; // No lat/long for specified CellID die(); ?>
Fix build break (renamed function)
from msrest import Serializer from ..commands import command, description from ._command_creation import get_mgmt_service_client @command('resource group list') @description('List resource groups') # TODO: waiting on Python Azure SDK bug fixes # @option('--tag-name -g <tagName>', L('the resource group's tag name')) # @option('--tag-value -g <tagValue>', L('the resource group's tag value')) # @option('--top -g <number>', L('Top N resource groups to retrieve')) def list_groups(args, unexpected): #pylint: disable=unused-argument from azure.mgmt.resource.resources import ResourceManagementClient, \ ResourceManagementClientConfiguration from azure.mgmt.resource.resources.models import ResourceGroup, ResourceGroupFilter rmc = get_mgmt_service_client(ResourceManagementClient, ResourceManagementClientConfiguration) # TODO: waiting on Python Azure SDK bug fixes #group_filter = ResourceGroupFilter(args.get('tag-name'), args.get('tag-value')) #groups = rmc.resource_groups.list(filter=None, top=args.get('top')) groups = rmc.resource_groups.list() serializable = Serializer().serialize_data(groups, "[ResourceGroup]") return serializable
from msrest import Serializer from ..commands import command, description from ._command_creation import get_service_client @command('resource group list') @description('List resource groups') # TODO: waiting on Python Azure SDK bug fixes # @option('--tag-name -g <tagName>', L('the resource group's tag name')) # @option('--tag-value -g <tagValue>', L('the resource group's tag value')) # @option('--top -g <number>', L('Top N resource groups to retrieve')) def list_groups(args, unexpected): #pylint: disable=unused-argument from azure.mgmt.resource.resources import ResourceManagementClient, \ ResourceManagementClientConfiguration from azure.mgmt.resource.resources.models import ResourceGroup, ResourceGroupFilter rmc = get_service_client(ResourceManagementClient, ResourceManagementClientConfiguration) # TODO: waiting on Python Azure SDK bug fixes #group_filter = ResourceGroupFilter(args.get('tag-name'), args.get('tag-value')) #groups = rmc.resource_groups.list(filter=None, top=args.get('top')) groups = rmc.resource_groups.list() serializable = Serializer().serialize_data(groups, "[ResourceGroup]") return serializable
Select all is applied one time only (as opposed to on all subsequent updates too)
/* eslint no-unused-vars: 0 */ /****************/ /** Select All **/ /****************/ gridState.processors['select-all'] = { watches: ['selection','data'], runs: function (options) { var all = options.model.selection.all; if (typeof all !== "boolean") { delete options.model.selection.all; return; } if (all){ if (options.model.logging) { console.log('Applying select all'); } options.model.data.forEach(function(row){ options.model.selection[row.$identity] = true; }); delete options.model.selection.all; } else { if (options.model.logging) { console.log('Clearing all selected rows'); } options.model.selection = {}; } } };
/* eslint no-unused-vars: 0 */ /****************/ /** Select All **/ /****************/ gridState.processors['select-all'] = { watches: ['selection','data'], runs: function (options) { var all = options.model.selection.all; if (typeof all !== "boolean") { delete options.model.selection.all; return; } if (all){ if (options.model.logging) { console.log('Applying select all'); } options.model.data.forEach(function(row){ options.model.selection[row.$identity] = true; }); } else { if (options.model.logging) { console.log('Clearing all selected rows'); } options.model.selection = {}; } } };
Add image property to callback data
'use strict'; var got = require('got'); var cheerio = require('cheerio'); var md = require('html-md'); module.exports = function(id, callback) { var url = 'http://www.stm.dk/_p_' + id + '.html'; got(url, function(err, data){ var $ = cheerio.load(data); var meta = $('meta[name="created"]'); var speech = $('.maininner.maininner-page'); speech.find('h1').remove(); speech.find('.nedtonet').remove(); var data = { source: url, date: meta.attr('content'), html: speech.html(), markdown: md(speech.html(), {inline: true}).replace(/\\/gi, '') }; var image = speech.find('.a110051').find('img').attr('src'); if(image){ speech.find('.a110051').remove(); image = 'http://www.stm.dk/' + image; } var linkElement = speech.find('a[onclick]'); if(linkElement.length){ var link = linkElement.attr('onclick').split('\'')[1]; linkElement.attr('href', link); data.video = link; speech.children().last().remove(); speech.children().last().remove(); speech.children().last().remove(); } callback(null, data) }); };
'use strict'; var got = require('got'); var cheerio = require('cheerio'); var md = require('html-md'); module.exports = function(id, callback) { var url = 'http://www.stm.dk/_p_' + id + '.html'; got(url, function(err, data){ var $ = cheerio.load(data); var meta = $('meta[name="created"]'); var speech = $('.maininner.maininner-page'); speech.find('h1').remove(); speech.find('.nedtonet').remove(); var data = { source: url, date: meta.attr('content'), html: speech.html(), markdown: md(speech.html(), {inline: true}).replace(/\\/gi, '') }; var linkElement = speech.find('a[onclick]'); if(linkElement.length){ var link = linkElement.attr('onclick').split('\'')[1]; linkElement.attr('href', link); data.video = link; speech.children().last().remove(); speech.children().last().remove(); speech.children().last().remove(); } callback(null, data) }); };
Remove sanitize from marked conf
'use strict'; import {Pipe} from 'angular2/angular2'; import {JsonPointer} from './JsonPointer'; import marked from 'marked'; marked.setOptions({ renderer: new marked.Renderer(), gfm: true, tables: true, breaks: false, pedantic: false, smartLists: true, smartypants: false }); @Pipe({ name: 'keys' }) export class KeysPipe { transform(obj) { return Object.keys(obj); } } @Pipe({ name: 'values' }) export class ValuesPipe { transform(obj) { return Object.keys(obj).map(key => obj[key]); } } @Pipe({ name: 'jsonPointerEscape' }) export class JsonPointerEscapePipe { transform(str) { return JsonPointer.escape(str); } } @Pipe({ name: 'marked' }) export class MarkedPipe { transform(str) { if (!str) return str; return marked(str); } }
'use strict'; import {Pipe} from 'angular2/angular2'; import {JsonPointer} from './JsonPointer'; import marked from 'marked'; marked.setOptions({ renderer: new marked.Renderer(), gfm: true, tables: true, breaks: false, pedantic: false, sanitize: true, smartLists: true, smartypants: false }); @Pipe({ name: 'keys' }) export class KeysPipe { transform(obj) { return Object.keys(obj); } } @Pipe({ name: 'values' }) export class ValuesPipe { transform(obj) { return Object.keys(obj).map(key => obj[key]); } } @Pipe({ name: 'jsonPointerEscape' }) export class JsonPointerEscapePipe { transform(str) { return JsonPointer.escape(str); } } @Pipe({ name: 'marked' }) export class MarkedPipe { transform(str) { if (!str) return str; return marked(str); } }
Fix call for status This might fix the UI call, but probably not
<?php /* PufferPanel - A Minecraft Server Management Panel Copyright (c) 2013 Dane Everitt This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ namespace PufferPanel\Core\Components; use \Unirest; /** * General Functions Trait */ trait Daemon { /** * Checks if the daemon is running. * * @param string $ip * @param int $port * @param int $timeout * @return bool */ public function avaliable($ip, $port = 5656, $timeout = 3) { Unirest\Request::timeout($timeout); try { Unirest\Request::get(\PufferPanel\Core\Daemon::buildBaseUrlForNode($ip, $port)); return true; } catch (\Exception $e) { return false; } } }
<?php /* PufferPanel - A Minecraft Server Management Panel Copyright (c) 2013 Dane Everitt This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ namespace PufferPanel\Core\Components; use \Unirest; /** * General Functions Trait */ trait Daemon { /** * Checks if the daemon is running. * * @param string $ip * @param int $port * @param int $timeout * @return bool */ public function avaliable($ip, $port = 5656, $timeout = 3) { Unirest\Request::timeout($timeout); try { Unirest::get(\PufferPanel\Core\Daemon::buildBaseUrlForNode($ip, $port)); return true; } catch (\Exception $e) { return false; } } }
Use comments to build the assertion name
import { TAP_ASSERT_DONE, TAP_COMMENT, TAP_PLAN } from '../actions' const initialState = { assertions: {}, currentCount: 0, lastComment: null, nextEstimatedCount: 0, plan: undefined } const assertName = (name, lastComment) => ( lastComment ? `[ ${lastComment.replace(/^#\s+/, '')} ] ${name}` : name ) export default (state = initialState, action) => { switch (action.type) { case TAP_ASSERT_DONE: return { ...state, assertions: { ...state.assertions, [`assert_${action.payload.id}`]: { ...action.payload, name: assertName(action.payload.name, state.lastComment) } }, currentCount: state.currentCount + 1, lastComment: null, plan: undefined } case TAP_COMMENT: return { ...state, lastComment: action.payload } case TAP_PLAN: return { ...state, currentCount: 0, plan: action.payload, nextEstimatedCount: state.currentCount } default: return state } }
import { TAP_ASSERT_DONE, TAP_PLAN } from '../actions' const initialState = { assertions: {}, currentCount: 0, nextEstimatedCount: 0, plan: undefined } export default (state = initialState, action) => { switch (action.type) { case TAP_ASSERT_DONE: return { ...state, assertions: { ...state.assertions, [`assert_${action.payload.id}`]: action.payload }, currentCount: state.currentCount + 1, plan: undefined } case TAP_PLAN: return { ...state, currentCount: 0, plan: action.payload, nextEstimatedCount: state.currentCount } default: return state } }
Sort languages by alphabetical order
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define */ define(function (require, exports, module) { 'use strict'; // Code that needs to display user strings should call require("strings") to load // strings.js. This file will dynamically load strings.js for the specified by bracketes.locale. // // Translations for other locales should be placed in nls/<locale<optional country code>>/strings.js // Localization is provided via the i18n plugin. // All other bundles for languages need to add a prefix to the exports below so i18n can find them. // TODO: dynamically populate the local prefix list below? module.exports = { root: true, "ca": true, "es": true, "fi": true, "it": true }; });
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define */ define(function (require, exports, module) { 'use strict'; // Code that needs to display user strings should call require("strings") to load // strings.js. This file will dynamically load strings.js for the specified by bracketes.locale. // // Translations for other locales should be placed in nls/<locale<optional country code>>/strings.js // Localization is provided via the i18n plugin. // All other bundles for languages need to add a prefix to the exports below so i18n can find them. // TODO: dynamically populate the local prefix list below? module.exports = { root: true, "fi": true, "it": true, "es": true, "ca": true }; });
Use symbol.for for node environments with potentially multiple loads
import _ from 'lodash' const unique = Symbol.for('lacona-unique-key') export default unique function getUniqueValue (result) { if (!_.isObject(result)) { return result } else if (result[unique] != null) { if (_.isFunction(result[unique])) { return result[unique](result) } else { return result[unique] } } else { return result } } export function checkAgainstUniqueList(result, uniqueList) { if (result == null) return true const value = getUniqueValue(result) if (_.isObject(value)) { return !_.some(uniqueList, _.partial(_.isEqual, _, value)) } else { return !_.includes(uniqueList, value) } } export function checkAgainstResultList(result, resultList) { if (result == null) return true const value = getUniqueValue(result) if (_.isObject(value)) { return !_.some(resultList, compareResult => _.isEqual(getUniqueValue(compareResult), value)) } else { return !_.some(resultList, compareResult => getUniqueValue(compareResult) === value) } } export function addToUniqueList(result, uniqueList) { const value = getUniqueValue(result) if (result != null) { uniqueList.splice(uniqueList.length, 0, value) } }
import _ from 'lodash' const unique = Symbol('lacona-unique-key') export default unique function getUniqueValue (result) { if (!_.isObject(result)) { return result } else if (result[unique] != null) { if (_.isFunction(result[unique])) { return result[unique](result) } else { return result[unique] } } else { return result } } export function checkAgainstUniqueList(result, uniqueList) { if (result == null) return true const value = getUniqueValue(result) if (_.isObject(value)) { return !_.some(uniqueList, _.partial(_.isEqual, _, value)) } else { return !_.includes(uniqueList, value) } } export function checkAgainstResultList(result, resultList) { if (result == null) return true const value = getUniqueValue(result) if (_.isObject(value)) { return !_.some(resultList, compareResult => _.isEqual(getUniqueValue(compareResult), value)) } else { return !_.some(resultList, compareResult => getUniqueValue(compareResult) === value) } } export function addToUniqueList(result, uniqueList) { const value = getUniqueValue(result) if (result != null) { uniqueList.splice(uniqueList.length, 0, value) } }
Add si_single to conditional controlling display of featured image
<?php echo "<!-- Using content.php template -->" ?> <?php if (is_single() || is_home()){ the_date('F j, Y', '<p class="date">', '</p>'); } ?> <h3><?php the_title() ?></h3> <?php if ((is_single() || is_home()) && get_option('show_byline_on_posts')) : ?> <div class="author-info"> <?php the_author(); ?> <p class="author-desc"> <small><?php the_author_meta(); ?></small></p> </div> <?php endif; if ( ! is_home() && ! is_search() && ! is_archive() ) : uw_mobile_menu(); endif; ?> <?php if ( is_archive() || is_home() || is_single() ) { the_post_thumbnail( array(130, 130), array( 'class' => 'attachment-post-thumbnail blogroll-img' ) ); the_content(); echo "<hr>"; } else the_content(); //comments_template(true); ?>
<?php if (is_single() || is_home()){ the_date('F j, Y', '<p class="date">', '</p>'); } ?> <h3><?php the_title() ?></h3> <?php if ((is_single() || is_home()) && get_option('show_byline_on_posts')) : ?> <div class="author-info"> <?php the_author(); ?> <p class="author-desc"> <small><?php the_author_meta(); ?></small></p> </div> <?php endif; if ( ! is_home() && ! is_search() && ! is_archive() ) : uw_mobile_menu(); endif; ?> <?php if ( is_archive() || is_home() ) { the_post_thumbnail( array(130, 130), array( 'class' => 'attachment-post-thumbnail blogroll-img' ) ); the_content(); echo "<hr>"; } else the_content(); //comments_template(true); ?>
Update plugin to work with version 6
var redback = require('redback'), Hoek = require('hoek'), Defaults = require('./defaults'); exports.register = function (plugin, options, next) { var settings = Hoek.applyToDefaults(Defaults, options); if (!settings.enabled) { return next(); } var ratelimit; if (options.client) { ratelimit = redback.use(options.client).createRateLimit('requests'); } else { ratelimit = redback.createClient().createRateLimit('requests'); } var error = plugin.hapi.error.wrap(new Error(), settings.error.code, settings.error.message); error.reformat(); plugin.ext('onRequest', function(request, reply) { if (request.path.match(settings.path)) { ratelimit.add(request.info.remoteAddress); ratelimit.count(request.info.remoteAddress, settings.interval, function (err, requests) { if (!err && requests > settings.requestLimit) { return reply(error); } else { return reply(); } }); } else { return reply(); } }); return next(); }; exports.register.attributes = { pkg: require('../package.json') };
var redback = require('redback'), Hoek = require('hoek'), Defaults = require('./defaults'); exports.register = function (plugin, options, next) { var settings = Hoek.applyToDefaults(Defaults, options); if (!settings.enabled) { return next(); } var ratelimit; if (options.client) { ratelimit = redback.use(options.client).createRateLimit('requests'); } else { ratelimit = redback.createClient().createRateLimit('requests'); } var error = plugin.hapi.error.wrap(new Error(), settings.error.code, settings.error.message); error.reformat(); plugin.ext('onRequest', function(request, reply) { if (request.path.match(settings.path)) { ratelimit.add(request.info.remoteAddress); ratelimit.count(request.info.remoteAddress, settings.interval, function (err, requests) { if (!err && requests > settings.requestLimit) { return reply(error); } else { return reply(); } }); } else { return reply(); } }); return next(); };
Use proper docblock for deprecation
<?php namespace Illuminate\Foundation\Bus; use ArrayAccess; /** * @deprecated since version 5.1. Use the DispatchesJobs trait instead. */ trait DispatchesCommands { /** * Dispatch a command to its appropriate handler. * * @param mixed $command * @return mixed */ protected function dispatch($command) { return app('Illuminate\Contracts\Bus\Dispatcher')->dispatch($command); } /** * Marshal a command and dispatch it to its appropriate handler. * * @param mixed $command * @param array $array * @return mixed */ protected function dispatchFromArray($command, array $array) { return app('Illuminate\Contracts\Bus\Dispatcher')->dispatchFromArray($command, $array); } /** * Marshal a command and dispatch it to its appropriate handler. * * @param mixed $command * @param \ArrayAccess $source * @param array $extras * @return mixed */ protected function dispatchFrom($command, ArrayAccess $source, $extras = []) { return app('Illuminate\Contracts\Bus\Dispatcher')->dispatchFrom($command, $source, $extras); } }
<?php namespace Illuminate\Foundation\Bus; use ArrayAccess; /** * This trait is deprecated. Use the DispatchesJobs trait. */ trait DispatchesCommands { /** * Dispatch a command to its appropriate handler. * * @param mixed $command * @return mixed */ protected function dispatch($command) { return app('Illuminate\Contracts\Bus\Dispatcher')->dispatch($command); } /** * Marshal a command and dispatch it to its appropriate handler. * * @param mixed $command * @param array $array * @return mixed */ protected function dispatchFromArray($command, array $array) { return app('Illuminate\Contracts\Bus\Dispatcher')->dispatchFromArray($command, $array); } /** * Marshal a command and dispatch it to its appropriate handler. * * @param mixed $command * @param \ArrayAccess $source * @param array $extras * @return mixed */ protected function dispatchFrom($command, ArrayAccess $source, $extras = []) { return app('Illuminate\Contracts\Bus\Dispatcher')->dispatchFrom($command, $source, $extras); } }
Remove initial error if reddit isn't given correct information
'use strict'; const r = require('../services/reddit'); let reportedItemNames = new Set(); let hasFinishedFirstRun = false; const SUBREDDITS = ['pokemontrades', 'SVExchange']; module.exports = { period: 60, onStart: true, task () { return r.get_subreddit(SUBREDDITS.join('+')).get_reports({limit: hasFinishedFirstRun ? 25 : 50}).then(items => { // Don't output the new reports on the first fetch, as that would cause old reports to be listed. // Unfortunately, there is no way to tell whether reports on an item have been ignored using the OAuth API. const newItemsToReport = hasFinishedFirstRun ? items.filter(item => !reportedItemNames.has(item.name)) : []; items.forEach(item => reportedItemNames.add(item.name)); hasFinishedFirstRun = true; return newItemsToReport.map(formatItem); }).catch((e) => console.log(`Error fetching subreddit reports. Error code: ${e.statusCode}`)); } }; function formatItem (item) { const permalink = item.constructor.name === 'Comment' ? item.link_url + item.id : item.url; const reportReason = (item.user_reports.length ? item.user_reports[0][0] : item.mod_reports.length ? item.mod_reports[0][0] : '') || '<no reason>'; return `[New report]: "${reportReason}" (on ${item.constructor.name.toLowerCase()} by /u/${item.author.name}, ${permalink} )`; }
'use strict'; const r = require('../services/reddit'); let reportedItemNames = new Set(); let hasFinishedFirstRun = false; const SUBREDDITS = ['pokemontrades', 'SVExchange']; module.exports = { period: 60, onStart: true, task () { return r.get_subreddit(SUBREDDITS.join('+')).get_reports({limit: hasFinishedFirstRun ? 25 : 50}).then(items => { // Don't output the new reports on the first fetch, as that would cause old reports to be listed. // Unfortunately, there is no way to tell whether reports on an item have been ignored using the OAuth API. const newItemsToReport = hasFinishedFirstRun ? items.filter(item => !reportedItemNames.has(item.name)) : []; items.forEach(item => reportedItemNames.add(item.name)); hasFinishedFirstRun = true; return newItemsToReport.map(formatItem); }); } }; function formatItem (item) { const permalink = item.constructor.name === 'Comment' ? item.link_url + item.id : item.url; const reportReason = (item.user_reports.length ? item.user_reports[0][0] : item.mod_reports.length ? item.mod_reports[0][0] : '') || '<no reason>'; return `[New report]: "${reportReason}" (on ${item.constructor.name.toLowerCase()} by /u/${item.author.name}, ${permalink} )`; }
Fix e2e tests for mock data changes
describe('Praad App', function() { 'use strict'; describe('Offer list view', function() { var offers, clickPromise; beforeEach(function() { browser.manage().deleteAllCookies(); browser.get('/'); clickPromise = element(by.css('.popup')).element(by.css('label')).click(); offers = element.all(by.repeater('offer in restaurant.offers')); }); it('should initially have 3 offers', function() { clickPromise.then(function() { expect(offers.count()).toBe(37); }); }); it('should filter the offer list as user types into the search box', function() { clickPromise.then(function() { element(by.model('search.query')).sendKeys('kana'); expect(offers.count()).toBe(11); var title = offers.first().element(by.binding('offer.title')).getText(); expect(title).toBe('Hiina menüü - Chicken eggplant'); }); }); }); });
describe('Praad App', function() { 'use strict'; describe('Offer list view', function() { var offers, clickPromise; beforeEach(function() { browser.manage().deleteAllCookies(); browser.get('/'); clickPromise = element(by.css('.popup')).element(by.css('label')).click(); offers = element.all(by.repeater('offer in restaurant.offers')); }); it('should initially have 3 offers', function() { clickPromise.then(function() { expect(offers.count()).toBe(13); }); }); it('should filter the offer list as user types into the search box', function() { clickPromise.then(function() { element(by.model('search.query')).sendKeys('kana'); expect(offers.count()).toBe(1); var title = offers.first().element(by.binding('offer.title')).getText(); expect(title).toBe('Pekingi kana'); }); }); }); });
Change state name from 'profile' to 'user'
angular .module('fitnessTracker', ['ui.router', 'templates', 'Devise']) .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('signup', { url: '/signup', templateUrl: 'auth/_signup.html', controller: 'AuthenticationController as AuthCtrl' }) .state('signin', { url: '/signin', templateUrl: 'auth/_signin.html', controller: 'AuthenticationController as AuthCtrl' }) .state('user', { url: '/user', template: 'user/_user.html', controller: 'UserController as UserCtrl' }); $urlRouterProvider.otherwise('/signin'); });
angular .module('fitnessTracker', ['ui.router', 'templates', 'Devise']) .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('signup', { url: '/signup', templateUrl: 'auth/_signup.html', controller: 'AuthenticationController as AuthCtrl' }) .state('signin', { url: '/signin', templateUrl: 'auth/_signin.html', controller: 'AuthenticationController as AuthCtrl' }) .state('profile', { url: '/user', template: 'user/_user.html', controller: 'UserController as UserCtrl' }); $urlRouterProvider.otherwise('/signin'); });
Clear preferences first in Chrome test
/* * (C) Copyright 2015 Boni Garcia (http://bonigarcia.github.io/) * * 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 io.github.bonigarcia.wdm.test; import org.junit.Before; import org.junit.BeforeClass; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.wdm.WebDriverManager; import io.github.bonigarcia.wdm.base.BrowserTestParent; /** * Test with Google Chrome browser. * * @author Boni Garcia (boni.gg@gmail.com) * @since 1.0.0 */ public class ChromeTest extends BrowserTestParent { @BeforeClass public static void setupClass() { WebDriverManager.chromedriver().clearPreferences().setup(); } @Before public void setupTest() { driver = new ChromeDriver(); } }
/* * (C) Copyright 2015 Boni Garcia (http://bonigarcia.github.io/) * * 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 io.github.bonigarcia.wdm.test; import org.junit.Before; import org.junit.BeforeClass; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.wdm.WebDriverManager; import io.github.bonigarcia.wdm.base.BrowserTestParent; /** * Test with Google Chrome browser. * * @author Boni Garcia (boni.gg@gmail.com) * @since 1.0.0 */ public class ChromeTest extends BrowserTestParent { @BeforeClass public static void setupClass() { WebDriverManager.chromedriver().setup(); } @Before public void setupTest() { driver = new ChromeDriver(); } }
Add table names to core model items
from django.db import models ## # Location Types ## class World(models.Model): name = models.CharField(max_length=30) homes = models.ManyToManyField(Home) class Meta: db_table = u'Worlds' class Home(models.Model): name = models.CharField(max_length=30) rooms = models.ManyToManyField(Room) class Meta: db_table = u'Homes' class Room(models.Model): name = models.CharField(max_length=30) class Meta: db_table = u'Rooms' ## # Device Types ## class Device(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class OutputDevice(Device): actions = models.ManyToManyField(Action) class Meta: abstract = True class InputDevice(Device): events = models.ManyToManyField(Event) class Meta: abstract = True ## # Input/Output ## class Action(models.Model): name = models.CharField(max_length=30) def run() class Meta: abstract = True class Event(models.Model): name = models.CharField(max_length=30) actions = models.ManyToMany(Action) def call(): for (action in self.actions): action.run() class Meta: abstract = True
from django.db import models ## # Location Types ## class World(models.Model): name = models.CharField(max_length=30) homes = models.ManyToManyField(Home) class Home(models.Model): name = models.CharField(max_length=30) rooms = models.ManyToManyField(Room) class Room(models.Model): name = models.CharField(max_length=30) ## # Device Types ## class Device(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class OutputDevice(Device): actions = models.ManyToManyField(Action) class Meta: abstract = True class InputDevice(Device): events = models.ManyToManyField(Event) class Meta: abstract = True ## # Input/Output ## class Action(models.Model): name = models.CharField(max_length=30) def run() class Meta: abstract = True class Event(models.Model): name = models.CharField(max_length=30) actions = models.ManyToMany(Action) def call(): for (action in self.actions): action.run() class Meta: abstract = True
Move inital_build task into own function
import os from fabric.api import run, env, settings, cd, put, sudo from fabric.contrib import files import private GIT_REPO = 'git://github.com/lextoumbourou/lextoumbourou.com.git' def prod(): env.hosts = list(private.PROD_SERVERS) def local(): env.hosts = ['localhost'] def initial_build(): """ Clone project and set permissions """ # Clone project if it doesn't exist with settings(warn_only=True): if run('test -d {0}'.format(private.APP_DIR)).failed: run('git clone {0} {1}'.format(GIT_REPO, private.APP_DIR)) # Make sure permissions are correct sudo('chown -R {0} {1}'.format(private.USER_GROUP, private.APP_DIR)) sudo('chmod -R 775 {0}'.format(private.APP_DIR)) def deploy(): """ Deploy code to production """ initial_build() # Perform Django app deployment tasks with cd(private.APP_DIR): run('git pull') put('private.py', 'lextoumbourou/private.py') run('python manage.py syncdb') run('python manage.py collectstatic --noinput')
import os from fabric.api import run, env, settings, cd, put, sudo from fabric.contrib import files import private def prod(): env.hosts = list(private.PROD_SERVERS) def local(): env.hosts = ['localhost'] def deploy(): """ Deploy code to production """ git_repo = 'git://github.com/lextoumbourou/lextoumbourou.com.git' with settings(warn_only=True): if run('test -d {0}'.format(private.APP_DIR)).failed: run('git clone {0} {1}'.format(git_repo, private.APP_DIR)) # Make sure permissions are correct sudo('chown -R {0} {1}'.format(private.USER_GROUP, private.APP_DIR)) sudo('chmod -R 775 {0}'.format(private.APP_DIR)) # Django app deployment tasks with cd(private.APP_DIR): run('git pull') put('private.py', 'lextoumbourou/private.py') run('python manage.py syncdb') run('python manage.py collectstatic --noinput')
Rewrite JS compilation task to make use of Webpack
const gulp = require('gulp'); const pump = require('pump'); const rename = require('gulp-rename'); const sass = require('gulp-sass'); const webpack = require('webpack-stream'); const uglify = require('gulp-uglify'); var config = { "pug": { "src": "./app/pug/*.pug", "dest": "./" }, "sass": { "src": "./app/sass/*.scss", "dest": "./css/" }, "js": { "src": "./app/js/*.js", "dest": "./js/" } }; gulp.task('pug', () => { return gulp.src(config.pug.src) .pipe(pug()) .pipe(gulp.dest(config.pug.dest)) }); gulp.task('sass', () => { return gulp.src(config.sass.src) .pipe(sass()) .pipe(gulp.dest(config.sass.dest)) }); gulp.task('js', function() { return gulp.src(config.js.src) .pipe(webpack({ watch: true, module: { loaders: [ { test: /\.jsx?/, loader: 'babel' }, ], }, })) .pipe(rename(function(path) { path.basename = 'app' })) .pipe(gulp.dest('./js/')); }); gulp.task('watch', () => { gulp.watch(config.sass.src, ['sass']); gulp.watch(config.js.src, ['js']); }); gulp.task('default', ['watch']);
const gulp = require('gulp'); const pump = require('pump'); const rename = require('gulp-rename'); const sass = require('gulp-sass'); const webpack = require('webpack-stream'); const uglify = require('gulp-uglify'); var config = { "pug": { "src": "./app/pug/*.pug", "dest": "./" }, "sass": { "src": "./app/sass/*.scss", "dest": "./css/" }, "js": { "src": "./app/js/*.js", "dest": "./js/" } }; gulp.task('pug', () => { return gulp.src(config.pug.src) .pipe(pug()) .pipe(gulp.dest(config.pug.dest)) }); gulp.task('sass', () => { return gulp.src(config.sass.src) .pipe(sass()) .pipe(gulp.dest(config.sass.dest)) }); gulp.task('js', (cb) => { pump([ gulp.src(config.js.src), uglify(), gulp.dest(config.js.dest) ], cb ); }); gulp.task('watch', () => { gulp.watch(config.sass.src, ['sass']); gulp.watch(config.js.src, ['js']); }); gulp.task('default', ['watch']);
Fix typo in package name.
package labels import ( "github.com/DVI-GI-2017/Jira__backend/models" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) const collection = "labels" func CheckExistence(mongo *mgo.Database, label *models.Label) (bool, error) { c, err := mongo.C(collection).Find(bson.M{"name": label.Name}).Count() return c != 0, err } func Create(mongo *mgo.Database, label interface{}) (result interface{}, err error) { return label, mongo.C(collection).Insert(label) } func All(mongo *mgo.Database) (result models.LabelsList, err error) { const defaultSize = 100 result = make(models.LabelsList, defaultSize) err = mongo.C(collection).Find(bson.M{}).All(&result) return } func FindById(mongo *mgo.Database, id bson.ObjectId) (*models.Label, error) { label := new(models.Label) err := mongo.C(collection).FindId(id).One(label) return label, err }
package projects import ( "github.com/DVI-GI-2017/Jira__backend/models" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) const collection = "labels" func CheckExistence(mongo *mgo.Database, label *models.Label) (bool, error) { c, err := mongo.C(collection).Find(bson.M{"name": label.Name}).Count() return c != 0, err } func Create(mongo *mgo.Database, label interface{}) (result interface{}, err error) { return label, mongo.C(collection).Insert(label) } func All(mongo *mgo.Database) (result models.LabelsList, err error) { const defaultSize = 100 result = make(models.LabelsList, defaultSize) err = mongo.C(collection).Find(bson.M{}).All(&result) return } func FindById(mongo *mgo.Database, id bson.ObjectId) (*models.Label, error) { label := new(models.Label) err := mongo.C(collection).FindId(id).One(label) return label, err }
i18n: Replace `@NonNls` with more appropriate `@NlsSafe` annotation GitOrigin-RevId: f3872ea7425784c82ad9e77e3a04b1805ab2685a
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.buildout.config; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.util.NlsSafe; import icons.PythonIcons; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public final class BuildoutCfgFileType extends LanguageFileType { public static final BuildoutCfgFileType INSTANCE = new BuildoutCfgFileType(); public static final @NlsSafe String DEFAULT_EXTENSION = "cfg"; private static final @NlsSafe String NAME = "BuildoutCfg"; private static final @NlsSafe String DESCRIPTION = "Buildout config"; private BuildoutCfgFileType() { super(BuildoutCfgLanguage.INSTANCE); } @Override @NotNull public String getName() { return NAME; } @Override @NotNull public String getDescription() { return DESCRIPTION; } @Override @NotNull public String getDefaultExtension() { return DEFAULT_EXTENSION; } @Override @Nullable public Icon getIcon() { return PythonIcons.Python.Buildout.Buildout; } }
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.buildout.config; import com.intellij.openapi.fileTypes.LanguageFileType; import icons.PythonIcons; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public final class BuildoutCfgFileType extends LanguageFileType { public static final BuildoutCfgFileType INSTANCE = new BuildoutCfgFileType(); @NonNls public static final String DEFAULT_EXTENSION = "cfg"; @NonNls private static final String NAME = "BuildoutCfg"; @NonNls private static final String DESCRIPTION = "Buildout config"; private BuildoutCfgFileType() { super(BuildoutCfgLanguage.INSTANCE); } @Override @NotNull public String getName() { return NAME; } @Override @NotNull public String getDescription() { return DESCRIPTION; } @Override @NotNull public String getDefaultExtension() { return DEFAULT_EXTENSION; } @Override @Nullable public Icon getIcon() { return PythonIcons.Python.Buildout.Buildout; } }
Add some debug output for convenience.
'use strict'; var debug = require('debug')('frontend:mqtt'); var express = require('express'); var router = express.Router(); var auth = require('../../passport'); var restUtils = require('../utils'); var os = require('os'); router.post('/mqtt', auth.requireAPIAuth(), function(req, res) { var userId = req.user.id; var topic = req.query.topic; var payload = req.body; if (typeof payload === 'object') { payload = JSON.stringify(payload); } var routingKey = userId + '.' + topic.replace('/', '.'); req.app.get('service').facet('amqp').then(function(amqp) { amqp.publish('amq.topic', routingKey, new Buffer(payload)); debug('Publishing to routing key', routingKey, 'payload', payload); restUtils.standardResponse(res, { "success": true }, {type: 'object'}); }); }); module.exports = function(parent) { parent.use(router); };
'use strict'; var express = require('express'); var router = express.Router(); var auth = require('../../passport'); var restUtils = require('../utils'); var os = require('os'); router.post('/mqtt', auth.requireAPIAuth(), function(req, res) { var userId = req.user.id; var topic = req.query.topic; var payload = req.body; if (typeof payload === 'object') { payload = JSON.stringify(payload); } var routingKey = userId + '.' + topic.replace('/', '.'); req.app.get('service').facet('amqp').then(function(amqp) { amqp.publish('amq.topic', routingKey, new Buffer(payload)); restUtils.standardResponse(res, { "success": true }, {type: 'object'}); }); }); module.exports = function(parent) { parent.use(router); };
Load the state before checking whether the state values match.
<?php namespace MartinBean\Facebook\Laravel; use Facebook\FacebookRedirectLoginHelper as BaseFacebookRedirectLoginHelper; use Request; use Session; class FacebookRedirectLoginHelper extends BaseFacebookRedirectLoginHelper { /** * Check if a redirect has a valid state. * * @return bool */ protected function isValidRedirect() { $this->loadState(); return $this->getCode() && Request::get('state', null) == $this->state; } /** * Return the code. * * @return string|null */ protected function getCode() { return Request::get('code', null); } /** * Stores a state string in session storage for CSRF protection. * * @param string $state */ protected function storeState($state) { Session::put($this->getSessionKey(), $state); } /** * Loads a state from session storage for CSRF validation. * * @return string|null */ protected function loadState() { return $this->state = Session::get($this->getSessionKey(), null); } /** * A helper method to get the session key to use. * * @return string */ protected function getSessionKey() { return 'facebook.state'; } }
<?php namespace MartinBean\Facebook\Laravel; use Facebook\FacebookRedirectLoginHelper as BaseFacebookRedirectLoginHelper; use Request; use Session; class FacebookRedirectLoginHelper extends BaseFacebookRedirectLoginHelper { /** * Check if a redirect has a valid state. * * @return bool */ protected function isValidRedirect() { return $this->getCode() && Request::get('state', null) == $this->state; } /** * Return the code. * * @return string|null */ protected function getCode() { return Request::get('code', null); } /** * Stores a state string in session storage for CSRF protection. * * @param string $state */ protected function storeState($state) { Session::put($this->getSessionKey(), $state); } /** * Loads a state from session storage for CSRF validation. * * @return string|null */ protected function loadState() { return $this->state = Session::get($this->getSessionKey(), null); } /** * A helper method to get the session key to use. * * @return string */ protected function getSessionKey() { return 'facebook.state'; } }
Test operator precedence and associativity
package golog import "testing" func TestBasic(t *testing.T) { single := make(map[string]string) single[`hello.`] = `hello` single[`a + b.`] = `+(a, b)` single[`first, second.`] = `','(first, second)` single[`\+ j.`] = `\+(j)` single[`a + b*c.`] = `+(a, *(b, c))` // test precedence single[`a + b + c.`] = `+(+(a, b), c)` // test left associativity single[`a^b^c.`] = `^(a, ^(b, c))` // test right associativity for test, wanted := range single { got, err := ReadTermStringOne(test, Read) maybePanic(err) if got.String() != wanted { t.Errorf("Reading `%s` gave `%s` instead of `%s`", test, got, wanted) } } // reading a couple simple terms oneTwoStr := `one. two.` oneTwo, err := ReadTermStringAll(oneTwoStr, Read) maybePanic(err) if oneTwo[0].String() != "one" { t.Errorf("Expected `one` in %#v", oneTwo) } if oneTwo[1].String() != "two" { t.Errorf("Expected `two` in %#v", oneTwo) } }
package golog import "testing" func TestBasic(t *testing.T) { single := make(map[string]string) single[`hello.`] = `hello` single[`a + b.`] = `+(a, b)` single[`first, second.`] = `','(first, second)` single[`\+ j.`] = `\+(j)` for test, wanted := range single { got, err := ReadTermStringOne(test, Read) maybePanic(err) if got.String() != wanted { t.Errorf("Reading `%s` gave `%s` instead of `%s`", test, got, wanted) } } // reading a couple simple terms oneTwoStr := `one. two.` oneTwo, err := ReadTermStringAll(oneTwoStr, Read) maybePanic(err) if oneTwo[0].String() != "one" { t.Errorf("Expected `one` in %#v", oneTwo) } if oneTwo[1].String() != "two" { t.Errorf("Expected `two` in %#v", oneTwo) } }
Add a bit of timeout to make it work better
import { polyfill } from 'smoothscroll-polyfill'; polyfill(); const previousScrolls = {}; window.history.scrollRestoration = 'manual'; window.addEventListener('scroll', (e) => { const path = document.location.pathname previousScrolls[path] = window.scrollY; }); export default function initScrolling(port) { port.subscribe(shouldScroll => { const path = document.location.pathname if (shouldScroll) { previousScrolls[path] = 0; window.scroll({ top: 0, behavior: 'smooth' }); } else { setTimeout(() => { window.scroll({ top: previousScrolls[path] }); }, 50) } }); }
import { polyfill } from 'smoothscroll-polyfill'; polyfill(); const previousScrolls = {}; window.history.scrollRestoration = 'manual'; window.addEventListener('scroll', (e) => { const path = document.location.pathname previousScrolls[path] = window.scrollY; }); export default function initScrolling(port) { port.subscribe(shouldScroll => { const path = document.location.pathname if (shouldScroll) { previousScrolls[path] = 0; window.scroll({ top: 0, behavior: 'smooth' }); } else { setTimeout(() => { window.scroll({ top: previousScrolls[path] }); }, 0) } }); }
Add webkit support for AudioContext
const audio = document.querySelector('audio') const audioContext = new (window.AudioContext || window.webkitAudioContext) const audioSource = audioContext.createMediaElementSource(audio) const analyser = audioContext.createAnalyser() let frequencyData = new Uint8Array(200) audioSource.connect(analyser) audioSource.connect(audioContext.destination) const height = window.screen.height / 3 const width = window.screen.width - 200 const bar = '1' const visualizer = d3.select('#visualizer') .append('svg') .attr('height', height) .attr('width', width) visualizer.selectAll('rect') .data(frequencyData) .enter() .append('rect') .attr('x', (d, i) => i * (width / frequencyData.length)) .attr('width', width / frequencyData.length - bar) function updateVisualizer () { window.requestAnimationFrame(updateVisualizer) analyser.getByteFrequencyData(frequencyData) visualizer.selectAll('rect') .data(frequencyData) .attr('y', d => height - d) .attr('height', d => d) .attr('fill', d => `rgb(${d}, ${d - 100}, ${d -50})`) } updateVisualizer()
'use strict' const audio = document.querySelector('audio') const audioContext = new window.AudioContext const audioSource = audioContext.createMediaElementSource(audio) const analyser = audioContext.createAnalyser() var frequencyData = new Uint8Array(200) audioSource.connect(analyser) audioSource.connect(audioContext.destination) const height = window.screen.height / 3 const width = window.screen.width - 200 const bar = '1' const visualizer = d3.select('#visualizer') .append('svg') .attr('height', height) .attr('width', width) visualizer.selectAll('rect') .data(frequencyData) .enter() .append('rect') .attr('x', (d, i) => i * (width / frequencyData.length)) .attr('width', width / frequencyData.length - bar) function updateChart () { window.requestAnimationFrame(updateChart) analyser.getByteFrequencyData(frequencyData) visualizer.selectAll('rect') .data(frequencyData) .attr('y', d => height - d) .attr('height', d => d) .attr('fill', d => `rgb(${d}, ${d - 100}, ${d -50})`) } updateChart()
[minor] Use buffers to prevent node from doing unwanted checks
'use strict'; var through = require('through2') , pumpify = require('pumpify') , split = require('split'); // // Expose the transform. // module.exports = condenseify; /** * Browserify transform to condense multiple blank lines * into a single blank line. * * @param {String} file File name * @param {Object} [options] Options object * @returns {Stream} Transform stream * @api public */ function condenseify(file, options) { if (/\.json$/.test(file)) return through(); var eol = new Buffer('\n') , appendNewLine = true , regex = /^[ \t]+$/ , isBlank = false; options = options || {}; function transform(line, encoding, next) { /* jshint validthis: true */ var length = line.length; if (!length) { isBlank = true; return next(); } if (!options['keep-non-empty'] && regex.test(line)) return next(); if (isBlank) { isBlank = false; this.push(eol); } appendNewLine = false; this.push(Buffer.concat([ line, eol ], ++length)); next(); } function flush(done) { /* jshint validthis: true */ if (appendNewLine) this.push(eol); done(); } return pumpify(split(), through(transform, flush)); }
'use strict'; var through = require('through2') , pumpify = require('pumpify') , split = require('split') , regex = /^[ \t]+$/; // // Expose the transform. // module.exports = condenseify; /** * Browserify transform to condense multiple blank lines * into a single blank line. * * @param {String} file File name * @param {Object} [options] Options object * @returns {Stream} Transform stream * @api public */ function condenseify(file, options) { if (/\.json$/.test(file)) return through(); var appendNewLine = true , isBlank = false; options = options || {}; function transform(line, encoding, next) { /* jshint validthis: true */ if (!line.length) { isBlank = true; return next(); } line = line.toString(); if (!options['keep-non-empty'] && regex.test(line)) return next(); if (isBlank) { isBlank = false; this.push('\n'); } appendNewLine = false; this.push(line +'\n'); next(); } function flush(done) { /* jshint validthis: true */ if (appendNewLine) this.push('\n'); done(); } return pumpify(split(), through(transform, flush)); }
Add lang_id parameter into breadcrumbs. :)
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model app\models\CttStaticdataCountrys */ $this->title = Yii::t('app', 'Update {modelClass}: ', [ 'modelClass' => 'Ctt Staticdata Countrys', ]) . ' ' . $model->name; $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Ctt Staticdata Countrys'), 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Ctt Staticdata Countrys(Language List)'), 'url' => ['lang-list', 'id' => $model->id]]; $this->params['breadcrumbs'][] = [ 'label' => $model->name, 'url' => [ 'view', 'id' => $model->id, 'lang_id' => $model->lang_id, ] ]; $this->params['breadcrumbs'][] = Yii::t('app', 'Update'); ?> <div class="ctt-staticdata-countrys-update"> <?= $this->render('_form', [ 'model' => $model, 'title' => Html::encode($this->title), 'model' => $model, 'mode' => 'edit', ]) ?> </div>
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model app\models\CttStaticdataCountrys */ $this->title = Yii::t('app', 'Update {modelClass}: ', [ 'modelClass' => 'Ctt Staticdata Countrys', ]) . ' ' . $model->name; $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Ctt Staticdata Countrys'), 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Ctt Staticdata Countrys(Language List)'), 'url' => ['lang-list', 'id' => $model->id]]; $this->params['breadcrumbs'][] = ['label' => $model->name, 'url' => ['view', 'id' => $model->id]]; $this->params['breadcrumbs'][] = Yii::t('app', 'Update'); ?> <div class="ctt-staticdata-countrys-update"> <?= $this->render('_form', [ 'model' => $model, 'title' => Html::encode($this->title), 'model' => $model, 'mode' => 'edit', ]) ?> </div>
Fix parameter spacing in statup update script invocation from workflow.
from airflow import DAG from airflow.operators import BashOperator, PythonOperator from datetime import datetime, timedelta default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': datetime(2015, 6, 1), 'email': ['airflow@airflow.com'], 'email_on_failure': False, 'email_on_retry': False, 'retries': 1, 'retry_delay': timedelta(minutes=5), # 'queue': 'bash_queue', # 'pool': 'backfill', # 'priority_weight': 10, # 'end_date': datetime(2016, 1, 1), } donor_index = "23" sample_id = "f82d213f-bc96-5b1d-e040-11ac0c486880" dag = DAG("freebayes-regenotype", default_args=default_args) t1 = BashOperator( task_id = "reserve_sample", bash_command = "su - postgres -c \"python /tmp/update-sample-status.py " + donor_index + " " + sample_id + " 1\"", dag = dag)
from airflow import DAG from airflow.operators import BashOperator, PythonOperator from datetime import datetime, timedelta default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': datetime(2015, 6, 1), 'email': ['airflow@airflow.com'], 'email_on_failure': False, 'email_on_retry': False, 'retries': 1, 'retry_delay': timedelta(minutes=5), # 'queue': 'bash_queue', # 'pool': 'backfill', # 'priority_weight': 10, # 'end_date': datetime(2016, 1, 1), } donor_index = "23" sample_id = "f82d213f-bc96-5b1d-e040-11ac0c486880" dag = DAG("freebayes-regenotype", default_args=default_args) t1 = BashOperator( task_id = "reserve_sample", bash_command = "su - postgres -c \"python /tmp/update-sample-status.py " + donor_index + " " + sample_id + "1\"", dag = dag)
[V0.4][Travis] Modify to match lexicographical order
//@@author A0143409J package seedu.address.logic.parser; import static org.junit.Assert.assertEquals; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import java.lang.reflect.Field; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import seedu.address.logic.commands.FinishCommand; import seedu.address.logic.commands.IncorrectCommand; public class FinishCommandParserTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void nullTest() throws Exception { thrown.expect(NullPointerException.class); FinishCommandParser.parse(null); } @Test public void validTest() throws Exception { Field field = FinishCommand.class.getDeclaredField("targetIndex"); field.setAccessible(true); FinishCommand finishCommand = (FinishCommand) FinishCommandParser.parse("1"); assertEquals(field.get(finishCommand), 1); } @Test public void invalidTest() throws Exception { Field field = IncorrectCommand.class.getDeclaredField("feedbackToUser"); field.setAccessible(true); IncorrectCommand incorrectCommand = (IncorrectCommand) FinishCommandParser.parse("+"); assertEquals(field.get(incorrectCommand), String.format(MESSAGE_INVALID_COMMAND_FORMAT, FinishCommand.MESSAGE_USAGE)); } }
//@@author A0143409J package seedu.address.logic.parser; import static org.junit.Assert.assertEquals; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import java.lang.reflect.Field; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import seedu.address.logic.commands.IncorrectCommand; import seedu.address.logic.commands.FinishCommand; public class FinishCommandParserTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void nullTest() throws Exception { thrown.expect(NullPointerException.class); FinishCommandParser.parse(null); } @Test public void validTest() throws Exception { Field field = FinishCommand.class.getDeclaredField("targetIndex"); field.setAccessible(true); FinishCommand finishCommand = (FinishCommand) FinishCommandParser.parse("1"); assertEquals(field.get(finishCommand), 1); } @Test public void invalidTest() throws Exception { Field field = IncorrectCommand.class.getDeclaredField("feedbackToUser"); field.setAccessible(true); IncorrectCommand incorrectCommand = (IncorrectCommand) FinishCommandParser.parse("+"); assertEquals(field.get(incorrectCommand), String.format(MESSAGE_INVALID_COMMAND_FORMAT, FinishCommand.MESSAGE_USAGE)); } }
Add closures with shared state example
package sh import "testing" func TestFunctionsClosures(t *testing.T) { for _, test := range []execTestCase{ { desc: "simpleClosure", execStr: ` fn func(a) { fn closure() { print($a) } return $closure } x <= func("1") y <= func("2") $x() $y() `, expectedStdout: "12", }, { desc: "closuresSharingState", execStr: ` fn func() { a = () fn add(elem) { a <= append($a, $elem) } fn view() { print($a) } return $add, $view } add, view <= func() $add("1") $add("3") $view() `, expectedStdout: "1 3", }, } { t.Run(test.desc, func(t *testing.T) { testExec(t, test) }) } }
package sh import "testing" func TestFunctionsClosures(t *testing.T) { for _, test := range []execTestCase{ { desc: "simpleClosure", execStr: ` fn func(a) { fn closure() { print($a) } return $closure } x <= func("1") y <= func("2") $x() $y() `, expectedStdout: "12", }, //{ //desc: "closuresSharingState", //execStr: ` //fn func() { //a = () //fn add(elem) { //a <= append($a, $elem) //} //fn dump() { //print($a) //} //return $add, $dump //} //add, dump <= func() //$add("1") //$add("3") //$dump() //`, //expectedStdout: "1 3", //}, } { t.Run(test.desc, func(t *testing.T) { testExec(t, test) }) } }
Add a method to find all measurements.
# -*- coding: utf-8 -*- from sqlalchemy import ( Column, Date, Integer, MetaData, Numeric, String, Table, ) def define_tables(metadata): Table('measurement', metadata, Column('id', Integer, primary_key=True), Column('weight', Numeric(4, 1), nullable=False), Column('code', String(25), nullable=False), Column('note', String(140), nullable=True), Column('date_measured', Date(), nullable=False), ) class Db(object): def __init__(self, engine): self._meta = MetaData(engine) define_tables(self._meta) def make_tables(self): self._meta.create_all() def drop_tables(self): self._meta.drop_all() @property def measurement(self): return self._meta.tables['measurement'] class MeasurementService(object): def __init__(self, table): self._table = table def find_all(self): s = self._table.select() return s.execute() def create(self, **kwargs): i = self._table.insert() i.execute(**kwargs)
# -*- coding: utf-8 -*- from sqlalchemy import ( Column, Date, Integer, MetaData, Numeric, String, Table, ) def define_tables(metadata): Table('measurement', metadata, Column('id', Integer, primary_key=True), Column('weight', Numeric(4, 1), nullable=False), Column('code', String(25), nullable=False), Column('note', String(140), nullable=True), Column('date_measured', Date(), nullable=False), ) class Db(object): def __init__(self, engine): self._meta = MetaData(engine) define_tables(self._meta) def make_tables(self): self._meta.create_all() def drop_tables(self): self._meta.drop_all() @property def measurement(self): return self._meta.tables['measurement'] class MeasurementService(object): def __init__(self, table): self._table = table def create(self, **kwargs): i = self._table.insert() i.execute(**kwargs)
Update the version to 0.1.8
#!/usr/bin/python # -*-coding:UTF-8 -*- from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) setup( name='dictmysqldb', version='0.1.8', description='A mysql package above MySQL-python for more convenient database manipulation with Python dictionary.', author='Guangyang Li', author_email='mail@guangyangli.com', license='MIT', py_modules=['DictMySQLdb'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7' ], keywords='mysql database', packages=find_packages(exclude=['MySQL-python']), install_requires=['MySQL-python'], )
#!/usr/bin/python # -*-coding:UTF-8 -*- from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) setup( name='dictmysqldb', version='0.1.7', description='A mysql package above MySQL-python for more convenient database manipulation with Python dictionary.', author='Guangyang Li', author_email='mail@guangyangli.com', license='MIT', py_modules=['DictMySQLdb'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7' ], keywords='mysql database', packages=find_packages(exclude=['MySQL-python']), install_requires=['MySQL-python'], )
Add all supported python versions to classifiers.
import sys from setuptools import setup, find_packages if sys.version_info < (2, 7, 0): print("Error: signac requires python version >= 2.7.x.") sys.exit(1) setup( name='signac', version='0.6.2', packages=find_packages(), zip_safe=True, author='Carl Simon Adorf', author_email='csadorf@umich.edu', description="Simple data management framework.", keywords='simulation database index collaboration workflow', url="https://bitbucket.org/glotzer/signac", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: BSD License", "Topic :: Scientific/Engineering :: Physics", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", ], extras_require={ 'db': ['pymongo>=3.0'], 'mpi': ['mpi4py'], 'gui': ['PySide'], }, entry_points={ 'console_scripts': [ 'signac = signac.__main__:main', 'signac-gui = signac.gui:main', ], }, )
import sys from setuptools import setup, find_packages if sys.version_info < (2, 7, 0): print("Error: signac requires python version >= 2.7.x.") sys.exit(1) setup( name='signac', version='0.6.2', packages=find_packages(), zip_safe=True, author='Carl Simon Adorf', author_email='csadorf@umich.edu', description="Simple data management framework.", keywords='simulation database index collaboration workflow', url="https://bitbucket.org/glotzer/signac", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: BSD License", "Topic :: Scientific/Engineering :: Physics", ], extras_require={ 'db': ['pymongo>=3.0'], 'mpi': ['mpi4py'], 'gui': ['PySide'], }, entry_points={ 'console_scripts': [ 'signac = signac.__main__:main', 'signac-gui = signac.gui:main', ], }, )
Use io.ReadFull instead of ioutil.ReadAll when reading Sensu API responses
package sensu import ( "fmt" "io" "net/http" "net/url" ) // ... func (api *API) doRequest(req *http.Request) ([]byte, *http.Response, error) { if api.User != "" && api.Pass != "" { req.SetBasicAuth(api.User, api.Pass) } res, err := api.Client.Do(req) if err != nil { status, ok := err.(*url.Error) if !ok { return nil, nil, fmt.Errorf("Unexpected error, got %T, wanted *url.Error", err) } return nil, nil, status.Err } defer res.Body.Close() if res.StatusCode >= 400 { return nil, nil, fmt.Errorf("%v", res.Status) } body := make([]byte, res.ContentLength) _, err = io.ReadFull(res.Body, body) if err != nil { return nil, nil, fmt.Errorf("Parsing response body returned: %v", err) } return body, res, nil }
package sensu import ( "fmt" "io/ioutil" "net/http" "net/url" ) // ... func (api *API) doRequest(req *http.Request) ([]byte, *http.Response, error) { if api.User != "" && api.Pass != "" { req.SetBasicAuth(api.User, api.Pass) } res, err := api.Client.Do(req) if err != nil { status, ok := err.(*url.Error) if !ok { return nil, nil, fmt.Errorf("Unexpected error, got %T, wanted *url.Error", err) } return nil, nil, status.Err } defer res.Body.Close() if res.StatusCode >= 400 { return nil, nil, fmt.Errorf("%v", res.Status) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, nil, fmt.Errorf("Parsing response body returned: %v", err) } return body, res, nil }
Remove incorrect debugging line, leave var_dump
<?php require_once('./config.php'); var_dump($_POST); $state = $_POST['shippingState']; if ( !strcmp("GA", $state) ) { // the shipping address is in Georgia, so go ahead $token = $_POST['stripeToken']; $email = $_POST['emailAddress']; echo "$token and $email"; $customer = Stripe_Customer::create(array( 'email' => $email, 'card' => $token )); $charge = Stripe_Charge::create(array( 'customer' => $customer->id, 'amount' => 1500, 'currency' => 'usd', 'description' => 'Widget, Qty 1' )); echo '<h1>Successfully charged $15.00!</h1>'; } else { echo "Sorry, we can only ship to addresses in GA."; echo "Hit the back button and try again with 'GA' in the state field."; } ?>
<?php require_once('./config.php'); echo "The POST is $_POST"; var_dump($_POST); $state = $_POST['shippingState']; if ( !strcmp("GA", $state) ) { // the shipping address is in Georgia, so go ahead $token = $_POST['stripeToken']; $email = $_POST['emailAddress']; echo "$token and $email"; $customer = Stripe_Customer::create(array( 'email' => $email, 'card' => $token )); $charge = Stripe_Charge::create(array( 'customer' => $customer->id, 'amount' => 1500, 'currency' => 'usd', 'description' => 'Widget, Qty 1' )); echo '<h1>Successfully charged $15.00!</h1>'; } else { echo "Sorry, we can only ship to addresses in GA."; echo "Hit the back button and try again with 'GA' in the state field."; } ?>
Make config values not case-sensitive.
import os from traceback import format_exc from apps.config.models import ConfigValue import functions_general """ Handle the setting/retrieving of server config directives. """ def host_os_is(osname): """ Check to see if the host OS matches the query. """ if os.name == osname: return True return False def get_configvalue(configname): """ Retrieve a configuration value. """ try: return ConfigValue.objects.get(conf_key__iexact=configname).conf_value except: functions_general.log_errmsg("Unable to get config value for %s:\n%s" % (configname, (format_exc()))) def set_configvalue(configname, newvalue): """ Sets a configuration value with the specified name. """ conf = ConfigValue.objects.get(conf_key=configname) conf.conf_value = newvalue conf.save()
import os from traceback import format_exc from apps.config.models import ConfigValue import functions_general """ Handle the setting/retrieving of server config directives. """ def host_os_is(osname): """ Check to see if the host OS matches the query. """ if os.name == osname: return True return False def get_configvalue(configname): """ Retrieve a configuration value. """ try: return ConfigValue.objects.get(conf_key=configname).conf_value except: functions_general.log_errmsg("Unable to get config value for %s:\n%s" % (configname, (format_exc()))) def set_configvalue(configname, newvalue): """ Sets a configuration value with the specified name. """ conf = ConfigValue.objects.get(conf_key=configname) conf.conf_value = newvalue conf.save()
Fix Webpack global scope issue In webpack 4 (Angular 8) the `_global = ...` will return undefined causing "Cannot read property WebSocket of undefined"
var _global = (function () { if (!this && typeof global !== 'undefined') { return global; } return this; })(); var NativeWebSocket = _global.WebSocket || _global.MozWebSocket; var websocket_version = require('./version'); /** * Expose a W3C WebSocket class with just one or two arguments. */ function W3CWebSocket(uri, protocols) { var native_instance; if (protocols) { native_instance = new NativeWebSocket(uri, protocols); } else { native_instance = new NativeWebSocket(uri); } /** * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket * class). Since it is an Object it will be returned as it is when creating an * instance of W3CWebSocket via 'new W3CWebSocket()'. * * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2 */ return native_instance; } if (NativeWebSocket) { ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'].forEach(function(prop) { Object.defineProperty(W3CWebSocket, prop, { get: function() { return NativeWebSocket[prop]; } }); }); } /** * Module exports. */ module.exports = { 'w3cwebsocket' : NativeWebSocket ? W3CWebSocket : null, 'version' : websocket_version };
var _global = (function() { return this; })(); var NativeWebSocket = _global.WebSocket || _global.MozWebSocket; var websocket_version = require('./version'); /** * Expose a W3C WebSocket class with just one or two arguments. */ function W3CWebSocket(uri, protocols) { var native_instance; if (protocols) { native_instance = new NativeWebSocket(uri, protocols); } else { native_instance = new NativeWebSocket(uri); } /** * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket * class). Since it is an Object it will be returned as it is when creating an * instance of W3CWebSocket via 'new W3CWebSocket()'. * * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2 */ return native_instance; } if (NativeWebSocket) { ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'].forEach(function(prop) { Object.defineProperty(W3CWebSocket, prop, { get: function() { return NativeWebSocket[prop]; } }); }); } /** * Module exports. */ module.exports = { 'w3cwebsocket' : NativeWebSocket ? W3CWebSocket : null, 'version' : websocket_version };
Use pypi version of lucene-querybuilder
from setuptools import setup, find_packages setup( name='neomodel', version='0.3.6', description='An object mapper for the neo4j graph database.', long_description=open('README.rst').read(), author='Robin Edwards', author_email='robin.ge@gmail.com', zip_safe=True, url='http://github.com/robinedwards/neomodel', license='MIT', packages=find_packages(), keywords='graph neo4j py2neo ORM', tests_require=['nose==1.1.2'], test_suite='nose.collector', install_requires=['py2neo==1.5', 'pytz==2013b', 'lucene-querybuilder==0.2'], classifiers=[ "Development Status :: 5 - Production/Stable", 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Topic :: Database", ])
from setuptools import setup, find_packages setup( name='neomodel', version='0.3.6', description='An object mapper for the neo4j graph database.', long_description=open('README.rst').read(), author='Robin Edwards', author_email='robin.ge@gmail.com', zip_safe=True, url='http://github.com/robinedwards/neomodel', license='MIT', packages=find_packages(), keywords='graph neo4j py2neo ORM', tests_require=['nose==1.1.2'], test_suite='nose.collector', install_requires=['py2neo==1.5', 'pytz==2013b', 'lucene-querybuilder==0.1.6'], dependency_links=['https://github.com/scholrly/lucene-querybuilder/zipball/4b12452e#egg=lucene-querybuilder'], classifiers=[ "Development Status :: 5 - Production/Stable", 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Topic :: Database", ])
Remove code to remove leading ? on RQL queries
define([ 'rql/js-array', 'dojo/_base/declare', './Memory' ], function (arrayEngine, declare, Memory) { return declare([Memory], { // summary: // This is a mixin or base class that allows us to use RQL for querying/filtering for client stores filter: function (q, options) { // strip the leading '?' since rql doesn't like it if (typeof q === 'string') { // the RQL engine doesn't understand our sort, start, and count properties, // so we apply those constraints after running the RQL query var subCollection = this._createSubCollection({ filtered: (this.filtered || []).concat(q) }); this._addQueryer(subCollection, arrayEngine.query(q, options)); var data = subCollection.data = subCollection.queryer(this.data); subCollection.total = data.length; return subCollection; } return this.inherited(arguments); } }); });
define([ 'rql/js-array', 'dojo/_base/declare', './Memory' ], function (arrayEngine, declare, Memory) { return declare([Memory], { // summary: // This is a mixin or base class that allows us to use RQL for querying/filtering for client stores filter: function (q, options) { // strip the leading '?' since rql doesn't like it if (typeof q === 'string') { q = q.replace(/^\?/, ''); // the RQL engine doesn't understand our sort, start, and count properties, // so we apply those constraints after running the RQL query var subCollection = this._createSubCollection({ filtered: (this.filtered || []).concat(q) }); this._addQueryer(subCollection, arrayEngine.query(q, options)); var data = subCollection.data = subCollection.queryer(this.data); subCollection.total = data.length; return subCollection; } return this.inherited(arguments); } }); });
[RateLimiter] Fix CI on PHP 8.2
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\RateLimiter\Tests\Policy; use PHPUnit\Framework\TestCase; use Symfony\Component\RateLimiter\Policy\Rate; class RateTest extends TestCase { /** * @dataProvider provideRate */ public function testFromString(Rate $rate) { $this->assertEquals($rate, Rate::fromString((string) $rate)); } public function provideRate(): iterable { yield [new Rate(new \DateInterval('PT15S'), 10)]; yield [Rate::perSecond(10)]; yield [Rate::perMinute(10)]; yield [Rate::perHour(10)]; yield [Rate::perDay(10)]; yield [Rate::perMonth(10)]; yield [Rate::perYear(10)]; } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\RateLimiter\Tests\Policy; use PHPUnit\Framework\TestCase; use Symfony\Component\RateLimiter\Policy\Rate; class RateTest extends TestCase { /** * @dataProvider provideRate */ public function testFromString(Rate $rate) { $this->assertEquals($rate, Rate::fromString((string) $rate)); } public function provideRate(): iterable { yield [new Rate(\DateInterval::createFromDateString('15 seconds'), 10)]; yield [Rate::perSecond(10)]; yield [Rate::perMinute(10)]; yield [Rate::perHour(10)]; yield [Rate::perDay(10)]; yield [Rate::perMonth(10)]; yield [Rate::perYear(10)]; } }
Modify key "phone" to "telefone"
(function(){ function close() { $('.md-show .md-close').click(); } function clean() { $('.md-show input[name="name"]').val(''), $('.md-show input[name="email"]').val(''), $('.md-show input[name="phone"]').val(''); } $('.btn-modal').click(function() { var name = $('.md-show input[name="name"]').val(), email = $('.md-show input[name="email"]').val(), phone = $('.md-show input[name="phone"]').val(); if (name.trim().length == 0 || email.trim().length == 0 || phone.trim().length == 0) { return; } dito.identify({ id: dito.generateID(email), name: name, email: email, data: { telefone: phone } }); clean(); close(); }); })();
(function(){ function close() { $('.md-show .md-close').click(); } function clean() { $('.md-show input[name="name"]').val(''), $('.md-show input[name="email"]').val(''), $('.md-show input[name="phone"]').val(''); } $('.btn-modal').click(function() { var name = $('.md-show input[name="name"]').val(), email = $('.md-show input[name="email"]').val(), phone = $('.md-show input[name="phone"]').val(); if (name.trim().length == 0 || email.trim().length == 0 || phone.trim().length == 0) { return; } dito.identify({ id: dito.generateID(email), name: name, email: email, data: { phone: phone, } }); clean(); close(); }); })();
Break up long, long line
import request from 'request'; import config from '../config/config'; export default { getFromConfig(callback) { let now = new Date(); let later = new Date().setDate(now.getDate() + 2); let url = 'https://www.googleapis.com/calendar/v3/calendars' + `/${config.google.calendarId}/events?key=${config.google.apiKey}` + `&timeMin=${now.toISOString()}&timeMax=${later.toISOString()}` + `&singleEvents=true&orderBy=startTime`; request(url, (error, response, body) => { if (!error && response.statusCode === 200) { if (body === null) { console.error(`Error: ${response}`); } else { callback(response.items); } } else { console.error(`Error: ${error}`); } }); } };
import request from 'request'; import config from '../config/config'; export default { getFromConfig(callback) { let now = new Date(); let later = new Date().setDate(now.getDate() + 2); let url = `https://www.googleapis.com/calendar/v3/calendars/${config.google.calendarId}/events?key=${config.google.apiKey}&singleEvents=true&orderBy=startTime&timeMin=${now.toISOString()}&timeMax=${later.toISOString()}`; request(url, (error, response, body) => { if (!error && response.statusCode === 200) { if (body === null) { console.error(`Error: ${response}`); } else { callback(response.items); } } else { console.error(`Error: ${error}`); } }); } };
Fix field label in init as well as bind
export class Basefield { id = ''; label = ''; columns = 8; index = undefined; parent = undefined; init(id = '', {label = '', columns = 8, parent, index} = {}) { this.id = id; this.label = label; this.columns = columns; this.index = index; this.parent = parent; this.fixLabel(); return this; } fixLabel() { if (this.label.length === 0) { this.label = this.id.substr(0, 1).toUpperCase() + this.id.substr(1); } } bind() { this.fixLabel(); } delete() { if (this.parent && typeof this.index === 'number') { this.parent.deleteChild(this.index); } } getValue() { return undefined; } setValue(value) { } }
export class Basefield { id = ''; label = ''; columns = 8; index = undefined; parent = undefined; init(id = '', {label = '', columns = 8, parent, index} = {}) { this.id = id; this.label = label; this.columns = columns; this.index = index; this.parent = parent; return this; } bind() { if (this.label.length === 0) { this.label = this.id.substr(0, 1).toUpperCase() + this.id.substr(1); } } delete() { if (this.parent && typeof this.index === 'number') { this.parent.deleteChild(this.index); } } getValue() { return undefined; } setValue(value) { } }
PM-133: Simplify and clean the livestream data logger
from pymoku import Moku, MokuException, NoDataException from pymoku.instruments import * import time # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku.get_by_name('example') i = Oscilloscope() m.attach_instrument(i) try: # 10Hz sample rate. The datalogger is actually just a mode of the Oscilloscope # instrument in ROLL mode. i.set_samplerate(10) i.set_xmode(OSC_ROLL) i.commit() # Stop a previous session, if any, then start a new single-channel log in real # time over the network. i.datalogger_stop() i.datalogger_start(start=0, duration=100, ch1=True, ch2=False, filetype='net') while True: ch, idx, samples = i.datalogger_get_samples() print("Received samples %d to %d from channel %d" % (idx, idx + len(samples) - 1, ch)) except NoDataException: print("Finished") finally: i.datalogger_stop() m.close()
from pymoku import Moku, MokuException, NoDataException from pymoku.instruments import * import time, logging, traceback logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.INFO) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku.get_by_name('example') i = Oscilloscope() m.attach_instrument(i) try: i.set_samplerate(10) i.set_xmode(OSC_ROLL) i.commit() time.sleep(1) i.datalogger_stop() i.datalogger_start(start=0, duration=100, use_sd=False, ch1=True, ch2=False, filetype='net') while True: ch, idx, d = i.datalogger_get_samples(timeout=5) print("Received samples %d to %d from channel %d" % (idx, idx + len(d) - 1, ch)) except NoDataException as e: # This will be raised if we try and get samples but the session has finished. print(e) except Exception as e: print(traceback.format_exc()) finally: i.datalogger_stop() m.close()
Set LOGPATH to nailgun folder by default
import os import os.path LOGPATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") LOGFILE = os.path.join(LOGPATH, "nailgun.log") LOGLEVEL = "DEBUG" CELERYLOGFILE = os.path.join(LOGPATH, "celery.log") CELERYLOGLEVEL = "DEBUG" PATH_TO_SSH_KEY = os.path.join(os.getenv("HOME"), ".ssh", "id_rsa") PATH_TO_BOOTSTRAP_SSH_KEY = os.path.join(os.getenv("HOME"), ".ssh", "bootstrap.rsa") COBBLER_URL = "http://localhost/cobbler_api" COBBLER_USER = "cobbler" COBBLER_PASSWORD = "cobbler" COBBLER_PROFILE = "centos-6.2-x86_64"
import os import os.path LOGPATH = "/var/log/nailgun" LOGFILE = os.path.join(LOGPATH, "nailgun.log") LOGLEVEL = "DEBUG" CELERYLOGFILE = os.path.join(LOGPATH, "celery.log") CELERYLOGLEVEL = "DEBUG" PATH_TO_SSH_KEY = os.path.join(os.getenv("HOME"), ".ssh", "id_rsa") PATH_TO_BOOTSTRAP_SSH_KEY = os.path.join(os.getenv("HOME"), ".ssh", "bootstrap.rsa") COBBLER_URL = "http://localhost/cobbler_api" COBBLER_USER = "cobbler" COBBLER_PASSWORD = "cobbler" COBBLER_PROFILE = "centos-6.2-x86_64"
Revert to name 'website' on error
import { Component } from 'react'; import h from 'react-hyperscript'; import Quote from './components/Quote'; import getRandomQuote from './utils/getRandomQuote'; class App extends Component { constructor(props) { super(props); this.state = { text: 'Loading...', name: 'website', }; } componentDidMount() { getRandomQuote() .then(quote => { const { text, name } = quote; this.setState({ text, name }); }) .catch(err => { this.setState({ text: err, name: 'website', }); console.error(err); }); } render() { const { text, name } = this.state; return h(Quote, { text, name }); } } export default App;
import { Component } from 'react'; import h from 'react-hyperscript'; import Quote from './components/Quote'; import getRandomQuote from './utils/getRandomQuote'; class App extends Component { constructor(props) { super(props); this.state = { text: 'Loading...', name: 'website', }; } componentDidMount() { getRandomQuote() .then(quote => { const { text, name } = quote; this.setState({ text, name }); }) .catch(err => { this.setState({ text: err }); console.error(err); }); } render() { const { text, name } = this.state; return h(Quote, { text, name }); } } export default App;
Change to sample pachube script
import clr from System import * from System.Net import WebClient from System.Xml import XmlDocument from System.Diagnostics import Trace url = "http://pachube.com/api/" apiKey = "<Your-Pachube-Api-Key-Here>" environmentId = -1 def Publish(topic, data): ms = MemoryStream() Trace.WriteLine("Pachube Sample") client = WebClient() client.Headers.Add('X-PachubeApiKey', apiKey) watts, temp = 25, 44 resp = client.UploadString(CreateFullUrl(), "PUT", str(watts) + "," + str(temp)) client.Dispose(); return 1 def CreateFullUrl(): return url + str(environmentId) + '.csv' def Shutdown(): return 1 def GetTopics(): return ["PowerMeter/CC128/Mark"]
import clr from System import * from System.Net import WebClient from System.Xml import XmlDocument from System.Diagnostics import Trace url = "http://pachube.com/api/" apiKey = "40ab667a92d6f892fef6099f38ad5eb31e619dffd793ff8842ae3b00eaf7d7cb" environmentId = 2065 def Publish(topic, data): ms = MemoryStream() Trace.WriteLine("Pachube Sample") client = WebClient() client.Headers.Add('X-PachubeApiKey', apiKey) watts, temp = 25, 44 resp = client.UploadString(CreateFullUrl(), "PUT", str(watts) + "," + str(temp)) client.Dispose(); return 1 def CreateFullUrl(): return url + str(environmentId) + '.csv' def Shutdown(): return 1 def GetTopics(): return ["PowerMeter/CC128/Mark"]
Revert "Options rewrite started, allows for the built in primitive types now." This reverts commit c1b43ee736baf7be8abd224fba9d1aa19d17e944.
require('../CactusJuice.js'); module.exports = (function () { var Options = CactusJuice.Util.Options; var Assertion = CactusJuice.Dev.Assertion; var assertException = Assertion.exception.bind(Assertion); var JSON = CactusJuice.Util.JSON; var stringify = JSON.stringify; return { a : function (assert) { var exception = assertException.curry(assert); var o = new Options({ type : "string" }); assert.eql("aoeu", o.parse("aoeu")); exception(/expected string, but got number/i, o.parse.bind(o, 1)); exception(/expected string, but got boolean/i, o.parse.bind(o, true)); o = new Options({ type : "number" }); assert.eql(100, o.parse(100)); exception(/expected number, but got string/i, o.parse.bind(o, "1")); } }; })();
require('../CactusJuice.js'); module.exports = (function () { var Options = CactusJuice.Util.Options; var Assertion = CactusJuice.Dev.Assertion; var assertException = Assertion.exception.bind(Assertion); var JSON = CactusJuice.Util.JSON; var stringify = JSON.stringify; return { a : function (assert) { var exception = assertException.curry(assert); var o = new Options({ type : "string" }); assert.eql("aoeu", o.parse("aoeu")); exception(/expected string, but got number/i, o.parse.bind(o, 1)); exception(/expected string, but got boolean/i, o.parse.bind(o, true)); o = new Options({ type : "number" }); assert.eql(100, o.parse(100)); exception(/expected number, but got string/i, o.parse.bind(o, "1")); o = new Options({ type : ["number"] }); assert.eql(JSON.stringify([1, 2]), JSON.stringify(o.parse([1, 2]))); } }; })();
Change apiURL default from docker to localhost As this is a public repository, we can't assume everybody will be using docker and have the same container name. MOM-554
'use strict'; var fs = require('fs'); var path = require('path'); exports.getApiConfig = function() { return Object.freeze({ port: process.env.SERVER_PORT || 4002, heartbeat: process.env.HEARTBEAT === 'true', logLevel: process.env.LOG_LEVEL || 'info', api: Object.freeze({ apiURL: process.env.API_URL || 'https://localhost:8080', username: process.env.API_USERNAME || 'root@openhim.org', password: process.env.API_PASSWORD || 'openhim-password', trustSelfSigned: process.env.TRUST_SELF_SIGNED === 'true' }) }); }; exports.getMediatorConfig = function() { var mediatorConfigFile = path.resolve('config', 'mediator.json'); return JSON.parse(fs.readFileSync(mediatorConfigFile)); };
'use strict'; var fs = require('fs'); var path = require('path'); exports.getApiConfig = function() { return Object.freeze({ port: process.env.SERVER_PORT || 4002, heartbeat: process.env.HEARTBEAT === 'true', logLevel: process.env.LOG_LEVEL || 'info', api: Object.freeze({ apiURL: process.env.API_URL || 'https://openhim-core:8080', username: process.env.API_USERNAME || 'root@openhim.org', password: process.env.API_PASSWORD || 'openhim-password', trustSelfSigned: process.env.TRUST_SELF_SIGNED === 'true' }) }); }; exports.getMediatorConfig = function() { var mediatorConfigFile = path.resolve('config', 'mediator.json'); return JSON.parse(fs.readFileSync(mediatorConfigFile)); };
Fix debug build test failure Not really a bug here, v8 seems overzealous with this CHECK failure
let ivm = require('isolated-vm'); let isolate = new ivm.Isolate; function makeContext() { let context = isolate.createContextSync(); let global = context.global; global.setSync('ivm', ivm); isolate.compileScriptSync(` function makeReference(ref) { return new ivm.Reference(ref); } function isReference(ref) { return ref instanceof ivm.Reference; } `).runSync(context); return { makeReference: global.getSync('makeReference'), isReference: global.getSync('isReference'), }; } let context1 = makeContext(); let context2 = makeContext(); [ context1, context2 ].forEach(context => { if (!context.isReference(new ivm.Reference({}))) { console.log('fail1'); } if (!context.isReference(context.makeReference({}))) { console.log('fail2'); } }); if (context1.isReference(context2.makeReference({}).derefInto())) { console.log('fail3'); } console.log('pass');
let ivm = require('isolated-vm'); let isolate = new ivm.Isolate; function makeContext() { let context = isolate.createContextSync(); let global = context.global; global.setSync('ivm', ivm); isolate.compileScriptSync(` function makeReference(ref) { return new ivm.Reference(ref); } function isReference(ref) { return ref instanceof ivm.Reference; } `).runSync(context); return { makeReference: global.getSync('makeReference'), isReference: global.getSync('isReference'), }; } let context1 = makeContext(); let context2 = makeContext(); [ context1, context2 ].forEach(context => { if (!context.isReference(new ivm.Reference({}))) { console.log('fail1'); } if (!context.isReference(context.makeReference(1))) { console.log('fail2'); } }); if (context1.isReference(context2.makeReference(1).derefInto())) { console.log('fail3'); } console.log('pass');
Add private constructor to mockserializable.
package com.tinkerpop.gremlin.structure; import java.io.Serializable; /** * @author Stephen Mallette (http://stephen.genoprime.com) */ public class MockSerializable implements Serializable { private String testField; private MockSerializable() {} public MockSerializable(final String testField) { this.testField = testField; } public String getTestField() { return this.testField; } public void setTestField(final String testField) { this.testField = testField; } @Override public boolean equals(Object oth) { if (this == oth) return true; else if (oth == null) return false; else if (!getClass().isInstance(oth)) return false; MockSerializable m = (MockSerializable) oth; if (testField == null) { return (m.testField == null); } else return testField.equals(m.testField); } }
package com.tinkerpop.gremlin.structure; import java.io.Serializable; /** * @author Stephen Mallette (http://stephen.genoprime.com) */ public class MockSerializable implements Serializable { private String testField; public MockSerializable(final String testField) { this.testField = testField; } public String getTestField() { return this.testField; } public void setTestField(final String testField) { this.testField = testField; } @Override public boolean equals(Object oth) { if (this == oth) return true; else if (oth == null) return false; else if (!getClass().isInstance(oth)) return false; MockSerializable m = (MockSerializable) oth; if (testField == null) { return (m.testField == null); } else return testField.equals(m.testField); } }
Update motor API with new data model
from Adafruit_MotorHAT import Adafruit_MotorHAT class Vehicle: def __init__(self, motor_hat=Adafruit_MotorHAT()): self.motor_hat = motor_hat self.motors = [] def release(self): self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(2).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(3).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(4).run(Adafruit_MotorHAT.RELEASE) def update_motor(self, index, command, speed): motor = self.motor_hat.getMotor(index + 1) motor.run(command + 1) motor.setSpeed(speed) motor_state = {"location": index, "command": command, "speed": speed} n = len(self.motors) if index < n: self.motors[index] = motor_state elif index == n: self.motors.append(motor_state) else: raise IndexError() def dict(self): return {"motors": self.motors}
from Adafruit_MotorHAT import Adafruit_MotorHAT class Vehicle: def __init__(self, motor_hat=Adafruit_MotorHAT()): self.motor_hat = motor_hat self.motors = [] def release(self): self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(2).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(3).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(4).run(Adafruit_MotorHAT.RELEASE) def update_motor(self, index, command, speed): motor = self.motor_hat.getMotor(index + 1) motor.run(command + 1) motor.setSpeed(speed) print("Set %d motor to %d command with %d speed" % (index + 1, command + 1, speed)) motor_state = {"location": index, "command": command, "speed": speed} n = len(self.motors) if index < n: self.motors[index] = motor_state elif index == n: self.motors.append(motor_state) else: raise IndexError() def dict(self): return {"motors": self.motors}
Create solutions directory if it does not exist
# -*- coding: utf-8 -*- """ nbtutor - a small utility to indicate which cells should be cleared (exercises). """ import os try: from nbconvert.preprocessors.base import Preprocessor except ImportError: from IPython.nbconvert.preprocessors.base import Preprocessor from traitlets import Unicode class ClearExercisePreprocessor(Preprocessor): solutions_dir = Unicode("_solutions").tag(config=True) def __init__(self, **kw): if not os.path.exists(self.solutions_dir): os.makedirs(self.solutions_dir) super(Preprocessor, self).__init__(**kw) def preprocess_cell(self, cell, resources, index): if 'clear_cell' in cell.metadata and cell.metadata.clear_cell: fname = os.path.join( self.solutions_dir, resources['metadata']['name'] + str(cell['execution_count']) + '.py') with open(fname, 'w') as f: f.write(cell['source']) cell['source'] = ["# %load {0}".format(fname)] cell['outputs'] = [] # cell['source'] = [] return cell, resources
# -*- coding: utf-8 -*- """ nbtutor - a small utility to indicate which cells should be cleared (exercises). """ import os try: from nbconvert.preprocessors.base import Preprocessor except ImportError: from IPython.nbconvert.preprocessors.base import Preprocessor from traitlets import Unicode class ClearExercisePreprocessor(Preprocessor): solutions_dir = Unicode("_solutions").tag(config=True) def preprocess_cell(self, cell, resources, index): if 'clear_cell' in cell.metadata and cell.metadata.clear_cell: fname = os.path.join( self.solutions_dir, resources['metadata']['name'] + str(cell['execution_count']) + '.py') with open(fname, 'w') as f: f.write(cell['source']) cell['source'] = ["# %load {0}".format(fname)] cell['outputs'] = [] # cell['source'] = [] return cell, resources
Use valid k8s port name
/** * Copyright 2005-2016 Red Hat, Inc. * * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.fabric8.jgroups; public class Constants { public static final short KUBERNETES_DISCOVERY_ID = 1001; public static final String JGROUPS_CLUSTER_NAME = "cluster"; public static final String JGROUPS_TCP_PORT = "jgroups-tcp"; }
/** * Copyright 2005-2016 Red Hat, Inc. * * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.fabric8.jgroups; public class Constants { public static final short KUBERNETES_DISCOVERY_ID = 1001; public static final String JGROUPS_CLUSTER_NAME = "cluster"; public static final String JGROUPS_TCP_PORT = "jgroups-tcp-port"; }
Add gravity between the player and the big thing
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update }); var player; var cursors; var heavy; function preload() { game.load.image('star', 'assets/star.png'); game.load.image('diamond', 'assets/diamond.png'); } function create() { game.physics.startSystem(Phaser.Physics.ARCADE); player = game.add.sprite(0, 400, 'star'); heavy = game.add.sprite(200, 200, 'diamond'); game.physics.arcade.enable(player); player.body.velocity.x = 60; cursors = game.input.keyboard.createCursorKeys(); } function update() { var rotSpeed = 0.05; var gravPower = 3; if (cursors.left.isDown) { player.body.velocity.rotate(0, 0, -rotSpeed); } else if (cursors.right.isDown) { player.body.velocity.rotate(0, 0, rotSpeed); } var offset = heavy.position.clone().subtract(player.body.position.x, player.body.position.y); var gravDir = offset.normalize(); var distSq = offset.getMagnitudeSq(); var grav = gravDir.setMagnitude(gravPower / distSq); player.body.velocity = player.body.velocity.add(grav.x, grav.y); }
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update }); var player; var cursors; function preload() { game.load.image('star', 'assets/star.png'); game.load.image('diamond', 'assets/diamond.png'); } function create() { game.physics.startSystem(Phaser.Physics.ARCADE); player = game.add.sprite(0, 400, 'star'); game.add.sprite(200, 200, 'diamond'); game.physics.arcade.enable(player); player.body.velocity.x = 60; cursors = game.input.keyboard.createCursorKeys(); } function update() { var rotSpeed = 0.05; if (cursors.left.isDown) { player.body.velocity.rotate(0, 0, -rotSpeed); } else if (cursors.right.isDown) { player.body.velocity.rotate(0, 0, rotSpeed); } }
Add send data ajax function
var mode = 0; //primary function calc_mode() { var modes = ["primary", "secondary", "tertiary"]; return modes[mode]; } function send_data() { $.ajax({ url: "calculate/"+primary+"/"+secondary+"/"+tertiary, context: document.body, type: "post", beforeSend :function() { //loading } }).done(function(data) { }); } $(function() { $(".add").button(); $(".edit").button(); $(".delete").button().click(function() { var res = confirm("Are you sure you want to delete this item?"); if (res) window.location.href=$(this).attr('href'); else return false; }); $(".view").button(); $(".submit").button(); $("#ingredients_table table").tablesorter(); $("#effects_table table").tablesorter(); $("#calc_ingredients tbody").find('tr').each(function(){ $(this).click(function(){ $('#'+calc_mode()).html($(this).text()); send_data(); }); }); $("#primary").click(function(){ $(this).text('--'); mode = 0; }); $("#secondary").click(function(){ $(this).text('--'); mode = 1; }); $("#tertiary").click(function(){ $(this).text('--'); mode = 2; }); });
var mode = 0; //primary function calc_mode() { var modes = ["primary", "secondary", "tertiary"]; return modes[mode]; } $(function() { $(".add").button(); $(".edit").button(); $(".delete").button().click(function() { var res = confirm("Are you sure you want to delete this item?"); if (res) window.location.href=$(this).attr('href'); else return false; }); $(".view").button(); $(".submit").button(); $("#ingredients_table table").tablesorter(); $("#effects_table table").tablesorter(); $("#calc_ingredients tbody").find('tr').each(function(){ $(this).click(function(){ $('#'+calc_mode()).html($(this).text()); }); }); $("#primary").click(function(){ $(this).text('--'); mode = 0; }); $("#secondary").click(function(){ $(this).text('--'); mode = 1; }); $("#tertiary").click(function(){ $(this).text('--'); mode = 2; }); });