text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Set default value for path of config | <?php
namespace RMiller\PhpSpecExtension;
use Behat\Testwork\ServiceContainer\Extension as ExtensionInterface;
use Behat\Testwork\ServiceContainer\ExtensionManager;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\... | <?php
namespace RMiller\PhpSpecExtension;
use Behat\Testwork\ServiceContainer\Extension as ExtensionInterface;
use Behat\Testwork\ServiceContainer\ExtensionManager;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\... |
Fix an error when deleting a GitHub webhook user | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProjectsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('projects', function (Blueprint $table) {
... | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProjectsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('projects', function (Blueprint $table) {
... |
Add call to show at pynotify | #!/usr/bin/env python
import urllib2
import ssl
# Define the sites we want to poll and the timeout.
SITES = (
'https://redmine.codegrove.org',
'http://koodilehto.fi',
'http://vakiopaine.net',
)
TIMEOUT = 5
try:
import gntp.notifier
notification = gntp.notifier.mini
except ImportError:
try:
... | #!/usr/bin/env python
import urllib2
import ssl
# Define the sites we want to poll and the timeout.
SITES = (
'https://redmine.codegrove.org',
'http://koodilehto.fi',
'http://vakiopaine.net',
)
TIMEOUT = 5
try:
import gntp.notifier
notification = gntp.notifier.mini
except ImportError:
try:
... |
Remove double slash in filename | <?php
namespace Fillet\Writer;
use Symfony\Component\Yaml\Dumper as YamlDumper;
/**
* Generates a Post for Sculpin
*
* @package Fillet\Writer
*/
class PostWriter extends AbstractWriter
{
/**
* Write out a set of data into a file
*
* @param array $data Data to use for constructing the page
*/
public ... | <?php
namespace Fillet\Writer;
use Symfony\Component\Yaml\Dumper as YamlDumper;
/**
* Generates a Post for Sculpin
*
* @package Fillet\Writer
*/
class PostWriter extends AbstractWriter
{
/**
* Write out a set of data into a file
*
* @param array $data Data to use for constructing the page
*/
public ... |
Rename the easter egg command. | package fi.helsinki.cs.tmc.cli.command;
import fi.helsinki.cs.tmc.cli.Application;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
/**
* Class is a test command class.
*/
public class TestComman... | package fi.helsinki.cs.tmc.cli.command;
import fi.helsinki.cs.tmc.cli.Application;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
/**
* Class is a test command class.
*/
public class TestComman... |
Make image upload work in all cases | $( document ).ready( function() {
function showUploadedImage( source ) {
$( "#userImage" ).attr( "src", source );
}
function createImageError() {
$( '#image-form' ).prepend( "<div class='alert alert-danger'>This isn't an image</div>" )
}
function removeImageError() {
$( '#ima... | $( document ).ready( function() {
function showUploadedImage( source ) {
$( "#userImage" ).attr( "src", source );
}
$( "#image-form" ).submit( function() {
var image = document.getElementById( "image" ).files[ 0 ];
if ( !image ) {
$( '#image-form' ).prepend( "<div class='... |
Change publication date to Epub; more up-to-date | import os.path
import string
import urllib, re
from datetime import datetime
from xml.dom.minidom import parse, parseString
# Django
from django.core import serializers
from django.conf import settings
from django.db import models
# Methodmint
def pubmed(keywords, latest_query=None):
# Get matching publications f... | import os.path
import string
import urllib, re
from datetime import datetime
from xml.dom.minidom import parse, parseString
# Django
from django.core import serializers
from django.conf import settings
from django.db import models
# Methodmint
def pubmed(keywords, latest_query=None):
# Get matching publications f... |
Change default day to 'empty' day for testing | import {Controller} from 'ringa';
import Repository from '../Repository';
import moment from 'moment';
export default class RepositoryController extends Controller {
constructor(bus) {
super('RepositoryController', bus);
this.repository = new Repository();
//---------------------------------
// Re... | import {Controller} from 'ringa';
import Repository from '../Repository';
import moment from 'moment';
export default class RepositoryController extends Controller {
constructor(bus) {
super('RepositoryController', bus);
this.repository = new Repository();
//---------------------------------
// Re... |
Change class name to DuplicateScripts | """This module provides plugins for basic duplicate code detection."""
from hairball.plugins import HairballPlugin
class DuplicateScripts(HairballPlugin):
"""Plugin that keeps track of which scripts have been
used more than once whithin a project."""
def __init__(self):
super(DuplicateScripts, ... | """This module provides plugins for basic duplicate code detection."""
from hairball.plugins import HairballPlugin
class DuplicateChecks(HairballPlugin):
"""Plugin that keeps track of which scripts have been
used more than once whithin a project."""
def __init__(self):
super(DuplicateChecks, se... |
Fix java test case as well for method rename | import java.io.File;
import org.opensim.modeling.*;
class TestXsensDataReader {
public static void test_XsensDataReader() {
// Test creation and population of XsensDataReaderSettings object
XsensDataReaderSettings settings = new XsensDataReaderSettings();
ExperimentalSensor nextSensor = ... | import java.io.File;
import org.opensim.modeling.*;
class TestXsensDataReader {
public static void test_XsensDataReader() {
// Test creation and population of XsensDataReaderSettings object
XsensDataReaderSettings settings = new XsensDataReaderSettings();
ExperimentalSensor nextSensor = ... |
Add Python 3 compatibility and flake8 testing | #!/usr/bin/env python2.7
from __future__ import print_function
import re, sys, markdown, requests, bs4 as BeautifulSoup
try: # Python 2
reload
except NameError: # Python 3
from importlib import reload
reload(sys)
sys.setdefaultencoding('utf8')
def check_url(url):
try:
return bool(... | #!/usr/bin/env python2.7
import re, sys, markdown, requests, bs4 as BeautifulSoup
reload(sys)
sys.setdefaultencoding('utf8')
def check_url(url):
try:
return bool(requests.head(url, allow_redirects=True))
except Exception as e:
print 'Error checking URL %s: %s' % (url, e)
return False
... |
Remove the requests dependency altogether.
(Makes no sense for such small a tool.) | from functools import partial
import subprocess
import urllib2
import multiprocessing
import json
def get_pkg_info(pkg_name):
req = urllib2.Request('http://pypi.python.org/pypi/%s/json' % (pkg_name,))
handler = urllib2.urlopen(req)
status = handler.getcode()
if status == 200:
content = handler... | from functools import partial
import subprocess
import requests
import multiprocessing
import json
def get_pkg_info(pkg_name, session):
r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,))
if r.status_code == requests.codes.ok:
return json.loads(r.text)
else:
raise ValueErr... |
fix: Add meta content for preventing double tab | import React from 'react'
import PropTypes from 'prop-types'
export default class HTML extends React.Component {
render() {
return (
<html {...this.props.htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
... | import React from 'react'
import PropTypes from 'prop-types'
export default class HTML extends React.Component {
render() {
return (
<html {...this.props.htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
... |
Correct logging level for messages. | #!/usr/bin/env python
from chunk import Chunk
import logging
import struct
class Parser(object):
ChunkAliasMap = {}
def __init__(self, kind):
self._kind = kind
self._chunks = []
def loadFile(self, filename):
with open(filename) as iff:
chunk = Chunk(iff)
logging.info('Reading file "%s... | #!/usr/bin/env python
from chunk import Chunk
import logging
import struct
class Parser(object):
ChunkAliasMap = {}
def __init__(self, kind):
self._kind = kind
self._chunks = []
def loadFile(self, filename):
with open(filename) as iff:
chunk = Chunk(iff)
logging.error('Reading file "%... |
Fix error when toggling slot selection | import * as Utils from '../../utils'
export const updateSlotSelectionStateInWorkspace = (state, payload) => {
const { elementId, slotId, type } = payload
const selectedSlots = Utils.selectedSlots(state)
let slotSelectionState = { }
// Toggle state, only select slot if it is not already selected
if(!Utils.is... | import * as Utils from '../../utils'
export const updateSlotSelectionStateInWorkspace = (state, payload) => {
const { elementId, slotId, type } = payload
const selectedSlots = Utils.selectedSlots(state)
let slotSelectionState = null
// Toggle state, only select slot if it is not already selected
if(!Utils.i... |
Indent and deindent selected block of text - gemo style | jQuery(function($) {
/* tab handling - gemo style */
$('#code').keydown(function(e) {
if (e.keyCode == 9 && !e.ctrlKey && !e.altKey) {
if (this.setSelectionRange) {
var start = this.selectionStart;
var end = this.selectionEnd;
var top = this.scrollTop;
... | jQuery(function($) {
/* tab insertion handling */
$('#code').keydown(function(e) {
if (e.keyCode == 9 && !e.ctrlKey && !e.altKey) {
if (this.setSelectionRange) {
var start = this.selectionStart;
var end = this.selectionEnd;
var top = this.scrollTop;
... |
Support python 3.7, 3.8, 3.9, 3.10 | #-*- coding: utf-8 -*-
from setuptools import setup, find_packages
import YaDiskClient
setup(
name='YaDiskClient',
version=YaDiskClient.__version__,
include_package_data=True,
py_modules=['YaDiskClient'],
url='https://github.com/TyVik/YaDiskClient',
license='MIT',
author='TyVik',
author... | #-*- coding: utf-8 -*-
from setuptools import setup, find_packages
import YaDiskClient
setup(
name='YaDiskClient',
version=YaDiskClient.__version__,
include_package_data=True,
py_modules=['YaDiskClient'],
url='https://github.com/TyVik/YaDiskClient',
license='MIT',
author='TyVik',
author... |
Add console log to debug message and sender | import config from '../../index';
import express from 'express';
import request from 'request';
class WebhookService {
constructor () {};
static tokenVerify (req, res) {
if (!req.query['hub.verify_token'] === config.FACEBOOK_PAGE_ACCESS_TOKEN) {
return res.send('Error, wrong token');
}
return r... | import config from '../../index';
import express from 'express';
import request from 'request';
class WebhookService {
constructor () {};
static tokenVerify (req, res) {
if (req.query['hub.verify_token'] !== config.FACEBOOK_PAGE_ACCESS_TOKEN) {
return res.send('Error, wrong token');
}
return re... |
Revert "api key deleted from the list of required parameters" | package org.atlasapi.application.auth;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.servlet.http.HttpServletRequest;
import org.atlasapi.application.Application;
import org.atlasapi.application.ApplicationSources;
import org.atlasapi.application.ApplicationStore;
import com.google.c... | package org.atlasapi.application.auth;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.servlet.http.HttpServletRequest;
import org.atlasapi.application.Application;
import org.atlasapi.application.ApplicationSources;
import org.atlasapi.application.ApplicationStore;
import com.google.c... |
Access proptypes via prop-types packages instead of React in LimitSelect component | /**
*
* LimitSelect
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { map } from 'lodash';
import styles from './styles.scss';
class LimitSelect extends React.Component {
componentWillMount() {
const id = _.uniqueId();
this.setSta... | /**
*
* LimitSelect
*
*/
import React from 'react';
// import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { map } from 'lodash';
import styles from './styles.scss';
class LimitSelect extends React.Component {
componentWillMount() {
const id = _.uniqueId();
this.set... |
MetaCPAN: Move MetaCPAN to group 'base'. | (function(env) {
env.ddg_spice_meta_cpan = function(api_result) {
"use strict";
if (!(api_result && api_result.author && api_result.version)) {
return Spice.failed('meta_cpan');
}
var query = DDG.get_query().replace(/\s*(metacpan|meta cpan|cpanm?)\s*/i, '').replace(/-/g... | (function(env) {
env.ddg_spice_meta_cpan = function(api_result) {
"use strict";
if (!(api_result && api_result.author && api_result.version)) {
return Spice.failed('meta_cpan');
}
var query = DDG.get_query().replace(/\s*(metacpan|meta cpan|cpanm?)\s*/i, '').replace(/-/g... |
Fix the webpack putting files into dist/ by mistake | require('dotenv').config();
const path = require('path');
const webpack = require('webpack');
// I don't really like doing it this way but it works for a limited number
// of configuration options.
const socketsEnabled = process.env.WEBSOCKETS_ENABLED &&
process.env.WEBSOCKETS_ENABLED != ('false' || '0');
co... | require('dotenv').config();
const webpack = require('webpack');
// I don't really like doing it this way but it works for a limited number
// of configuration options.
const socketsEnabled = process.env.WEBSOCKETS_ENABLED &&
process.env.WEBSOCKETS_ENABLED != ('false' || '0');
const appEntry = socketsEnabled ... |
Add Metalsmith plugins to list of ignored unused packages
Add metalsmith-* to list of packages ignored when checking unused | 'use strict';
const depcheck = require('depcheck');
const ora = require('ora');
function skipUnused(currentState) {
return currentState.get('skipUnused') || // manual option to ignore this
currentState.get('global') || // global modules
currentState.get('update') || ... | 'use strict';
const depcheck = require('depcheck');
const ora = require('ora');
function skipUnused(currentState) {
return currentState.get('skipUnused') || // manual option to ignore this
currentState.get('global') || // global modules
currentState.get('update') || ... |
FIX stock transfer restrict lot when lost is reserved | from openerp import models, fields, api, _
from openerp.exceptions import UserError
class StockPackOperation(models.Model):
_inherit = 'stock.pack.operation'
code = fields.Selection(
related='picking_id.picking_type_id.code',
string='Operation Type',
readonly=True)
@api.one
... | from openerp import models, fields, api, _
from openerp.exceptions import UserError
class StockPackOperation(models.Model):
_inherit = 'stock.pack.operation'
code = fields.Selection(
related='picking_id.picking_type_id.code',
string='Operation Type',
readonly=True)
@api.one
... |
Use Type[ET] as enum passed to init is a Type | from __future__ import absolute_import
from enum import Enum
from typing import TypeVar, Optional, Any, Type # noqa
from odin.exceptions import ValidationError
from . import Field
__all__ = ("EnumField",)
ET = TypeVar("ET", Enum, Enum)
class EnumField(Field):
"""
Field for handling Python enums.
"""... | from __future__ import absolute_import
from enum import Enum
from typing import TypeVar, Optional, Any # noqa
from odin.exceptions import ValidationError
from . import Field
__all__ = ("EnumField", )
ET = TypeVar('ET', Enum, Enum)
class EnumField(Field):
"""
Field for handling Python enums.
"""
... |
Remove method declared in parent. | <?php
namespace Rogue\Types;
class ActionType extends Type
{
private const HOST_EVENT = 'host-event';
private const HAVE_CONVERSATION = 'have-a-conversation';
private const DONATE_SOMETHING = 'donate-something';
private const MAKE_SOMETHING = 'make-something';
private const SHARE_SOMETHING = 'shar... | <?php
namespace Rogue\Types;
class ActionType extends Type
{
private const HOST_EVENT = 'host-event';
private const HAVE_CONVERSATION = 'have-a-conversation';
private const DONATE_SOMETHING = 'donate-something';
private const MAKE_SOMETHING = 'make-something';
private const SHARE_SOMETHING = 'shar... |
Update key shortcut for new signature | $(document).ready(function() {
$(document).keyup(function(e) {
var tag = e.target.tagName.toLowerCase();
if (tag != 'input' && tag != 'textarea' && tag != 'select' && !e.ctrlKey) {
if (e.keyCode==78 || e.keyCode==77) {
$('.nav-menu-icon').trigger('click');
} e... | $(document).ready(function() {
$(document).keyup(function(e) {
var tag = e.target.tagName.toLowerCase();
if (tag != 'input' && tag != 'textarea' && tag != 'select' && !e.ctrlKey) {
if (e.keyCode==78 || e.keyCode==77) {
$('.nav-menu-icon').trigger('click');
} e... |
Fix handling of create_sample command on dev API endpoint
This was completely broken. | from logging import getLogger
from virtool.api.response import no_content
from virtool.fake.wrapper import FakerWrapper
from virtool.http.routes import Routes
from virtool.samples.fake import create_fake_sample
from virtool.subtractions.fake import create_fake_fasta_upload, create_fake_finalized_subtraction
from virto... | from logging import getLogger
from virtool.api.response import no_content
from virtool.fake.wrapper import FakerWrapper
from virtool.http.routes import Routes
from virtool.samples.fake import create_fake_samples
from virtool.subtractions.fake import create_fake_fasta_upload, create_fake_finalized_subtraction
from virt... |
Fix gruntfile.js default build task. | /// <binding BeforeBuild='bower, concat' ProjectOpened='bower:install' />
/*
This file in the main entry point for defining grunt tasks and using grunt plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409
*/
module.exports = function (grunt) {
grunt.initConfig({
bower... | /// <binding BeforeBuild='bower, concat' ProjectOpened='bower:install' />
/*
This file in the main entry point for defining grunt tasks and using grunt plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409
*/
module.exports = function (grunt) {
grunt.initConfig({
bower... |
Fix bug in the ascii bar graph | __author__="UShareSoft"
def print_graph(values):
max=0
for v in values:
if len(v)>max:
max=len(v)
for v in values:
value = int(values[v])
if len(v)<max:
newV=v+(" " * int(max-len(v)))
... | # To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
__author__="UShareSoft"
def print_graph(values):
max=0
for v in values:
if len(v)>max:
... |
Fix the Monasca Log API tempest tests
The Tempest Manager class must have changed and the service
argument apparently no longer exists. Instead, it was being set
as the scope which caused the catalog to not be retrieved
See-also: If934bac4e2cd833fe4e381c373218383354969ec
Change-Id: I43c023e91eb93e2c19096b0de812eabf7b... | # Copyright 2015-2016 FUJITSU LIMITED
#
# 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... | # Copyright 2015 FUJITSU LIMITED
#
# 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 writ... |
Use 'text' input on non-touch devices
Auditors: eater, cbhl | (function(Perseus) {
var InputInteger = Perseus.Widget.extend({
initialize: function() {
if (window.Modernizr && Modernizr.touch) {
this.$input = $("<input type='number'>");
} else {
this.$input = $("<input type='text'>");
}
},
render: function() {
t... | (function(Perseus) {
var InputInteger = Perseus.Widget.extend({
initialize: function() {
this.$input = $("<input type='number'>");
},
render: function() {
this.$el.empty();
this.$el.append(this.$input);
return $.when(this);
},
focus: function() {
this.$inpu... |
Clean up order of imports | #!/usr/bin/env python
import os
import sys
import hashlib
import hmac
# Add the lib directory to the path for Lambda to load our libs
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import requests # NOQA
def verify_signature(secret, signature, payload):
computed_hash = hmac.new(str(secret), pay... | #!/usr/bin/env python
import os
import sys
import hashlib
# Add the lib directory to the path for Lambda to load our libs
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import requests # NOQA
import hmac # NOQA
def verify_signature(secret, signature, payload):
computed_hash = hmac.new(str(secr... |
Fix a missed details -> field switchover | "use strict";
var m = require("mithril"),
id = require("./id"),
hide = require("./hide"),
label = require("./label"),
css = require("./types.css");
module.exports = function(args, view) {
return {
controller : function(options) {
var ctrl = this;
ctr... | "use strict";
var m = require("mithril"),
id = require("./id"),
hide = require("./hide"),
label = require("./label"),
css = require("./types.css");
module.exports = function(args, view) {
return {
controller : function(options) {
var ctrl = this;
ctr... |
Fix a weird situation when a function run in a thread raises StopIteration, which was erroneusly interpreted that the thread returned None. | from __future__ import with_statement
import sys
import threado
import threading
import Queue
class ThreadPool(object):
def __init__(self, idle_time=5.0):
self.lock = threading.Lock()
self.threads = list()
self.idle_time = idle_time
def run(self, func, *args, **keys):
with self... | from __future__ import with_statement
import threado
import threading
import Queue
class ThreadPool(object):
def __init__(self, idle_time=5.0):
self.lock = threading.Lock()
self.threads = list()
self.idle_time = idle_time
@threado.stream
def run(inner, self, func, *args, **keys):
... |
Add command to publish js file | <?php namespace Bsharp\Laralytics;
use Illuminate\Translation\TranslationServiceProvider;
/**
* Class LaralyticsServiceProvider
* @package Bsharp\Laralytics
*/
class LaralyticsServiceProvider extends TranslationServiceProvider
{
protected $defer = false;
public function boot()
{
// Include Lar... | <?php namespace Bsharp\Laralytics;
use Illuminate\Translation\TranslationServiceProvider;
/**
* Class LaralyticsServiceProvider
* @package Bsharp\Laralytics
*/
class LaralyticsServiceProvider extends TranslationServiceProvider
{
protected $defer = false;
public function boot()
{
// Include Lar... |
Fix unittest for true headers.. | from twisted.trial import unittest
from ooni.utils.trueheaders import TrueHeaders
dummy_headers_dict = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB']
}
dummy_headers_dict2 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
'Header3': ['Va... | from twisted.trial import unittest
from ooni.utils.txagentwithsocks import TrueHeaders
dummy_headers_dict = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB']
}
dummy_headers_dict2 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
'Header3':... |
Add off as a noop function to touch editor.
Closes #3107 | var createTouchEditor = function createTouchEditor() {
var noop = function () {},
TouchEditor;
TouchEditor = function (el, options) {
/*jshint unused:false*/
this.textarea = el;
this.win = { document : this.textarea };
this.ready = true;
this.wrapping = document.... | var createTouchEditor = function createTouchEditor() {
var noop = function () {},
TouchEditor;
TouchEditor = function (el, options) {
/*jshint unused:false*/
this.textarea = el;
this.win = { document : this.textarea };
this.ready = true;
this.wrapping = document.... |
Add PropBase.flatten() support for flattening lists | import facter
from collections import MutableMapping
from piper.abc import DynamicItem
class PropBase(DynamicItem):
def __init__(self):
super(PropBase, self).__init__(None)
self._props = None
@property
def properties(self):
"""
Collect system properties and return a dicti... | import facter
from collections import MutableMapping
from piper.abc import DynamicItem
class PropBase(DynamicItem):
def __init__(self):
super(PropBase, self).__init__(None)
self._props = None
@property
def properties(self):
"""
Collect system properties and return a dicti... |
Add trailing comma in array for consistency | <?php
namespace OpenDominion\Factories;
use Carbon\Carbon;
use OpenDominion\Models\Round;
use OpenDominion\Models\RoundLeague;
class RoundFactory
{
// todo: move to config somewhere?
const ROUND_DURATION_IN_DAYS = 50;
/**
* Creates and returns a new Round in a RoundLeague.
*
* @param Roun... | <?php
namespace OpenDominion\Factories;
use Carbon\Carbon;
use OpenDominion\Models\Round;
use OpenDominion\Models\RoundLeague;
class RoundFactory
{
// todo: move to config somewhere?
const ROUND_DURATION_IN_DAYS = 50;
/**
* Creates and returns a new Round in a RoundLeague.
*
* @param Roun... |
Include display metadata in mime bundle | from IPython.display import display, JSON
import json
# Running `npm run build` will create static resources in the static
# directory of this Python package (and create that directory if necessary).
def _jupyter_labextension_paths():
return [{
'name': '{{cookiecutter.extension_name}}',
'src': '... | from IPython.display import display, JSON
import json
# Running `npm run build` will create static resources in the static
# directory of this Python package (and create that directory if necessary).
def _jupyter_labextension_paths():
return [{
'name': '{{cookiecutter.extension_name}}',
'src': '... |
Change restrict to a Element: <routeStrips></routeScripts>. Change replaceWith for de new DOM | /**
* Created by Victor Avendano on 1/10/15.
* avenda@gmail.com
*/
'use strict';
(function(){
var mod = angular.module('routeScripts', ['ngRoute']);
mod.directive('routeScripts', ['$rootScope','$compile',
function($rootScope, $compile){
return {
restrict: 'E',
lin... | /**
* Created by Victor Avendano on 1/10/15.
* avenda@gmail.com
*/
'use strict';
(function(){
var mod = angular.module('routeScripts', ['ngRoute']);
mod.directive('routeScripts', ['$rootScope','$compile',
function($rootScope, $compile){
return {
restrict: 'A',
lin... |
Update to allow the url to be passed into a constructor for the service (the service returns a constructor). | /*
* Copyright: 2012, V. Glenn Tarcea
* MIT License Applies
*/
angular.module('AngularStomp', []).
factory('ngstomp', function($rootScope) {
Stomp.WebSocketClass = SockJS;
var stompClient = {};
function NGStomp(url) {
this.stompClient = Stomp.client(url);
}
... | /*
* Copyright: 2012, V. Glenn Tarcea
* MIT License Applies
*/
angular.module('AngularStomp', []).
factory('ngstomp', function($rootScope) {
Stomp.WebSocketClass = SockJS;
var stompClient = Stomp.client('http://localhost:15674/stomp');
return {
subscribe: function(queue, cal... |
Add RequestContext for object detail | from django import http
from django.core.exceptions import ObjectDoesNotExist
from django_databrowse.datastructures import EasyModel
from django_databrowse.sites import DatabrowsePlugin
from django.shortcuts import render_to_response
from django.template import RequestContext
import urlparse
class ObjectDetailPlugin(D... | from django import http
from django.core.exceptions import ObjectDoesNotExist
from django_databrowse.datastructures import EasyModel
from django_databrowse.sites import DatabrowsePlugin
from django.shortcuts import render_to_response
import urlparse
class ObjectDetailPlugin(DatabrowsePlugin):
def model_view(self, ... |
Fix list of examples at ‘/examples.’ | /* eslint-disable no-console */
import React from 'react';
import request from 'superagent';
import JsonFormatter from './JsonFormatter';
import AttributesKit from '../../src';
class VisualTesting extends React.Component {
constructor(props) {
super(props);
this.state = {
fixtures: [],
};
}
... | /* eslint-disable no-console */
import React from 'react';
import request from 'superagent';
import JsonFormatter from './JsonFormatter';
import AttributesKit from '../../src';
class VisualTesting extends React.Component {
constructor(props) {
super(props);
this.state = {
fixtures: [],
};
}
... |
Make sure JS files from addExtraJS are loaded after in-page <script>s
In production we were getting an error that suggested that tabs.js was
being loaded before map.js.
These are loaded by different mechanisms (warning: this is all awful):
- map.js is loaded via {% javascript 'google-map' %} in the <body>
which ... | /*
* Test for mobile / desktop and load appropriate libs/scripts
*/
// this is not yet ideal... it reacts a bit slow if the cdn fails
(function () {
// create links to all the extra js needed
var extra_js = [];
for ( i=0; i<pombola_settings.extra_js.length; i++ ) {
var extra = pombola_settin... | /*
* Test for mobile / desktop and load appropriate libs/scripts
*/
// this is not yet ideal... it reacts a bit slow if the cdn fails
(function () {
// create links to all the extra js needed
var extra_js = [];
for ( i=0; i<pombola_settings.extra_js.length; i++ ) {
var extra = pombola_settin... |
Remove debug output on default | //= require diaspora_jsxc
// initialize jsxc xmpp client
$(document).ready(function() {
if (app.currentUser.authenticated()) {
$.post('api/v1/tokens', null, function(data) {
if (jsxc && data['token']) {
var jid = app.currentUser.get('diaspora_id');
jsxc.init({
root: '/assets/diasp... | //= require diaspora_jsxc
// initialize jsxc xmpp client
$(document).ready(function() {
if (app.currentUser.authenticated()) {
$.post('api/v1/tokens', null, function(data) {
if (jsxc && data['token']) {
var jid = app.currentUser.get('diaspora_id');
jsxc.init({
root: '/assets/diasp... |
Add task for Travis CI | /* jshint: node:true */
module.exports = function (grunt) {
'use strict';
grunt.initConfig({
phplint: {
application: ["lib/*.php", "tests/**/*.php"]
},
phpcs: {
application: {
src: 'lib/*.php'
},
options: {
... | /* jshint: node:true */
module.exports = function (grunt) {
'use strict';
grunt.initConfig({
phplint: {
application: ["lib/*.php", "tests/**/*.php"]
},
phpcs: {
application: {
src: 'lib/*.php'
},
options: {
... |
Ch18: Use GCBV queryset to get PostGetMixin obj. | from django.shortcuts import get_object_or_404
from .models import Post
class PostGetMixin:
date_field = 'pub_date'
model = Post
month_url_kwarg = 'month'
year_url_kwarg = 'year'
errors = {
'url_kwargs':
"Generic view {} must be called with "
"year, month, and slu... | from django.shortcuts import get_object_or_404
from .models import Post
class PostGetMixin:
date_field = 'pub_date'
month_url_kwarg = 'month'
year_url_kwarg = 'year'
errors = {
'url_kwargs':
"Generic view {} must be called with "
"year, month, and slug.",
}
d... |
Send the gecos input from USER through the sanitization as well | from twisted.words.protocols import irc
from txircd.modbase import Command
import string
class UserCommand(Command):
def onUse(self, user, data):
if not user.username:
user.registered -= 1
user.setUsername(data["ident"])
user.setRealname(data["gecos"])
if user.registered... | from twisted.words.protocols import irc
from txircd.modbase import Command
import string
class UserCommand(Command):
def onUse(self, user, data):
if not user.username:
user.registered -= 1
user.setUsername(data["ident"])
user.realname = data["gecos"]
if user.registered =... |
Put screenshot folder creation recursively
Not recursive by default : `http://php.net/manual/fr/function.mkdir.php` | <?php
namespace emuse\BehatHTMLFormatter\Context;
use Behat\MinkExtension\Context\RawMinkContext;
class ScreenshotContext extends RawMinkContext
{
private $currentScenario;
private $screenshotDir;
public function __construct($screenshotDir)
{
$this->screenshotDir = $screenshotDir;
}
... | <?php
namespace emuse\BehatHTMLFormatter\Context;
use Behat\MinkExtension\Context\RawMinkContext;
class ScreenshotContext extends RawMinkContext
{
private $currentScenario;
private $screenshotDir;
public function __construct($screenshotDir)
{
$this->screenshotDir = $screenshotDir;
}
... |
Use the mock discovery module | from experiment_config_lib import ControllerConfig
from sts.topology import MeshTopology
from sts.control_flow import Fuzzer, Interactive
from sts.input_traces.input_logger import InputLogger
from sts.invariant_checker import InvariantChecker
from sts.simulation_state import SimulationConfig
# Use POX as our controlle... | from experiment_config_lib import ControllerConfig
from sts.topology import MeshTopology
from sts.control_flow import Fuzzer, Interactive
from sts.input_traces.input_logger import InputLogger
from sts.invariant_checker import InvariantChecker
from sts.simulation_state import SimulationConfig
# Use POX as our controlle... |
Decrease scipy version to 0.17 (for RTD) | # -*- coding: utf-8 -*-
from setuptools import setup
with open('README.rst') as rdm:
README = rdm.read()
setup(
name='stagpy',
use_scm_version=True,
description='Tool for StagYY output files processing',
long_description=README,
url='https://github.com/StagPython/StagPy',
author='Marti... | # -*- coding: utf-8 -*-
from setuptools import setup
with open('README.rst') as rdm:
README = rdm.read()
setup(
name='stagpy',
use_scm_version=True,
description='Tool for StagYY output files processing',
long_description=README,
url='https://github.com/StagPython/StagPy',
author='Marti... |
Remove po files from gh-pages | module.exports = {
all: {
files: [
{
expand: true,
src: [
'index.html',
'404.html',
'sitemap.xml',
'robots.txt'
],
dest: global.dist
},
... | module.exports = {
all: {
files: [
{
expand: true,
src: [
'index.html',
'404.html',
'sitemap.xml',
'robots.txt'
],
dest: global.dist
},
... |
Return store assets as JSON | <?php
/**
* eTinyMCE backend controller.
*
* @package Rootd_Tinymce
* @author Rick Buczynski <me@rickbuczynski.com>
* @copyright 2014 Rick Buczynski. All Rights Reserved.
*/
class Rootd_Tinymce_Adminhtml_BackendController
extends Mage_Adminhtml_Controller_Action
{
// temporary
p... | <?php
/**
* eTinyMCE backend controller.
*
* @package Rootd_Tinymce
* @author Rick Buczynski <me@rickbuczynski.com>
* @copyright 2014 Rick Buczynski. All Rights Reserved.
*/
class Rootd_Tinymce_Adminhtml_BackendController
extends Mage_Adminhtml_Controller_Action
{
// temporary
p... |
Fix exception in propel subscriber | <?php
namespace Knp\Component\Pager\Event\Subscriber\Sortable;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Knp\Component\Pager\Event\ItemsEvent;
class PropelQuerySubscriber implements EventSubscriberInterface
{
public function items(ItemsEvent $event)
{
$query = $event->target... | <?php
namespace Knp\Component\Pager\Event\Subscriber\Sortable;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Knp\Component\Pager\Event\ItemsEvent;
class PropelQuerySubscriber implements EventSubscriberInterface
{
public function items(ItemsEvent $event)
{
$query = $event->target... |
Update naming convention to fix sorting bug | (function(){
"use strict"
$(document).ready(init);
function init(){
$(".sort").on('click', sortActivities);
$(".user-activities").on('click', ".card", showDescription);
}
function sortActivities() {
var type = $(this).text().toLowerCase(),
$activities = $(".user-activity"),
order... | (function(){
"use strict"
$(document).ready(init);
function init(){
$(".sort").on('click', sortActivities);
$(".user-activities").on('click', ".card", showDescription);
}
function sortActivities() {
var type = $(this).text().toLowerCase(),
$activities = $(".user-activity"),
order... |
Add `async.parallel` option to run tests in parallel instead of in series | /*
* grunt-casperjs
* https://github.com/ronaldlokers/grunt-casperjs
*
* Copyright (c) 2013 Ronald Lokers
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
var casperjs = require('./lib/casperjs').init(grunt).casperjs;
grunt.registerMultiTask('casperjs', 'Run CasperJs t... | /*
* grunt-casperjs
* https://github.com/ronaldlokers/grunt-casperjs
*
* Copyright (c) 2013 Ronald Lokers
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
var casperjs = require('./lib/casperjs').init(grunt).casperjs;
grunt.registerMultiTask('casperjs', 'Run CasperJs t... |
Use name 'default color' for "global" color setting | import VisualizationComponent from '../core/VisualizationComponent';
import vcharts from '../external/vcharts/src';
export default class Scatter extends VisualizationComponent {
static get options () {
return [
{name: 'data', type: 'table'},
{name: 'x', type: 'string'},
{name: 'y', type: 'strin... | import VisualizationComponent from '../core/VisualizationComponent';
import vcharts from '../external/vcharts/src';
export default class Scatter extends VisualizationComponent {
static get options () {
return [
{name: 'data', type: 'table'},
{name: 'x', type: 'string'},
{name: 'y', type: 'strin... |
Use open mode syntax on example file | from __future__ import print_function
import os
import glob
import pyingest.parsers.aps as aps
import pyingest.parsers.arxiv as arxiv
import pyingest.serializers.classic
import traceback
import json
import xmltodict
from datetime import datetime
import sys
input_list = 'bibc.2.out'
testfile=[]
xmldir = '/proj/ads/full... | from __future__ import print_function
import os
import glob
import pyingest.parsers.aps as aps
import pyingest.parsers.arxiv as arxiv
import pyingest.serializers.classic
import traceback
import json
import xmltodict
from datetime import datetime
input_list = 'bibc.2.out'
testfile=[]
xmldir = '/proj/ads/fulltext/source... |
Use correct database name instead of None when not supplied. | #!/usr/bin/env python
import os
from six.moves.urllib_parse import urlparse
def from_docker_envvars(config):
# linked postgres database (link name 'pg' or 'postgres')
if 'PG_PORT' in os.environ:
pg_url = urlparse(os.environ['PG_PORT'])
if not pg_url.scheme == 'tcp':
raise ValueEr... | #!/usr/bin/env python
import os
from six.moves.urllib_parse import urlparse
def from_docker_envvars(config):
# linked postgres database (link name 'pg' or 'postgres')
if 'PG_PORT' in os.environ:
pg_url = urlparse(os.environ['PG_PORT'])
if not pg_url.scheme == 'tcp':
raise ValueEr... |
Remove now useless test for initial sites value in form | """Test cases for Zinnia's admin forms"""
from django.test import TestCase
from django.contrib.admin.widgets import RelatedFieldWidgetWrapper
from zinnia.models import Category
from zinnia.admin.forms import EntryAdminForm
from zinnia.admin.forms import CategoryAdminForm
class EntryAdminFormTestCase(TestCase):
... | """Test cases for Zinnia's admin forms"""
from django.test import TestCase
from django.contrib.admin.widgets import RelatedFieldWidgetWrapper
from zinnia.models import Category
from zinnia.admin.forms import EntryAdminForm
from zinnia.admin.forms import CategoryAdminForm
class EntryAdminFormTestCase(TestCase):
... |
Add a script to show per-residue score from a PDB file. | #!/usr/bin/env python2
from setuptools import setup, find_packages
# Uploading to PyPI
# =================
# The first time only:
# $ python setup.py register -r pypi
#
# Every version bump:
# $ git tag <version>; git push --tags
# $ python setup.py sdist upload -r pypi
version = '0.4.1'
setup(
name='klab',
... | #!/usr/bin/env python2
from setuptools import setup, find_packages
# Uploading to PyPI
# =================
# The first time only:
# $ python setup.py register -r pypi
#
# Every version bump:
# $ git tag <version>; git push --tags
# $ python setup.py sdist upload -r pypi
version = '0.4.1'
setup(
name='klab',
... |
Disable the save button when there's nothing to save | import React, { Component } from 'react'
import styles from './ProjectButtons.styl'
export default class extends Component {
constructor() {
super()
this.state = { isSaving: false }
}
render() {
const { isSaving } = this.state
const { onCancelChanges, onSaveChanges, changesExist } = this.props
... | import React, { Component } from 'react'
import styles from './ProjectButtons.styl'
export default class extends Component {
constructor() {
super()
this.state = { isSaving: false }
}
render() {
const { isSaving } = this.state
const { onCancelChanges, onSaveChanges, changesExist } = this.props
... |
Remove stray debug log statement. | package com.openxc.remote.sources;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public abstract class JsonVehicleDataSource
extends AbstractVehicleDataSource {
private static final String TAG = "JsonVehicleDataSource";
public JsonVehicleDataSource() {
s... | package com.openxc.remote.sources;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public abstract class JsonVehicleDataSource
extends AbstractVehicleDataSource {
private static final String TAG = "JsonVehicleDataSource";
public JsonVehicleDataSource() {
s... |
Remove Response::HTTP_BAD_REQUEST for symfony 2.3 compatibility | <?php
/*
* This file is part of the qandidate/symfony-json-request-transformer package.
*
* (c) Qandidate.com <opensource@qandidate.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Qandidate\Common\Symfony\HttpKerne... | <?php
/*
* This file is part of the qandidate/symfony-json-request-transformer package.
*
* (c) Qandidate.com <opensource@qandidate.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Qandidate\Common\Symfony\HttpKerne... |
Fix trailing line style violation | from six.moves import configparser
def parse_mysql_cnf(dbinfo):
"""
Attempt to parse mysql database config file for connection settings.
Ideally we would hook into django's code to do this, but read_default_file is handled by the mysql C libs
so we have to emulate the behaviour
Settings that are ... | from six.moves import configparser
def parse_mysql_cnf(dbinfo):
"""
Attempt to parse mysql database config file for connection settings.
Ideally we would hook into django's code to do this, but read_default_file is handled by the mysql C libs
so we have to emulate the behaviour
Settings that are ... |
pluggable-backends: Use get_app over to include django-mailer support over a standard import and ImportError exception handling.
git-svn-id: 12265af7f62f437cb19748843ef653b20b846039@130 590c3fc9-4838-0410-bb95-17a0c9b37ca9 |
from django.conf import settings
from django.db.models.loading import get_app
from django.core.urlresolvers import reverse
from django.template.loader import render_to_string
from django.utils.translation import ugettext
from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigur... |
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template.loader import render_to_string
from django.utils.translation import ugettext
from django.contrib.sites.models import Site
from notification import backends
from notification.message import message_to_text
# favour djan... |
Use RandomUsersRetriever when ENDPOINT_ID is not set | /* eslint-disable no-console */
import AccessTokenRetriever from './access-token-retriever';
import ConfigurationProvider from './configuration-provider';
import WebServer from './web-server';
import WindowsGraphUsersRetriever from './windows-graph-users-retriever';
import RandomUsersRetriever from './random-users-ret... | /* eslint-disable no-console */
import AccessTokenRetriever from './access-token-retriever';
import ConfigurationProvider from './configuration-provider';
import WebServer from './web-server';
import WindowsGraphUsersRetriever from './windows-graph-users-retriever';
export default class Main {
constructor() {
t... |
Fix bug where empty mapping was processed | <?php
declare(strict_types=1);
namespace Mihaeu\PhpDependencies\Formatters;
use Mihaeu\PhpDependencies\Dependencies\Dependency;
use Mihaeu\PhpDependencies\Dependencies\DependencySet;
use Mihaeu\PhpDependencies\Dependencies\DependencyMap;
class DependencyStructureMatrixBuilder
{
public function buildMatrix(Depen... | <?php
declare(strict_types=1);
namespace Mihaeu\PhpDependencies\Formatters;
use Mihaeu\PhpDependencies\Dependencies\Dependency;
use Mihaeu\PhpDependencies\Dependencies\DependencySet;
use Mihaeu\PhpDependencies\Dependencies\DependencyMap;
class DependencyStructureMatrixBuilder
{
public function buildMatrix(Depen... |
Fix hashcode generation for existing URLs | # -*- coding: utf-8 -*-
import string
from django.db import models
class Blacklist(models.Model):
domain = models.CharField(max_length=255, unique=True, null=True)
def __unicode__(self):
return self.domain
class URL(models.Model):
hashcode = models.CharField(max_length=10, unique=True,
... | # -*- coding: utf-8 -*-
import string
from django.db import models
class Blacklist(models.Model):
domain = models.CharField(max_length=255, unique=True, null=True)
def __unicode__(self):
return self.domain
class URL(models.Model):
hashcode = models.CharField(max_length=10, unique=True,
... |
Revert "Added a workaround for abstract models not being handled correctly."
This reverts commit a3e44c187b5abfa6d9b360cecc5c1daa746134f5. | # -*- coding: utf-8 -*-
from django.db.models import F, Q
from django.core.management.base import NoArgsCommand
from modeltranslation.settings import DEFAULT_LANGUAGE
from modeltranslation.translator import translator
from modeltranslation.utils import build_localized_fieldname
class Command(NoArgsCommand):
help... | # -*- coding: utf-8 -*-
from django.db.models import F, Q
from django.core.management.base import NoArgsCommand
from modeltranslation.settings import DEFAULT_LANGUAGE
from modeltranslation.translator import translator
from modeltranslation.utils import build_localized_fieldname
class Command(NoArgsCommand):
help... |
Fix URL of locator records in packaged themes | <?php
namespace Concrete\Core\Filesystem\FileLocator;
use Concrete\Core\Package\PackageList;
use Concrete\Core\Page\Theme\Theme;
use Illuminate\Filesystem\Filesystem;
class ThemeLocation extends AbstractLocation
{
protected $filesystem;
protected $pkgHandle;
protected $themeHandle;
public function g... | <?php
namespace Concrete\Core\Filesystem\FileLocator;
use Concrete\Core\Package\PackageList;
use Concrete\Core\Page\Theme\Theme;
use Illuminate\Filesystem\Filesystem;
class ThemeLocation extends AbstractLocation
{
protected $filesystem;
protected $pkgHandle;
protected $themeHandle;
public function g... |
Add color to asset.name in console output | const chalk = require('chalk');
function composeWebpackOutput(stats) {
if (!stats.hasErrors() && !stats.hasWarnings()) {
composeSuccessOutput(stats);
return;
}
composeErrorOutput(stats);
}
function composeSuccessOutput(stats) {
console.log();
const assets = Object
.keys(stats.co... | const chalk = require('chalk');
function composeWebpackOutput(stats) {
if (!stats.hasErrors() && !stats.hasWarnings()) {
composeSuccessOutput(stats);
return;
}
composeErrorOutput(stats);
}
function composeSuccessOutput(stats) {
console.log();
const assets = Object
.keys(stats.co... |
Add convenience methods for creating/deleting all tables, for bootstrapping/testing use
Signed-off-by: Joonas Bergius <9be13466ab086d7a8db93edb14ffb6760790b15e@gmail.com> | from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class... | from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class... |
Adjust for compatibility with Python 2.5 | try:
from collections import Mapping
except ImportError:
# compatibility with Python 2.5
Mapping = dict
def quacks_like_dict(object):
"""Check if object is dict-like"""
return isinstance(object, Mapping)
def deep_merge(a, b):
"""Merge two deep dicts non-destructively
Uses a stack ... | import collections
def quacks_like_dict(object):
"""Check if object is dict-like"""
return isinstance(object, collections.Mapping)
def deep_merge(a, b):
"""Merge two deep dicts non-destructively
Uses a stack to avoid maximum recursion depth exceptions
>>> a = {'a': 1, 'b': {1: 1, 2: ... |
Fix TMN specific site param | /*
Copyright (c) 2013, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License.
See the accompanying LICENSE file for terms.
*/
'use strict';
// The `pathTo()` function is written in ES3 so it's serializable and able to
// run in all JavaScript environments.
module.exports = function pathTo(rou... | /*
Copyright (c) 2013, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License.
See the accompanying LICENSE file for terms.
*/
'use strict';
// The `pathTo()` function is written in ES3 so it's serializable and able to
// run in all JavaScript environments.
module.exports = function pathTo(rou... |
Move this to the bottom... | from django.contrib import admin
from django.contrib.auth.models import Group
from .models import Editor
class ContributorMixin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if not change:
obj.submitted_by = request.user
obj.edited_by.add(request.user)
o... | from django.contrib import admin
from django.contrib.auth.models import Group
from .models import Editor
class ContributorMixin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
super(ContributorMixin, self).save_model(request, obj, form, change)
if not change:
obj.... |
Document class changed for recent model changes. | package de.fh_bielefeld.newsboard.model;
import java.util.OptionalDouble;
import java.util.OptionalInt;
/**
* Domain class representing a classification of a document or sentence.
*
* @author Felix Meyer, Lukas Taake
*/
public class Classification {
private OptionalInt sentenceId = OptionalInt.empty();
pr... | package de.fh_bielefeld.newsboard.model;
import java.util.OptionalDouble;
import java.util.OptionalInt;
/**
* Domain class representing a classification of a document or sentence.
*
* @author Felix Meyer, Lukas Taake
*/
public class Classification {
private OptionalInt sentenceId = OptionalInt.empty();
pr... |
Revert "fixxed controller for login"
This reverts commit d3fccddb534ffee732125af1284c0f00708422ae. | var app = angular.module("adminApp", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/login.html',
controller: 'login.Controller.js',
controllerAs: 'vm',
... | var app = angular.module("adminApp", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/login.html',
controller: 'signInController'
})
.when('/dash... |
Fix webpack server for uri containing / | const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
inject: 'body'
});
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
e... | const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
inject: 'body'
});
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
e... |
LILY-2266: Allow clearing of social media fields with inline editing | angular.module('app.directives').directive('editableLink', editableLink);
function editableLink() {
return {
restrict: 'E',
scope: {
viewModel: '=',
type: '@',
field: '@',
object: '=?',
socialMediaName: '@?',
},
templateUrl... | angular.module('app.directives').directive('editableLink', editableLink);
function editableLink() {
return {
restrict: 'E',
scope: {
viewModel: '=',
type: '@',
field: '@',
object: '=?',
socialMediaName: '@?',
},
templateUrl... |
Use long array syntax to support PHP 5.x. | <?php
namespace Vikpe;
class HtmlHeadingNormalizerTest extends \PHPUnit_Framework_TestCase
{
const TEST_FILES_DIR = __DIR__.'/file/';
private function getTestFileContents($filename)
{
return file_get_contents(self::TEST_FILES_DIR.$filename);
}
public function assertHtmlStringEqualsHtmlSt... | <?php
namespace Vikpe;
class HtmlHeadingNormalizerTest extends \PHPUnit_Framework_TestCase
{
const TEST_FILES_DIR = __DIR__.'/file/';
private function getTestFileContents($filename)
{
return file_get_contents(self::TEST_FILES_DIR.$filename);
}
public function assertHtmlStringEqualsHtmlSt... |
spec-helper: Add support for function call attribute (&) | window.m = angular.mock.module;
window.compileHtml = function(htmlStr, data, parentElement = null) {
data = data || {};
var $scope;
inject(function($compile, $rootScope) {
parentElement = parentElement || document.body;
angular.element(parentElement).html(htmlStr);
$scope = $rootScop... | window.m = angular.mock.module;
window.compileHtml = function(htmlStr, data, parentElement = null) {
data = data || {};
var $scope;
inject(function($compile, $rootScope) {
parentElement = parentElement || document.body;
angular.element(parentElement).html(htmlStr);
$scope = $rootScop... |
Support adding hosts by DNS | import socket
from django.core.management.base import BaseCommand, CommandError
from django.db.utils import IntegrityError
from iptools import validate_ip, validate_cidr, IpRange
from hostmonitor.models import Host
def resolve_dns(name):
return set([x[4][0] for x in socket.getaddrinfo(name, 80)])
class Comman... | from iptools import validate_ip, validate_cidr, IpRange
from django.core.management.base import BaseCommand, CommandError
from hostmonitor.models import Host
class Command(BaseCommand):
args = '<target target ...>'
help = 'Add the specified hosts or CIDR networks (not network/broadcast)'
def add_host(sel... |
Copy only the participants list instead of using .extend() | 'use strict';
angular.module('Teem')
.directive('participate', function() {
return {
controller: [
'$scope', '$element', '$attrs', 'SessionSvc', '$timeout', 'CommunitiesSvc',
function($scope, $element, $attrs, SessionSvc, $timeout, CommunitiesSvc) {
$scope.participateCopyOn = $attrs.pa... | 'use strict';
angular.module('Teem')
.directive('participate', function() {
return {
controller: [
'$scope', '$element', '$attrs', 'SessionSvc', '$timeout', 'CommunitiesSvc',
function($scope, $element, $attrs, SessionSvc, $timeout, CommunitiesSvc) {
$scope.participateCopyOn = $attrs.pa... |
Allow null published_at, fix Validation message | <?php
namespace Metrique\Building\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Metrique\Building\Rules\AbsoluteUrlPathRule;
class PageRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
... | <?php
namespace Metrique\Building\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Metrique\Building\Rules\AbsoluteUrlPathRule;
class PageRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
... |
Bump version to fix build | from setuptools import setup
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
setup(
name='pyvault',
version='1.8.1',
description='Python password manager',
long_description=long_descripti... | from setuptools import setup
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
setup(
name='pyvault',
version='1.8',
description='Python password manager',
long_description=long_description... |
Add more rules in the documentation router. | <?php
use Hoa\Router;
$router = new Router\Http();
$router
->get(
'c',
'(?<vendor>)/(?<chapter>)\.html'
)
->get(
'hack',
'(?<chapter>)\.html'
)
->get(
'full',
'/(?<vendor>)/(?<chapter>)\.html'
)
->_get(
'literature',
'http://... | <?php
use Hoa\Router;
$router = new Router\Http();
$router
->get(
'c',
'(?<vendor>)/(?<chapter>)\.html'
)
->get(
'hack',
'(?<chapter>)\.html'
)
->get(
'full',
'/(?<vendor>)/(?<chapter>)\.html'
)
->_get(
'literature',
'http://... |
Handle playback of multiple tracks | define([
'libs/bean',
'libs/bonzo',
'libs/qwery',
'utils/loadJSON',
'sc'
], function(
bean,
bonzo,
qwery,
loadJSON
) {
var sound;
return {
init: function() {
loadJSON('/soundcloud-keys.json', function(data) {
SC.initialize({
... | define([
'libs/bean',
'libs/bonzo',
'libs/qwery',
'utils/loadJSON',
'sc'
], function(
bean,
bonzo,
qwery,
loadJSON
) {
var sound;
return {
init: function() {
loadJSON('/soundcloud-keys.json', function(data) {
SC.initialize({
... |
Add status fallback when an error does not expose one | "use strict";
function createDefaultFormatter() {
return function defaultFormatter(ctx, errors) {
ctx.body = {};
if (errors && errors.length) {
ctx.status = 500;
if (errors.length === 1) {
ctx.status = errors[0].status || ctx.status;
}
ctx.body['ok'] = 0;
ctx.body['statu... | "use strict";
function createDefaultFormatter() {
return function defaultFormatter(ctx, errors) {
ctx.body = {};
if (errors && errors.length) {
ctx.status = 500;
if (errors.length === 1) {
ctx.status = errors[0].status;
}
ctx.body['ok'] = 0;
ctx.body['status'] = ctx.stat... |
Use correct m2m join table name in LatestCommentsFeed
git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@9089 bcc190cf-cafb-0310-a4f2-bffc1f526a37 | from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
... | from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
... |
Fix arrays and add path support | /**
* @file
* Text reporter
*/
var Colors = require('colors/safe');
var _ = require('lodash');
/**
* Text reporter
* @param {Object} validationData
* @param {Object} [options]
* @param {Boolean} options.noColors
* @returns {String}
*/
module.exports = function textReporter(validationData, options) {
optio... | /**
* @file
* Text reporter
*/
var Colors = require('colors/safe');
var _ = require('lodash');
/**
* Text reporter
* @param {Object} validationData
* @param {Object} [options]
* @param {Boolean} options.noColors
* @returns {String}
*/
module.exports = function textReporter(validationData, options) {
optio... |
Convert everything to unicode strings before inserting to DB | #-*- coding: utf-8 -*-
from email.MIMEBase import MIMEBase
from django.core.mail.backends.base import BaseEmailBackend
from database_email_backend.models import Email, Attachment
class DatabaseEmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
if not email_messages:
retur... | #-*- coding: utf-8 -*-
from email.MIMEBase import MIMEBase
from django.core.mail.backends.base import BaseEmailBackend
from database_email_backend.models import Email, Attachment
class DatabaseEmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
if not email_messages:
retur... |
Add comments; and run task before watching | var gulp = require("gulp");
var sass = require("gulp-sass");
var nano = require('gulp-cssnano');
/*
Build civil.css
*/
gulp.task("sass", function () {
gulp.src("./sass/**/*.scss")
.pipe(sass({
//outputStyle: "compressed",
includePaths: ["./bower_components/bourbon/app/assets/style... | var gulp = require("gulp");
var sass = require("gulp-sass");
var nano = require('gulp-cssnano');
gulp.task("sass", function () {
gulp.src("./sass/**/*.scss")
.pipe(sass({
//outputStyle: "compressed",
includePaths: ["./bower_components/bourbon/app/assets/stylesheets/"]
}))
... |
Attach metadata to the right function | define(['../is', '../array/last', '../functional'], function(is, last, functional) {
var map = functional.map;
var filter = functional.filter;
var forEach = functional.forEach;
function annotate() {
var args = Array.prototype.slice.call(arguments);
var fn = args.shift();
var doc... | define(['../is', '../array/last', '../functional'], function(is, last, functional) {
var map = functional.map;
var filter = functional.filter;
var forEach = functional.forEach;
function annotate() {
var args = Array.prototype.slice.call(arguments);
var fn = args.shift();
if(is.... |
Set grunt watch use default task to generate .min.js file | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: ';',
sourceMap: true
},
dist: {
src: ['src/**/*.js'],
dest: 'assets/<%=... | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: ';',
sourceMap: true
},
dist: {
src: ['src/**/*.js'],
dest: 'assets/<%=... |
Fix wrong module name in migrations | from django.utils.encoding import smart_str
from kitsune.products.models import Product
from taggit.models import Tag
from kitsune.wiki.models import Document
tags_to_migrate = {
# source tag -> product
'firefox': ['firefox'],
'sync': ['firefox', 'mobile'],
'persona': ['firefox'],
'desktop': ['fir... | from django.utils.encoding import smart_str
from kitsune.products.models import Product
from kitsune.taggit.models import Tag
from kitsune.wiki.models import Document
tags_to_migrate = {
# source tag -> product
'firefox': ['firefox'],
'sync': ['firefox', 'mobile'],
'persona': ['firefox'],
'desktop... |
Store roles and permissions in user session instead of reloading them each request | var model = require('./model');
var middleware = module.exports = {};
middleware.loadRoles = function (req, res, next) {
if (req.user && !req.session.user) {
model.role.model.find({'_id': { $in: req.user.roles }}, function (err, docs) {
if (err) next();
var roles = [];
... | var model = require('./model');
var middleware = module.exports = {};
middleware.loadRoles = function (req, res, next) {
if (req.user) {
model.role.model.find({'_id': { $in: req.user.roles }}, function (err, docs) {
if (err) next();
var roles = [];
var permissions = []... |
Fix match time not showing for fixtures | import React, { Component } from "react";
import { formatTime } from "../../common/util/date";
export default class extends Component {
render() {
const { match } = this.props;
if (match.live || match.ended) {
return (
<span className={match.live && "live"}>
{match.ft && (!match.et |... | import React, { Component } from "react";
import { formatTime } from "../../common/util/date";
export default class extends Component {
render() {
const { match } = this.props;
if (match.fixture) {
return match.time && <span>{formatTime(match.date, match.time)}</span>;
}
if (match.live || mat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.