text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix glmnet test and add multinomial gradient test
import numpy as np import scipy.sparse as sps from sklearn.preprocessing import StandardScaler from numpy.testing import assert_allclose from pyglmnet import GLM def test_glmnet(): """Test glmnet.""" glm = GLM(distr='poisson') scaler = StandardScaler() n_samples, n_features = 10000, 100 density ...
import numpy as np import scipy.sparse as sps from sklearn.preprocessing import StandardScaler from numpy.testing import assert_allclose from pyglmnet import GLM def test_glmnet(): """Test glmnet.""" glm = GLM(distr='poisson') scaler = StandardScaler() n_samples, n_features = 10000, 100 density ...
Replace usage of `formatMessage(findTranslationByKey` with `t`
import Ember from 'ember'; import ValidatorsMessages from 'ember-cp-validations/validators/messages'; const { Logger:logger } = Ember; export default function() { ValidatorsMessages.reopen({ intl: Ember.inject.service(), prefix: 'errors', getDescriptionFor(attribute, context = {}) { let key = `${...
import Ember from 'ember'; import ValidatorsMessages from 'ember-cp-validations/validators/messages'; const { Logger:logger } = Ember; export default function() { ValidatorsMessages.reopen({ intl: Ember.inject.service(), prefix: 'errors', getDescriptionFor(attribute, context = {}) { let key = `${...
Make more similar to original version
var Immutable = require('immutable'); var is = Immutable.is.bind(Immutable); function shallowEqualImmutable(objA, objB) { if (objA === objB || is(objA, objB)) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var ...
var Immutable = require('immutable'); var is = Immutable.is.bind(Immutable), getKeys = Object.keys.bind(Object); function shallowEqualImmutable(objA, objB) { if (is(objA, objB)) { return true; } var keysA = getKeys(objA), keysB = getKeys(objB), keysAlength = keysA.length, keysBlength =...
Fix VarDumper Server for Dumps where no request exist
<?php namespace FroshProfiler\Components\VarDumper; use Enlight_Controller_Front; use Symfony\Component\VarDumper\Dumper\ContextProvider\ContextProviderInterface; /** * Class RequestContextProvider * @author Soner Sayakci <shyim@posteo.de> */ class RequestContextProvider implements ContextProviderInterface { ...
<?php namespace FroshProfiler\Components\VarDumper; use Enlight_Controller_Front; use Symfony\Component\VarDumper\Dumper\ContextProvider\ContextProviderInterface; /** * Class RequestContextProvider * @author Soner Sayakci <shyim@posteo.de> */ class RequestContextProvider implements ContextProviderInterface { ...
Allow core jquery-git to be used for unit tests.
(function() { // Insert a script tag pointing at the desired version of jQuery // Get the version from the url var jqueryRE = /[\\?&]jquery=([^&#]*)/, results = jqueryRE.exec( location.search ), version = "", jq, myScriptTag = document.getElementsByTagName( "script" )[document.getElementsByTagName( "script"...
(function() { // Insert a script tag pointing at the desired version of jQuery // Get the version from the url var jqueryRE = /[\\?&]jquery=([^&#]*)/, results = jqueryRE.exec( location.search ), version = "", jq, myScriptTag = document.getElementsByTagName( "script" )[document.getElementsByTagName( "script"...
Fix prefix of deprecated property
package de.linkvt.bachelor.features.annotations; import de.linkvt.bachelor.features.Feature; import de.linkvt.bachelor.features.FeatureCategory; import org.semanticweb.owlapi.model.OWLAnnotation; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.springfram...
package de.linkvt.bachelor.features.annotations; import de.linkvt.bachelor.features.Feature; import de.linkvt.bachelor.features.FeatureCategory; import org.semanticweb.owlapi.model.OWLAnnotation; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.springfram...
Fix redirect after new pledge form is sent
import { connect } from 'react-redux' import I18n from 'i18n-js' import { toggleSessionPopup } from '../../UserSession/actions/sessionActions' import { setEntity } from '../../lib/actions/entityActions' import PledgeForm from '../components/PledgeForm' import redirectTo from '../../lib/browser/redirectTo' const mapSta...
import { connect } from 'react-redux' import I18n from 'i18n-js' import { toggleSessionPopup } from '../../UserSession/actions/sessionActions' import { setEntity } from '../../lib/actions/entityActions' import PledgeForm from '../components/PledgeForm' const mapStateToProps = function(state, ownProps) { return { ...
Replace reserved token if address already exists
import { observable, action } from 'mobx'; class ReservedTokenStore { @observable tokens; constructor(tokens = []) { this.tokens = tokens; } @action addToken = (token) => { const currentToken = this.tokens.find(t => t.addr === token.addr) if (currentToken) { const index = this.tokens.inde...
import { observable, action } from 'mobx'; class ReservedTokenStore { @observable tokens; constructor(tokens = []) { this.tokens = tokens; } @action addToken = (token) => { this.tokens.push(token); } @action setTokenProperty = (index, property, value) => { let newToken = {...this.tokens[ind...
Make use of expanduser() more sane
import logging import logging.config LOG_CONFIG = { 'version': 1, 'formatters': { 'standard': {'format': 'voltron: [%(levelname)s] %(message)s'} }, 'handlers': { 'default': { 'class': 'logging.StreamHandler', 'formatter': 'standard' } }, 'loggers'...
import logging import logging.config LOG_CONFIG = { 'version': 1, 'formatters': { 'standard': {'format': 'voltron: [%(levelname)s] %(message)s'} }, 'handlers': { 'default': { 'class': 'logging.StreamHandler', 'formatter': 'standard' } }, 'loggers'...
Fix extra space on 'Bienvenue !'
// Is device mobile? if (window.innerWidth >= 850) { // Give video its source, will initiate load. Otherwise, it won't load anything and will be hidden by CSS. // This is so the video doesn't burn mobile data on phones. // Also it's a stylistic nightmare. document.getElementsByTagName('video')[0].src = ...
// Is device mobile? if (window.innerWidth >= 850) { // Give video its source, will initiate load. Otherwise, it won't load anything and will be hidden by CSS. // This is so the video doesn't burn mobile data on phones. // Also it's a stylistic nightmare. document.getElementsByTagName('video')[0].src = ...
Remove calls to `path.resolve` with no root directory
import path from 'path'; import {exec} from 'node-promise-es6/child-process'; async function cli(fixture, env = null) { const child = await exec( 'jasmine', { cwd: path.resolve(__dirname, `../../fixtures/${fixture}`), env: Object.assign({}, process.env, env) } ); return child.stdout; } d...
import path from 'path'; import {exec} from 'node-promise-es6/child-process'; async function cli(fixture, env = null) { const child = await exec( 'jasmine', { cwd: path.resolve(`fixtures/${fixture}`), env: Object.assign({}, process.env, env) } ); return child.stdout; } describe('jasmine-...
ROO-17: Create Spring Web Flow add-on
package org.springframework.roo.addon.web.flow; import org.springframework.roo.shell.CliAvailabilityIndicator; import org.springframework.roo.shell.CliCommand; import org.springframework.roo.shell.CliOption; import org.springframework.roo.shell.CommandMarker; import org.springframework.roo.support.lifecycle.ScopeDevel...
package org.springframework.roo.addon.web.flow; import org.springframework.roo.shell.CliAvailabilityIndicator; import org.springframework.roo.shell.CliCommand; import org.springframework.roo.shell.CliOption; import org.springframework.roo.shell.CommandMarker; import org.springframework.roo.support.lifecycle.ScopeDevel...
Check if epages6 settings are configured
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jonas Gratz # Copyright (c) 2015 Jonas Gratz # # License: MIT # """This module exports the PerlEpages6 plugin class.""" import sublime from SublimeLinter.lint import Linter, util class PerlEpages6(Linter): """...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jonas Gratz # Copyright (c) 2015 Jonas Gratz # # License: MIT # """This module exports the PerlEpages6 plugin class.""" import sublime from SublimeLinter.lint import Linter, util class PerlEpages6(Linter): """...
Add pass timestamp rather than date object
/* eslint-disable import/prefer-default-export */ import React from 'react'; /** * Hook to simplify the use of the native date picker component by unwrapping * the callback event and firing the callback only when the date is changing, * providing a value to conditionally render the native picker and a callback * t...
/* eslint-disable import/prefer-default-export */ import React from 'react'; /** * Hook to simplify the use of the native date picker component by unwrapping * the callback event and firing the callback only when the date is changing, * providing a value to conditionally render the native picker and a callback * t...
Add FindValue() and WatchValue() fuzz calls to the mix. git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@140439 91177308-0d34-0410-b5e6-96231b3b80d8
""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): obj.GetFrameID() obj.GetPC() obj.SetPC(0xffffffff) obj.GetSP() obj.GetFP() obj.GetPCAddress() obj.GetSymbolContext(0) obj.GetModule() obj.GetCo...
""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): obj.GetFrameID() obj.GetPC() obj.SetPC(0xffffffff) obj.GetSP() obj.GetFP() obj.GetPCAddress() obj.GetSymbolContext(0) obj.GetModule() obj.GetCo...
Add ip forwarding and packet by packet sniffing code.
#!/etc/usr/python from scapy.all import * import sys iface = "eth0" filter = "ip" #victim in this case is the initiator VICTIM_IP = "192.168.1.121" MY_IP = "192.168.1.154" # gateway is the target GATEWAY_IP = "192.168.1.171" #VICTIM_MAC = "### don't want so show###" MY_MAC = "08:00:27:7b:80:18" #target mac address GA...
#!/etc/usr/python from scapy.all import * import sys iface = "eth0" filter = "ip" #victim in this case is the initiator VICTIM_IP = "192.168.1.121" MY_IP = "192.168.1.154" # gateway is the target GATEWAY_IP = "192.168.1.171" #VICTIM_MAC = "### don't want so show###" MY_MAC = "08:00:27:7B:80:18" #target mac address GA...
Optimize twitter bootstrap nav-tabs javascript
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directl...
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directl...
Store jobs with reduced redundancy on S3
'use stirct' var opbeat = require('opbeat').start() var uuid = require('node-uuid') var AWS = require('aws-sdk') var Printer = require('ipp-printer') var port = process.env.PORT || 3000 var s3 = new AWS.S3() var printer = new Printer({ name: 'printbin', port: port, zeroconf: false }) printer.on('job', function (job...
'use stirct' var opbeat = require('opbeat').start() var uuid = require('node-uuid') var AWS = require('aws-sdk') var Printer = require('ipp-printer') var port = process.env.PORT || 3000 var s3 = new AWS.S3() var printer = new Printer({ name: 'printbin', port: port, zeroconf: false }) printer.on('job', function (job...
Mark es_test decorator as nottest Second try...
import json from nose.plugins.attrib import attr from nose.tools import nottest class ElasticTestMixin(object): def checkQuery(self, query, json_output, is_raw_query=False): if is_raw_query: raw_query = query else: raw_query = query.raw_query msg = "Expected Query:...
import json from nose.plugins.attrib import attr class ElasticTestMixin(object): def checkQuery(self, query, json_output, is_raw_query=False): if is_raw_query: raw_query = query else: raw_query = query.raw_query msg = "Expected Query:\n{}\nGenerated Query:\n{}".for...
polly.py: Fix vcvarsall_dir for Visual Studio 2017 [skip ci]
# Copyright (c) 2014, Ruslan Baratov # All rights reserved. import detail.util import os import sys def get(arch, vs_version): vs_path_env = 'VS{}0COMNTOOLS'.format(vs_version) vs_path = os.getenv(vs_path_env) if not vs_path: sys.exit( 'Environment variable {} is empty, ' 'looks like Visual ...
# Copyright (c) 2014, Ruslan Baratov # All rights reserved. import detail.util import os import sys def get(arch, vs_version): vs_path_env = 'VS{}0COMNTOOLS'.format(vs_version) vs_path = os.getenv(vs_path_env) if not vs_path: sys.exit( 'Environment variable {} is empty, ' 'looks like Visual ...
[KARAF-1109] Update the archetypes itest to reflect the new karaf-command-archetype artifactId git-svn-id: 71d8a689455c5fbb0f077bc40adcfc391e14cb9d@1214843 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may ...
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may ...
Replace magic number with symbolic constant
<?php namespace Bauhaus\Http; use Psr\Http\Message\ResponseInterface; use Bauhaus\Http\Message; use Bauhaus\Http\Response\Status; use Bauhaus\Http\Response\StatusInterface; class Response extends Message implements ResponseInterface { const DEFAULT_STATUS_CODE = 200; private $status = null; public func...
<?php namespace Bauhaus\Http; use Psr\Http\Message\ResponseInterface; use Bauhaus\Http\Message; use Bauhaus\Http\Response\Status; use Bauhaus\Http\Response\StatusInterface; class Response extends Message implements ResponseInterface { private $status = null; public function __construct(StatusInterface $stat...
Remove double $ from variable
<?php /* * The MIT License (MIT) * * Copyright (c) 2016 Bruno P. Kinoshita, Peter Florijn * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limit...
<?php /* * The MIT License (MIT) * * Copyright (c) 2016 Bruno P. Kinoshita, Peter Florijn * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limit...
Simplify f-string to remove cast
import subprocess from pathlib import Path po_path: Path = Path(__file__).resolve().parent def run_babel(command: str, input: Path, output_file: Path, locale: str): subprocess.run( [ "pybabel", command, f"--input={input}", f"--output-file={output_file}", ...
import subprocess from pathlib import Path po_path: Path = Path(__file__).resolve().parent def run_babel(command: str, input: Path, output_file: Path, locale: str): subprocess.run( [ "pybabel", command, f"--input={str(input)}", f"--output-file={str(output_f...
Add message for system-generated definitions.
package org.reldb.dbrowser.ui.content.rel.operator; import org.eclipse.swt.graphics.Image; import org.reldb.dbrowser.ui.content.rel.DbTreeAction; import org.reldb.dbrowser.ui.content.rel.DbTreeItem; import org.reldb.dbrowser.ui.content.rel.NaiveShowTab; import org.reldb.dbrowser.ui.content.rel.RelPanel; import org.rel...
package org.reldb.dbrowser.ui.content.rel.operator; import org.eclipse.swt.graphics.Image; import org.reldb.dbrowser.ui.content.rel.DbTreeAction; import org.reldb.dbrowser.ui.content.rel.DbTreeItem; import org.reldb.dbrowser.ui.content.rel.NaiveShowTab; import org.reldb.dbrowser.ui.content.rel.RelPanel; import org.rel...
Use Fira Code again in Hyper
module.exports = { config: { fontSize: 12, fontFamily: '"Fira Code", Monoid, Menlo, "DejaVu Sans Mono", "Lucida Console", monospace, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"', css: ` header { box-shadow: 0px 2px 20px rgba(0, 0, 0, 0.17); } .hyperterm_main { ...
module.exports = { config: { fontSize: 13, fontFamily: '"Operator Mono", "Fira Code", Monoid, Menlo, "DejaVu Sans Mono", "Lucida Console", monospace', css: ` header { box-shadow: 0px 2px 20px rgba(0, 0, 0, 0.17); } .hyperterm_main { border-color: transparent !important; ...
Remove borough from locality lookup We may have gotten overeager adding borough everywhere, it's definitely below locality in the heirarchy.
/* Look up which admin fields should be populated for a record in a given layer. * * The logic is: look up eveything above in the WOF heirarchy, ignoring things like * 'dependency' * * Note: this filtering really only matters for geonames currently, since OSM and OA * consist entirely of venue and address records...
/* Look up which admin fields should be populated for a record in a given layer. * * The logic is: look up eveything above in the WOF heirarchy, ignoring things like * 'dependency' * * Note: this filtering really only matters for geonames currently, since OSM and OA * consist entirely of venue and address records...
Update test for new column naming rules. Remove '' as a name and call column 'C1'
import sys sys.path.insert(1, "../../../") import h2o def cupMediumGBM(ip,port): # Connect to h2o h2o.init(ip,port) train = h2o.import_frame(path=h2o.locate("bigdata/laptop/usecases/cup98LRN_z.csv")) test = h2o.import_frame(path=h2o.locate("bigdata/laptop/usecases/cup98VAL_z.csv")) train["TARGET_B"] = trai...
import sys sys.path.insert(1, "../../../") import h2o def cupMediumGBM(ip,port): # Connect to h2o h2o.init(ip,port) train = h2o.import_frame(path=h2o.locate("bigdata/laptop/usecases/cup98LRN_z.csv")) test = h2o.import_frame(path=h2o.locate("bigdata/laptop/usecases/cup98VAL_z.csv")) train["TARGET_B"] = trai...
Fix CSS getting required in AJAX request
<?php namespace Concrete\Package\KintDebug; use Concrete\Core\Package\Package; use View; defined('C5_EXECUTE') or die(_("Access Denied.")); require_once __DIR__ . '/vendor/autoload.php'; class Controller extends Package { protected $pkgHandle = 'kint_debug'; protected $appVersionRequired = '5.7.0.4'; pr...
<?php namespace Concrete\Package\KintDebug; use Concrete\Core\Package\Package; use View; defined('C5_EXECUTE') or die(t("Access Denied.")); require_once __DIR__ . '/vendor/autoload.php'; class Controller extends Package { protected $pkgHandle = 'kint_debug'; protected $appVersionRequired = '5.7.0.4'; pr...
Allow Revolut username to be minimum 3 characters
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the ...
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the ...
Fix spelling of 'IPv4' and 'IPv6' (cosmetic)
ACTION_CREATE = 0 ACTION_VIEW = 1 ACTION_UPDATE = 2 ACTION_DELETE = 3 ACTIONS = { ACTION_CREATE: 'Create', ACTION_VIEW: 'View', ACTION_UPDATE: 'Update', ACTION_DELETE: 'Delete', } LEVEL_GUEST = 0 LEVEL_USER = 1 LEVEL_ADMIN = 2 LEVELS = { LEVEL_GUEST: 'Guest', LEVEL_USER: 'User', LEVEL_AD...
ACTION_CREATE = 0 ACTION_VIEW = 1 ACTION_UPDATE = 2 ACTION_DELETE = 3 ACTIONS = { ACTION_CREATE: 'Create', ACTION_VIEW: 'View', ACTION_UPDATE: 'Update', ACTION_DELETE: 'Delete', } LEVEL_GUEST = 0 LEVEL_USER = 1 LEVEL_ADMIN = 2 LEVELS = { LEVEL_GUEST: 'Guest', LEVEL_USER: 'User', LEVEL_AD...
Add checking if resctrl path exists Signed-off-by: Katarzyna Kujawa <6d81612c80214d850c10c80be3c4dcdb2935414e@intel.com>
// +build linux // Copyright 2020 Google 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 requi...
// +build linux // Copyright 2020 Google 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 requi...
Replace 'assert session != null' with Assert.notnull(Object, String)
/* * Copyright 2010 The myBatis Team * * 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 applic...
/* * Copyright 2010 The myBatis Team * * 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 applic...
Delete images instead of printing
#!/usr/bin/env python from collections import defaultdict import subprocess import os KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4) def find_obsolete_images(images): for image_name, versions in images.items(): if len(versions) > KEEP_LAST_VERSIONS: obsolete_versions = sorted(ve...
#!/usr/bin/env python from collections import defaultdict import subprocess import os KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4) def find_obsolete_images(images): for image_name, versions in images.items(): if len(versions) > KEEP_LAST_VERSIONS: obsolete_versions = sorted(ve...
Fix a Flow type annotation in ValidationError
/** * Node.js API Starter Kit (https://reactstarter.com/nodejs) * * Copyright © 2016-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /* @flow */ // TODO: Log the error to Google Stac...
/** * Node.js API Starter Kit (https://reactstarter.com/nodejs) * * Copyright © 2016-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /* @flow */ // TODO: Log the error to Google Stac...
Load lib extensions after loading middleware
var Protos = require('../'); Protos.bootstrap(__dirname, { // Server configuration server: { host: 'localhost', port: 8080, multiProcess: false, stayUp: false }, // Application environments environments: { default: 'development', development: function(app) { app.debugLog ...
var Protos = require('../'); Protos.bootstrap(__dirname, { // Server configuration server: { host: 'localhost', port: 8080, multiProcess: false, stayUp: false }, // Application environments environments: { default: 'development', development: function(app) { app.debugLog ...
Use field.to_python to do django type conversions on the field before checking if dirty. This solves issues where you might have a decimal field that you write a string to, eg: >>> m = MyModel.objects.get(id=1) >>> m.my_decimal_field Decimal('1.00') >>> m.my_decimal_field = u'1.00' # from a form or something >>...
# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(reset_state, sender=self.__cl...
# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(reset_state, sender=self.__cl...
Throw a specific exception instead of a generic one
package me.devsaki.hentoid.parsers; import android.webkit.URLUtil; import java.util.List; import me.devsaki.hentoid.database.domains.Content; import me.devsaki.hentoid.database.domains.ImageFile; import timber.log.Timber; public abstract class BaseParser implements ImageListParser { private int currentStep; ...
package me.devsaki.hentoid.parsers; import android.webkit.URLUtil; import java.util.List; import me.devsaki.hentoid.database.domains.Content; import me.devsaki.hentoid.database.domains.ImageFile; import timber.log.Timber; public abstract class BaseParser implements ImageListParser { private int currentStep; ...
Use in every case a hash for addon name
"""Util addons functions.""" import hashlib import pathlib import re RE_SLUGIFY = re.compile(r'[^a-z0-9_]+') RE_SHA1 = re.compile(r"[a-f0-9]{40}") def get_hash_from_repository(repo): """Generate a hash from repository.""" key = repo.lower().encode() return hashlib.sha1(key).hexdigest()[:8] def extract_...
"""Util addons functions.""" import hashlib import pathlib import re import unicodedata RE_SLUGIFY = re.compile(r'[^a-z0-9_]+') def slugify(text): """Slugify a given text.""" text = unicodedata.normalize('NFKD', text) text = text.lower() text = text.replace(" ", "_") text = RE_SLUGIFY.sub("", tex...
Use click.echo() for python 2.7 compatibility
import logging from regparser.tree.depth import optional_rules from regparser.tree.depth.derive import derive_depths import click logger = logging.getLogger(__name__) @click.command() @click.argument('markers', type=click.STRING, required=True) def outline_depths(markers) -> None: """ Infer an outline's st...
import logging from regparser.tree.depth import optional_rules from regparser.tree.depth.derive import derive_depths import click logger = logging.getLogger(__name__) @click.command() @click.argument('markers', type=click.STRING, required=True) def outline_depths(markers) -> None: """ Infer an outline's st...
Fix for intel routing changes
// ==UserScript== // @id iitc-plugin-console@hansolo669 // @name IITC plugin: console // @category Debug // @version 0.0.2 // @namespace https://github.com/hansolo669/iitc-tweaks // @updateURL https://iitc.reallyawesomedomain.com/console.meta.js // @downloadURL https://ii...
// ==UserScript== // @id iitc-plugin-console@hansolo669 // @name IITC plugin: console // @category Debug // @version 0.0.1 // @namespace https://github.com/hansolo669/iitc-tweaks // @updateURL https://iitc.reallyawesomedomain.com/console.meta.js // @downloadURL https://ii...
[FIX] purchase_stock_picking_return_invoicing: Hide button on proper counter We should hide the view refunds button when there are no refunds, not when there aren't invoices. It hasn't been detected till now, because you usually have an invoice before doing a refund, but in case you include this purchase order in a v...
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) # Copyright 2017-2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Purchase Stock Picking Return Invoicing", "summary": "Add an option to refund returned pickings", "version": "14.0.1.1.0", ...
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) # Copyright 2017-2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Purchase Stock Picking Return Invoicing", "summary": "Add an option to refund returned pickings", "version": "14.0.1.0.0", ...
Replace level 1,2,3 with ERROR, WARNING, NOTICE.
var HTMLCS_RUNNER = new function() { this.run = function(standard) { var self = this; // At the moment, it passes the whole DOM document. HTMLCS.process(standard, document, function() { var messages = HTMLCS.getMessages(); var length = messages.length; ...
var HTMLCS_RUNNER = new function() { this.run = function(standard) { var self = this; // At the moment, it passes the whole DOM document. HTMLCS.process(standard, document, function() { var messages = HTMLCS.getMessages(); var length = messages.length; ...
Use the plugin() method instead of __call()
<?php namespace SxBootstrap\View\Helper\Bootstrap; //use SxBootstrap\Exception; use Zend\View\Helper\AbstractHelper; /** * ViewHelper to add twitter bootstrap to the head. * This WILL use the headScript and headLink helpers. */ class Bootstrap extends AbstractHelper { public function __invoke() { $...
<?php namespace SxBootstrap\View\Helper\Bootstrap; //use SxBootstrap\Exception; use Zend\View\Helper\AbstractHelper; /** * ViewHelper to add twitter bootstrap to the head. * This WILL use the headScript and headLink helpers. */ class Bootstrap extends AbstractHelper { public function __invoke() { $...
Fix indentation, remove unused import, avoid deprecated method
package com.rarchives.ripme.tst.ripper.rippers; import java.io.IOException; import java.net.URL; import com.rarchives.ripme.ripper.rippers.ErotivRipper; import org.junit.jupiter.api.Test; public class ErotivRipperTest extends RippersTest { @Test public void testGetGID() throws IOException { URL url =...
package com.rarchives.ripme.tst.ripper.rippers; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import com.rarchives.ripme.ripper.rippers.ErotivRipper; import org.junit.jupiter.api.Test; public class ErotivRipperTest extends RippersTest { @Test public void testGetGID() throw...
Update newListing no longer require furnishing detail
from django import forms from .models import Listing, HousingUser class ListingForm(forms.ModelForm): furnished_details = forms.CharField(required=False, widget=forms.Textarea(attrs={ "placeholder": "Example: bed and desk only"})) additional_lease_terms = forms.CharField(required=False, widget=...
from django import forms from .models import Listing, HousingUser class ListingForm(forms.ModelForm): furnished_details = forms.CharField(widget=forms.Textarea(attrs={ "placeholder": "Example: bed and desk only"})) additional_lease_terms = forms.CharField(required=False, widget=forms.Textarea(a...
Remove Home from list of popular pages
from collections import OrderedDict from django.db.models import Count from mpages.models import Page, PageRead def menus(request): main_menu = Page.objects.get(slug="main-menu") recent_updates = Page.objects.all().order_by("-updated")[:10] updates = OrderedDict() for page in recent_updates: ...
from collections import OrderedDict from django.db.models import Count from mpages.models import Page, PageRead def menus(request): main_menu = Page.objects.get(slug="main-menu") recent_updates = Page.objects.all().order_by("-updated")[:10] updates = OrderedDict() for page in recent_updates: ...
Remove setting response status code on permission validation
const Factories = use('core/factories'); const Errors = use('core/errors'); const PermissionsFactory = Factories('Permissions'); function checkPermissions(body) { if (!this.request.handler.permission) { return body; } if (!this.request.session) { ...
const Factories = use('core/factories'); const Errors = use('core/errors'); const PermissionsFactory = Factories('Permissions'); function checkPermissions(body) { if (!this.request.handler.permission) { return body; } if (!this.request.session) { ...
Use an OrderedDict to ensure the first option is the default option
#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK from collections import OrderedDict # the order here matters as the default option should always be first in the dict so that it is # automatically selected in combo boxes that use this li...
#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK COLLECTION_CONTACTS = { u'Data Portal / Other': u'data@nhm.ac.uk', u'Algae, Fungi & Plants': u'm.carine@nhm.ac.uk', u'Economic & Environmental Earth Sciences': u'g.miller@nhm....
chore(pins): Update pin to new dictionary hotfix pin - Update pin to new dictionary hotfix pin
from setuptools import setup, find_packages setup( name='gdcdatamodel', packages=find_packages(), install_requires=[ 'pytz==2016.4', 'graphviz==0.4.2', 'jsonschema==2.5.1', 'python-dateutil==2.4.2', 'dictionaryutils', 'gdcdictionary', 'psqlgraph', ...
from setuptools import setup, find_packages setup( name='gdcdatamodel', packages=find_packages(), install_requires=[ 'pytz==2016.4', 'graphviz==0.4.2', 'jsonschema==2.5.1', 'python-dateutil==2.4.2', 'dictionaryutils', 'gdcdictionary', 'psqlgraph', ...
Disable debug output of sqla
from sqlalchemy import create_engine from tornado.web import Application, url from buildbox.config import settings from buildbox.db.backend import Backend from buildbox.web.frontend.build_list import BuildListHandler from buildbox.web.frontend.build_details import BuildDetailsHandler application = Application( [...
from sqlalchemy import create_engine from tornado.web import Application, url from buildbox.config import settings from buildbox.db.backend import Backend from buildbox.web.frontend.build_list import BuildListHandler from buildbox.web.frontend.build_details import BuildDetailsHandler application = Application( [...
Write CSS to file in CACHE dir
<?php @ini_set('display_errors', 'off'); define('DOCROOT', rtrim(realpath(dirname(__FILE__) . '/../../../'), '/')); define('DOMAIN', rtrim(rtrim($_SERVER['HTTP_HOST'], '/') . str_replace('/extensions/less_compiler/lib', NULL, dirname($_SERVER['PHP_SELF'])), '/')); // Include some parts of the engine require_onc...
<?php @ini_set('display_errors', 'off'); define('DOCROOT', rtrim(realpath(dirname(__FILE__) . '/../../../'), '/')); define('DOMAIN', rtrim(rtrim($_SERVER['HTTP_HOST'], '/') . str_replace('/extensions/less_compiler/lib', NULL, dirname($_SERVER['PHP_SELF'])), '/')); // Include some parts of the engine require_onc...
Change Buffalo spawn egg colors
package totemic_commons.pokefenn.entity; import cpw.mods.fml.common.registry.EntityRegistry; import totemic_commons.pokefenn.Totemic; import totemic_commons.pokefenn.entity.animal.EntityBuffalo; import totemic_commons.pokefenn.lib.Strings; /** * Created by Pokefenn. * Licensed under MIT (If this is one of my Mods) ...
package totemic_commons.pokefenn.entity; import cpw.mods.fml.common.registry.EntityRegistry; import totemic_commons.pokefenn.Totemic; import totemic_commons.pokefenn.entity.animal.EntityBuffalo; import totemic_commons.pokefenn.lib.Strings; /** * Created by Pokefenn. * Licensed under MIT (If this is one of my Mods) ...
Test commit, magnus tok ikke feil
package models; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToO...
package models; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToO...
Revert "fix util.js usage and use utils.Adapter" This reverts commit 6bfb11f7f626735a63202ec846b3aaf49dbb9898.
var srcDir = __dirname + "/../"; module.exports = { all: { src: [ srcDir + "*.js", srcDir + "lib/*.js", srcDir + "adapter/example/*.js", srcDir + "tasks/**/*.js", srcDir + "www/**/*.js", '!' + srcDir + "www/li...
var srcDir = __dirname + "/../"; module.exports = { all: { src: [ srcDir + "*.js", srcDir + "lib/*.js", srcDir + "adapter/example/*.js", srcDir + "tasks/**/*.js", srcDir + "www/**/*.js", '!' + srcDir + "www/li...
Fix bug with array_agg_mult() function not actually being created.
"""Actions to run at server startup. """ from django.db import connection from django.db import transaction def run(): """Call this from manage.py or tests. """ _add_custom_mult_agg_function() def _add_custom_mult_agg_function(): """Make sure the Postgresql database has a custom function array_agg_...
"""Actions to run at server startup. """ from django.db import connection def run(): """Call this from manage.py or tests. """ _add_custom_mult_agg_function() def _add_custom_mult_agg_function(): """Make sure the Postgresql database has a custom function array_agg_mult. NOTE: Figured out the r...
Add Switch and Redirect for Router
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router, Redirect, Route, Switch, } from 'react-router-dom'; import './styles/index.css'; import Background from './components/Background'; import Footer from './components/Footer'; import Header from './components/Header'; im...
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter, Route } from 'react-router-dom'; import './styles/index.css'; import Background from './components/Background'; import Footer from './components/Footer'; import Header from './components/Header'; import ScrollToTop from './components/S...
Fix instance reference in helper
Template.taggedCourses.onCreated(function(){ // Get reference to template instance var instance = this; // Accessing the Iron.controller to invoke getParams method of Iron Router. var router = Router.current(); // Getting Params of the URL instance.tag = router.params.tag; // Subscribe to courses tagge...
Template.taggedCourses.helpers({ 'courses': function () { return Courses.find().fetch(); }, 'tag': function () { // Get reference to template instance var instance = this; // Get tag from instance var tag = instance.tag; return tag; } }); Template.taggedCourses.o...
Use static imports for standard test utilities pr-link: Alluxio/alluxio#8985 change-id: cid-2520d114c17da815ef1c596fb55e0b9a64d7070d
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDI...
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDI...
Sort emissions in `froMEmissions` helper
import React from 'react' import ObservableView from './view' const isEmission = (obj) => ( typeof obj === 'object' && typeof obj.x === 'number' && obj.x === obj.x && obj.x > 0 && obj.d !== undefined && obj.d !== null ) const selectValue = obj => obj.x function fromEmissions(arr, end) { if (!Array.isAr...
import React from 'react' import ObservableView from './view' const isEmission = (obj) => ( typeof obj === 'object' && typeof obj.x === 'number' && obj.x === obj.x && obj.x > 0 && obj.d !== undefined && obj.d !== null ) const selectValue = obj => obj.x function fromEmissions(arr, end) { if (!Array.isAr...
Update - removed redundant constants from class
<?php /** * Copyright 2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "li...
<?php /** * Copyright 2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "li...
FIX bug in event creation
############################################################################## # # Copyright (C) 2018 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Nathan Fluckiger <nathan.fluckiger@hotmail.ch> # # The licence is in the file __manifest__.py # #########...
############################################################################## # # Copyright (C) 2018 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Nathan Fluckiger <nathan.fluckiger@hotmail.ch> # # The licence is in the file __manifest__.py # #########...
Use port from environment variable if specified
package main import ( "fmt" "io/ioutil" "log" "net/http" "os" "sort" ) func init() { log.SetOutput(os.Stdout) } func handler(w http.ResponseWriter, r *http.Request) { log.Println("Got", r.Method, "to:", r.URL) var keys []string for k := range r.Header { keys = append(keys, k) } sort.Strings(keys) lo...
package main import ( "fmt" "io/ioutil" "log" "net/http" "os" "sort" ) func init() { log.SetOutput(os.Stdout) } func handler(w http.ResponseWriter, r *http.Request) { log.Println("Got", r.Method, "to:", r.URL) var keys []string for k := range r.Header { keys = append(keys, k) } sort.Strings(keys) lo...
Add array sort for node 0.8
var dirGlob = require('../../../lib/fs/dir-glob'); require('chai').should(); describe('lib', function () { describe('fs', function () { describe('dir-glob', function () { var globSync; beforeEach(function () { globSync = dirGlob.globSync; }); ...
var dirGlob = require('../../../lib/fs/dir-glob'); require('chai').should(); describe('lib', function () { describe('fs', function () { describe('dir-glob', function () { var globSync; beforeEach(function () { globSync = dirGlob.globSync; }); ...
Use session middleware before mounting grant
var koa = require('koa') , router = require('koa-router') , mount = require('koa-mount') , bodyParser = require('koa-bodyparser') , koaqs = require('koa-qs') , session = require('koa-session') , accesslog = require('koa-accesslog') var Grant = require('grant-koa') , grant = new Grant(require('./config.j...
var koa = require('koa') , router = require('koa-router') , mount = require('koa-mount') , bodyParser = require('koa-bodyparser') , koaqs = require('koa-qs') , session = require('koa-session') , accesslog = require('koa-accesslog') var Grant = require('grant-koa') , grant = new Grant(require('./config.j...
Refactor server and add simple debug mode
var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io')(server); var midi = require('midi'); var debug = false; var httpPort = 80; var midiPort = 1; // Midi Stuff // Set up a new input. var input = new midi.input(); var output = new midi.out...
var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io')(server); var midi = require('midi'); var port = 80; // Midi Stuff // Set up a new input. var input = new midi.input(); var output = new midi.output(); // Get the name of a specified in...
Reformat & move comment checking stuff to subclass.
<?php namespace Gothick\AkismetClient; class ClientResult { const PRO_TIP_HEADER = 'X-akismet-pro-tip'; /** * Raw string we got back from the Akismet API as an answer * @var string */ protected $raw_result; /** * Akismet's X-akismet-pro-tip header, which sometimes has * useful extra information. * @...
<?php namespace Gothick\AkismetClient; class ClientResult { const PRO_TIP_HEADER = 'X-akismet-pro-tip'; private $raw_result; private $pro_tip; public function __construct(\GuzzleHttp\Psr7\Response $response) { if ($response->getStatusCode() != 200) { // Our clients...
Add GraphQL schema description for page_size for deleteMany and updateMany
'use strict'; const { GraphQLInt, GraphQLString } = require('graphql'); // Pagination arguments const paginationActionTypes = ['find', 'update', 'delete']; const fullPaginationActionTypes = ['find']; const getPaginationArgument = function ({ action: { actionType, multiple }, defaultPageSize, maxPageSize }) { // O...
'use strict'; const { GraphQLInt, GraphQLString } = require('graphql'); // Pagination arguments const paginationActionTypes = ['find']; const getPaginationArgument = function ({ action: { actionType, multiple }, defaultPageSize, maxPageSize }) { // Only with safe operations that return an array, i.e. only with fi...
Add externals to stop rollup unresolved dependency warnings
import resolve from 'rollup-plugin-node-resolve'; import common from 'rollup-plugin-commonjs'; import json from 'rollup-plugin-json'; import replace from 'rollup-plugin-re'; import typescript from 'rollup-plugin-typescript'; export default { input: 'lib/index.ts', output: { file: 'dist/bundle.js', format: ...
import resolve from 'rollup-plugin-node-resolve'; import common from 'rollup-plugin-commonjs'; import json from 'rollup-plugin-json'; import replace from 'rollup-plugin-re'; import typescript from 'rollup-plugin-typescript'; export default { input: 'lib/index.ts', output: { file: 'dist/bundle.js', format: ...
Add options object to props
var React = require('react'); var data = require('./data.full.js'); var options = { rowHeight: 40 }; var ReactDataTable = React.createClass({ render: function() { var createCell = function createCell (key, value) { return <td key={key}>{value}</td>; }; var createRow = function createRow (row) {...
var React = require('react'); var data = require('./data.full.js'); var ReactDataTable = React.createClass({ render: function() { var createCell = function createCell (key, value) { return <td key={key}>{value}</td>; }; var createRow = function createRow (row) { return ( <tr key={ro...
Switch to start_all_workers in RPC server This does the same as the logic present but it emits the registry callback event for resources.PROCESS AFTER_SPAWN that some plugins may be expecting. Change-Id: I6f9aeca753a5d3c0052f553a2ac46786ca113e1e Related-Bug: #1687896
#!/usr/bin/env python # Copyright 2011 VMware, 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 # #...
#!/usr/bin/env python # Copyright 2011 VMware, 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 # #...
Enable Apollo devtools in production
import React from "react"; import ReactDOM from "react-dom"; import { RoutingApp } from "./modules/RoutingApp"; import store from "./store"; import { Provider } from "react-redux"; import { STUY_SPEC_API_URL } from "./constants"; import { ApolloProvider } from "react-apollo"; import { ApolloClient } from "apollo-clien...
import React from "react"; import ReactDOM from "react-dom"; import { RoutingApp } from "./modules/RoutingApp"; import store from "./store"; import { Provider } from "react-redux"; import { STUY_SPEC_API_URL } from "./constants"; import { ApolloProvider } from "react-apollo"; import { ApolloClient } from "apollo-clien...
Update to current master. `IPython.notebook.notebook_path` now returns the complete path including the notebook name.
// convert current notebook to html by calling "ipython nbconvert" and open static html file in new tab define([ 'base/js/namespace', 'jquery', ], function(IPython, $) { "use strict"; if (IPython.version[0] != 3) { console.log("This extension requires IPython 3.x") return } var nb...
// convert current notebook to html by calling "ipython nbconvert" and open static html file in new tab "using strict"; nbconvertPrintView = function(){ var kernel = IPython.notebook.kernel; var name = IPython.notebook.notebook_name; var path = IPython.notebook.notebook_path; if (path.length > ...
Add SNS topic for event NewCorsSiteRequestReceived
from amazonia.classes.sns import SNS from troposphere import Ref, Join, cloudwatch from troposphere.sns import Topic, Subscription def user_registration_topic(emails): return topic("UserRegistrationReceived", emails) def new_cors_site_request_received_topic(emails): return topic("NewCorsSiteRequestReceived",...
from amazonia.classes.sns import SNS from troposphere import Ref, Join, cloudwatch from troposphere.sns import Topic, Subscription def user_registration_topic(emails): return topic("UserRegistrationReceived", emails) def topic(topic_title, emails): topic = Topic(topic_title, DisplayName=Join("", ...
Fix version number to be higher
from setuptools import setup with open("README.md", "r") as fh: long_description = fh.read() setup( name = 'invokust', version = '0.71', author = 'Max Williams', author_email = 'futuresharks@gmail.com', description = 'A small wrapper for locust to allow running load tests from within Python or...
from setuptools import setup with open("README.md", "r") as fh: long_description = fh.read() setup( name = 'invokust', version = '0.7', author = 'Max Williams', author_email = 'futuresharks@gmail.com', description = 'A small wrapper for locust to allow running load tests from within Python or ...
Switch from "display:none" to "visibility:hidden". That way the page layout won't be affected but it will still be hidden.
(function () { "use strict"; var settings, visibility; if (window !== window.top) { return; } safari.self.tab.dispatchMessage('getSettings'); safari.self.addEventListener('message', function (event) { if (event.name === 'settings') { settings = event.message; ...
(function () { "use strict"; var settings, display; if (window !== window.top) { return; } safari.self.tab.dispatchMessage('getSettings'); safari.self.addEventListener('message', function (event) { if (event.name === 'settings') { settings = event.message; ...
Fix path for static files
package webserver import ( "log" "github.com/gin-gonic/contrib/static" "github.com/gin-gonic/gin" cors "github.com/tommy351/gin-cors" ) func Run(listen string) { gin.SetMode(gin.DebugMode) r := gin.New() r.Use(gin.Recovery()) r.Use(cors.Middleware(cors.Options{ AllowOrigins: []string{"*"}, AllowHeaders:...
package webserver import ( "log" "github.com/gin-gonic/contrib/static" "github.com/gin-gonic/gin" cors "github.com/tommy351/gin-cors" ) func Run(listen string) { gin.SetMode(gin.DebugMode) r := gin.New() r.Use(gin.Recovery()) r.Use(cors.Middleware(cors.Options{ AllowOrigins: []string{"*"}, AllowHeaders:...
Handle greasemonkey matching differently than ext
// ==UserScript== // @name Bring Stars Back (Netflix) // @namespace theinternetftw.com // @include https://www.netflix.com/ // @include https://www.netflix.com/browse // @include https://www.netflix.com/browse/* // @include https://www.netflix.com/title/* // @version 1.0.4 // @grant G...
// ==UserScript== // @name Bring Stars Back (Netflix) // @namespace theinternetftw.com // @include https://www.netflix.com/ // @include https://www.netflix.com/browse/* // @include https://www.netflix.com/title/* // @version 1.0.4 // @grant GM_xmlhttpRequest // @grant GM_setValue //...
Fix: Add encoding line for Python 3
# -*- coding: utf-8 -*- import sys import os import operator sys.path.insert(1, os.path.abspath('..')) from wsinfo import Info cnt = 0 max_cnt = 100 servers = {} with open("urls.txt", "r") as f: for url in f.readlines(): url = url[:-1] try: w = Info(url) if w.server != "":...
import sys import os import operator sys.path.insert(1, os.path.abspath('..')) from wsinfo import Info cnt = 0 max_cnt = 100 servers = {} with open("urls.txt", "r") as f: for url in f.readlines(): url = url[:-1] try: w = Info(url) if w.server != "": if not w...
Change the application name to 'Check Forbidden'
''' cd dropbox/codes/check_forbidden py -3.4 setup.py py2exe Libraries used: import tkinter import tkinter.filedialog import csv import os import re from time import sleep import zipfile ''' from distutils.core import setup import py2exe setup( console=[{'author': 'Shun Sakurai', ...
''' cd dropbox/codes/check_forbidden py -3.4 setup.py py2exe Libraries used: import tkinter import tkinter.filedialog import csv import os import re from time import sleep import zipfile ''' from distutils.core import setup import py2exe setup( console=[{'author': 'Shun Sakurai', ...
Move Author Managers into an abstract base class Copying of the default manager causes the source model to become poluted. To supply additional managers without replacing the default manager, the Django docs recommend inheriting from an abstract base class. https://docs.djangoproject.com/en/dev/topics/db/models/#prox...
"""Author model for Zinnia""" from django.db import models from django.contrib.auth import get_user_model from django.utils.encoding import python_2_unicode_compatible from zinnia.managers import entries_published from zinnia.managers import EntryRelatedPublishedManager class AuthorManagers(models.Model): publish...
"""Author model for Zinnia""" from django.db import models from django.contrib.auth import get_user_model from django.utils.encoding import python_2_unicode_compatible from zinnia.managers import entries_published from zinnia.managers import EntryRelatedPublishedManager @python_2_unicode_compatible class Author(get_...
Revert "Fix missing prepending extension" This reverts commit fa787a65bf64820654b6b403f1a75a8772e6c56a.
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use PHPUnit\Framework\TestCase; use So...
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use PHPUnit\Framework\TestCase; use So...
Increase timeout to improve test consistency
/* eslint-disable no-console */ const { ServiceBroker, Transporters: { AMQP: AmqpTransport } } = require("../../../.."); const AMQP_URL = process.env.AMQP_URI || "amqp://guest:guest@localhost:5672"; const amqpTransporter = new AmqpTransport(AMQP_URL); const broker = new ServiceBroker({ nodeID: "slow-nodeID", logg...
/* eslint-disable no-console */ const { ServiceBroker, Transporters: { AMQP: AmqpTransport } } = require("../../../.."); const AMQP_URL = process.env.AMQP_URI || "amqp://guest:guest@localhost:5672"; const amqpTransporter = new AmqpTransport(AMQP_URL); const broker = new ServiceBroker({ nodeID: "slow-nodeID", logg...
Remove explicit OT dep; we get it via basictracer
from setuptools import setup, find_packages setup( name='lightstep', version='2.2.0', description='LightStep Python OpenTracing Implementation', long_description='', author='LightStep', license='', install_requires=['thrift==0.9.2', 'jsonpickle', ...
from setuptools import setup, find_packages setup( name='lightstep', version='2.2.0', description='LightStep Python OpenTracing Implementation', long_description='', author='LightStep', license='', install_requires=['thrift==0.9.2', 'jsonpickle', ...
Fix StringStream to conform to latest pypy Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
from rpython.rlib.streamio import Stream, StreamError class StringStream(Stream): def __init__(self, string): self._string = string self.pos = 0 self.max = len(string) - 1 def write(self, data): raise StreamError("StringStream is not writable") def truncate(self, ...
from rpython.rlib.streamio import Stream, StreamError class StringStream(Stream): def __init__(self, string): self._string = string self.pos = 0 self.max = len(string) - 1 def write(self, data): raise StreamError("StringStream is not writable") def truncate(self, si...
Fix bug in migration script
"""Added column 'weight' to Banner, Logo and Background. Revision ID: 587c89cfa8ea Revises: 2c0bfc379e01 Create Date: 2012-05-11 14:36:15.518757 """ # downgrade revision identifier, used by Alembic. revision = '587c89cfa8ea' down_revision = '2c0bfc379e01' from alembic import op import sqlalchemy as sa def upgrade...
"""Added column 'weight' to Banner, Logo and Background. Revision ID: 587c89cfa8ea Revises: 2c0bfc379e01 Create Date: 2012-05-11 14:36:15.518757 """ # downgrade revision identifier, used by Alembic. revision = '587c89cfa8ea' down_revision = '2c0bfc379e01' from alembic import op import sqlalchemy as sa def upgrade...
Remove /submit endpoint from UI blueprint for now
# -*- coding: utf-8 -*- # import nacl.exceptions # import nacl.signing from flask import Blueprint, current_app, render_template # from nacl.encoding import URLSafeBase64Encoder # from nacl.signing import VerifyKey __all__ = [ 'ui', ] ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Show the u...
# -*- coding: utf-8 -*- import base64 import json from nacl.encoding import URLSafeBase64Encoder import nacl.exceptions import nacl.signing from flask import Blueprint, abort, current_app, render_template, request from nacl.signing import VerifyKey __all__ = [ 'ui', ] ui = Blueprint('ui', __name__) @ui.route(...
Add UpAllCommand to Mongrate application.
<?php namespace Mongrate\MongrateBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\Console\Application; class MongrateBundle extends Bundle { public function registerCommands(Application $application) { $config = $application->getKernel() ->getContainer() ...
<?php namespace Mongrate\MongrateBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\Console\Application; class MongrateBundle extends Bundle { public function registerCommands(Application $application) { $config = $application->getKernel() ->getContainer() ...
Remove unnecessary properties from index
package io.georocket.index.generic; import java.util.HashMap; import java.util.Map; import io.georocket.index.xml.MetaIndexer; import io.georocket.storage.ChunkMeta; import io.georocket.storage.IndexMeta; /** * Default implementation of {@link MetaIndexer} that extracts generic * attributes from chunk metadata and...
package io.georocket.index.generic; import java.util.HashMap; import java.util.Map; import io.georocket.index.xml.MetaIndexer; import io.georocket.storage.ChunkMeta; import io.georocket.storage.IndexMeta; /** * Default implementation of {@link MetaIndexer} that extracts generic * attributes from chunk metadata and...
Convert permission IDs into strings
<?php namespace Flarum\Core\Groups; use Flarum\Core\Model; use Illuminate\Database\Eloquent\Builder; /** * @todo document database columns with @property */ class Permission extends Model { /** * {@inheritdoc} */ protected $table = 'permissions'; /** * Define the relationship with the gr...
<?php namespace Flarum\Core\Groups; use Flarum\Core\Model; use Illuminate\Database\Eloquent\Builder; /** * @todo document database columns with @property */ class Permission extends Model { /** * {@inheritdoc} */ protected $table = 'permissions'; /** * Define the relationship with the gr...
Apply votes quietly every 5 seconds
var countVotes = function () { "use strict"; // find votes for object var deltaVotesQuery = { delta: { $exists: true } }; var deltaVotes = Votes.find(deltaVotesQuery).fetch(); var voteTable = {}; // count how many votes each object has _.forEach(deltaVotes, function (vote) { var p...
var countVotes = function () { "use strict"; // find votes for object var deltaVotesQuery = { delta: { $exists: true } }; var deltaVotes = Votes.find(deltaVotesQuery).fetch(); var voteTable = {}; // count how many votes each object has _.forEach(deltaVotes, function (vote) { var p...
Add a bit more info about rational surfaces
import sqlite3 conn = sqlite3.connect('surfaces.db') c = conn.cursor() c.execute('''CREATE TABLE bibliography ( kdim INT, pg INT, q INT, K2 INT, chi INT, e INT, h11 INT, sp INT, ref TEXT ); ''') rationalsurfaces = [(-1, 0, 0, 9, 3, 1, 0, 7, '''The projective plane, birational to the Hirzebruch surface...
import sqlite3 conn = sqlite3.connect('surfaces.db') c = conn.cursor() c.execute('''CREATE TABLE bibliography ( kdim INT, pg INT, q INT, K2 INT, chi INT, e INT, h11 INT, sp INT, ref TEXT ); ''') rationalsurfaces = [(-1, 0, 0, "NULL", "NULL", "NULL", 0, 4, '''The projective plane, birational to the Hir...
Allow to render layout resources as smarty templates
<?php class CM_Response_Resource_Layout extends CM_Response_Resource_Abstract { protected function _process() { $content = null; $mimeType = null; if ($pathRaw = $this->getRender()->getLayoutPath('resource/' . $this->getRequest()->getPath(), null, true, false)) { $file = new C...
<?php class CM_Response_Resource_Layout extends CM_Response_Resource_Abstract { protected function _process() { $file = null; if ($path = $this->getRender()->getLayoutPath('resource/' . $this->getRequest()->getPath(), null, true, false)) { $file = new CM_File($path); } ...
Make directional light gizmo invisible
import M_Gizmo from './M_Gizmo'; import Arrow from '../../../low_level/primitives/Arrow'; import ClassicMaterial from '../../../low_level/materials/ClassicMaterial'; import M_Mesh from '../meshes/M_Mesh'; import Vector4 from '../../../low_level/math/Vector4'; export default class M_DirectionalLightGizmo extends M_Gizm...
import M_Gizmo from './M_Gizmo'; import Arrow from '../../../low_level/primitives/Arrow'; import ClassicMaterial from '../../../low_level/materials/ClassicMaterial'; import M_Mesh from '../meshes/M_Mesh'; import Vector4 from '../../../low_level/math/Vector4'; export default class M_DirectionalLightGizmo extends M_Gizm...
[Bitbay] Use compact JSON instead of replacing whitespaces in String
package org.knowm.xchange.bitbay.v3.service; import java.io.IOException; import java.util.UUID; import org.knowm.xchange.Exchange; import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTrades; import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTradesQuery; import org.knowm.xchange.exceptions.ExchangeException; im...
package org.knowm.xchange.bitbay.v3.service; import java.io.IOException; import java.util.UUID; import java.util.regex.Pattern; import org.knowm.xchange.Exchange; import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTrades; import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTradesQuery; import org.knowm.xchange....
Add tailing / to APT_REPO_BASE_URL
# # Copyright 2012 Cisco Systems, Inc. # # Author: Soren Hansen <sorhanse@cisco.com> # # 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...
# # Copyright 2012 Cisco Systems, Inc. # # Author: Soren Hansen <sorhanse@cisco.com> # # 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...
Update database close timeout value.
import thread import time from django.db import close_old_connections class DatabaseConnectionMaintainer(object): DB_TIMEOUT_SECONDS = 5*60 def __init__(self): self.clients = set() # self.device_to_protocol = {} self.is_recent_db_change_occurred = False self.delay_and_execute...
import thread import time from django.db import close_old_connections class DatabaseConnectionMaintainer(object): def __init__(self): self.clients = set() # self.device_to_protocol = {} self.is_recent_db_change_occurred = False self.delay_and_execute(3600, self.close_db_connection...
Fix typo in the file header.
<?php /** * Class Google\Site_Kit\Core\Assets\External\GoogleCharts * * @package Google\Site_Kit * @copyright 2020 Google LLC * @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://sitekit.withgoogle.com */ namespace Google\Site_Kit\Core\Assets\External; use Google\S...
<?php /** * Class Google\Site_Kit\Core\Assets\External\GoogleCharts * * @package Google\Site_Kit * @copyright 2019 Google LLC * @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://sitekit.withgoogle.com */ namespace Google\Site_Kit\Core\Assets\External; use Google\S...
Insert main body of code into function
import pandas as pd import numpy as np import operator from sys import argv import os def extract( file_name ): with open(file_name) as f: for i,line in enumerate(f,1): if "SCN" in line: return i def main(lta_name): os.system('ltahdr -i'+ lta_name + '> lta_file.txt') di...
import pandas as pd import numpy as np import operator from sys import argv import os def extract( file_name ): with open(file_name) as f: for i,line in enumerate(f,1): if "SCN" in line: return i os.system('ltahdr -i'+ argv[1]+ '> lta_fi...
Add main_image to BlogPost API response.
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField from django.contrib.auth.models import User from fluent_contents.rendering import render_placeholder from rest_framework import serializers from .models import BlogPost class BlogPostContentsField(serializers.Field): def t...
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField from django.contrib.auth.models import User from fluent_contents.rendering import render_placeholder from rest_framework import serializers from .models import BlogPost class BlogPostContentsField(serializers.Field): def t...