text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Update so order by links are escaped
@include('rapyd::toolbar', array('label'=>$label, 'buttons_right'=>$buttons['TR'])) <table{!! $dg->buildAttributes() !!}> <thead> <tr> @foreach ($dg->columns as $column) <th{!! $column->buildAttributes() !!}> @if ($column->orderby) @if ($dg->onOrderby($column->or...
@include('rapyd::toolbar', array('label'=>$label, 'buttons_right'=>$buttons['TR'])) <table{!! $dg->buildAttributes() !!}> <thead> <tr> @foreach ($dg->columns as $column) <th{!! $column->buildAttributes() !!}> @if ($column->orderby) @if ($dg->onOrderby($column->or...
Add keys to query list
var React = require('react'); var actions = require('../actions'); var { Navigation } = require('react-router'); var QueryStore = require('../stores/query_store.js'); var QueryList = React.createClass({ mixins: [QueryStore.listenTo, Navigation], getInitialState() { return { queries: [] }; }, _o...
var React = require('react'); var actions = require('../actions'); var { Navigation } = require('react-router'); var QueryStore = require('../stores/query_store.js'); var QueryList = React.createClass({ mixins: [QueryStore.listenTo, Navigation], getInitialState() { return { queries: [] }; }, _o...
Add docstrings to Gist integration tests @esacteksab would be so proud
# -*- coding: utf-8 -*- """Integration tests for methods implemented on Gist.""" from .helper import IntegrationHelper import github3 class TestGist(IntegrationHelper): """Gist integration tests.""" def test_comments(self): """Show that a user can iterate over the comments on a gist.""" cas...
from .helper import IntegrationHelper import github3 class TestGist(IntegrationHelper): def test_comments(self): """Show that a user can iterate over the comments on a gist.""" cassette_name = self.cassette_name('comments') with self.recorder.use_cassette(cassette_name): gist ...
Use window.localStorage in all cases
/* global chrome, confirm */ var utils = require('./utils'); function StorageHandler (updateFiles) { this.sync = function () { if (typeof chrome === 'undefined' || !chrome || !chrome.storage || !chrome.storage.sync) { return; } var obj = {}; var done = false; var count = 0; function ...
/* global chrome, confirm, localStorage */ var utils = require('./utils'); function StorageHandler (updateFiles) { this.sync = function () { if (typeof chrome === 'undefined' || !chrome || !chrome.storage || !chrome.storage.sync) { return; } var obj = {}; var done = false; var count = 0; ...
Set h1 to null if no headings are present
package bamboo.task; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import java.util.regex.Pattern; public class HeadingContentHandler extends DefaultHandler { private static Pattern WHITESPACE_RE = Pattern.compile("\\s+"); private StringBuilder tex...
package bamboo.task; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import java.util.regex.Pattern; public class HeadingContentHandler extends DefaultHandler { private static Pattern WHITESPACE_RE = Pattern.compile("\\s+"); private StringBuilder tex...
Change user name to something more practical. Signed-off-by: Se7enChat <e5dc7202134ade0d04c45466a5972470210b05f6@zoho.com>
<?php namespace Se7enChat\Libraries\Web\Presenters; use Se7enChat\Boundaries\IndexOutputPort; use Se7enChat\Gateways\UserInterfaceGateway; class IndexPresenter implements IndexOutputPort { private $userInterface; private $lessUrl; private $cssUrl; public function __construct(UserInterfaceGateway $ui) ...
<?php namespace Se7enChat\Libraries\Web\Presenters; use Se7enChat\Boundaries\IndexOutputPort; use Se7enChat\Gateways\UserInterfaceGateway; class IndexPresenter implements IndexOutputPort { private $userInterface; private $lessUrl; private $cssUrl; public function __construct(UserInterfaceGateway $ui) ...
Add bump:major task to Grunt
"use strict"; module.exports = function (grunt) { grunt.initConfig({ bump: { options: { files: ["package.json"], commit: true, commitMessage: "Release %VERSION%", commitFiles: ["package.json"], createTag: true, ...
"use strict"; module.exports = function (grunt) { grunt.initConfig({ bump: { options: { files: ["package.json"], commit: true, commitMessage: "Release %VERSION%", commitFiles: ["package.json"], createTag: true, ...
Implement correct derivation of SoftMax
import numpy as np class Activator: @staticmethod def sigmoid(signal, deriv=False): if deriv: return np.multiply(signal, 1 - signal) activation = 1 / (1 + np.exp(-signal)) return activation @staticmethod def tanh(signal, deriv=False): if deriv: ...
import numpy as np class Activator: @staticmethod def sigmoid(signal, deriv=False): if deriv: return np.multiply(signal, 1 - signal) activation = 1 / (1 + np.exp(-signal)) return activation @staticmethod def tanh(signal, deriv=False): if deriv: ...
Add retry and failure detection to callback.execute
#! /usr/bin/python import json import requests from ufyr.decorators import retry class Callback(object): def __init__(self, url, method='GET', req_kwargs={}, **kwargs): assert isinstance(url, (str, unicode)) assert isinstance(method, (str, unicode)) assert isinstance(req_kwargs,...
#! /usr/bin/python import json import requests class Callback(object): def __init__(self, url, method='GET', req_kwargs={}, **kwargs): assert isinstance(url, (str, unicode)) assert isinstance(method, (str, unicode)) assert isinstance(req_kwargs, dict) se...
Remove leftover print call in paginator
""".. Ignore pydocstyle D400. ================== Elastic Paginators ================== Paginator classes used in Elastic app. .. autoclass:: resolwe.elastic.pagination.LimitOffsetPostPagination """ from __future__ import absolute_import, division, print_function, unicode_literals from rest_framework.pagination im...
""".. Ignore pydocstyle D400. ================== Elastic Paginators ================== Paginator classes used in Elastic app. .. autoclass:: resolwe.elastic.pagination.LimitOffsetPostPagination """ from __future__ import absolute_import, division, print_function, unicode_literals from rest_framework.pagination im...
Disable exception logging of status code 500 during testing.
# -*- coding: utf-8 -*- """ This module sets up the view for handling ``500 Internal Server Error`` errors. """ import datetime import flask import flask_classful from orchard.errors import blueprint class Error500View(flask_classful.FlaskView): """ View for ``500 Internal Server Error`` errors. ...
# -*- coding: utf-8 -*- """ This module sets up the view for handling ``500 Internal Server Error`` errors. """ import datetime import flask import flask_classful from orchard.errors import blueprint class Error500View(flask_classful.FlaskView): """ View for ``500 Internal Server Error`` errors. ...
Change directory of tempest config
import json import logging import os import requests from jinja2 import Template from os.path import abspath, dirname, exists, join from .utils import run_cmd LOG = logging.getLogger(__name__) class Framework(object): def __init__(self, environment): self.admin = environment.admin self.guests ...
import json import logging import os import requests from jinja2 import Template from os.path import abspath, dirname, exists, join from .utils import run_cmd LOG = logging.getLogger(__name__) class Framework(object): def __init__(self, environment): self.admin = environment.admin self.guests ...
Update Python version classifiers to supported versions
#!/usr/bin/env python # -*- coding: utf-8 -*- import xml4h try: from setuptools import setup except ImportError: from distutils.core import setup setup( name=xml4h.__title__, version=xml4h.__version__, description='XML for Humans in Python', long_description=open('README.rst').read(), aut...
#!/usr/bin/env python # -*- coding: utf-8 -*- import xml4h try: from setuptools import setup except ImportError: from distutils.core import setup setup( name=xml4h.__title__, version=xml4h.__version__, description='XML for Humans in Python', long_description=open('README.rst').read(), aut...
Add method to get protocol list
package controller; import constant.Urls; import domain.Protocol; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import repository.ProtocolRepository; import ...
package controller; import constant.Urls; import domain.Protocol; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import repository.ProtocolRepository; import ...
Use prepublish.js to compile in grunt
'use strict'; module.exports = function(grunt) { var growl = require('growl'); var path = require('path'); var shell = require('shelljs'); var bin = ['node_modules', '.bin'].join(path.sep); var lsc = [bin, 'lsc'].join(path.sep); var npm = 'npm'; grunt.registerTask('livescript_src', 'upda...
'use strict'; module.exports = function(grunt) { var growl = require('growl'); var path = require('path'); var shell = require('shelljs'); var bin = ['node_modules', '.bin'].join(path.sep); var lsc = [bin, 'lsc'].join(path.sep); var npm = 'npm'; grunt.registerTask('livescript_src', 'upda...
Fix bug where images could not be created
/** * Image.js * * @description :: This represents a product image with file paths for different variations (original, thumb, ...). * @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models */ module.exports = { attributes: { width: { type: 'integer', min: 0 }, ...
/** * Image.js * * @description :: This represents a product image with file paths for different variations (original, thumb, ...). * @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models */ module.exports = { attributes: { width: { type: 'integer', min: 0 }, ...
Add method to log error without throwable Add Ln.e(message) in addition to Ln.e(message, error).
package com.genymobile.scrcpy; import android.util.Log; /** * Log both to Android logger (so that logs are visible in "adb logcat") and standard output/error (so that they are visible in the terminal * directly). */ public final class Ln { private static final String TAG = "scrcpy"; enum Level { ...
package com.genymobile.scrcpy; import android.util.Log; /** * Log both to Android logger (so that logs are visible in "adb logcat") and standard output/error (so that they are visible in the terminal * directly). */ public final class Ln { private static final String TAG = "scrcpy"; enum Level { ...
Update path fonts gulp task
var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var uglify = require('gulp-uglify'); var buffer = require('vinyl-buffer'); // build src gulp.task('browserify', function(cb){ return browserify('./src/app.js', { debug: true ...
var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var uglify = require('gulp-uglify'); var buffer = require('vinyl-buffer'); // build src gulp.task('browserify', function(cb){ return browserify('./src/app.js', { debug: true ...
Move mouse events to thumbnail
import React, { PropTypes } from 'react'; import '../../css/SearchGifView.css' class SearchGifView extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.handleMouseOver = this.handleMouseOver.bind(this); this.handleMou...
import React, { PropTypes } from 'react'; import '../../css/SearchGifView.css' class SearchGifView extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.handleMouseOver = this.handleMouseOver.bind(this); this.handleMou...
Use host instead of hostname Former-commit-id: 40b779195685a054d6247559f4f3fed5ac39d985 Former-commit-id: 426cf513caae3bca89af65bfdcfe1e5751b917d1 Former-commit-id: 8577ea950f5083c9f65a589b2ac1bacb1646f749
/** * Created by crispin on 10/12/2015. */ function loadEmbedIframe(onSave) { // add modal window $('.workspace-menu').append(templates.embedIframe()); // variables var modal = $(".modal"); // modal functions function closeModal() { modal.remove(); } function saveUrl() { ...
/** * Created by crispin on 10/12/2015. */ function loadEmbedIframe(onSave) { // add modal window $('.workspace-menu').append(templates.embedIframe()); // variables var modal = $(".modal"); // modal functions function closeModal() { modal.remove(); } function saveUrl() { ...
Append the event name in case of server methods too
// Dependencies var ParseMethod = require("./method") , Enny = require("enny") , Ul = require("ul") , Typpy = require("typpy") ; module.exports = function (_input, instName) { var input = Ul.clone(_input); if (Typpy(input, String)) { input = [input]; } var output = {} , eP = nul...
// Dependencies var ParseMethod = require("./method") , Enny = require("enny") , Ul = require("ul") , Typpy = require("typpy") ; module.exports = function (_input, instName) { var input = Ul.clone(_input); if (Typpy(input, String)) { input = [input]; } var output = {} , eP = nul...
Revert to puppeteer (keeping chromium install for dependencies)
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html process.env.CHROME_BIN = require('puppeteer').executablePath() module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular/cli'], plugins:...
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html process.env.CHROME_BIN = require('puppeteer').executablePath() module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular/cli'], plugins:...
Handle request error: controller backupDatabase, restoreDatabase
angular.module('myapp') .controller('HomeController', ['$scope', '$timeout', 'SnapshotServices', function ($scope, $timeout, SnapshotServices) { $scope.listSnapshot = []; $scope.currentSnapshot = ""; $scope.getSnapshots = function () { SnapshotServices.getSnapshots().then(functi...
angular.module('myapp') .controller('HomeController', ['$scope', '$timeout', 'SnapshotServices', function ($scope, $timeout, SnapshotServices) { $scope.listSnapshot = []; $scope.currentSnapshot = ""; $scope.getSnapshots = function () { SnapshotServices.getSnapshots().then(functi...
Return Pubmed title and abstract
#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubm...
#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubm...
Use list comprehensions to format all errors where message is not a dict
from rest_framework import status from rest_framework.exceptions import APIException, ParseError 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_fr...
from rest_framework import status from rest_framework.exceptions import APIException, ParseError 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_fr...
Move from deprecated HttpKernel's to Debug's FlattenException.
<?php /** * Copyright 2014 SURFnet bv * * 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 agr...
<?php /** * Copyright 2014 SURFnet bv * * 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 agr...
FIX method POST on login_check
<?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class SecurityController extends Controller { /** * @param Request $request * @return \Symfony\Compone...
<?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class SecurityController extends Controller { /** * @param Request $request * @return \Symfony\Compone...
Rewrite get() to be less repetitive but still stupid
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from time import sleep class APIQuerier: def __init__ (self, uri, url_opener, sleep_time=300, max_tries=0): self.uri = uri ...
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from time import sleep class APIQuerier: def __init__ (self, uri, url_opener, sleep_time=300, max_tries=0): self.uri = uri ...
Add LegalRepresentativeProofOfIdentity to legal user
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.entities.user import User from mangopaysdk.tools.enums import PersonType from mangopaysdk.tools.enums import KYCLevel class UserLegal (User): def __init__(self, id = None): super(UserLegal, self).__init__(id) self._setPersonT...
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.entities.user import User from mangopaysdk.tools.enums import PersonType from mangopaysdk.tools.enums import KYCLevel class UserLegal (User): def __init__(self, id = None): super(UserLegal, self).__init__(id) self._setPersonT...
Update community to use new lib namespace
import sys from lib.core import Tokenizer from lib.utilities import url_to_json def run(project_id, repo_path, cursor, **options): t_sub = options.get('sub') t_star = options.get('star') t_forks = options.get('forks') cursor.execute(''' SELECT url FROM project...
import sys from core import Tokenizer from utilities import url_to_json def run(project_id, repo_path, cursor, **options): t_sub = options.get('sub') t_star = options.get('star') t_forks = options.get('forks') cursor.execute(''' SELECT url FROM projects ...
Use compatible release versions for all dependencies
import os from setuptools import setup, find_packages import glob VERSION = "0.6.3" src_dir = os.path.dirname(__file__) install_requires = [ "troposphere~=1.8.0", "boto3~=1.3.1", "botocore~=1.4.38", "PyYAML~=3.11", "awacs~=0.6.0", "colorama~=0.3.7", ] tests_require = [ "nose~=1.0", "...
import os from setuptools import setup, find_packages import glob VERSION = "0.6.3" src_dir = os.path.dirname(__file__) install_requires = [ "troposphere>=1.8.0", "boto3>=1.3.1", "botocore>=1.4.38", "PyYAML>=3.11", "awacs>=0.6.0", "colorama==0.3.7", ] tests_require = [ "nose>=1.0", "...
Update pagesavehook for new fields
<?php namespace Tev\Tev\Hook; use Tev\Tev\Url\Cache; /** * Hook for saving pages. */ class PageSaveHook { /** * After a page is saved, check if it is new or if its RealURL config has * been changed. * * If it has, clear the RealURL config cache. * * @param string ...
<?php namespace Tev\Tev\Hook; use Tev\Tev\Url\Cache; /** * Hook for saving pages. */ class PageSaveHook { /** * After a page is saved, check if it is new or if its RealURL config has * been changed. * * If it has, clear the RealURL config cache. * * @param string ...
Modify filter to show new computational sample templates.
class MCWorkflowProcessTemplatesComponentController { /*@ngInit*/ constructor(templates) { this.templates = templates.get(); this.templateTypes = [ { title: 'CREATE SAMPLES', cssClass: 'mc-create-samples-color', icon: 'fa-cubes', ...
class MCWorkflowProcessTemplatesComponentController { /*@ngInit*/ constructor(templates) { this.templates = templates.get(); this.templateTypes = [ { title: 'CREATE SAMPLES', cssClass: 'mc-create-samples-color', icon: 'fa-cubes', ...
Add methods to linked list.
class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): return '{val}'.format(val=self.val) class LinkedList(object): def __init__(self, iterable=()): self._current = None self.head = None self.length = 0 ...
class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): return '{val}'.format(val=self.val) class LinkedList(object): def __init__(self, iterable=()): self._current = None self.head = None self.length = 0 ...
Use substrings rather than prefixes
chrome.extension.sendMessage({}, function(response) { var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); var colorMapping = { 'blocked': 'rgb(199, 37, 67)', 'needs ': 'rgb(199, 37, 67)' }; ...
chrome.extension.sendMessage({}, function(response) { var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); var colorMapping = { 'blocked': 'rgb(199, 37, 67)', 'needs ': 'rgb(199, 37, 67)' }; ...
Update test to ignore refund-payments for admins
<?php declare(strict_types=1); namespace Tests\Feature; use Spatie\Permission\Models\Permission; use Spatie\Permission\Models\Role; use Tests\TestCase; class PermissionsAndRolesTest extends TestCase { public function testPermissionsLoadedInDatabase(): void { $allPermissions = Permission::all(); ...
<?php declare(strict_types=1); namespace Tests\Feature; use Spatie\Permission\Models\Permission; use Spatie\Permission\Models\Role; use Tests\TestCase; class PermissionsAndRolesTest extends TestCase { public function testPermissionsLoadedInDatabase(): void { $allPermissions = Permission::all(); ...
Change global to node compatible
const path = require('path'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); const WebpackAutoInject = require('webpack-auto-inject-version'); module.exports = { entry: { 'typedjson': './src/typedjson.ts', 'typedjson.min': './src/typedjson.ts', }, devtool: 'source-map', module: { rules:...
const path = require('path'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); const WebpackAutoInject = require('webpack-auto-inject-version'); module.exports = { entry: { 'typedjson': './src/typedjson.ts', 'typedjson.min': './src/typedjson.ts', }, devtool: 'source-map', module: { rules:...
Fix `protocol not supported` on Windows
import sys import zmq from crankycoin import config, logger WIN32 = 'win32' in sys.platform class Queue(object): QUEUE_BIND_IN = config['user']['queue_bind_in'] if not WIN32 else config['user']['win_queue_bind_in'] QUEUE_BIND_OUT = config['user']['queue_bind_out'] if not WIN32 else config['user']['win_queue_...
import zmq from crankycoin import config, logger class Queue(object): QUEUE_BIND_IN = config['user']['queue_bind_in'] QUEUE_BIND_OUT = config['user']['queue_bind_out'] QUEUE_PROCESSING_WORKERS = config['user']['queue_processing_workers'] @classmethod def start_queue(cls): try: ...
Update schema to handle null and default for datatime
<?php namespace Bolt\Extension\Bolt\Members\Storage\Schema\Table; use Bolt\Storage\Database\Schema\Table\BaseTable; /** * Account table. * * @author Gawain Lynch <gawain.lynch@gmail.com> */ class Account extends BaseTable { /** * @inheritDoc */ protected function addColumns() { $thi...
<?php namespace Bolt\Extension\Bolt\Members\Storage\Schema\Table; use Bolt\Storage\Database\Schema\Table\BaseTable; /** * Account table. * * @author Gawain Lynch <gawain.lynch@gmail.com> */ class Account extends BaseTable { /** * @inheritDoc */ protected function addColumns() { $thi...
Add timezone to programme date format
<?php namespace XmlTv\Tv; class Programme { const DATE_FORMAT = 'YmdHis O'; /** * @var string */ public $start; /** * @var string */ public $stop; /** * @var string */ public $channel; /** * @var string */ public $title; /** * @...
<?php namespace XmlTv\Tv; class Programme { const DATE_FORMAT = 'YmdHis'; /** * @var string */ public $start; /** * @var string */ public $stop; /** * @var string */ public $channel; /** * @var string */ public $title; /** * @va...
Load language from cookie if exist
<?php namespace ContentTranslator; class Switcher { public static $cookieKey = 'wp_content_translator_language'; public static $currentLanguage; public function __construct() { if ($lang = $this->getRequestedLang()) { $this->switchToLanguage($lang); } } public fun...
<?php namespace ContentTranslator; class Switcher { public static $currentLanguage; public function __construct() { if (isset($_GET['lang']) && !empty($_GET['lang'])) { $this->switchToLanguage($_GET['lang']); } } /** * Switches language and sets user cookie ...
Fix to can receive notification by Hook
(function(){ var onMessageCreated = function(session, store) { return function(data) { store.find('message', data.message.id).then(function(message) { var room = message.get('room'), title = message.get('senderName') + ' > ' + room.get('organization.slug') + ' / ' + room.get('name'); ...
(function(){ var onMessageCreated = function(session, store) { return function(data) { store.find('message', data.message.id).then(function(message) { var room = message.get('room'), title = message.get('senderName') + ' > ' + room.get('organization.slug') + ' / ' + room.get('name'); ...
Make tree builder with root node (fix deprecation) Make tree builder with root node (fix deprecation in symfony 4.2) and maintain backwards compatibility
<?php namespace Corley\MaintenanceBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder() { if (method_exists...
<?php namespace Corley\MaintenanceBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder() { $treeBuilder = new...
Use $eval to maintain state
<?php #YOLO namespace yolo; function yolisp($swag, array $env = []) { if (!is_array($swag)) { if (isset($env[$swag])) { return $env[$swag]; } else if (function_exists($swag)) { return $swag; } else { throw new \Exception("Could not find $swag in environm...
<?php #YOLO namespace yolo; function yolisp($swag, array $env = []) { if (!is_array($swag)) { if (isset($env[$swag])) { return $env[$swag]; } else if (function_exists($swag)) { return $swag; } else { throw new \Exception("Could not find $swag in environm...
Return unicode from the server Fixes #18
import os import aiohttp import json from aiohttp import web from .consts import KUDAGO_API_BASE_URL, CLIENT_DIR async def serve_api(request): url = '{}/{}/?{}'.format( KUDAGO_API_BASE_URL, request.match_info['path'], request.query_string, ) response = await aiohttp.get(url) b...
import os import aiohttp import json from aiohttp import web from .consts import KUDAGO_API_BASE_URL, CLIENT_DIR async def serve_api(request): url = '{}/{}/?{}'.format( KUDAGO_API_BASE_URL, request.match_info['path'], request.query_string, ) response = await aiohttp.get(url) b...
Add aiohttpClient plus example usage Closes #20
"""setup.py""" from codecs import open as codecs_open from setuptools import setup with codecs_open('README.rst', 'r', 'utf-8') as f: __README = f.read() with codecs_open('HISTORY.rst', 'r', 'utf-8') as f: __HISTORY = f.read() setup( name='jsonrpcclient', version='2.2.4', description='Send JSON-R...
"""setup.py""" from codecs import open as codecs_open from setuptools import setup with codecs_open('README.rst', 'r', 'utf-8') as f: __README = f.read() with codecs_open('HISTORY.rst', 'r', 'utf-8') as f: __HISTORY = f.read() setup( name='jsonrpcclient', version='2.2.4', description='Send JSON-R...
Increase blog slug max length
from datetime import datetime from django import forms from django.utils.translation import ugettext_lazy as _ from pinax.apps.blog.models import Post class BlogForm(forms.ModelForm): slug = forms.SlugField( max_length = 40, help_text = _("a short version of the title consisting only of le...
from datetime import datetime from django import forms from django.utils.translation import ugettext_lazy as _ from pinax.apps.blog.models import Post class BlogForm(forms.ModelForm): slug = forms.SlugField( max_length = 20, help_text = _("a short version of the title consisting only of le...
Correct the name of the spider
# -*- coding: utf-8 -*- import scrapy import json from locations.items import GeojsonPointItem class SuperAmericaSpider(scrapy.Spider): name = "speedway" allowed_domains = ["www.speedway.com"] start_urls = ( 'https://www.speedway.com/GasPriceSearch', ) def parse(self, response): ...
# -*- coding: utf-8 -*- import scrapy import json from locations.items import GeojsonPointItem class SuperAmericaSpider(scrapy.Spider): name = "superamerica" allowed_domains = ["superamerica.com"] start_urls = ( 'https://www.speedway.com/GasPriceSearch', ) def parse(self, response): ...
Set BroadCastConfig width and height to Integers, and check for null values; return -1 if null. This allows us to avoid the problem of ints defaulting to 0 which messes up the default settings for screen width/height
package io.cine.android; import android.util.Log; /** * Created by thomas on 1/16/15. */ public class BroadcastConfig { private Integer width; private Integer height; private String requestedCamera; private String lockedOrientation; public int getWidth() { if (width == null){ ...
package io.cine.android; import android.util.Log; /** * Created by thomas on 1/16/15. */ public class BroadcastConfig { private int width; private int height; private String requestedCamera; private String lockedOrientation; public int getWidth() { return width; } public void ...
Stop rendering after delay on first slide
/*global shower*/ // Start the app require( ['detector', 'app', 'container', 'renderer'], function ( Detector, app, container, renderer ) { if ( ! Detector.webgl ) { Detector.addGetWebGLMessage(); container.innerHTML = ""; } app.init(); app.draw(); var lastSlideNumber = -1; var rendering = false; ...
/*global shower*/ // Start the app require( ['detector', 'app', 'container', 'renderer'], function ( Detector, app, container, renderer ) { if ( ! Detector.webgl ) { Detector.addGetWebGLMessage(); container.innerHTML = ""; } app.init(); app.draw(); var lastSlideNumber = -1; var rendering = false; ...
Add else to search listener function in Search Service for readability.
'use strict'; module.exports = function(app) { app.factory('SearchService', ['$rootScope', function($rs) { let searchResults = []; let searchListener = function(prop, searchArray, $input) { let inputStr; let matchFound = false; let matchExists = false; let objIndex; $input.on...
'use strict'; module.exports = function(app) { app.factory('SearchService', ['$rootScope', function($rs) { let searchResults = []; let searchListener = function(prop, searchArray, $input) { let inputStr; let matchFound = false; let matchExists = false; let objIndex; $input.on...
Fix for crazy routes issue
<?php namespace Chula\ControllerProvider; use Silex\Application; use Silex\ControllerProviderInterface; use \Michelf\Markdown; use Chula\Tools\Encryption; class HomePage implements ControllerProviderInterface { public function connect(Application $app) { $controllers = $app['controllers_factory']; ...
<?php namespace Chula\ControllerProvider; use Silex\Application; use Silex\ControllerProviderInterface; use \Michelf\Markdown; use Chula\Tools\Encryption; class HomePage implements ControllerProviderInterface { public function connect(Application $app) { $controllers = $app['controllers_factory']; ...
Fix deleting S3 files after they are uploaded
(function(Rubeus) { Rubeus.cfg.s3 = { uploadMethod: 'PUT', uploadUrl: null, uploadAdded: function(file, item) { var self = this; var parent = self.getByID(item.parentID); var name = file.name; // Make it possible to upload into subfolders ...
(function(Rubeus) { Rubeus.cfg.s3 = { uploadMethod: 'PUT', uploadUrl: null, uploadAdded: function(file, item) { var self = this; var parent = self.getByID(item.parentID); var name = file.name; // Make it possible to upload into subfolders ...
Return data as list if field is unset
import os import urllib2 import json import sys from urlparse import urljoin from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase class LookupModule(LookupBase): def run(self, terms, variables, **kwargs): key = terms[0] try: field = terms[1] e...
import os import urllib2 import json import sys from urlparse import urljoin from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase class LookupModule(LookupBase): def run(self, terms, variables, **kwargs): key = terms[0] try: field = terms[1] e...
Complete the data print interface.
#!/usr/bin/env python # -*- coding: utf-8 -* # # @author XU Kai(xukai.ken@gmail.com) # @date 2016-12-04 星期日 # # # #fileOverview 树莓派串口操作事件,用来输入和输出陀螺仪数据信息 # # # import os import sys import math import codecs import serial sensor = serial.Serial(port='/dev/ttyAMA0', baudrate='9600', timeout=1) def convert(hexVal): ...
#!/usr/bin/env python # -*- coding: utf-8 -* # # @author XU Kai(xukai.ken@gmail.com) # @date 2016-12-04 星期日 # # # #fileOverview 树莓派串口操作事件,用来输入和输出陀螺仪数据信息 # # # import os import sys import math import codecs import serial sensor = serial.Serial(port='/dev/ttyAMA0', baudrate='9600', timeout=1) def convert(hexVal): ...
Add parsing of simple key-value query params (sort, filter, etc.)
import Ember from 'ember'; export default Ember.Mixin.create({ /** Parse the links in the JSONAPI response and convert to a meta-object */ normalizeQueryResponse(store, clazz, payload) { const result = this._super(...arguments); result.meta = result.meta || {}; if (payload.links) { resu...
import Ember from 'ember'; export default Ember.Mixin.create({ /** Parse the links in the JSONAPI response and convert to a meta-object */ normalizeQueryResponse(store, clazz, payload) { const result = this._super(...arguments); result.meta = result.meta || {}; if (payload.links) { re...
Fix mconsole options array values
<?php namespace Milax\Mconsole\Models; use Illuminate\Database\Eloquent\Model; class MconsoleOption extends Model { use \Cacheable; protected $fillable = ['group', 'label', 'key', 'value', 'type', 'options', 'enabled', 'rules']; protected $casts = [ 'options' => 'array', 'rules'...
<?php namespace Milax\Mconsole\Models; use Illuminate\Database\Eloquent\Model; class MconsoleOption extends Model { use \Cacheable; protected $fillable = ['group', 'label', 'key', 'value', 'type', 'options', 'enabled', 'rules']; protected $casts = [ 'options' => 'array', 'rules'...
Add index assertion during segment exit and fix segment cleanup logic
class StackFrame(object): def __init__(self, instance): self.instance = instance self.data = {} self.idx = 0 self.return_value = None def __setitem__(self, key, value): print('\tSET<{}> {}: {}'.format(self.idx, key, value)) self.data[key] = (self.idx, value) ...
class StackFrame(object): def __init__(self, instance): self.instance = instance self.data = {} self.idx = 0 self.return_value = None def __setitem__(self, key, value): print('\tSET<{}> {}: {}'.format(self.idx, key, value)) self.data[key] = (self.idx, value) ...
Save message before send sms has been added
const Factories = use('core/factories'); const Config = use('config'); const NotificationSmsFactory = Factories('NotificationSms'); class NotificationSms { constructor() { this.provider = require(`./providers/${Config.smsGate.providers[Config.smsGate.active].name}`); ...
const Factories = use('core/factories'); const Config = use('config'); const NotificationSmsFactory = Factories('NotificationSms'); class NotificationSms { constructor() { this.provider = require(`./providers/${Config.smsGate.providers[Config.smsGate.active].name}`); ...
Fix catalog proptype on homepage
import React from 'react' import PropTypes from 'prop-types' import { translate } from 'react-i18next' import Link from '../link' import Section from './section' import CatalogPreview from '../catalog-preview' const Catalogs = ({ catalogs, t }) => ( <Section title={t('catalogsSectionTitle')}> <div className='ca...
import React from 'react' import PropTypes from 'prop-types' import { translate } from 'react-i18next' import Link from '../link' import Section from './section' import CatalogPreview from '../catalog-preview' const Catalogs = ({ catalogs, t }) => ( <Section title={t('catalogsSectionTitle')}> <div className='ca...
Use ~/.snakewatch/default.json if exists, fallback on built-in.
import json import os import importlib class Config(object): available_actions = {} def __init__(self, cfg, *args): if isinstance(cfg, str): fp = open(cfg, 'r') self.cfg = json.load(fp) fp.close() elif isinstance(cfg, list): self.cfg = cfg ...
import json import importlib class Config(object): available_actions = {} def __init__(self, cfg, *args): if isinstance(cfg, str): fp = open(cfg, 'r') self.cfg = json.load(fp) fp.close() elif isinstance(cfg, list): self.cfg = cfg self...
Use searchRoute property instead of function
angular.module('OpiferEntityPicker', ['ui.bootstrap.typeahead']) .directive('entityPicker', function() { var tpl = '<input type="text" ng-model="search" typeahead="object.name for object in getObject($viewValue)" typeahead-on-select="onSelect($item, $model, $label)" typeahead-loading="loadingL...
angular.module('OpiferEntityPicker', ['ui.bootstrap.typeahead']) .directive('entityPicker', function() { var tpl = '<input type="text" ng-model="search" typeahead="object.name for object in getObject($viewValue)" typeahead-on-select="onSelect($item, $model, $label)" typeahead-loading="loadingL...
Check media_type instead of class type The `parsers` list should contain instances, not classes.
import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ ...
import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ ...
Fix clean logs script wrong date parsing
#!/usr/bin/env python # encoding: utf-8 import os import datetime from config import USER_DIRECTORY, LOG_DIRECTORY_NAME, STORE_LOGS NOW = datetime.datetime.now() def clean_log(filepath): delete = False with open(filepath) as fp: line = fp.readline() try: date_str = ' '.join(line...
#!/usr/bin/env python # encoding: utf-8 import os import datetime from config import USER_DIRECTORY, LOG_DIRECTORY_NAME, STORE_LOGS NOW = datetime.datetime.now() def clean_log(filepath): delete = False with open(filepath) as fp: line = fp.readline() try: date_str = ' '.join(line...
Remove extra wait time in set volume
const Effect = require('./Effect'); /** * Affect the volume of an effect chain. */ class VolumeEffect extends Effect { /** * Default value to set the Effect to when constructed and when clear'ed. * @const {number} */ get DEFAULT_VALUE () { return 100; } /** * Return the n...
const Effect = require('./Effect'); /** * Affect the volume of an effect chain. */ class VolumeEffect extends Effect { /** * Default value to set the Effect to when constructed and when clear'ed. * @const {number} */ get DEFAULT_VALUE () { return 100; } /** * Return the n...
Stop looping to do nothing, just pass.
"""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ ...
"""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ ...
Add replaceable slot tag, for upgrades that can be replaced without returning the existing upgrade
package com.elmakers.mine.bukkit.wand; import org.bukkit.configuration.ConfigurationSection; import com.elmakers.mine.bukkit.api.magic.Mage; public class WandUpgradeSlot { private final String slotType; private boolean hidden = false; private boolean swappable = false; private boolean replaceable = f...
package com.elmakers.mine.bukkit.wand; import org.bukkit.configuration.ConfigurationSection; import com.elmakers.mine.bukkit.api.magic.Mage; public class WandUpgradeSlot { private final String slotType; private boolean hidden = false; private boolean swappable = false; private Wand slotted; publ...
Allow passing of a hostname for the docs server.
module.exports = function(grunt) { 'use strict'; var host = grunt.option('host') || 'localhost'; grunt.loadNpmTasks('grunt-contrib'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-traceur'); grunt.initConfig({ connect: { docs: { options: { keepalive: true, ...
module.exports = function(grunt) { 'use strict'; grunt.loadNpmTasks('grunt-contrib'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-traceur'); grunt.initConfig({ connect: { docs: { options: { keepalive: true, open: 'http://localhost:8000/docs' } ...
Fix bug with text/plain response
import random import yaml from flask import jsonify, Response, render_template class Which(object): def __init__(self, mime_type, args): self.mime_type = mime_type self.args = args @property def _excuse(self): stream = open("excuses.yaml", 'r') excuses = yaml.load(stream)...
import random import yaml from flask import jsonify, Response, render_template class Which(object): def __init__(self, mime_type, args): self.mime_type = mime_type self.args = args @property def _excuse(self): stream = open("excuses.yaml", 'r') excuses = yaml.load(stream)...
Change content type when execute command
package com.decker.Essentials; import java.io.IOException; import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.decker.Essentials.Category.Category; import com.decker.Essentials.User.User; public class Center extends org.si...
package com.decker.Essentials; import java.io.IOException; import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.decker.Essentials.Category.Category; import com.decker.Essentials.User.User; public class Center extends org.si...
Add fileio.TextFile and use it when reading and writing text files in RDD and Context.
from __future__ import absolute_import, unicode_literals import logging from io import BytesIO, StringIO from . import codec from .file import File log = logging.getLogger(__name__) class TextFile(File): """ Derived from :class:`pysparkling.fileio.File`. :param file_name: Any text file name. S...
from __future__ import absolute_import, unicode_literals import logging from io import StringIO from . import codec from .file import File log = logging.getLogger(__name__) class TextFile(File): """ Derived from :class:`pysparkling.fileio.File`. :param file_name: Any text file name. Supports t...
Check cb is a function before calling it
/* * stompit.connect * Copyright (c) 2013 Graham Daws <graham.daws@gmail.com> * MIT licensed */ var net = require('net'); var util = require('./util'); var Client = require('./client'); function connect(){ var args = net._normalizeConnectArgs(arguments); var options = util.extend({ ...
/* * stompit.connect * Copyright (c) 2013 Graham Daws <graham.daws@gmail.com> * MIT licensed */ var net = require('net'); var util = require('./util'); var Client = require('./client'); function connect(){ var args = net._normalizeConnectArgs(arguments); var options = util.extend({ ...
Check the existence of the images_path ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK Traceback (most recent call last): File "/opt/xos/observer/event_loop.py", line 349, in sync failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) Fil...
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted...
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted...
Return 400 for inexistant accounts
import logging from django.conf import settings from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from .models import Notification, Account logger = logging.getLogger(__name__) # Maybe use a form for this? :D @csrf_exempt def create_notification(request, slug): topic = ...
import logging from django.conf import settings from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from .models import Notification, Account logger = logging.getLogger(__name__) # Maybe use a form for this? :D @csrf_exempt def create_notification(request, slug): topic = ...
Check if app is installed for user before displying Summary: Fixes T11595. Previously if a user didn't have permissions to view an application it would still appear in the application typeahead in various menus. This change will prevent that by checking if the app is installed for the viewer before displaying it as an...
<?php final class PhabricatorApplicationDatasource extends PhabricatorTypeaheadDatasource { public function getBrowseTitle() { return pht('Browse Applications'); } public function getPlaceholderText() { return pht('Type an application name...'); } public function getDatasourceApplicationClass() ...
<?php final class PhabricatorApplicationDatasource extends PhabricatorTypeaheadDatasource { public function getBrowseTitle() { return pht('Browse Applications'); } public function getPlaceholderText() { return pht('Type an application name...'); } public function getDatasourceApplicationClass() ...
Fix bug with reloading on Login page
(() => { 'use strict'; angular .module('app') .controller('LoginController', LoginController); LoginController.$inject = ['growl', '$window', '$http', '$routeSegment', 'TokenService', 'Endpoints']; function LoginController(growl, $window, $http, $routeSegment, TokenService, Endpoints)...
(() => { 'use strict'; angular .module('app') .controller('LoginController', LoginController); LoginController.$inject = ['growl', '$window', '$http', '$routeSegment', 'TokenService', 'Endpoints']; function LoginController(growl, $window, $http, $routeSegment, TokenService, Endpoints)...
Increase coverage base to 100%
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'], options: { jshintrc: '.jshintrc', } }, ...
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'], options: { jshintrc: '.jshintrc', } }, ...
Fix the issue when use with multiple cursors and scroll the view when selected
import sublime_plugin class SelectExactMatchCommand(sublime_plugin.TextCommand): last_selection = None def run(self, edit): selections = self.view.sel() words_selection = False for selection in selections: if selection.empty(): words_selection = True ...
import sublime_plugin class SelectExactMatchCommand(sublime_plugin.TextCommand): last_selection = None def run(self, edit): selections = self.view.sel() if selections[0].empty(): selections.add(self.view.word(selections[0])) return word = self.view.substr(self....
Add helper classes to the event row
<table> <thead> <tr> <th scope="col" class="date">Time</th> <th scope="col" class="title">Event Title</th> </tr> </thead> <tbody class="vcalendar"> <?php $oddrow = false; foreach ($context as $eventinstance) { //Start building an ar...
<table> <thead> <tr> <th scope="col" class="date">Time</th> <th scope="col" class="title">Event Title</th> </tr> </thead> <tbody class="vcalendar"> <?php $oddrow = false; foreach ($context as $eventinstance) { //Start building an ar...
Make some fixes in the Character component methods
var React = require('react'); var Character = React.createClass({ getThumbnail: function() { var image = 'http://placehold.it/250x250'; if(this.props.character.thumbnail) { var path = this.props.character.thumbnail.path; var extension = this.props.character.thumbnail.extension; image = pa...
var React = require('react'); var Character = React.createClass({ getThumbnail: function() { var image = 'http://placehold.it/250x250'; if(this.props.character.thumbnail) { image = this.props.character.thumbnail.path+'.'+this.props.character.thumbnail.extension; } return ( <img classNam...
Simplify and make better :) Removed deep watch because it broke on when using scopes. Instead it now sets a series of getters on the scope for each property found on the given scope. Also it's much more performant.
angular.module('drg.ngIncludeScope', []) .directive( 'ngIncludeScope', function() { 'use strict'; return { restrict: 'A', link : function( scope, elem, attrs ) { var keys = []; scope.$watch( attrs.ngIncludeScope, function( newScope, oldScope ) { var key; ...
angular.module('drg.ngIncludeScope', []) .directive( 'ngIncludeScope', function() { 'use strict'; return { restrict: 'A', link : function( scope, elem, attrs ) { scope.$watch( attrs.ngIncludeScope, function( newScope, oldScope ) { var key, newKeys...
Add SVT options to plotting script.
import climate import lmj.plot import numpy as np import source import plots @climate.annotate( root='load experiment data from this directory', pattern=('plot data from files matching this pattern', 'option'), markers=('plot traces of these markers', 'option'), spline=('interpolate data with a splin...
import climate import lmj.plot import numpy as np import source import plots @climate.annotate( root='load experiment data from this directory', pattern=('plot data from files matching this pattern', 'option'), markers=('plot traces of these markers', 'option'), spline=('interpolate data with a splin...
Make stop words a set for speed optimization.
import os from operator import itemgetter import re from haystack.query import SearchQuerySet from pombola.hansard import models as hansard_models BASEDIR = os.path.dirname(__file__) # normal english stop words and hansard-centric words to ignore with open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU') as f: STOP...
import os from operator import itemgetter import re from haystack.query import SearchQuerySet from pombola.hansard import models as hansard_models BASEDIR = os.path.dirname(__file__) # normal english stop words and hansard-centric words to ignore STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read()...
refactor: Remove unnecessary reference from webpack dev build.
// For output.filename configuration: // // CHANGE "component-name" in this file to your real component name! // DO NOT CHANGE "[name]", which denotes the entry property names that webpack automatically inserts for you! module.exports = { entry: { dev: ['webpack/hot/dev-server', './demo/demo.js'], dist: ['./ma...
// For output.filename configuration: // // Change "component-name" in this file to your real component name! // DO NOT CHANGE "[name]", which denotes the entry property names that webpack automatically inserts for you! module.exports = { entry: { dev: ['webpack/hot/dev-server', './main.js', './demo/demo.js'], ...
Update default value of mode
/* Toast notification popup jQuery plugin (c) 2016 Nupin Mathew <nupindev@gmail.com> License: MIT */ $(function () { /*Method to show a toast notification like popup with a message which will be closed after a fixed time*/ $.fn.showToast = function (options) { var defaults = { me...
/* Toast notification popup jQuery plugin (c) 2016 Nupin Mathew <nupindev@gmail.com> License: MIT */ $(function () { /*Method to show a toast notification like popup with a message which will be closed after a fixed time*/ $.fn.showToast = function (options) { var defaults = { me...
Change js coverage report format for jenkins
module.exports = function(config) { config.set({ basePath: '../../', files: [ 'web/js/vendor/angular.js', 'web/js/vendor/angular-*.js', 'test/lib/angular/angular-mocks.js', 'web/js/vendor/jquery*.js', 'web/js/**/*.js', 'test/un...
module.exports = function(config) { config.set({ basePath: '../../', files: [ 'web/js/vendor/angular.js', 'web/js/vendor/angular-*.js', 'test/lib/angular/angular-mocks.js', 'web/js/vendor/jquery*.js', 'web/js/**/*.js', 'test/un...
Svgo: Remove unused property `_multiPass`, `settings.multipass` is used instead.
"use strict"; var SvgFile = require('./svg-file'); class Svgo extends require('./worker-messenger') { constructor() { super('js/svgo-worker.js'); this._abortOnNextIteration = false; this._currentJob = Promise.resolve(); } load(svgText) { return this._requestResponse({ action: 'load', ...
"use strict"; var SvgFile = require('./svg-file'); class Svgo extends require('./worker-messenger') { constructor() { super('js/svgo-worker.js'); this._multiPass = false; this._abortOnNextIteration = false; this._currentJob = Promise.resolve(); } load(svgText) { return this._requestResponse...
Allow manifest output name to be configured
/** * A Rollup plugin to generate a manifest of chunk names to their filenames * (including their content hash). This manifest is then used by the template * to point to the currect URL. * @return {Object} */ export default function (config) { if (!config) { config = {}; } const manifest = { ...
/** * A Rollup plugin to generate a manifest of chunk names to their filenames * (including their content hash). This manifest is then used by the template * to point to the currect URL. * @return {Object} */ export default function (config) { const manifest = { files: [], entries: {}, }; ...
Allow loading of external urls specified in the swagger resource location resolves #843
$(function() { var springfox = { "baseUrl": function() { var urlMatches = /(.*)\/swagger-ui.html.*/.exec(window.location.href); return urlMatches[1]; }, "securityConfig": function(cb) { $.getJSON(this.baseUrl() + "/configuration/security", function(data) {...
$(function() { var springfox = { "baseUrl": function() { var urlMatches = /(.*)\/swagger-ui.html.*/.exec(window.location.href); return urlMatches[1]; }, "securityConfig": function(cb) { $.getJSON(this.baseUrl() + "/configuration/security", function(data) {...
Fix how we calculate total to really account for deleted objects
from django.contrib import admin from django.core.exceptions import ValidationError from django import forms from django.utils.translation import ugettext_lazy as _ from revenue.models import Receipt, FeeLine class FeeLinesInlineFormSet(forms.BaseInlineFormSet): def clean(self): super(FeeLinesInlineFormS...
from django.contrib import admin from django.core.exceptions import ValidationError from django.forms import BaseInlineFormSet, ModelForm from django.utils.translation import ugettext_lazy as _ from revenue.models import Receipt, FeeLine class FeeLinesInlineFormSet(BaseInlineFormSet): def clean(self): su...
Make coverage php version option verbose
<?php namespace Phug\DevTool\Command; use Phug\DevTool\AbstractCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class CoverageReportCommand extends Abs...
<?php namespace Phug\DevTool\Command; use Phug\DevTool\AbstractCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class CoverageReportCommand extends Abs...
Remove whitespace from campaign text area
class CampaignView { constructor(){ } getIndex(campaigns) { console.log('Campaign View: Get index'); var campaignHTML = `<h1>Campaign Index<h1>`; for(let i = 0; i < campaigns.length; i++) { campaignHTML += `<button class='campaign_show' data-id='${campaigns[i].id}'>Campaign ${campaigns[i].nam...
class CampaignView { constructor(){ } getIndex(campaigns) { console.log('Campaign View: Get index'); var campaignHTML = `<h1>Campaign Index<h1>`; for(let i = 0; i < campaigns.length; i++) { campaignHTML += `<button class='campaign_show' data-id='${campaigns[i].id}'>Campaign ${campaigns[i].nam...
Use MySQLi interface for example
<?php require('json-rpc/json-rpc.php'); if (function_exists('xdebug_disable')) { xdebug_disable(); } $link = new mysqli('localhost', 'user', 'password', 'db_name'); class MysqlDemo { public function query($query) { global $link; if (preg_match("/create|drop/", $query)) { throw new Exception("Sor...
<?php require('json-rpc/json-rpc.php'); if (function_exists('xdebug_disable')) { xdebug_disable(); } @mysql_connect('localhost', 'user', 'password'); @mysql_select_db('database_name'); class MysqlDemo { public function query($query) { if (preg_match("/create|drop/", $query)) { throw new Exception("S...
Fix issue with "load more" button status
'use strict'; angular .module('lwControllers') .controller('Posts', function($rootScope, $scope, $routeParams, $location, Article, Analytics, Admin) { $rootScope.title = 'Posts — LilyMandarin'; Analytics.page(); $rootScope.tab = 'posts'; $sc...
'use strict'; angular .module('lwControllers') .controller('Posts', function($rootScope, $scope, $routeParams, $location, Article, Analytics, Admin) { $rootScope.title = 'Posts — LilyMandarin'; Analytics.page(); $rootScope.tab = 'posts'; $sc...
ALign with the relevant code
var replaceAll = function( oldToken ) { var configs = this; return { from: function( string ) { return { to: function( newToken ) { var _token; var index = -1; if ( configs.ignoringCase ) { _token = oldToken.toLowerCase(); while(( ...
var replaceAll = function( oldToken ) { var configs = this; return { from: function( string ) { return { to: function( newToken ) { var _token; var index = -1; if ( configs.ignoringCase ) { _token = oldToken.toLowerCase(); while(( ...
Use get_profile_for_user() in profile signal handler
from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_user_fieldname, get_profile_for_user from mezzanine.conf import settings from mezzanine.utils.models import lazy_model_ops __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE"...
from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_user_fieldname from mezzanine.conf import settings from mezzanine.utils.models import lazy_model_ops __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): # This w...
Simplify indexes for managed installs
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Capsule\Manager as Capsule; class Managedinstalls extends Migration { public function up() { $capsule = new Capsule(); $capsule::schema()->create('managedinstalls', function (B...
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Capsule\Manager as Capsule; class Managedinstalls extends Migration { public function up() { $capsule = new Capsule(); $capsule::schema()->create('managedinstalls', function (B...
Add condition to only launch server if -s or --server is specified Now you can launch client, server or updater on its own, launch nothing, or launch the whole thing altogether!
import os import sys import time from multiprocessing import Process, Event import mfhclient import server import update from arguments import parse from settings import HONEYPORT, HIVEPORT def main(): update_event = Event() mfhclient_process = Process( args=(args, update_event,), name="mfh...
import os import sys import time from multiprocessing import Process, Event import mfhclient import server import update from arguments import parse from settings import HONEYPORT def main(): update_event = Event() mfhclient_process = Process( args=(args, update_event,), name="mfhclient_pro...
Update url patterns - accept only exact patterns
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib.staticfiles.views import serve from django.views.decorators.csrf import csrf_exempt from .graphql.api import schema from .graphql.views import GraphQLView from .plugins.views import...
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib.staticfiles.views import serve from django.views.decorators.csrf import csrf_exempt from .graphql.api import schema from .graphql.views import GraphQLView from .plugins.views import...
Fix error due to path not found When the project does not have the /bin directory in the root this error appears: [PhpGitHooks\Module\JsonLint\Contract\Exception\JsonLintViolationsException] Could not open input file: bin/jsonlint But it does exist in /vendor/bin. This fix tries to find it in both paths.
<?php namespace PhpGitHooks\Infrastructure\Tool; class ToolPathFinder { const COMPOSER_VENDOR_DIR = '/../../../'; const COMPOSER_INSTALLED_FILE = 'composer/installed.json'; /** @var array */ private $tools = array( 'phpcs' => 'squizlabs/php_codesniffer', 'php-cs-fixer' => 'friendsofph...
<?php namespace PhpGitHooks\Infrastructure\Tool; class ToolPathFinder { const COMPOSER_VENDOR_DIR = '/../../../'; const COMPOSER_INSTALLED_FILE = 'composer/installed.json'; /** @var array */ private $tools = array( 'phpcs' => 'squizlabs/php_codesniffer', 'php-cs-fixer' => 'friendsofph...