text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Add fields to the query
Added the fields which are then by default in the profile normalisation. | // Load modules
var Crypto = require('crypto');
// Declare internals
var internals = {};
exports = module.exports = function (options) {
return {
protocol: 'oauth2',
useParamsAuth: true,
auth: 'https://www.facebook.com/v2.3/dialog/oauth',
token: 'https://graph.facebook.com/oau... | // Load modules
var Crypto = require('crypto');
// Declare internals
var internals = {};
exports = module.exports = function (options) {
return {
protocol: 'oauth2',
useParamsAuth: true,
auth: 'https://www.facebook.com/v2.3/dialog/oauth',
token: 'https://graph.facebook.com/oau... |
Fix bug with getting url for transition | import Router from '@ember/routing/router';
export function initialize() {
const isEmbedded = window !== window.top;
if (isEmbedded) {
Router.reopen({
notifyTopFrame: function() {
window.top.postMessage({
action: 'did-transition',
url: this.currentURL
})
}.on... | import Router from '@ember/routing/router';
export function initialize() {
const isEmbedded = window !== window.top;
if (isEmbedded) {
Router.reopen({
notifyTopFrame: function() {
window.top.postMessage({
action: 'did-transition',
url: this.currentURL
})
}.on... |
Fix new lines in definition of UD module | """Looks up a term from urban dictionary
@package ppbot
@syntax ud <word>
"""
import requests
import json
from modules import *
class Urbandictionary(Module):
def __init__(self, *args, **kwargs):
"""Constructor"""
Module.__init__(self, kwargs=kwargs)
self.url = "http://www.urbandictiona... | """Looks up a term from urban dictionary
@package ppbot
@syntax ud <word>
"""
import requests
import json
from modules import *
class Urbandictionary(Module):
def __init__(self, *args, **kwargs):
"""Constructor"""
Module.__init__(self, kwargs=kwargs)
self.url = "http://www.urbandictiona... |
Make the "empty queue" log message less verbose | <?php
namespace Phive\TaskQueue;
use Phive\Queue\NoItemAvailableException;
use Phive\TaskQueue\ExecutorAdapter\ExecutorAdapter;
class Executor
{
/**
* @var ExecutorAdapter
*/
private $adapter;
/**
* @var ExecutionContext
*/
protected $context;
public function __construct(Exe... | <?php
namespace Phive\TaskQueue;
use Phive\Queue\NoItemAvailableException;
use Phive\TaskQueue\ExecutorAdapter\ExecutorAdapter;
class Executor
{
/**
* @var ExecutorAdapter
*/
private $adapter;
/**
* @var ExecutionContext
*/
protected $context;
public function __construct(Exe... |
Fix encoding (thanks to Yasushi Masuda) | # -*- coding: utf-8 -*-
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import sys
from reportlab.platypus import PageBreak, Spacer
from flowables import *
import shlex
from log import log
def parseRaw (data):
'''Parse and process a simple DSL to handle creation of flowables.
Supported (can... | #$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import sys
from reportlab.platypus import PageBreak, Spacer
from flowables import *
import shlex
from log import log
def parseRaw (data):
'''Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
... |
Test travis fails with wrong test | const OrderLib = artifacts.require("OrderLib");
const MarketContractOraclize = artifacts.require("MarketContractOraclize");
const utility = require('./utility.js');
contract('OrderLib', function(accounts) {
var orderLib;
it("Orders are signed correctly", async function() {
orderLib = await OrderLib.dep... | const OrderLib = artifacts.require("OrderLib");
const MarketContractOraclize = artifacts.require("MarketContractOraclize");
const utility = require('./utility.js');
contract('OrderLib', function(accounts) {
var orderLib;
it("Orders are signed correctly", async function() {
orderLib = await OrderLib.dep... |
Use `selected = false`, over `_.omit` to deselect a source
From a basic functionality standpoint, this accomplishes the same purpose as
the previous implementation using `_.omit`. However, rather than removing the
`selected` attribute from the sources, this will keep the structure the same by
only altering the value o... | 'use strict';
var _ = require('underscore'),
events = require('./events'),
qualitySelectorFactory = require('./components/QualitySelector'),
sourceInterceptorFactory = require('./middleware/SourceInterceptor');
module.exports = function(videojs) {
videojs = videojs || window.videojs;
qualitySelecto... | 'use strict';
var _ = require('underscore'),
events = require('./events'),
qualitySelectorFactory = require('./components/QualitySelector'),
sourceInterceptorFactory = require('./middleware/SourceInterceptor');
module.exports = function(videojs) {
videojs = videojs || window.videojs;
qualitySelecto... |
Update google-cloud-bigquery version to incorporate PollingFuture retry changes.
Specifically: https://github.com/googleapis/google-cloud-python/commit/f576d148f802666dbd11cf7c50a0629a77f81665
Change-Id: Id3244786ffa73cbe3a166cfe35cb7f2219140a31 | # Copyright 2017 Verily Life Sciences Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright 2017 Verily Life Sciences Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
Fix permalinks test which was breaking other tests. | from django.contrib.contenttypes.models import ContentType
from django.core import urlresolvers
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.test import TestCase
from ..permalinks import expand, resolve, PermalinkError
class TestPermalinkModel(models.Model):
d... | from django.contrib.contenttypes.models import ContentType
from django.core import urlresolvers
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.test import TestCase
from ..permalinks import expand, resolve, PermalinkError
class TestPermalinkModel(models.Model):
d... |
Update the minimum name and slug length for Businesses (3->4) | <?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class BusinessFormRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation... | <?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class BusinessFormRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation... |
Fix Travis while the Atom support is incomplete. | # Copyright (c) 2014, Matt Layman
import os
import sys
from werkzeug.contrib.atom import AtomFeed
from handroll import logger
from handroll.composers import Composer
class AtomComposer(Composer):
"""Compose an Atom feed from an Atom metadata file (``.atom``).
The ``AtomComposer`` parses the metadata speci... | # Copyright (c) 2014, Matt Layman
import os
import sys
from werkzeug.contrib.atom import AtomFeed
from handroll import logger
from handroll.composers import Composer
class AtomComposer(Composer):
"""Compose an Atom feed from an Atom metadata file (``.atom``).
The ``AtomComposer`` parses the metadata speci... |
Improve the error handling, better use of ArgumentParser. | # This file is part of Viper - https://github.com/botherder/viper
# See the file 'LICENSE' for copying permission.
import argparse
class ArgumentErrorCallback(Exception):
def __init__(self, message, level=''):
self.message = message.strip() + '\n'
self.level = level.strip()
def __str__(self... | # This file is part of Viper - https://github.com/botherder/viper
# See the file 'LICENSE' for copying permission.
import argparse
class ArgumentParser(argparse.ArgumentParser):
def error(self, message):
raise Exception('error: {}\n'.format(message))
class Module(object):
cmd = ''
description ... |
Reset warnings before testing warnings | # -*- coding: utf-8 -*
from __future__ import absolute_import, unicode_literals
import warnings
from django.test import SimpleTestCase
from wagtail.utils.deprecation import RemovedInWagtail17Warning, SearchFieldsShouldBeAList
class TestThisShouldBeAList(SimpleTestCase):
def test_add_a_list(self):
with ... | # -*- coding: utf-8 -*
from __future__ import absolute_import, unicode_literals
import warnings
from django.test import SimpleTestCase
from wagtail.utils.deprecation import RemovedInWagtail17Warning, SearchFieldsShouldBeAList
class TestThisShouldBeAList(SimpleTestCase):
def test_add_a_list(self):
with ... |
Fix broken code, comment out sun.awt.X11.XLayerProtocol | package dr.inference.model;
import dr.xml.*;
//import sun.awt.X11.XLayerProtocol;
/**
* @author Joseph Heled
* Date: 4/09/2009
*/
public class ValuesPoolParser extends dr.xml.AbstractXMLObjectParser {
public static String VALUES_POOL = "valuesPool";
public static String VALUES = "values";
publ... | package dr.inference.model;
import dr.xml.*;
import sun.awt.X11.XLayerProtocol;
/**
* @author Joseph Heled
* Date: 4/09/2009
*/
public class ValuesPoolParser extends dr.xml.AbstractXMLObjectParser {
public static String VALUES_POOL = "valuesPool";
public static String VALUES = "values";
public... |
Revise to include 'SerialPort' object as field, instead of inheriting therefrom | /* *\
** SICU Stress Measurement System **
** Project P04 | C380 Team A **
** EBME 380: Biomedical Engineering Design Experience **
** ... | /* *\
** SICU Stress Measurement System **
** Project P04 | C380 Team A **
** EBME 380: Biomedical Engineering Design Experience **
** ... |
Make readpst partial output ingest. | from ingestors.base import Ingestor
from ingestors.support.temp import TempFileSupport
from ingestors.support.shell import ShellSupport
from ingestors.support.ole import OLESupport
from ingestors.directory import DirectoryIngestor
class OutlookPSTIngestor(Ingestor, TempFileSupport, ShellSupport, OLESupport):
MIME... | from ingestors.base import Ingestor
from ingestors.support.temp import TempFileSupport
from ingestors.support.shell import ShellSupport
from ingestors.support.ole import OLESupport
from ingestors.directory import DirectoryIngestor
class OutlookPSTIngestor(Ingestor, TempFileSupport, ShellSupport, OLESupport):
MIME... |
Fix unused variable and url selection | /**
* Created by Andrew on 12/7/2015.
*/
function LaughingMan() {
this.laughingManImage = "https://i.imgur.com/u6A3oCM.gif";
}
LaughingMan.prototype.start = function() {
if (!document.getElementsByTagName) return;
var imageArray = document.getElementsByTagName("img");
var content = new Array();
... | /**
* Created by Andrew on 12/7/2015.
*/
function LaughingMan() {
this.laughingManImage = "https://i.imgur.com/u6A3oCM.gif";
}
LaughingMan.prototype.start = function() {
if (!document.getElementsByTagName) return;
var imageArray = document.getElementsByTagName("img");
var content = new Array();
... |
Test Edge 17 instead of 16 | var baseKarma = require('./base-karma')
module.exports = function(config) {
var baseConfig = baseKarma(config);
config.set(Object.assign(baseConfig, {
browsers: [
'bs_firefox_android',
'bs_chrome_mac',
'bs_ie_11',
'bs_edge',
],
reporters: [
'mocha', 'BrowserStack',
]... | var baseKarma = require('./base-karma')
module.exports = function(config) {
var baseConfig = baseKarma(config);
config.set(Object.assign(baseConfig, {
browsers: [
'bs_firefox_android',
'bs_chrome_mac',
'bs_ie_11',
'bs_edge',
],
reporters: [
'mocha', 'BrowserStack',
]... |
Check for an empty result | (function (env) {
"use strict";
env.ddg_spice_thumbtack = function(api_result){
if (!api_result || api_result.error || !api_result.data || !api_result.data.length) {
return Spice.failed('thumbtack');
}
// Render the response
DDG.require('maps', function() {
... | (function (env) {
"use strict";
env.ddg_spice_thumbtack = function(api_result){
// Don't show anything if we weren't able to return 2 or more services.
// In future iterations, we should support a different view in the case
// of a single result.
if (!api_result || api_result.er... |
Add laravel 5.2 compat by checking query builder return type | <?php
namespace Amelia\Rememberable\Eloquent;
use Illuminate\Database\Eloquent\Collection;
class Builder extends \Illuminate\Database\Eloquent\Builder
{
/**
* @var \Amelia\Rememberable\Query\Builder
*/
protected $query;
/**
* Get the hydrated models without eager loading.
*
* @p... | <?php
namespace Amelia\Rememberable\Eloquent;
use Illuminate\Database\Eloquent\Collection;
class Builder extends \Illuminate\Database\Eloquent\Builder
{
/**
* @var \Amelia\Rememberable\Query\Builder
*/
protected $query;
/**
* Get the hydrated models without eager loading.
*
* @p... |
Stop event bubbling when clicking on document toolbar | $(document).ready(function(){
var i=0;
var $td;
var state;
function checkDocumentsStatuses(){
$.getJSON("/api/documents_states", function(data){
var $bars = $(".bar");
for(i=0;i<$bars.length;i++){
$($bars[i]).css("width", data[i] + "%");
}
});
setTimeout(checkDocumentsStat... | $(document).ready(function(){
var i=0;
var $td;
var state;
function checkDocumentsStatuses(){
$.getJSON("/api/documents_states", function(data){
var $bars = $(".bar");
for(i=0;i<$bars.length;i++){
$($bars[i]).css("width", data[i] + "%");
}
});
setTimeout(checkDocumentsStat... |
Call boomcms:publish command if new templates are installed | <?php
namespace BoomCMS\Console\Commands;
use BoomCMS\Core\Template\Manager as TemplateManager;
use Illuminate\Console\Command;
use PDOException;
class InstallTemplates extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'boomcms:installTemplates';
... | <?php
namespace BoomCMS\Console\Commands;
use BoomCMS\Core\Template\Manager as TemplateManager;
use Illuminate\Console\Command;
use PDOException;
class InstallTemplates extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'boomcms:installTemplates';
... |
Fix sku generation not updating list grid properly | (function($, BLCAdmin) {
// Add utility functions for products to the BLCAdmin object
BLCAdmin.product = {
refreshSkusGrid : function($container, listGridUrl) {
BLC.ajax({
url : listGridUrl,
type : "GET"
}, function(data) {
... | (function($, BLCAdmin) {
// Add utility functions for products to the BLCAdmin object
BLCAdmin.product = {
refreshSkusGrid : function($container, listGridUrl) {
BLC.ajax({
url : listGridUrl,
type : "GET"
}, function(data) {
... |
Allow javerage to persist as the user if debug is on, otherwise use request.user - allows this to work behind pubcookie/other auth | from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.conf import settings
import logging
from myuw_api.sws_dao import Quarter
from myuw_api.pws_dao import Person as PersonDAO
logger = logging... | from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
import logging
from myuw_api.sws_dao import Quarter
from myuw_api.pws_dao import Person as PersonDAO
logger = logging.getLogger('myuw_mobile.views')
... |
Use source key instead of meta and detail fields |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... |
Fix line length > 80 characters | ChannelInfo = BlazeComponent.extendComponent({
onCreated: function () {
},
onRendered: function () {
var self = this;
self.$channelInfo = self.$('.channel-info');
self.$channelFooter = $('.channel-footer');
self.$channelBody = $('.channel-body');
this.autorun(function () {
if (App.cha... | ChannelInfo = BlazeComponent.extendComponent({
onCreated: function () {
},
onRendered: function () {
var self = this;
self.$channelInfo = self.$('.channel-info');
self.$channelFooter = $('.channel-footer');
self.$channelBody = $('.channel-body');
this.autorun(function () {
if (App.cha... |
Fix dass bei News Detail Preview Image Admin felder doppelt waren | <?php
class Vpc_Abstract_Image_Trl_Form_ImageData extends Vpc_Abstract_Image_Trl_ImageData
{
public function load($row)
{
$src = $this->_getImageUrl($row->component_id);
if ($src) {
return "<img src=\"$src\" />";
}
return '';
}
}
class Vpc_Abstract_Image_Trl_Form... | <?php
class Vpc_Abstract_Image_Trl_Form_ImageData extends Vpc_Abstract_Image_Trl_ImageData
{
public function load($row)
{
$src = $this->_getImageUrl($row->component_id);
if ($src) {
return "<img src=\"$src\" />";
}
return '';
}
}
class Vpc_Abstract_Image_Trl_Form... |
Support assignees when creating a new issue | package org.kohsuke.github;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Kohsuke Kawaguchi
*/
public class GHIssueBuilder {
private final GHRepository repo;
private final Requester builder;
private List<String> labels = new ArrayList<String>();
private... | package org.kohsuke.github;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Kohsuke Kawaguchi
*/
public class GHIssueBuilder {
private final GHRepository repo;
private final Requester builder;
private List<String> labels = new ArrayList<String>();
GHIssu... |
Change Shortcut for Deploy as Ctrl+Shift+P | /**
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.o... | /**
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.o... |
Include an event with the response log message
This is now required by structlog | """Logging helpers and utilities."""
import uuid
from functools import wraps
from timeit import default_timer as timer
from typing import Any, Callable, TypeVar
import structlog
from flask import make_response, request
__all__ = ["log_route"]
F = TypeVar("F", bound=Callable[..., Any])
def log_route() -> Callable[... | """Logging helpers and utilities."""
import uuid
from functools import wraps
from timeit import default_timer as timer
from typing import Any, Callable, TypeVar
import structlog
from flask import make_response, request
__all__ = ["log_route"]
F = TypeVar("F", bound=Callable[..., Any])
def log_route() -> Callable[... |
Change package to geobuf, matching the module name. | from codecs import open as codecs_open
import distutils.log
import os.path
import shutil
from setuptools import setup, find_packages
import subprocess
# Try to convert README markdown to restructured text using pandoc.
try:
subprocess.call(
'pandoc --from=markdown --to=rst --output=README README.md',
... | from codecs import open as codecs_open
import distutils.log
import os.path
import shutil
from setuptools import setup, find_packages
import subprocess
# Try to convert README markdown to restructured text using pandoc.
try:
subprocess.call(
'pandoc --from=markdown --to=rst --output=README README.md',
... |
Increase to version 0.3.11 due to TG-dev requiring it for ming support | from setuptools import setup, find_packages
import os
version = '0.3.11'
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read()
except IOError:
README = CHANGES = ''
setup(name='tgext.admin... | from setuptools import setup, find_packages
import os
version = '0.3.10'
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read()
except IOError:
README = CHANGES = ''
setup(name='tgext.admin... |
Store ContentItem refs in PageViews by basename | <?php
/**
* @copyright 2017 Vladimir Jimenez
* @license https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
*/
namespace allejo\stakx\Object;
class DynamicPageView extends PageView
{
/**
* The Content Items that belong to this Page View. This array will only have elements if it is a dynamic Page... | <?php
/**
* @copyright 2017 Vladimir Jimenez
* @license https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
*/
namespace allejo\stakx\Object;
class DynamicPageView extends PageView
{
/**
* The Content Items that belong to this Page View. This array will only have elements if it is a dynamic Page... |
Mark the unused Servlet Container callback methods as final to ensure subclasses do not rely upon them. | package org.springframework.security.ui;
import org.springframework.core.Ordered;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.FilterChain;
import javax.servlet.ServletResponse;
import javax.servlet.FilterConf... | package org.springframework.security.ui;
import org.springframework.core.Ordered;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.FilterChain;
import javax.servlet.ServletResponse;
import javax.servlet.FilterConf... |
Update pid sequence so it will work even if sequence already exists | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from pidman.pid.noid import decode_noid
from pidman.pid import models as pid_models
def pid_sequence_lastvalue(apps, schema_editor):
# if the database has existing pids, update the sequence last value
# s... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from pidman.pid.noid import decode_noid
from pidman.pid import models as pid_models
def pid_sequence_lastvalue(apps, schema_editor):
# if the database has existing pids, update the sequence last value
# s... |
Put SPI slave configurations on Host. | """
Created on 18 May 2017
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
import sys
from scs_dfe.particulate.opc_n2 import OPCN2
from scs_host.bus.i2c import I2C
from scs_host.sys.host import Host
from scs_mfr.test.test import Test
# --------------------------------------------------------------... | """
Created on 18 May 2017
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
import sys
from scs_dfe.particulate.opc_n2 import OPCN2
from scs_host.bus.i2c import I2C
from scs_host.sys.host import Host
from scs_mfr.test.test import Test
# --------------------------------------------------------------... |
Add ability to set state of subheader | import { getColor } from './helpers';
import { StyleSheet, View, Text } from 'react-native';
import { TYPO, THEME_NAME } from './config';
import React, { Component, PropTypes } from 'react';
const styles = StyleSheet.create({
container: {
padding: 16
},
text: TYPO.paperFontBody1
});
export default... | import { getColor } from './helpers';
import { StyleSheet, View, Text } from 'react-native';
import { TYPO, THEME_NAME } from './config';
import React, { Component, PropTypes } from 'react';
const styles = StyleSheet.create({
container: {
padding: 16
},
text: TYPO.paperFontBody1
});
export default... |
Add comments & revise space complexity | """Leetcode 118. Pascal's Triangle
Easy
URL: https://leetcode.com/problems/pascals-triangle/
Given a non-negative integer numRows, generate the first numRows of
Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly
above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
... | """Leetcode 118. Pascal's Triangle
Easy
URL: https://leetcode.com/problems/pascals-triangle/
Given a non-negative integer numRows, generate the first numRows of
Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly
above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
... |
Update generics to match changes in jdbi3 branch | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed u... | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed u... |
Fix typo in Mongoose backend | module.exports = function(Model, options) {
options || (options = {})
options.idAttribute || (options.idAttribute = '_id')
var idQuery = function(model) {
var query = {};
query[options.idAttribute] = model[options.idAttribute];
return query;
};
this.create = function(model,... | module.exports = function(Model, options) {
options || (options = {})
options.idAttribute || (options.idAttribute = '_id')
var idQuery = function(model) {
var query = {};
query[options.idAttribute] = model[options.idAttribute];
};
this.create = function(model, callback) {
M... |
Fix issues due to module rename | #!/usr/bin/env python
# Copyright 2016 University of Chicago
# Licensed under the APL 2.0 license
import logging
import logging.handlers
import os
LOG_FILENAME = '~/logs/fsurf.log'
MAX_BYTES = 1024*1024*50 # 50 MB
NUM_BACKUPS = 10 # 10 files
def initialize_logging():
"""
Initialize logging for fsurf
... | #!/usr/bin/env python
# Copyright 2016 University of Chicago
# Licensed under the APL 2.0 license
import log
import log.handlers
import os
LOG_FILENAME = '~/logs/fsurf.log'
MAX_BYTES = 1024*1024*50 # 50 MB
NUM_BACKUPS = 10 # 10 files
def initialize_logging():
"""
Initialize logging for fsurf
:retur... |
Use postcss-sass-extend instead of postcss-extend. | import path from 'path';
import mixins from 'postcss-mixins';
import nested from 'postcss-nested';
import extend from 'postcss-sass-extend';
import repeat from 'postcss-for';
import simpleVars from 'postcss-simple-vars'
import cssMqpacker from 'css-mqpacker';
import gulp from 'gulp';
import gulpLoadPlugins from... | import path from 'path';
import mixins from 'postcss-mixins';
import nested from 'postcss-nested';
import extend from 'postcss-extend';
import repeat from 'postcss-for';
import simpleVars from 'postcss-simple-vars';
import each from 'postcss-each';
import cssMqpacker from 'css-mqpacker';
import gulp from 'gulp'... |
ASN-8: Add TODO note to unfinished validator method | /*
* Created by brightSPARK Labs
* www.brightsparklabs.com
*/
package com.brightsparklabs.asanti.validator;
import com.brightsparklabs.asanti.model.data.DecodedAsnData;
import com.brightsparklabs.asanti.model.schema.typedefinition.AsnSchemaTypeDefinition;
import com.brightsparklabs.asanti.validator.rule.Validation... | /*
* Created by brightSPARK Labs
* www.brightsparklabs.com
*/
package com.brightsparklabs.asanti.validator;
import com.brightsparklabs.asanti.model.data.DecodedAsnData;
import com.brightsparklabs.asanti.model.schema.typedefinition.AsnSchemaTypeDefinition;
import com.brightsparklabs.asanti.validator.rule.Validation... |
:new: Add env variable to debug resolutions | // @flow
import path from 'path'
import flatten from 'lodash/flatten'
import browserResolve from 'browser-resolve'
import { createFileResolver } from 'pundle-api'
import manifest from '../package.json'
function createComponent({ formats, aliases = {} }: { formats: { [string]: string }, aliases: { [string]: string } ... | // @flow
import path from 'path'
import flatten from 'lodash/flatten'
import browserResolve from 'browser-resolve'
import { createFileResolver } from 'pundle-api'
import manifest from '../package.json'
function createComponent({ formats, aliases = {} }: { formats: { [string]: string }, aliases: { [string]: string } ... |
New: Use regex to remove non alphanumerics from post titles | from lxml import html
import re
import requests
from constants import SEP_URL
class SEPSearchResult():
query = None
results = None
def __init__(self, query):
self.set_query(query)
def set_query(self, query):
pattern = re.compile('[^a-zA-Z\d\s]')
stripped_query = re.sub(patte... | from lxml import html
import re
import requests
from constants import SEP_URL
class SEPSearchResult():
query = None
results = None
def __init__(self, query):
self.set_query(query)
def set_query(self, query):
self.query = str(query).lower().split()
@property
def url(self):
... |
Make sure looking up by id works correctly | import motor
import error
from tornado import gen
from bson.objectid import ObjectId
class Connection(object):
def __init__(self, host='localhost', port=None, db=None):
self.host = host
self.port = port
self.db = db
class Database(object):
def __init__(self, connection):
if n... | import motor
import error
from tornado import gen
class Connection(object):
def __init__(self, host='localhost', port=None, db=None):
self.host = host
self.port = port
self.db = db
class Database(object):
def __init__(self, connection):
if not isinstance(connection, Connectio... |
Fix FirstChildPage if child page doesn't exist | <?php
class Kwc_Basic_LinkTag_FirstChildPage_Data extends Kwf_Component_Data
{
private $_pageCache = false;
public function __get($var)
{
if ($var == 'url') {
$page = $this->_getFirstChildPage();
return $page ? $page->url : '';
} else if ($var == 'rel') {
... | <?php
class Kwc_Basic_LinkTag_FirstChildPage_Data extends Kwf_Component_Data
{
private $_pageCache = false;
public function __get($var)
{
if ($var == 'url') {
$page = $this->_getFirstChildPage();
return $page ? $page->url : '';
} else if ($var == 'rel') {
... |
Fix log not saving on pause | import Liker from './content/liker';
import OptionManager from './utils/option-manager';
import Debug from './content/debug';
const debug = new Debug();
(async function () {
try {
debug.log('navigated:', window.location.href);
if (process.env.NODE_ENV === 'development') {
['yt-navigate', 'yt-navigate... | import Liker from './content/liker';
import OptionManager from './utils/option-manager';
import Debug from './content/debug';
const debug = new Debug();
(async function () {
try {
debug.log('navigated:', window.location.href);
if (process.env.NODE_ENV === 'development') {
['yt-navigate', 'yt-navigate... |
Fix volume button scrolling on phones. | package cc.hughes.droidchatty;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
public class SingleThreadView extends FragmentActivity
{
public static final String THREAD_I... | package cc.hughes.droidchatty;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
public class SingleThreadView extends FragmentActivity
{
public static final String THREAD_I... |
Change package name from VCCS to vccs_auth.
There will be a separate package containing the authentication client,
and it does not appear possible to (cleanly) generate two packages
from the same setup.py/same repository. | #!/usr/bin/env python
#
from setuptools import setup, find_packages
import sys, os
from distutils import versionpredicate
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README')).read()
version = '0.1dev'
install_requires = [
'pyhsm >= 1.0.3',
'ndnkdf >= 0.1',
'py-bcr... | #!/usr/bin/env python
#
from setuptools import setup, find_packages
import sys, os
from distutils import versionpredicate
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README')).read()
version = '0.1dev'
install_requires = [
'pyhsm >= 1.0.3',
'ndnkdf >= 0.1',
'py-bcr... |
Add settings table to get new nb | <?php require("_header.php"); ?>
<div class="row">
<!--left-->
<div class="col-md-3" id="leftCol">
<div class="row">
<ul class="nav nav-stacked" id="sidebar">
<li><a href="#secAdultes">BD Adultes</a></li... | <?php require("_header.php"); ?>
<div class="row">
<!--left-->
<div class="col-md-3" id="leftCol">
<div class="row">
<ul class="nav nav-stacked" id="sidebar">
<li><a href="#secAdultes">BD Adultes</a></li... |
PIO-129: Remove Unittests done as integrationtests, due to NotImplementedErrors from moto | from unittest2 import TestCase
import simplejson as json
import boto3
from moto import mock_s3
import permission_lambda
class PermissionLambdaTests(TestCase):
@mock_s3
def test_get_usofa_accountlist_from_bucket(self):
bucketname = "testbucket"
usofa_data = {
"account1": {
... | from unittest2 import TestCase
import simplejson as json
import boto3
from moto import mock_s3
import permission_lambda
class PermissionLambdaTests(TestCase):
def _get_permission_statements(self, client, queue_url):
""" Return a list of policy statements for given queue"""
policy_response = client... |
Fix warning invalid props for textarea | import React, { Component, PropTypes } from 'react'
import classnames from 'classnames'
import { ControlButtons } from './'
class FormControl extends Component {
render () {
const { componentClass: Component, className, style, submitted, ...props } = this.props
const {
$formRedux: { formInline, submit... | import React, { Component, PropTypes } from 'react'
import classnames from 'classnames'
import { ControlButtons } from './'
class FormControl extends Component {
render () {
const { componentClass: Component, className, style, submitted, ...props } = this.props
const {
$formRedux: { formInline, submit... |
Fix generation of translated modules | <?php
/**
* Created by PhpStorm.
* User: Conrad
* Date: 9/11/2015
* Time: 5:28 PM
*/
class ContentModuleSiteTreeTranslatableExtension extends DataExtension
{
public function onTranslatableCreate($saveTranslation)
{
if ($saveTranslation) {
//create new modules
$manyManys = a... | <?php
/**
* Created by PhpStorm.
* User: Conrad
* Date: 9/11/2015
* Time: 5:28 PM
*/
class ContentModuleSiteTreeTranslatableExtension extends DataExtension
{
public function onTranslatableCreate($saveTranslation)
{
if ($saveTranslation) {
//create new modules
$manyManys = a... |
Add ignition to exculded uris | <?php
return [
/* -----------------------------------------------------------------
| Theme
| -----------------------------------------------------------------
*/
'theme' => 'bootstrap-3',
/* -----------------------------------------------------------------
| Route settings
| ... | <?php
return [
/* -----------------------------------------------------------------
| Theme
| -----------------------------------------------------------------
*/
'theme' => 'bootstrap-3',
/* -----------------------------------------------------------------
| Route settings
| ... |
Prepend menu- to all menu item IDs | <?php
declare(strict_types=1);
namespace PerFi\PerFiBundle\EventListener;
use Avanzu\AdminThemeBundle\Event\SidebarMenuEvent;
use Avanzu\AdminThemeBundle\Model\MenuItemModel;
use Symfony\Component\HttpFoundation\Request;
class MenuItemListener
{
public function onSetupMenu(SidebarMenuEvent $event)
{
... | <?php
declare(strict_types=1);
namespace PerFi\PerFiBundle\EventListener;
use Avanzu\AdminThemeBundle\Event\SidebarMenuEvent;
use Avanzu\AdminThemeBundle\Model\MenuItemModel;
use Symfony\Component\HttpFoundation\Request;
class MenuItemListener
{
public function onSetupMenu(SidebarMenuEvent $event)
{
... |
Add Karma as Grunt task | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
bump: {
options: {
files: ['package.json'],
updateConfigs: ['pkg'],
commit: true,
commitMessage: 'Release v%VERSION%',
... | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
bump: {
options: {
files: ['package.json'],
updateConfigs: ['pkg'],
commit: true,
commitMessage: 'Release v%VERSION%',
... |
Update illuminate paginator return instance rather than paginator on make | <?php
namespace Michaeljennings\Carpenter\Pagination;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\BootstrapThreePresenter;
use Michaeljennings\Carpenter\Contracts\Paginator as PaginatorContract;
class IlluminateDriver implements PaginatorContract
{
/**
* An instance of the IOC ... | <?php
namespace Michaeljennings\Carpenter\Pagination;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\BootstrapThreePresenter;
use Michaeljennings\Carpenter\Contracts\Paginator as PaginatorContract;
class IlluminateDriver implements PaginatorContract
{
/**
* An instance of the IOC ... |
Remove public modifier from Method getter. | package com.novoda.downloadmanager;
import java.util.Map;
class DownloadManagerRequest {
private final Map<String, String> headers;
private final String url;
private final Method method;
DownloadManagerRequest(Map<String, String> headers, String url, Method method) {
this.headers = headers;
... | package com.novoda.downloadmanager;
import java.util.Map;
class DownloadManagerRequest {
private final Map<String, String> headers;
private final String url;
private final Method method;
DownloadManagerRequest(Map<String, String> headers, String url, Method method) {
this.headers = headers;
... |
Fix tests for django 2.2 | import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SECRET_KEY = 'fake-key'
HASHID_FIELD_SALT = 'gg ez'
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.messages",
"django.contrib.sessions",
"django.contrib.admin",
"tests",
]
DATABASES = {
... | import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SECRET_KEY = 'fake-key'
HASHID_FIELD_SALT = 'gg ez'
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.messages",
"django.contrib.sessions",
"django.contrib.admin",
"tests",
]
DATABASES = {
... |
Use updated symbol path for file-system-roots plugin |
var myApp = angular.module('CordovaAppHarness', ['ngRoute']);
myApp.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/', {
templateUrl: 'views/list.html',
controller: 'ListCtrl'
});
$routeProvider.when('/add', {
templateUrl: 'views/add.html',
contro... |
var myApp = angular.module('CordovaAppHarness', ['ngRoute']);
myApp.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/', {
templateUrl: 'views/list.html',
controller: 'ListCtrl'
});
$routeProvider.when('/add', {
templateUrl: 'views/add.html',
contro... |
Update leaflet request to be over https | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
... | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
... |
Increase cluster-test timeout for slow CI machines. | var helper = require('./specHelper');
var cluster = require('cluster');
var http = require('http');
describe("clustering", function() {
beforeEach(function() {
helper.testComplete(false);
});
it ('should be able to delegate requests to children', function() {
waitsFor(helper.testComplete, "child to c... | var helper = require('./specHelper');
var cluster = require('cluster');
var http = require('http');
describe("clustering", function() {
beforeEach(function() {
helper.testComplete(false);
});
it ('should be able to delegate requests to children', function() {
waitsFor(helper.testComplete, "child to c... |
Add test for Argument setter. |
define(
[
'chai',
'fixtures',
'argumenta/widgets/Argument',
'argumenta/widgets/Base'
],
function(chai, fixtures, Argument, Base) {
var assert = chai.assert;
describe('Argument', function() {
it('should be a function', function() {
assert.isFunction(Argument);
});
... |
define(
[
'chai',
'fixtures',
'argumenta/widgets/Argument',
'argumenta/widgets/Base'
],
function(chai, fixtures, Argument, Base) {
var assert = chai.assert;
describe('Argument', function() {
it('should be a function', function() {
assert.isFunction(Argument);
});
... |
Test char rnn with static batch size | import tensorflow as tf
from .char_rnn import char_rnn
def test_char_rnn():
for i, (sentence_shape, labels_shape) in enumerate([
[[11, 64, 8], [11, 64]],
[[None, 64, 8], [None, 64]],
[[None, None, 8], [None, None]],
[[None, None, None], [None, None]]]):
for... | import tensorflow as tf
from .char_rnn import char_rnn
def test_char_rnn():
for i, (sentence_shape, labels_shape) in enumerate([
[[None, 64, 8], [None, 64]],
[[None, None, 8], [None, None]],
[[None, None, None], [None, None]]]):
for mode in [tf.contrib.learn.ModeKeys.T... |
Allow collapse all accordion tabs in profileeditor | (function($){
$(function(){
$('.button-collapse').sideNav();
}); // end of document ready
})(jQuery); // end of jQuery name space
// Keep one tab expanded while editing profile
/*$('li div.collapsible-header').on('click',function(e){
if($(this).parents('li').hasClass('active')){
e.stopPropagation();
... | (function($){
$(function(){
$('.button-collapse').sideNav();
}); // end of document ready
})(jQuery); // end of jQuery name space
// Keep one tab expanded while editing profile
$('li div.collapsible-header').on('click',function(e){
if($(this).parents('li').hasClass('active')){
e.stopPropagation();
}
... |
Fix exception 'local variable 'move' referenced before assignment' in case of upload of unknown file formats | #!/usr/bin/env python
# vim: set fileencoding=utf-8 :
from flask import flash
from old_xml_import import old_xml_import
from sml_import import sml_import
import gzip
from model import db, Sample
from sqlalchemy.sql import func
def move_import(xmlfile, filename, user):
move = None
if filename.endswith('.gz'... | #!/usr/bin/env python
# vim: set fileencoding=utf-8 :
from flask import flash
from old_xml_import import old_xml_import
from sml_import import sml_import
import gzip
from model import db, Sample
from sqlalchemy.sql import func
def move_import(xmlfile, filename, user):
if filename.endswith('.gz'):
xmlfil... |
Mixins/Clonable: Create a deep clone of block data when cloning | (function() {
var _ = window._;
var SirTrevor = window.SirTrevor;
var BlockMixins = SirTrevor.BlockMixins;
var Block = SirTrevor.Block;
Block.prototype.availableMixins.push('clonable');
BlockMixins.Clonable = {
mixinName: 'Clonable',
initializeClonable: function() {
... | (function() {
var SirTrevor = window.SirTrevor;
var BlockMixins = SirTrevor.BlockMixins;
var Block = SirTrevor.Block;
Block.prototype.availableMixins.push('clonable');
BlockMixins.Clonable = {
mixinName: 'Clonable',
initializeClonable: function() {
// For this mixin to ... |
Return cancelers from Aff actions | 'use strict';
var Control_Monad_Aff = require('../Control.Monad.Aff');
var pg = require('pg');
exports.newPool = function(config) {
return function(onSuccess, onError) {
onSuccess(new pg.Pool(config));
return Control_Monad_Aff.nonCanceler;
};
};
exports.withConnection = function(pool) {
r... | 'use strict';
var pg = require('pg');
exports.newPool = function(config) {
return function(onSuccess, onError) {
onSuccess(new pg.Pool(config));
};
};
exports.withConnection = function(pool) {
return function(body) {
return function(onSuccess, onError) {
pool.connect(function(... |
Remove static call to constructor. | <?php
/**
* Created by PhpStorm.
* User: etcinit
* Date: 10/3/15
* Time: 6:57 PM
*/
namespace Chromabits\Illuminated\Http\Factories;
use Chromabits\Illuminated\Http\ApiResponse;
use Chromabits\Illuminated\Http\Interfaces\ApiResponseFactoryInterface;
use Chromabits\Nucleus\Exceptions\LackOfCoffeeException;
use Ch... | <?php
/**
* Created by PhpStorm.
* User: etcinit
* Date: 10/3/15
* Time: 6:57 PM
*/
namespace Chromabits\Illuminated\Http\Factories;
use Chromabits\Illuminated\Http\ApiResponse;
use Chromabits\Illuminated\Http\Interfaces\ApiResponseFactoryInterface;
use Chromabits\Nucleus\Exceptions\LackOfCoffeeException;
use Ch... |
Allow for extra slashes in project paths, such as mq patch queues. |
# Mimic the hggit extension.
try:
from hggit import *
hggit_reposetup = reposetup
except ImportError:
# Allow this module to be imported without
# hg-git installed, eg for setup.py
pass
__version__ = "0.1.0"
def reposetup(ui, repo, **kwargs):
"""
Automatically adds Bitbucket->GitHub mir... |
# Mimic the hggit extension.
try:
from hggit import *
hggit_reposetup = reposetup
except ImportError:
# Allow this module to be imported without
# hg-git installed, eg for setup.py
pass
__version__ = "0.1.0"
def reposetup(ui, repo, **kwargs):
"""
Automatically adds Bitbucket->GitHub mir... |
Mark the module as not zip safe.
The template finder code in Flask doesn't handle zipped eggs well,
and thus won't find index.template.html. This makes the module
crash when attempting to load the UI. | from setuptools import setup
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'flask_swagger_ui/README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='flask-swagger-ui',
... | from setuptools import setup
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'flask_swagger_ui/README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='flask-swagger-ui',
... |
fix: Add key iterator for categories map | /**
* Created by farid on 8/16/2017.
*/
import React, {Component} from "react";
import Category from "./Category";
import {getCategories} from "../actions/Category";
import {connect} from "react-redux";
export class HomePage extends Component {
componentDidMount() {
this.props.getCategories();
}
... | /**
* Created by farid on 8/16/2017.
*/
import React, {Component} from "react";
import Category from "./Category";
import {getCategories} from "../actions/Category";
import {connect} from "react-redux";
export class HomePage extends Component {
componentDidMount() {
this.props.getCategories();
}
... |
Fix unicode issues with new tag | from django.dispatch import Signal, receiver
from django.core.mail import EmailMultiAlternatives
from search.models import Person
import logging
from django.conf import settings
unknown_tag_signal = Signal(providing_args=['author', 'title', 'tags'])
logger = logging.getLogger('search')
@receiver(unknown_tag_signal)
... | from django.dispatch import Signal, receiver
from django.core.mail import EmailMultiAlternatives
from search.models import Person
import logging
from django.conf import settings
unknown_tag_signal = Signal(providing_args=['author', 'title', 'tags'])
logger = logging.getLogger('search')
@receiver(unknown_tag_signal)
... |
Validate that we can translate a NEWOBJECT into a FETCHOBJECT | import os
import select
import groundstation.fs_watcher as fs_watcher
from groundstation.peer_socket import PeerSocket
from groundstation.utils import path2id
from integration_fixture import StationIntegrationFixture, \
TestListener, \
TestClient
class... | import os
import select
import groundstation.fs_watcher as fs_watcher
from groundstation.peer_socket import PeerSocket
from integration_fixture import StationIntegrationFixture, \
TestListener, \
TestClient
class StationFSWatcherIntegration(StationInteg... |
Add 'configuration' node in 'product_attribute' fixture | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\CoreBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use Sylius... | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\CoreBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use Sylius... |
Patch to make work like we expect | import json
import logging
import os
import sys
def json_patch(path):
logging.warn("Attempting to load local settings from %r" % (path,))
try:
d = json.load(open(path))
except IOError:
logging.exception("Unable to open json settings in %r" % (path,))
raise SystemExit(-1)
except... | import json
import logging
import os
import sys
def json_patch(path):
logging.warn("Attempting to load local settings from %r" % (path,))
try:
d = json.load(open(path))
except IOError:
logging.exception("Unable to open json settings in %r" % (path,))
raise SystemExit(-1)
except... |
Configure accept attr in image form type. | <?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\ImageBundle\Form\... | <?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\ImageBundle\Form\... |
Add profile link inside karma render | <?php
namespace App\Middlewares;
use App\Message;
use App\Gitter\Middleware\MiddlewareInterface;
/**
* Проверяет слово "карма" и выводит статус
*
* Class KarmaRenderMiddleware
* @package App\Gitter\Middleware
*/
class KarmaRenderMiddleware implements MiddlewareInterface
{
/**
* @param Message $message
... | <?php
namespace App\Middlewares;
use App\Message;
use App\Gitter\Middleware\MiddlewareInterface;
/**
* Проверяет слово "карма" и выводит статус
*
* Class KarmaRenderMiddleware
* @package App\Gitter\Middleware
*/
class KarmaRenderMiddleware implements MiddlewareInterface
{
/**
* @param Message $message
... |
Fix merging of Laravel .htaccess with h5bp .htaccess | (function(exports) {
"use strict";
var request = require('request');
var Sink = require('pipette').Sink;
var unzipper = require('../process-zip');
var fs = require('fs');
exports.downloadLaravel = function(grunt, init, done) {
unzipper.processZip(request('https://github.com/laravel/laravel/archive/mast... | (function(exports) {
"use strict";
var request = require('request');
var Sink = require('pipette').Sink;
var unzipper = require('../process-zip');
exports.downloadLaravel = function(grunt, init, done) {
unzipper.processZip(request('https://github.com/laravel/laravel/archive/master.zip'), {
fromdir:... |
Add documentation to card import handler | package editor.gui.ccp.handler;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;
import javax.swing.TransferHandler;
import editor.database.card.Card;
import editor.gui.ccp.data.D... | package editor.gui.ccp.handler;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;
import javax.swing.TransferHandler;
import editor.database.card.Card;
import editor.gui.ccp.data.D... |
Use builder to create object. | package com.theaccountant.accountabilityhack.processor;
import com.theaccountant.accountabilityhack.data.SchoolEntry;
import com.theaccountant.accountabilityhack.data.SchoolRegistry;
import java.io.IOException;
public final class FteAantalProcessor implements Processor {
public void process(final SchoolRegistry... | package com.theaccountant.accountabilityhack.processor;
import com.theaccountant.accountabilityhack.data.SchoolEntry;
import com.theaccountant.accountabilityhack.data.SchoolRegistry;
import java.io.IOException;
public final class FteAantalProcessor implements Processor {
public void process(final SchoolRegistry... |
Add UA and matched UA to device-detection view output. | from pywurfl.algorithms import DeviceNotFound
from django.http import Http404
from molly.utils.views import BaseView
from molly.utils.breadcrumbs import NullBreadcrumb
from molly.wurfl.vsm import vsa
from molly.wurfl import device_parents
from molly.wurfl.wurfl_data import devices
class IndexView(BaseView):
bre... | from pywurfl.algorithms import DeviceNotFound
from django.http import Http404
from molly.utils.views import BaseView
from molly.utils.breadcrumbs import NullBreadcrumb
from molly.wurfl.vsm import vsa
from molly.wurfl import device_parents
from molly.wurfl.wurfl_data import devices
class IndexView(BaseView):
bre... |
Return cursor instead of our own cursor | <?php
namespace EasyRepository\t{{$mt=uniqid(true)}};
use PDO;
use EasySQL\Cursor;
@foreach ($files as $query)
class {{$query->getName()}}Repository
{
protected $dbh;
public function __construct(PDO $pdo)
{
$this->dbh = $pdo;
}
@foreach ($query->getMethods() as $name => $method)
pub... | <?php
namespace EasyRepository\t{{$mt=uniqid(true)}};
use PDO;
use EasySQL\Cursor;
@foreach ($files as $query)
class {{$query->getName()}}Repository
{
protected $dbh;
public function __construct(PDO $pdo)
{
$this->dbh = $pdo;
}
@foreach ($query->getMethods() as $name => $method)
pub... |
ui: Enable compile-error dev server overlay, SPA routing | const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
module.exports = {
mode: 'development',
output: {
filename: 'static/[name].js',
publicPath: '/',
},
module: {
rules: [
{
test: /\.elm$/,
exclude: [/elm-stuff/, /node_modules/],
... | const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
module.exports = {
mode: 'development',
output: {
filename: 'static/[name].js',
publicPath: '/',
},
module: {
rules: [
{
test: /\.elm$/,
exclude: [/elm-stuff/, /node_modules/],
... |
Add onExit disconnect of websockets | angular.module('urlShortener', ['ui.router', 'base64', 'ngStomp'])
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
//starter screen
.state('starter', {
url: "/starter",
templateUrl: "templates/starter.html",
co... | angular.module('urlShortener', ['ui.router', 'base64', 'ngStomp'])
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
//starter screen
.state('starter', {
url: "/starter",
templateUrl: "templates/starter.html",
co... |
Throw exceptions error responses from server | import requests
import json
from datetime import datetime
def _json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, datetime):
serial = obj.isoformat()
return serial
class SwisClient:
def __init__(self, hostname, username, password,... | import requests
import json
from datetime import datetime
def _json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, datetime):
serial = obj.isoformat()
return serial
class SwisClient:
def __init__(self, hostname, username, password,... |
Align cfg logo right on larger screens | <footer class="row">
<div class="c-footer col-xs-12 col-md-offset-2 col-md-8">
<div class="row">
<div class="col-xs-6 col-sm-4">
<img
src="{{ asset('img/logos/okf.svg') }}"
alt="Logo der OpenKnowledge Foundation Deutschland" height=... | <footer class="row">
<div class="c-footer col-xs-12 col-md-offset-2 col-md-8">
<div class="row">
<div class="col-xs-6 col-sm-4">
<img
src="{{ asset('img/logos/okf.svg') }}"
alt="Logo der OpenKnowledge Foundation Deutschland" height=... |
Fix count param, use local es for now | import json
import requests
from elasticsearch_dsl import Search
from elasticsearch_dsl.result import Response
class ShareSearch(Search):
BASE_URL = 'http://localhost:8000/api/search/abstractcreativework/_search'
HEADERS = {'content-type': 'application/json'}
PARAMS = dict(raw=True)
def execute(self... | import json
import requests
from elasticsearch_dsl import Search
from elasticsearch_dsl.result import Response
class ShareSearch(Search):
BASE_URL = 'https://osf.io/api/v1/share/search/'
HEADERS = {'content-type': 'application/json'}
PARAMS = dict(raw=True)
def execute(self):
return Response... |
Change celery and kombu requirements to match ckanext-datastorer | from setuptools import setup, find_packages
setup(
name='ckanext-archiver',
version='0.1',
packages=find_packages(),
install_requires=[
'celery==2.4.2',
'kombu==2.1.3',
'kombu-sqlalchemy==1.1.0',
'SQLAlchemy>=0.6.6',
'requests==0.6.4',
'messytables>=0.1.4... | from setuptools import setup, find_packages
setup(
name='ckanext-archiver',
version='0.1',
packages=find_packages(),
install_requires=[
'celery==2.4.5',
'kombu==1.5.1',
'kombu-sqlalchemy==1.1.0',
'SQLAlchemy>=0.6.6',
'requests==0.6.4',
'messytables>=0.1.4... |
Remove default value and cast always to array the options | <?php
namespace Avanzu\AdminThemeBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://s... | <?php
namespace Avanzu\AdminThemeBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://s... |
Fix bug where a validator chain was called as a promise instead of a function | import _ from 'lodash';
import BPromise from 'bluebird';
import { resolve } from '../utils';
export function parallel(...validators) {
return function(context) {
return BPromise.all(_.map(validators, (validator) => validator(context)));
};
}
export function series(...validators) {
return function(context) {... | import _ from 'lodash';
import BPromise from 'bluebird';
export function parallel(...validators) {
return function(context) {
return BPromise.all(_.map(validators, (validator) => validator(context)));
};
}
export function series(...validators) {
return function(context) {
return BPromise.mapSeries(valid... |
Send rest of request params | <?php
use PHPUnit\Framework\TestCase;
class DelegatedAuthorizationsTest extends TestCase
{
public function testDelegatedAuthorizations()
{
$profileId = "profileId";
$email = "emailOfAccountToAccess";
$callback_url = "http://www.example.com/callback";
$scopes = ["read_events"];
... | <?php
use PHPUnit\Framework\TestCase;
class DelegatedAuthorizationsTest extends TestCase
{
public function testDelegatedAuthorizations()
{
$profileId = "profileId";
$args = array(
"profile_id" => $profileId,
);
$http = $this->createMock('HttpRequest');
$htt... |
Remove obsolete object from scope | 'use strict';
angular.module('com.module.sandbox')
.controller('SandboxFormsCtrl', function ($scope, CoreService) {
var now = new Date();
$scope.formOptions = {};
$scope.formData = {
name: null,
description: null,
startDate: now,
startTime: now,
endDate: now,
endTime... | 'use strict';
angular.module('com.module.sandbox')
.controller('SandboxFormsCtrl', function ($scope, CoreService) {
var now = new Date();
$scope.formOptions = {};
$scope.formData = {
name: null,
description: null,
startDate: now,
startTime: now,
endDate: now,
endTime... |
Add image when path is set, not only when SplInfo is present | <?php
declare(strict_types=1);
namespace SitemapPlugin\Generator;
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
use SitemapPlugin\Factory\SitemapImageUrlFactoryInterface;
use Sylius\Component\Core\Model\ProductImageInterface;
use Sylius\Component\Core\Model\ProductInterface;
final class ProductToImageSitemapAr... | <?php
declare(strict_types=1);
namespace SitemapPlugin\Generator;
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
use SitemapPlugin\Factory\SitemapImageUrlFactoryInterface;
use Sylius\Component\Core\Model\ProductImageInterface;
use Sylius\Component\Core\Model\ProductInterface;
final class ProductToImageSitemapAr... |
Resolve style errors on input block | module.exports = {
className: 'input-block',
template: require('./index.html'),
lazy: false,
data: {
name: 'Input',
icon: '/images/blocks_input.png',
attributes: {
inputType: {
label: 'Input Type',
type: 'dropdownChoice',
... | module.exports = {
className: 'input-block',
template: require('./index.html'),
lazy: false,
data: {
name: 'Input',
icon: '/images/blocks_input.png',
attributes: {
inputType: {
label: 'Input Type',
type: 'dropdownChoice',
... |
Make plugin loader more robust | class PluginLoader:
def load(self, directory):
ret = []
for plugin in directory.children:
plugin_file = plugin.find(name=plugin.name, type='py')
if not plugin_file:
continue
plugin_class = plugin_file.classes[plugin.name]
... | class PluginLoader:
def load(self, directory):
ret = []
for plugin in directory.children:
plugin_file = plugin.find(name=plugin.name, type='py')
plugin_class = plugin_file.classes[plugin.name]
self._check_attributes(plugin_class)
plugin_instance = ... |
Comment on alterative of using rectangle as bounding box. | /**
* Copyright (c) 2013 Marshall Farrier
* http://www.opensource.org/licenses/mit-license.php
*
* Handles image drawing for use in sprites
*
* Dependencies:
* extend.js
* point.js
*/
var _c = _c || {};
(function(_c) {
'use strict';
_c.draw = _c.draw || {};
_c.draw.Image = _c.Base.extend({
... | /**
* Copyright (c) 2013 Marshall Farrier
* http://www.opensource.org/licenses/mit-license.php
*
* Handles image drawing for use in sprites
*
* Dependencies:
* extend.js
* point.js
*/
var _c = _c || {};
(function(_c) {
'use strict';
_c.draw = _c.draw || {};
_c.draw.Image = _c.Base.extend({
... |
Fix typo startContanier should be startContainer. | define([], function() {
var saveSelection, restoreSelection;
if (window.getSelection && document.createRange) {
saveSelection = function(el) {
var sel = window.getSelection && window.getSelection();
if (sel && sel.rangeCount > 0) {
return sel.getRangeAt(0);
... | define([], function() {
var saveSelection, restoreSelection;
if (window.getSelection && document.createRange) {
saveSelection = function(el) {
var sel = window.getSelection && window.getSelection();
if (sel && sel.rangeCount > 0) {
return sel.getRangeAt(0);
... |
Add minimum version for pycryptodome | from setuptools import setup
setup(
name='scuevals-api',
packages=['scuevals_api'],
include_package_data=True,
test_suite='tests',
entry_points={
'console_scripts': [
'app=scuevals_api.cmd:cli'
]
},
install_requires=[
'alembic==0.9.7',
'beautifuls... | from setuptools import setup
setup(
name='scuevals-api',
packages=['scuevals_api'],
include_package_data=True,
test_suite='tests',
entry_points={
'console_scripts': [
'app=scuevals_api.cmd:cli'
]
},
install_requires=[
'alembic==0.9.7',
'beautifuls... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.