text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Update to include User ID in result | '''
This module extracts the student IDs from the collection certificates_generatedcertificate
of the students who completed the course and achieved a certificate. The ids
are then used to extract the usernames of the course completers
Usage:
python course_completers.py
'''
from collections import defaultdict
from... | '''
This module extracts the student IDs from the collection certificates_generatedcertificate
of the students who completed the course and achieved a certificate. The ids
are then used to extract the usernames of the course completers
Usage:
python course_completers.py
'''
from collections import defaultdict
from... |
Add case for when there are no node backrefs on logs. Again, this whole method will change when eliminating backrefs from nodelogs is merged. | # -*- coding: utf-8 -*-
from rest_framework import permissions
from website.models import Node, NodeLog
from api.nodes.permissions import ContributorOrPublic
from api.base.utils import get_object_or_error
class ContributorOrPublicForLogs(permissions.BasePermission):
def has_object_permission(self, request, vie... | # -*- coding: utf-8 -*-
from rest_framework import permissions
from website.models import Node, NodeLog
from api.nodes.permissions import ContributorOrPublic
from api.base.utils import get_object_or_error
class ContributorOrPublicForLogs(permissions.BasePermission):
def has_object_permission(self, request, vie... |
Move strict inside for browser use
don't want to leak stuff ... | /* global ftUtils, moment */
var app = angular.module('flowList', ['ui.grid']);
app.controller('flowListCtrl', function($scope, $http) {
'use strict';
$http.get('/json/rawFlowsForLast/5/minutes')
.success(function(data, status, headers, config) {
var retList = [];
data.hits.h... | /* global ftUtils, moment */
'use strict';
var app = angular.module('flowList', ['ui.grid']);
app.controller('flowListCtrl', function($scope, $http) {
$http.get('/json/rawFlowsForLast/5/minutes')
.success(function(data, status, headers, config) {
var retList = [];
data.hits.hits.f... |
Add flavour text for assembling burger | import Entity, { printMessage, action, time, state } from "Entity.js";
import { addItem, removeItem, isInInventory } from 'inventory.js';
export class Prep extends Entity {
name() {
return 'prep area';
}
actions() {
return [
action("Cut potatoes.", () => {
printMessage("You cut the potato ... | import Entity, { printMessage, action, time, state } from "Entity.js";
import { addItem, removeItem, isInInventory } from 'inventory.js';
export class Prep extends Entity {
name() {
return 'prep area';
}
actions() {
return [
action("Cut potatoes.", () => {
printMessage("You cut the potato ... |
Remove options var
Boot parent service with credentials
Change url | <?php
namespace PhpWatson\Sdk\Language\ToneAnalyser\V3;
use PhpWatson\Sdk\Service;
class ToneAnalyserService extends Service
{
/**
* Base url for the service
*
* @var string
*/
protected $url = "https://gateway.watsonplatform.net/tone-analyzer/api";
/**
* API servi... | <?php
namespace PhpWatson\Sdk\Language\ToneAnalyser\V3;
use PhpWatson\Sdk\Service;
class ToneAnalyserService extends Service
{
/**
* {@inheritdoc}
*/
protected $url = "https://watson-api-explorer.mybluemix.net/tone-analyzer/api";
/**
* {@inheritdoc}
*/
protected $ve... |
Patch binfile name only when needed in open_archive | # coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
from ..path import basename
@contextlib.contextmanager
def open_archive(fs_url, archive):
... | # coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
from ..path import basename
@contextlib.contextmanager
def open_archive(fs_url, archive):
... |
Include exception when trying send_sms function. | #! /usr/bin/env python3
"""sendsms.py: program for sending SMS."""
from sys import argv
from googlevoice import Voice
from googlevoice.util import LoginError
# E-mail SMTP settings
with open('/home/nick/dev/prv/serupbot/email_password.txt') as email_password:
password = email_password.read().strip()
# Google v... | #! /usr/bin/env python3
"""sendsms.py: program for sending SMS."""
from sys import argv
from googlevoice import Voice
from googlevoice.util import LoginError
# E-mail SMTP settings
with open('/home/nick/dev/prv/serupbot/email_password.txt') as email_password:
password = email_password.read().strip()
def send(... |
Fix bug in class Article, volume should be string type | from neomodel import (StructuredNode, StringProperty, IntegerProperty, ArrayProperty,
RelationshipTo, RelationshipFrom)
# Create your models here.
class Article(StructuredNode):
title = StringProperty()
journal = StringProperty()
year = IntegerProperty()
volume = StringProperty()
authors = Rel... | from neomodel import (StructuredNode, StringProperty, IntegerProperty, ArrayProperty,
RelationshipTo, RelationshipFrom)
# Create your models here.
class Article(StructuredNode):
title = StringProperty()
journal = StringProperty()
year = IntegerProperty()
volume = IntegerProperty()
authors = Re... |
Delete the inputs after send the message | var base_url_prod="http://147.83.7.157:8080"
var App = angular.module('messages', []);
App.controller('controller1', ['$scope', '$http', function($scope, $http) {
var refresh = function() {
$http.get(base_url_prod+'/messages/carlos').success(function (response) {
console.log("Acabo de recib... | var base_url_prod="http://147.83.7.157:8080"
var App = angular.module('messages', []);
App.controller('controller1', ['$scope', '$http', function($scope, $http) {
var refresh = function() {
$http.get(base_url_prod+'/messages/carlos').success(function (response) {
console.log("Acabo de recib... |
:wrench: Tweak img alt in LoginContainer | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { get } from 'axios';
import FlintLogo from 'components/FlintLogo';
import './LoginContainer.scss';
export default class LoginContainer extends Component {
static propTypes = {
children: ... | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { get } from 'axios';
import FlintLogo from 'components/FlintLogo';
import './LoginContainer.scss';
export default class LoginContainer extends Component {
static propTypes = {
children: ... |
Improve mongo logging, so we only log unexpected disconnects.
This cleans things up a bit so normal shutdown doesn't spew mongo
disconnect errors. | 'use strict';
var logger = require('./logger'),
mongoose = require('mongoose');
// Log unexpected events.
var events = ['disconnecting', 'disconnected', 'close', 'reconnected', 'error'];
events.forEach(function(event) {
mongoose.connection.on(event, function(error) {
var logEvent = true;
if(event === '... | 'use strict';
var logger = require('./logger'),
mongoose = require('mongoose');
// Log unexpected events.
var events = ['disconnecting', 'disconnected', 'close', 'reconnected', 'error'];
events.forEach(function(event) {
mongoose.connection.on(event, function() {
logger.warning('Mongo '+ event, arguments);
... |
Hide http warning on localhost | (function () {
'use strict';
/**
* @ngdoc function
* @name passmanApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the passmanApp
*/
angular.module('passmanApp')
.controller('MainCtrl', ['$scope', '$rootScope', '$location', function ($scope, $rootScope, $location) {
$scope.select... | (function () {
'use strict';
/**
* @ngdoc function
* @name passmanApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the passmanApp
*/
angular.module('passmanApp')
.controller('MainCtrl', ['$scope', '$rootScope', '$location', function ($scope, $rootScope, $location) {
$scope.select... |
Add the submit function to the last button
Etc.. | var count = 1;
$(document).ready(function() {
var b = $(".bottom-arrow");
var u = $(".up-arrow");
b.click(function(e) {
if ($(".slide" + (+count + 1)).length) {
count++;
goToByScroll("slide" + count);
b.html('<span class="arrow-bounce">▼</span>');
u.html('<span class="arrow-bounc... | var count = 1;
$(document).ready(function() {
var b = $(".bottom-arrow");
var u = $(".up-arrow");
b.click(function(e) {
if ($(".slide" + (+count + 1)).length) {
count++;
goToByScroll("slide" + count);
b.html('<span class="arrow-bounce">▼</span>');
u.html('<span class="arrow-bounc... |
Add input_pattern instead of min_pattern_length
Signed-off-by: Koichi Shiraishi <13fbd79c3d390e5d6585a21e11ff5ec1970cff0c@zchee.io> | import deoplete.util
from .base import Base
class Source(Base):
def __init__(self, vim):
Base.__init__(self, vim)
self.name = 'go'
self.mark = '[go]'
self.filetypes = ['go']
self.input_pattern = '[^. \t0-9]\.\w*'
self.is_bytepos = True
def get_complete_api(sel... | import deoplete.util
from .base import Base
class Source(Base):
def __init__(self, vim):
Base.__init__(self, vim)
self.name = 'go'
self.mark = '[go]'
self.filetypes = ['go']
self.min_pattern_length = 0
self.is_bytepos = True
def get_complete_api(self, findstar... |
Fix bug caused by giving post detail view a new name | from django.conf.urls import url, include
from rest_framework import routers
import service.authors.views
import service.friendrequest.views
import service.users.views
import service.nodes.views
import service.posts.views
router = routers.DefaultRouter()
router.register(r'users', service.users.views.UserViewSet)
rout... | from django.conf.urls import url, include
from rest_framework import routers
import service.authors.views
import service.friendrequest.views
import service.users.views
import service.nodes.views
import service.posts.views
router = routers.DefaultRouter()
router.register(r'users', service.users.views.UserViewSet)
rout... |
Remove shapes command until it's ready | import os
from setuptools import find_packages, setup
import sys
PY2 = sys.version_info[0] == 2
# Get version
with open(os.path.join('tilezilla', 'version.py')) as f:
for line in f:
if line.find('__version__') >= 0:
version = line.split("=")[1].strip()
version = version.strip('"')... | import os
from setuptools import find_packages, setup
import sys
PY2 = sys.version_info[0] == 2
# Get version
with open(os.path.join('tilezilla', 'version.py')) as f:
for line in f:
if line.find('__version__') >= 0:
version = line.split("=")[1].strip()
version = version.strip('"')... |
Add improvement from eneff that makes program terminate more cleanly | // Code from my dotGo.eu 2014 presentation
//
// Copyright (c) 2014 John Graham-Cumming
//
// Implement a factory and a task. Call run() on your factory.
package main
import (
"bufio"
"log"
"os"
"sync"
)
type task interface {
process()
print()
}
type factory interface {
make(line string) task
}
func run(f f... | // Code from my dotGo.eu 2014 presentation
//
// Copyright (c) 2014 John Graham-Cumming
//
// Implement a factory and a task. Call run() on your factory.
package main
import (
"bufio"
"log"
"os"
"sync"
)
type task interface {
process()
print()
}
type factory interface {
make(line string) task
}
func run(f f... |
Revert "Disable Django-CMS test on Django 1.10+"
Django CMS tests should work now with Django 1.10 and 1.11 too, since
the Django CMS version 3.4.5 supports them.
This reverts commit fcfe2513fc8532dc2212a254da42d75048e76de7. | from django.contrib.auth.models import AnonymousUser
from django.utils.crypto import get_random_string
import pytest
from cms import api
from cms.page_rendering import render_page
from form_designer.contrib.cms_plugins.form_designer_form.cms_plugins import FormDesignerPlugin
from form_designer.models import FormDefini... | import django
from django.contrib.auth.models import AnonymousUser
from django.utils.crypto import get_random_string
import pytest
from cms import api
from cms.page_rendering import render_page
from form_designer.contrib.cms_plugins.form_designer_form.cms_plugins import FormDesignerPlugin
from form_designer.models imp... |
Handle selectBy for profile items. PL-11101. | package com.amee.domain;
import java.util.Date;
public class ProfileItemsFilter extends LimitFilter {
private Date startDate = new Date();
private Date endDate = null;
/**
* Setting this to 'start' will only include items which start during the query window.
* Setting 'end' will include only i... | package com.amee.domain;
import java.util.Date;
public class ProfileItemsFilter extends LimitFilter {
private Date startDate = new Date();
private Date endDate = null;
@Override
public int getResultLimitDefault() {
return 50;
}
@Override
public int getResultLimitMax() {
... |
Resolve some issues bringing the new candidates chart into master | var TopicChartsView = Backbone.View.extend({
initialize: function() {
this.$el = $("#charts-container");
this.template = JST["templates/topic-charts/topicChartsTemplate"];
},
render: function() {
this.$el.html(this.template({ charts: this.collection }));
if (this.collection[0].collection.options... | var TopicChartsView = Backbone.View.extend({
initialize: function() {
this.$el = $("#charts-container");
this.template = JST["templates/topic-charts/topicChartsTemplate"];
},
render: function() {
this.$el.html(this.template({ charts: this.collection }));
if (this.collection.topicId == 1) {
... |
Move delay to virtual scheduler method | import { Observable } from 'rxjs/Observable'
import { of } from 'rxjs/observable/of'
import { merge } from 'rxjs/observable/merge'
import { delay } from 'rxjs/operator/delay'
import { takeUntil } from 'rxjs/operator/takeUntil'
import { share } from 'rxjs/operator/share'
const makeVirtualEmission = (scheduler, value, d... | import { Observable } from 'rxjs/Observable'
import { of } from 'rxjs/observable/of'
import { merge } from 'rxjs/observable/merge'
import { delay } from 'rxjs/operator/delay'
import { takeUntil } from 'rxjs/operator/takeUntil'
import { share } from 'rxjs/operator/share'
const makeVirtualEmission = (scheduler, value) =... |
Add check to ensure that the input has been parsed. | // Test for actor system parser.
var code =
"actor ScriptConsole(inStream, outStream, errStream){\n" +
"var reader = IO.LineReader(inStream);\n"+
"var outWriter = IO.TextWriter(outStream);\n"+
"var errWriter = IO.TextWriter(errStream);\n"+
"lineIn <- reader.lineOut;\n"+
"input lineIn (cmd)\n"... | // Test for actor system parser.
var code =
"actor ScriptConsole(inStream, outStream, errStream){\n" +
"var reader = IO.LineReader(inStream);\n"+
"var outWriter = IO.TextWriter(outStream);\n"+
"var errWriter = IO.TextWriter(errStream);\n"+
"lineIn <- reader.lineOut;\n"+
"input lineIn (cmd)\n"... |
Fix mock to import app from cli | import pytest
from click.testing import CliRunner
from cli import main
@pytest.fixture
def runner():
return CliRunner()
@pytest.fixture(params=['fr', 'en', 'tlh'])
def lang(request):
return request.param
@pytest.fixture(params=['-l', '--language'])
def cli_param(request):
return request.param
@pyte... | import pytest
from click.testing import CliRunner
from cli import main
@pytest.fixture
def runner():
return CliRunner()
@pytest.fixture(params=['fr', 'en', 'tlh'])
def lang(request):
return request.param
@pytest.fixture(params=['-l', '--language'])
def cli_param(request):
return request.param
@pyte... |
Add newline to the end of the file | <?php
namespace ActiveCollab\DatabaseStructure\Test;
use ActiveCollab\DatabaseStructure\Field\Scalar\BooleanField;
/**
* @package ActiveCollab\DatabaseStructure\Test
*/
class BooleanFieldTest extends TestCase
{
/**
* @expectedException \LogicException
*/
public function testExceptionWhenBooleanFi... | <?php
namespace ActiveCollab\DatabaseStructure\Test;
use ActiveCollab\DatabaseStructure\Field\Scalar\BooleanField;
/**
* @package ActiveCollab\DatabaseStructure\Test
*/
class BooleanFieldTest extends TestCase
{
/**
* @expectedException \LogicException
*/
public function testExceptionWhenBooleanFi... |
Add product_security.xml file entry in update_xml section
bzr revid: mga@tinyerp.com-c1c968b6c0a6dd356a1ae7bc971a2daa2356a46d | {
"name" : "Products & Pricelists",
"version" : "1.0",
"author" : "Tiny",
"category" : "Generic Modules/Inventory Control",
"depends" : ["base"],
"init_xml" : [],
"demo_xml" : ["product_demo.xml"],
"description": """
This is the base module to manage products and pricelists in Tiny ERP.
Products support vari... | {
"name" : "Products & Pricelists",
"version" : "1.0",
"author" : "Tiny",
"category" : "Generic Modules/Inventory Control",
"depends" : ["base"],
"init_xml" : [],
"demo_xml" : ["product_demo.xml"],
"description": """
This is the base module to manage products and pricelists in Tiny ERP.
Products support vari... |
Fix apollo client in SSR mode | import { ApolloClient, InMemoryCache } from 'apollo-boost';
import { createUploadLink } from 'apollo-upload-client';
import fetch from 'isomorphic-unfetch';
let apolloClient = null;
let isBrowser = typeof window !== 'undefined';
function create(initialState) {
// TODO: server-side requests must have an absolute UR... | import { ApolloClient, InMemoryCache } from 'apollo-boost';
import { createUploadLink } from 'apollo-upload-client';
import fetch from 'isomorphic-unfetch';
let apolloClient = null;
let isBrowser = typeof window !== 'undefined';
function create(initialState) {
return new ApolloClient({
connectToDevTools: isBro... |
Fix the tinyInteger default value on MySQL | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateIncidentsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('incidents', function(Blueprint $table)
{
$table->increments('id');
$ta... | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateIncidentsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('incidents', function(Blueprint $table)
{
$table->increments('id');
$ta... |
QS-969: Fix missing menu icon in UserPage top left place | import React, { PropTypes, Component } from 'react';
import TopLeftMenuLink from '../ui/TopLeftMenuLink';
import RegularTopTitle from '../ui/RegularTopTitle';
import TopRightUserIcons from './TopRightUserIcons';
export default class UserTopNavbar extends Component {
static propTypes = {
centerText: PropTyp... | import React, { PropTypes, Component } from 'react';
import TopLeftIcon from '../ui/TopLeftIcon';
import RegularTopTitle from '../ui/RegularTopTitle';
import TopRightUserIcons from './TopRightUserIcons';
export default class UserTopNavbar extends Component {
static propTypes = {
centerText: PropTypes.strin... |
Move from props to state | import React from 'react';
class ApplicationPreviewContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
previewUrl: 'http://localhost:8000'
};
}
render() {
return (
<div>
<div className="input-group mb-3">
<input type="text" classNa... | import PropTypes from 'prop-types';
import React from 'react';
class ApplicationPreviewContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
previewUrl: props.previewUrl || 'http://localhost:8000'
};
}
render() {
return (
<div>
<div className="... |
Stop opening devtools on launch | const electron = require('electron')
const app = electron.app // Module to control application life.
const BrowserWindow = electron.BrowserWindow // Module to create native browser window.
let mainWindow
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
... | const electron = require('electron')
const app = electron.app // Module to control application life.
const BrowserWindow = electron.BrowserWindow // Module to create native browser window.
let mainWindow
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
... |
Add PMs to service creation. | /**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
package foam.nanos.boot;
import foam.core.*;
import foam.nanos.*;
import foam.nanos.pm.PM;
public class NSpecFactory
implements XFactory
{
NSpec spec_;
ProxyX x_;
boolean isCreating_ ... | /**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
package foam.nanos.boot;
import foam.core.*;
import foam.nanos.*;
public class NSpecFactory
implements XFactory
{
NSpec spec_;
ProxyX x_;
public NSpecFactory(ProxyX x, NSpec spec) {
... |
Fix bug causing header not to be regenerated | <?php
namespace ZeroRPC;
class ChannelException extends \RuntimeException {}
class Channel {
const PROTOCOL_VERSION = 3;
private static $channels = array();
protected $id;
protected $envelope;
protected $socket;
private $callbacks = array();
public function __construct($id, $envelope, $socket) {
... | <?php
namespace ZeroRPC;
class ChannelException extends \RuntimeException {}
class Channel {
const PROTOCOL_VERSION = 3;
private static $channels = array();
protected $id;
protected $envelope;
protected $socket;
private $callbacks = array();
public function __construct($id, $envelope, $socket) {
... |
Handle slug collisions by adding a little salt. | var _ = require('underscore');
var getSlug = require('speakingurl');
var SLUG_MAP_FILE = "src/data/slug_map.json";
module.exports = function(grunt) {
function readMap() {
try {
return grunt.file.readJSON(SLUG_MAP_FILE);
}
catch (e) {
return {};
}
}
var contents = r... | var _ = require('underscore');
var getSlug = require('speakingurl');
var SLUG_MAP_FILE = "src/data/slug_map.json";
module.exports = function(grunt) {
function readMap() {
try {
return grunt.file.readJSON(SLUG_MAP_FILE);
}
catch (e) {
return {};
}
}
var contents = r... |
Remove finishedLoading() call, remove a.close on click method - not using, it was there for trying out items purposes | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative pat... | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative pat... |
Make URL shortener more forgiving | var standardPageTypes = {
'event': /^(19|20)[0-9]{2}\//
};
var resolveUrl = function(urlFragment) {
return (/^http:\/\//).test(urlFragment) ? urlFragment : 'http://lanyrd.com/' + urlFragment.replace(/^\//, '');
};
var shortenUrl = function(url) {
return url.replace(/^(http:\/\/.*?)?\//, '');
};
var resolvePageTyp... | var standardPageTypes = {
'event': /^(19|20)[0-9]{2}\//
};
var resolveUrl = function(urlFragment) {
return (/^http:\/\//).test(urlFragment) ? urlFragment : 'http://lanyrd.com/' + urlFragment.replace(/^\//, '');
};
var shortenUrl = function(url) {
return url.replace(/^(http:\/\/){1}(www\.)?(lanyrd\.com\/){1}|\//, '... |
Switch of weak pointers for now as it does not yet play nice with stdout | /**
* @define {boolean} HS_DEBUG is like goog.DEBUG, but for ghcjs internals
*/
var HS_DEBUG = true;
/**
* @define {boolean} enable weak pointers and finalizers
*/
var HS_WEAKS = false;
/**
* @define {boolean} enable traceLog in the run loop
*/
var HS_TRACE = true;
/**
* @define {boolean} enable tracing in hs... | /**
* @define {boolean} HS_DEBUG is like goog.DEBUG, but for ghcjs internals
*/
var HS_DEBUG = true;
/**
* @define {boolean} enable weak pointers and finalizers
*/
var HS_WEAKS = true;
/**
* @define {boolean} enable traceLog in the run loop
*/
var HS_TRACE = true;
/**
* @define {boolean} enable tracing in hsc... |
Speed up the scrolling on link clicks | /*!
* Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('body').on('click', '.page-scroll... | /*!
* Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('body').on('click', '.page-scroll... |
fix(Brush): Use floor instead of round for determining brush's selected pixels | /**
* Gets the pixels within the circle.
* @export @public @method
* @name getCircle
*
* @param {number} radius The radius of the circle.
* @param {number} rows The number of rows.
* @param {number} columns The number of columns.
* @param {number} [xCoord = 0] The x-location of the center of th... | /**
* Gets the pixels within the circle.
* @export @public @method
* @name getCircle
*
* @param {number} radius The radius of the circle.
* @param {number} rows The number of rows.
* @param {number} columns The number of columns.
* @param {number} [xCoord = 0] The x-location of the center of th... |
Clean up email notification message | import smtplib
from email.mime.text import MIMEText
def send_mail(job_id=None, job_fail=None, mail_to=None, mail_from=None, mail_server=None):
mail_from = "Inferno Daemon <inferno@localhost.localdomain>" if not mail_from else mail_from
if not job_id or not job_fail:
raise Exception("Empty job failure... | import smtplib
from email.mime.text import MIMEText
def send_mail(job_id=None, job_fail=None, mail_to=None, mail_from=None, mail_server=None):
mail_from = "Inferno Daemon <inferno@localhost.localdomain>" if not mail_from else mail_from
if not job_id or not job_fail:
raise Exception("Empty job failure ... |
Add CORS headers to dev server media. | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.http import HttpResponse
from django.views.static import serve as static_serve
from funfactory.monkeypatches import patch
# Apply funfactory monkeypatch... | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.http import HttpResponse
from funfactory.monkeypatches import patch
# Apply funfactory monkeypatches.
patch()
# Uncomment the next two lines to enable ... |
Change padding depend on window width (the bigger the more big the width is) |
var imgWidth = new Array();
var imagePadding = 100;
function imageWidth()
{
var width = $(window).width() - imagePadding;
$(".img_flex").each(function(index)
{
if (width != $(this).width())
{
if (width < imgWidth[index])
{
$(this).width(width);
... |
var imgWidth = new Array();
function imageWidth()
{
var width = $(window).width() - fixedPadding;
$(".img_flex").each(function(index)
{
if (width != $(this).width())
{
if (width < imgWidth[index])
{
$(this).width(width);
}
els... |
Clean bug with static file serving | from django.contrib.auth.forms import AuthenticationForm
from django.contrib.sites.models import get_current_site
from django.conf import settings
from haystack.forms import SearchForm
from entities.models import Entity
from oshot.forms import EntityChoiceForm
def forms(request):
context = {"search_form": Search... | from django.contrib.auth.forms import AuthenticationForm
from django.contrib.sites.models import get_current_site
from django.conf import settings
from haystack.forms import SearchForm
from entities.models import Entity
from oshot.forms import EntityChoiceForm
def forms(request):
context = {"search_form": Search... |
Fix style in cooper test. | import pagoda.cooper
class Base(object):
def setUp(self):
self.world = pagoda.cooper.World()
class TestMarkers(Base):
def setUp(self):
super(TestMarkers, self).setUp()
self.markers = pagoda.cooper.Markers(self.world)
def test_c3d(self):
self.markers.load_c3d('examples/co... | import pagoda.cooper
class Base(object):
def setUp(self):
self.world = pagoda.cooper.World()
class TestMarkers(Base):
def setUp(self):
super(TestMarkers, self).setUp()
self.markers = pagoda.cooper.Markers(self.world)
def test_c3d(self):
self.markers.load_c3d('examples/co... |
Use Li method for thresholding instead of Otsu | import numpy as np
from scipy import ndimage as ndi
from skimage.filters import threshold_li
def _extract_roi(image, axis=-1):
max_frame = np.max(image, axis=axis)
initial_mask = max_frame > threshold_li(max_frame)
regions = ndi.label(initial_mask)[0]
region_sizes = np.bincount(np.ravel(regions))
... | import numpy as np
from scipy import ndimage as ndi
from skimage.filters import threshold_otsu
def _extract_roi(image, axis=-1):
max_frame = np.max(image, axis=axis)
initial_mask = max_frame > threshold_otsu(max_frame)
regions = ndi.label(initial_mask)[0]
region_sizes = np.bincount(np.ravel(regions))
... |
Use HTTPS frame in clickjacking example | <div style="left: 110px; top: 90px; position: absolute;">SCROLL DOWN</div>
<img src="play.png" onclick="alert('never triggered');" width="80" height="80" style="left: 110px; top: 710px; position: absolute;">
<?php
$opacity = (isset($_GET['opacity']) ? $_GET['opacity'] : '0.5');
$url = (isset($_GET['url']) ? $_GET['url'... | <div style="left: 110px; top: 90px; position: absolute;">SCROLL DOWN</div>
<img src="play.png" onclick="alert('never triggered');" width="80" height="80" style="left: 110px; top: 710px; position: absolute;">
<?php
$opacity = (isset($_GET['opacity']) ? $_GET['opacity'] : '0.5');
$url = (isset($_GET['url']) ? $_GET['url'... |
Use the app string version of foreign keying. It prevents a circular import. | from django.db import models
class Activity(models.Model):
group = models.CharField(max_length=4)
grouptype = models.TextField()
groupdetail = models.TextField()
details = models.TextField()
disabled = models.BooleanField()
time = models.DecimalField(decimal_places=2, max_digits=10)
unique_... | from django.db import models
class Activity(models.Model):
group = models.CharField(max_length=4)
grouptype = models.TextField()
groupdetail = models.TextField()
details = models.TextField()
disabled = models.BooleanField()
time = models.DecimalField(decimal_places=2, max_digits=10)
unique_... |
Fix for loading bar flicking to empty for some steps. | /*
* Copyright 2013 MovingBlocks
*
* 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 t... | /*
* Copyright 2013 MovingBlocks
*
* 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 t... |
Move logging for bookmarks close from voyager to vlui | 'use strict';
/**
* @ngdoc directive
* @name vlui.directive:bookmarkList
* @description
* # bookmarkList
*/
angular.module('vlui')
.directive('bookmarkList', function (Bookmarks, consts, Logger) {
return {
templateUrl: 'bookmarklist/bookmarklist.html',
restrict: 'E',
replace: true,
r... | 'use strict';
/**
* @ngdoc directive
* @name vlui.directive:bookmarkList
* @description
* # bookmarkList
*/
angular.module('vlui')
.directive('bookmarkList', function (Bookmarks, consts) {
return {
templateUrl: 'bookmarklist/bookmarklist.html',
restrict: 'E',
replace: true,
require: ... |
Migrate all settings to local storage for v3.3. | // listen to install/update events
chrome.runtime.onInstalled.addListener(function(details){
switch(details.reason) {
case 'install':
chrome.tabs.create({url: '/docs/pro-for-trello-installed.html'});
break;
case 'update':
var version = chrome.runtime.getManifest().version;
if(version == '2.0.1') { ... | // listen to install/update events
chrome.runtime.onInstalled.addListener(function(details){
switch(details.reason) {
case 'install':
chrome.tabs.create({url: '/docs/pro-for-trello-installed.html'});
break;
case 'update':
var version = chrome.runtime.getManifest().version;
if(version == '2.0.1') { ... |
Add common interfeces to the subscription interface | <?php
/*
* This file is part of the Active Collab Payments project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
declare(strict_types=1);
namespace ActiveCollab\Payments\Subscription;
use ActiveCollab\DateValue\DateTimeValueInterface;
use ActiveCollab\Payments\Common\GatewayedObjectInterface... | <?php
/*
* This file is part of the Active Collab Payments project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
declare(strict_types=1);
namespace ActiveCollab\Payments\Subscription;
use ActiveCollab\DateValue\DateTimeValueInterface;
use ActiveCollab\Payments\Common\GatewayedObjectInterface... |
Fix path (just happened to work on Win7, fails on Win8) | /*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the ri... | /*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the ri... |
Make the babel-loader test more explicit in dicom_viewer | module.exports = function (config) {
config.module.rules.push({
resource: {
test: /node_modules(\/|\\)vtk\.js(\/|\\).*.glsl$/,
include: [/node_modules(\/|\\)vtk\.js(\/|\\)/]
},
use: [
'shader-loader'
]
});
config.module.rules.push({
... | module.exports = function (config) {
config.module.rules.push({
resource: {
test: /\.glsl$/,
include: [/node_modules(\/|\\)vtk\.js(\/|\\)/]
},
use: [
'shader-loader'
]
});
config.module.rules.push({
resource: {
test: /\.... |
Decrease splinter timeout to 3 seconds
@alexmuller
@maxfliri | from pymongo import MongoClient
from splinter import Browser
from features.support.support import Api
class SplinterClient(object):
def __init__(self, database_name):
self.database_name = database_name
self._write_api = Api.start('write', '5001')
def storage(self):
return MongoClien... | from pymongo import MongoClient
from splinter import Browser
from features.support.support import Api
class SplinterClient(object):
def __init__(self, database_name):
self.database_name = database_name
self._write_api = Api.start('write', '5001')
def storage(self):
return MongoClien... |
Clarify the role of each test in the simple relationships acceptance tests | import Ember from 'ember';
import { test } from 'qunit';
import moduleForAcceptance from '../../tests/helpers/module-for-acceptance';
const { get } = Ember;
moduleForAcceptance('Acceptance | simple relationships', {
beforeEach() {
this.author = server.create('author');
this.post = server.create('post', {
... | import Ember from 'ember';
import { test } from 'qunit';
import moduleForAcceptance from '../../tests/helpers/module-for-acceptance';
const { get } = Ember;
moduleForAcceptance('Acceptance | simple relationships', {
beforeEach() {
this.author = server.create('author');
this.post = server.create('post', {
... |
Change plugin type to profile_reader
This repairs the profile reading at startup. It should not be a mesh reader.
Contributes to issue CURA-34. | # Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import GCodeReader
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"plugin": {
"name": catalog.i18nc("@label", "GCode Reader"),
"author"... | # Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import GCodeReader
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"plugin": {
"name": catalog.i18nc("@label", "GCode Reader"),
"author"... |
Add items to the list component after they are put into the DOM, such that the itemFocus finds the dom correctly when positioning itself | jsio('from common.javascript import Class, bind');
jsio('import browser.events as events');
jsio('import browser.dom as dom');
jsio('import browser.css as css');
jsio('import browser.ItemView');
jsio('import browser.ListComponent');
jsio('import .Panel');
css.loadStyles(jsio.__path);
exports = Class(Panel, function(... | jsio('from common.javascript import Class, bind');
jsio('import browser.events as events');
jsio('import browser.dom as dom');
jsio('import browser.css as css');
jsio('import browser.ItemView');
jsio('import browser.ListComponent');
jsio('import .Panel');
css.loadStyles(jsio.__path);
exports = Class(Panel, function(... |
Set highlighted background color on the newly added evidence | window.FactRelationView = Backbone.View.extend({
tagName: "li",
className: "fact-relation",
events: {
"click .relation-actions>.weakening": "disbelieveFactRelation",
"click .relation-actions>.supporting": "believeFactRelation"
},
initialize: function() {
this.useTemplate('fact_relations','fact_r... | window.FactRelationView = Backbone.View.extend({
tagName: "li",
className: "fact-relation",
events: {
"click .relation-actions>.weakening": "disbelieveFactRelation",
"click .relation-actions>.supporting": "believeFactRelation"
},
initialize: function() {
this.useTemplate('fact_relations','fact_r... |
Update setup.py file for numscons build. | #!/usr/bin/env python
from os.path import join
def configuration(parent_package = '', top_path = None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('spatial', parent_package, top_path)
config.add_data_dir('tests')
#config.add_extension('_vq',
... | #!/usr/bin/env python
from os.path import join
def configuration(parent_package = '', top_path = None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('cluster', parent_package, top_path)
config.add_data_dir('tests')
#config.add_extension('_vq',
... |
Move sitemaps to non-language prefix url | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from cms.sitemaps import CMSSitemap
from django.conf import settings
from django.conf.urls import include, patterns, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.contrib.... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from cms.sitemaps import CMSSitemap
from django.conf import settings
from django.conf.urls import include, patterns, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.contrib.... |
fix(paths): Rename test directory path into mocks | /*
* This file is part of the easy framework.
*
* (c) Julien Sergent <sergent.julien@icloud.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
module.exports.entityManager = require( 'easy/mocks/entitymanager.mock' )
module.exports.req... | /*
* This file is part of the easy framework.
*
* (c) Julien Sergent <sergent.julien@icloud.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
module.exports.entityManager = require( 'easy/test/entitymanager.mock' )
module.exports.requ... |
Change code as per @johnotander's suggestion | 'use strict'
var postcss = require('postcss')
var isVendorPrefixed = require('is-vendor-prefixed')
module.exports = postcss.plugin('postcss-remove-prefixes', function (options) {
if (!options) {
options = {
ignore: []
}
}
if (!Array.isArray(options.ignore)) {
throw TypeError("options.ignore m... | 'use strict'
var postcss = require('postcss')
var isVendorPrefixed = require('is-vendor-prefixed')
module.exports = postcss.plugin('postcss-remove-prefixes', function (options) {
if (!options) {
options = {};
}
var ignore = options.ignore ? Array.isArray(options.ignore) ? options.ignore : false : [];
if... |
Check unique combination of 'name' and 'in' parameters of @RequestParameter | <?php declare(strict_types = 1);
namespace Apitte\Core\Annotation\Controller;
use Doctrine\Common\Annotations\Annotation\Target;
use Doctrine\Common\Annotations\AnnotationException;
/**
* @Annotation
* @Target("METHOD")
*/
final class RequestParameters
{
/** @var RequestParameter[] */
private $parameters = [];... | <?php declare(strict_types = 1);
namespace Apitte\Core\Annotation\Controller;
use Doctrine\Common\Annotations\Annotation\Target;
use Doctrine\Common\Annotations\AnnotationException;
/**
* @Annotation
* @Target("METHOD")
*/
final class RequestParameters
{
/** @var RequestParameter[] */
private $parameters = [];... |
Correct name for Pypi package | from setuptools import setup, find_packages
setup(
name='emencia-cms-snippet',
version=__import__('snippet').__version__,
description=__import__('snippet').__doc__,
long_description=open('README.rst').read(),
author='David Thenon',
author_email='dthenon@emencia.com',
url='http://pypi.python... | from setuptools import setup, find_packages
setup(
name='snippet',
version=__import__('snippet').__version__,
description=__import__('snippet').__doc__,
long_description=open('README.rst').read(),
author='David Thenon',
author_email='dthenon@emencia.com',
url='http://pypi.python.org/pypi/em... |
Load tasks module on app load. | # -*- coding: utf-8 -*-
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .. import DEFER_METHOD_CELERY
from ..settings import SST_DEFAULT_SETTINGS, GA_DEFAULT_SETTINGS, update_default_settings
SST_DEFAULT_SETTINGS.update(
cookie_path=getattr(settings, 'SESSION_COOKIE_... | # -*- coding: utf-8 -*-
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from ..settings import SST_DEFAULT_SETTINGS, GA_DEFAULT_SETTINGS, update_default_settings
SST_DEFAULT_SETTINGS.update(
cookie_path=getattr(settings, 'SESSION_COOKIE_PATH', '/'),
cookie_salt=getatt... |
Allow InstanceSlaHistory to be managed by staff | from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic
from nodeconductor.structure.models import ProjectRole
PERMISSION_LOGICS = (
('iaas.Instance', FilteredCollaboratorsPermissionLogic(
collaborators_query='project__roles__permission_group__user',
c... | from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic
from nodeconductor.structure.models import ProjectRole
PERMISSION_LOGICS = (
('iaas.Instance', FilteredCollaboratorsPermissionLogic(
collaborators_query='project__roles__permission_group__user',
c... |
Improve track API file header. | /**
* Track API errors.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Un... | /**
* Cache data.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless r... |
Attach event handlers in routing unit. | <?php
// Jivoo
// Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk)
// Licensed under the MIT license.
// See the LICENSE file or http://opensource.org/licenses/MIT for more information.
namespace Jivoo\Core\Units;
use Jivoo\Core\UnitBase;
use Jivoo\Core\App;
use Jivoo\Core\Store\Document;
use Jivoo\Control... | <?php
// Jivoo
// Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk)
// Licensed under the MIT license.
// See the LICENSE file or http://opensource.org/licenses/MIT for more information.
namespace Jivoo\Core\Units;
use Jivoo\Core\UnitBase;
use Jivoo\Core\App;
use Jivoo\Core\Store\Document;
use Jivoo\Control... |
Move external git folder integration tests to a separate class | import unittest
import util
from git_wrapper import GitWrapper
class GitWrapperIntegrationTest(util.RepoTestCase):
def test_paths(self):
self.open_tar_repo('project01')
assert('test_file.txt' in self.repo.paths)
assert('hello_world.rb' in self.repo.paths)
def test_stage(self):
... | import unittest
import util
from git_wrapper import GitWrapper
class GitWrapperIntegrationTest(util.RepoTestCase):
def test_paths(self):
self.open_tar_repo('project01')
assert('test_file.txt' in self.repo.paths)
assert('hello_world.rb' in self.repo.paths)
def test_stage(self):
... |
Allow changing what object is returned from Command instances. | """
Commands helpers.
"""
import functools
from curious.commands.command import Command
def command(*args, klass: type=Command, **kwargs):
"""
A decorator to mark a function as a command.
This will put a `factory` attribute on the function, which can later be called to create the Command instance.
A... | """
Commands helpers.
"""
import functools
from curious.commands.command import Command
def command(*args, **kwargs):
"""
A decorator to mark a function as a command.
This will put a `factory` attribute on the function, which can later be called to create the Command instance.
All arguments are pass... |
Add @Keep annotation on unsubscribed field
Since it's accessed via reflection, this needs to be kept un-obfuscated. | package com.jakewharton.rxbinding.internal;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Keep;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import rx.Subscription;
public abstract class MainThreadSubscription implements Subscription, Runnable {
private sta... | package com.jakewharton.rxbinding.internal;
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import rx.Subscription;
public abstract class MainThreadSubscription implements Subscription, Runnable {
private static final Handler mainThread = new Handle... |
Put / after dir path | #!/usr/bin/env python
import json
from pathlib import Path
import ptt_core
l = ptt_core.l
_TARGETS_DIR_PATH = Path('targets/')
if not _TARGETS_DIR_PATH.exists():
_TARGETS_DIR_PATH.mkdir()
def generate_target_from(json_path):
l.info('Generate target from {} ...'.format(json_path))
txt_path = _TARGE... | #!/usr/bin/env python
import json
from pathlib import Path
import ptt_core
l = ptt_core.l
_TARGETS_DIR_PATH = Path('targets')
if not _TARGETS_DIR_PATH.exists():
_TARGETS_DIR_PATH.mkdir()
def generate_target_from(json_path):
l.info('Generate target from {} ...'.format(json_path))
txt_path = _TARGET... |
Improve http check to allow https as well
We switch from 'startswith' to a regex check which allows both as we
tested with https facebook urls and it failed to handle them properly. | # -*- coding: utf-8 -*-
# © Copyright 2009 Andre Engelbrecht. All Rights Reserved.
# This script is licensed under the BSD Open Source Licence
# Please see the text file LICENCE for more information
# If this script is distributed, it must be accompanied by the Licence
import re
from datetime import datetime
from d... | # -*- coding: utf-8 -*-
# © Copyright 2009 Andre Engelbrecht. All Rights Reserved.
# This script is licensed under the BSD Open Source Licence
# Please see the text file LICENCE for more information
# If this script is distributed, it must be accompanied by the Licence
from datetime import datetime
from django.short... |
Update to use ClinGen curation app and test curation app Google Analytics codes | 'use strict';
// Minimal inline IE8 html5 compatibility
require('shivie8');
// Read and clear stats cookie
var cookie = require('cookie-monster')(document);
window.stats_cookie = cookie.get('X-Stats') || '';
cookie.set('X-Stats', '', {path: '/', expires: new Date(0)});
// Use a separate tracker for dev / test
var ga... | 'use strict';
// Minimal inline IE8 html5 compatibility
require('shivie8');
// Read and clear stats cookie
var cookie = require('cookie-monster')(document);
window.stats_cookie = cookie.get('X-Stats') || '';
cookie.set('X-Stats', '', {path: '/', expires: new Date(0)});
// Use a separate tracker for dev / test
var ga... |
Rework commented out code a tad | # Copyright 2013 IBM Corporation
# All rights reserved
# This is the main application.
# It should check for existing UDP socket to negotiate socket listen takeover
# It will have three paths into it:
# -Unix domain socket
# -TLS socket
# -WSGI
# Additionally, it will be able to receive particular UDP packets to... | # Copyright 2013 IBM Corporation
# All rights reserved
# This is the main application.
# It should check for existing UDP socket to negotiate socket listen takeover
# It will have three paths into it:
# -Unix domain socket
# -TLS socket
# -WSGI
# Additionally, it will be able to receive particular UDP packets to... |
Make History example run anytime. | <?php declare(strict_types = 1);
use Apixu\Exception\ApixuException;
use Apixu\Exception\InternalServerErrorException;
use Apixu\Exception\ErrorException;
require dirname(__DIR__) . '/vendor/autoload.php';
try {
$api = \Apixu\ApixuBuilder::instance()->setApiKey($_SERVER['APIXUKEY'])->build();
} catch (ApixuExcep... | <?php declare(strict_types = 1);
use Apixu\Exception\ApixuException;
use Apixu\Exception\InternalServerErrorException;
use Apixu\Exception\ErrorException;
require dirname(__DIR__) . '/vendor/autoload.php';
try {
$api = \Apixu\ApixuBuilder::instance()->setApiKey($_SERVER['APIXUKEY'])->build();
} catch (ApixuExcep... |
Make MoveDirections each a byte. | package main
import (
twodee "../libs/twodee"
)
const (
UpLayer twodee.GameEventType = iota
DownLayer
UpWaterLevel
DownWaterLevel
PlayerMove
GameIsClosing
PlayExploreMusic
PauseMusic
ResumeMusic
PlayerPickedUpItem
sentinel
)
const (
NumGameEventTypes = int(sentinel)
)
type MoveDirection byte
const (
... | package main
import (
twodee "../libs/twodee"
)
const (
UpLayer twodee.GameEventType = iota
DownLayer
UpWaterLevel
DownWaterLevel
PlayerMove
GameIsClosing
PlayExploreMusic
PauseMusic
ResumeMusic
PlayerPickedUpItem
sentinel
)
const (
NumGameEventTypes = int(sentinel)
)
type MoveDirection int
const (
N... |
Switch Dartium buildbot script to stable 1.6
BUG=
Review URL: https://codereview.chromium.org/504383002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@291655 0039d316-1c4b-4281-b951-d872f2087c98 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation sc... | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation sc... |
ALIEN-Github-3: Use the component name descriptor | 'use strict';
angular.module('alienUiApp').controller(
'NewCloudController', ['$scope', '$modalInstance', '$http', function($scope, $modalInstance, $http) {
$scope.newCloud = {};
$http.get('rest/passprovider').success(function(response) {
$scope.paasProviders = response.data;
for (var i=0; i<$scope.paas... | 'use strict';
angular.module('alienUiApp').controller(
'NewCloudController', ['$scope', '$modalInstance', '$http', function($scope, $modalInstance, $http) {
$scope.newCloud = {};
$http.get('rest/passprovider').success(function(response) {
$scope.paasProviders = response.data;
for (var i=0; i<$scope.paas... |
Set default updateInterval to 2 minutes.
Supercell's API only updates every 10 minutes. | module.exports = {
asyncLimit: 5,
updateInterval: 60 * 2, // 2 Minutes
clans: [
{
tag: '',
channelId: ''
}
],
coc: {
apiKey: '',
},
discord: {
clientId: '',
userToken: ''
},
starColors: [
0xff484e, // 0 Stars
0xffbc48, // 1 Star
0xc7ff48, // 2 Stars
0x4d... | module.exports = {
asyncLimit: 5,
updateInterval: 90,
clans: [
{
tag: '',
channelId: ''
}
],
coc: {
apiKey: '',
},
discord: {
clientId: '',
userToken: ''
},
starColors: [
0xff484e, // 0 Stars
0xffbc48, // 1 Star
0xc7ff48, // 2 Stars
0x4dff48 // 3 Stars
... |
Use a Twitter Python API version that has a pip for it | from setuptools import setup
setup(
name='birdseed',
version='0.2.1',
description='Twitter random number seeder/generator',
url='https://github.com/ryanmcdermott/birdseed',
author='Ryan McDermott',
author_email='ryan.mcdermott@ryansworks.com',
license='MIT',
classi... | from setuptools import setup
setup(
name='birdseed',
version='0.2.1',
description='Twitter random number seeder/generator',
url='https://github.com/ryanmcdermott/birdseed',
author='Ryan McDermott',
author_email='ryan.mcdermott@ryansworks.com',
license='MIT',
classi... |
Tweak raw text parameter name | from __future__ import unicode_literals
import os
try:
from io import StringIO
except ImportError: # pragma: no cover
from StringIO import StringIO
from rock.exceptions import ConfigError
ROCK_SHELL = (os.environ.get('ROCK_SHELL') or '/bin/bash -c').split()
ROCK_SHELL.insert(1, os.path.basename(ROCK_SHELL[0]... | from __future__ import unicode_literals
import os
try:
from io import StringIO
except ImportError: # pragma: no cover
from StringIO import StringIO
from rock.exceptions import ConfigError
ROCK_SHELL = (os.environ.get('ROCK_SHELL') or '/bin/bash -c').split()
ROCK_SHELL.insert(1, os.path.basename(ROCK_SHELL[0]... |
FIX : ignore __esModule key | import 'ui-router-extras';
import futureRoutes from 'app/routes.json!';
var routing = function(module) {
module.requires.push('ct.ui.router.extras.future');
var RouterConfig = ['$stateProvider', '$futureStateProvider', function ($stateProvider, $futureStateProvider) {
$futureStateProvider.stateFactory('load... | import 'ui-router-extras';
import futureRoutes from 'app/routes.json!';
var routing = function(module) {
module.requires.push('ct.ui.router.extras.future');
var RouterConfig = ['$stateProvider', '$futureStateProvider', function ($stateProvider, $futureStateProvider) {
$futureStateProvider.stateFactory('load... |
Use xml.sax.saxutils.escape instead of deprecated cgi.escape
```
/usr/local/lib/python3.6/dist-packages/mammoth/writers/html.py:34: DeprecationWarning: cgi.escape is deprecated, use html.escape instead
return cgi.escape(text, quote=True)
``` | from __future__ import unicode_literals
from xml.sax.saxutils import escape
from .abc import Writer
class HtmlWriter(Writer):
def __init__(self):
self._fragments = []
def text(self, text):
self._fragments.append(_escape_html(text))
def start(self, name, attributes=None):
... | from __future__ import unicode_literals
from .abc import Writer
import cgi
class HtmlWriter(Writer):
def __init__(self):
self._fragments = []
def text(self, text):
self._fragments.append(_escape_html(text))
def start(self, name, attributes=None):
attribute_string = _gen... |
Store request information in exception | <?php
class PodioError extends Exception {
public $body;
public $status;
public $url;
public function __construct($body, $status, $url) {
$this->body = json_decode($body, TRUE);
$this->status = $status;
$this->url = $url;
$this->request = $this->body['request'];
if (!empty($this->body['erro... | <?php
class PodioError extends Exception {
public $body;
public $status;
public $url;
public function __construct($body, $status, $url) {
$this->body = json_decode($body, TRUE);
$this->status = $status;
$this->url = $url;
if (!empty($this->body['error_description'])) {
$this->message = $t... |
Switch authenticator to migrate back to Django style passwords | from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from hashlib import sha1
class SimpleHashModelBackend(ModelBackend):
supports_anonymous_user = False
supports_object_permissions = False
supports_inactive_user = False
def authenticate(self, username=No... | from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from hashlib import sha1
class SimpleHashModelBackend(ModelBackend):
supports_anonymous_user = False
supports_object_permissions = False
supports_inactive_user = False
def authenticate(self, username=No... |
Revert basic bot random turtle factor
Former-commit-id: 53ffe42cf718cfedaa3ec329b0688c093513683c
Former-commit-id: 6a282c036f4e11a0aa9e954f72050053059ac557
Former-commit-id: c52f52d401c4a3768c7d590fb02f3d08abd38002 | from hlt import *
from networking import *
playerTag, gameMap = getInit()
sendInit("BasicBot"+str(playerTag))
while True:
moves = []
gameMap = getFrame()
for y in range(0, len(gameMap.contents)):
for x in range(0, len(gameMap.contents[y])):
site = gameMap.contents[y][x]
if site.owner == playerTag:
dir... | from hlt import *
from networking import *
playerTag, gameMap = getInit()
sendInit("BasicBot"+str(playerTag))
turtleFactor = random.randint(1, 20)
while True:
moves = []
gameMap = getFrame()
for y in range(0, len(gameMap.contents)):
for x in range(0, len(gameMap.contents[y])):
site = gameMap.contents[y][x]
... |
Set crossorigin attribute to empty string. |
/* global BackgroundCheck:false */
function convertImageToDataURI(img) {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
return canvas.toDataURL('image/png');
}
document.addEventListener('... |
/* global BackgroundCheck:false */
function convertImageToDataURI(img) {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
return canvas.toDataURL('image/png');
}
document.addEventListener('... |
Trim whitespace on category tags | <?php
namespace App\Helpers\BBCode\Tags;
class WikiCategoryTag extends LinkTag {
function __construct()
{
$this->token = false;
$this->element = '';
}
public function Matches($state, $token)
{
$peekTag = $state->Peek(5);
$pt = $state->PeekTo(']');
return ... | <?php
namespace App\Helpers\BBCode\Tags;
class WikiCategoryTag extends LinkTag {
function __construct()
{
$this->token = false;
$this->element = '';
}
public function Matches($state, $token)
{
$peekTag = $state->Peek(5);
$pt = $state->PeekTo(']');
return ... |
Use pop for getting blocking parameter | """Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt
def show(image, blocking=False, title='', **kwargs):
"""Show *image*. If *blocking* is False the call is nonblocking. *title*
is the image title. *kwargs* are passed to matplotlib's ... | """Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt
def show(image, blocking=False, title='', **kwargs):
"""Show *image*. If *blocking* is False the call is nonblocking. *title*
is the image title. *kwargs* are passed to matplotlib's ... |
Update check_requires_python and describe behavior in docstring | from __future__ import absolute_import
import logging
import sys
from pip._vendor import pkg_resources
from pip._vendor.packaging import specifiers
from pip._vendor.packaging import version
logger = logging.getLogger(__name__)
def get_metadata(dist):
if (isinstance(dist, pkg_resources.DistInfoDistribution) and... | from __future__ import absolute_import
import logging
import sys
from pip._vendor import pkg_resources
from pip._vendor.packaging import specifiers
from pip._vendor.packaging import version
logger = logging.getLogger(__name__)
def get_metadata(dist):
if (isinstance(dist, pkg_resources.DistInfoDistribution) and... |
Clarify what the code is for | $(function(){
setup_table();
});
function setup_table() {
var filter_container, filter;
$('#dists').DataTable({
paging: false,
autoWidth: false,
scrollX: false,
info: false,
columnDefs: [
{
targets: [ 2, 3, 4, 5, 6 ],
sear... | $(function(){
setup_table();
});
function setup_table() {
$('#dists').DataTable({
paging: false,
autoWidth: false,
scrollX: false,
info: false,
columnDefs: [
{
targets: [ 2, 3, 4, 5, 6 ],
searchable: false
},
... |
Fix up to the child watcher example.
Without yielding to the ioloop after each call to client.delete() the child
znodes would be deleted but that would never be reported. | import logging
import random
from tornado import gen
from zoonado import exc
log = logging.getLogger()
def arguments(parser):
parser.add_argument(
"--path", "-p", type=str, default="/examplewatcher",
help="ZNode path to use for the example."
)
def watcher_callback(children):
children.so... | import logging
import random
from tornado import gen
from zoonado import exc
log = logging.getLogger()
def arguments(parser):
parser.add_argument(
"--path", "-p", type=str, default="/examplewatcher",
help="ZNode path to use for the example."
)
def watcher_callback(children):
children.so... |
Change from_spotify and from_gpm to classmethods | class Track():
artist = ""
name = ""
track_id = ""
def __init__(self, artist, name, track_id=""):
self.artist = artist
self.name = name
self.track_id = track_id
@classmethod
def from_spotify(cls, track):
track_id = track.get("id")
name = track.get("name"... | class Track():
artist = ""
name = ""
track_id = ""
def __init__(self, artist, name, track_id=""):
self.artist = artist
self.name = name
self.track_id = track_id
@staticmethod
def from_spotify(self, track):
track_id = track.get("id")
name = track.get("nam... |
Update to use theme header. | <?php
/*
* Theme Name: Bootstrap
* Author: Paladin Digital
*/
$theme = 'themes::paladindigital.laravel-bootstrap';
?><!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-B... | <!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
@yield('head')
@yield('meta')
@... |
fix(changed): Clarify early exit log message | "use strict";
const chalk = require("chalk");
const Command = require("@lerna/command");
const collectUpdates = require("@lerna/collect-updates");
const output = require("@lerna/output");
module.exports = factory;
function factory(argv) {
return new ChangedCommand(argv);
}
class ChangedCommand extends Command {
... | "use strict";
const chalk = require("chalk");
const Command = require("@lerna/command");
const collectUpdates = require("@lerna/collect-updates");
const output = require("@lerna/output");
module.exports = factory;
function factory(argv) {
return new ChangedCommand(argv);
}
class ChangedCommand extends Command {
... |
Add apache headers to interceptor
git-svn-id: 0f15cb08c8344e4f03ae17f6299848a7299a746f@1506125 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | package org.apache.rave.rest.interceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.rave.rest.model.JsonResponseWrapper;
/**
* Created with IntelliJ IDEA.
* User: erinnp
... |
Add publish task (for gh-pages) | ///
var pkg = require("./package.json")
, gulp = require("gulp")
, plumber = require("gulp-plumber")
///
// Lint JS
///
var jshint = require("gulp-jshint")
, jsonFiles = [".jshintrc", "*.json"]
, jsFiles = ["*.js", "src/**/*.js"]
gulp.task("scripts.lint", function() {
gulp.src([].concat(jsonFiles).concat(jsF... | ///
var pkg = require("./package.json")
, gulp = require("gulp")
, plumber = require("gulp-plumber")
///
// Lint JS
///
var jshint = require("gulp-jshint")
, jsonFiles = [".jshintrc", "*.json"]
, jsFiles = ["*.js", "src/**/*.js"]
gulp.task("scripts.lint", function() {
gulp.src([].concat(jsonFiles).concat(jsF... |
Replace out-of-place h3 with a p styled as heading
Resolves: https://trello.com/c/ZpypHwAa/526-fix-banner-styling | <?php
$showBannerOnNetwork = get_site_option('banner_setting');
$showBannerBySite = get_field('show_banner', 'options');
if ($showBannerOnNetwork == true && ($showBannerBySite == true || $showBannerBySite === null)) {
$bannerTitle = get_site_option('banner_title');
$bannerLinkText = get_site_option('banner_link... | <?php
$showBannerOnNetwork = get_site_option('banner_setting');
$showBannerBySite = get_field('show_banner', 'options');
if ($showBannerOnNetwork == true && ($showBannerBySite == true || $showBannerBySite === null)) {
$bannerTitle = get_site_option('banner_title');
$bannerLinkText = get_site_option('banner_link... |
Fix trying to display result in case of not 2D vectors | from sys import argv, stderr
from drawer import *
from kmeans import kmeans
def read_vectors(file_name):
result = None
with open(file_name, 'r') as f:
vector_length = int(f.readline())
vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines()))
if all((len(x) == vect... | from sys import argv, stderr
from drawer import *
from kmeans import kmeans
def read_vectors(file_name):
result = None
with open(file_name, 'r') as f:
vector_length = int(f.readline())
vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines()))
if all((len(x) == vect... |
Add comments and call _super | /* jshint node: true */
'use strict';
var imagemin = require('broccoli-imagemin');
module.exports = {
name: 'ember-cli-imagemin',
included: function() {
this._super.included.apply(this, arguments);
// Default options
var defaultOptions = {
enabled: this.app.env === 'production'
};
// ... | /* jshint node: true */
'use strict';
var imagemin = require('broccoli-imagemin');
module.exports = {
name: 'ember-cli-imagemin',
included: function(app) {
this.app = app;
var defaultOptions = {
enabled: this.app.env === 'production'
};
if (this.app.options.imagemin === false) {
thi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.