text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix typo and missing acces modifier | <?php
namespace Qandidate\Toggle;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
/**
* A condition written as a symfony language expression that gets evaluated against the
* full context, allowing access to several keys of the context in a single condition
*/
class ExpressionCondition extends Condit... | <?php
namespace Qandidate\Toggle;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
/**
* A condition written as a symfony language expression that gets evaluated against the
* full context, allowing access to several keys of the context in a single condition
*/
class ExpressionCondition extends Condit... |
Use new path name to Models for test case | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.opensim.view;
import java.io.File;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
/**
*
* @author Jingjing
*/
public class TestEnvironment {
private sta... | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.opensim.view;
import java.io.File;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
/**
*
* @author Jingjing
*/
public class TestEnvironment {
private sta... |
Make name more specific to avoid clash in repo | package test.ccn.security.access;
import java.util.SortedSet;
import junit.framework.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.parc.ccn.data.ContentName;
import com.parc.ccn.library.CCNLibrary;
import com.parc.ccn.library.EnumeratedNameList;
import com.parc.ccn.library.io.repo.Reposit... | package test.ccn.security.access;
import java.util.SortedSet;
import junit.framework.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.parc.ccn.data.ContentName;
import com.parc.ccn.library.CCNLibrary;
import com.parc.ccn.library.EnumeratedNameList;
import com.parc.ccn.library.io.repo.Reposit... |
Use the logic from sdc-login for zone lookup | /*
* pushit push hooks
*
* Right now, only contains functions that are run in variable expansion
*/
var child_process = require('child_process');
var util = require('util');
var common = require('./common');
var debug = common.debug;
var verbose = common.verbose;
/*
* Runs an ssh command on the remote host
*... | /*
* pushit push hooks
*
* Right now, only contains functions that are run in variable expansion
*/
var child_process = require('child_process');
var util = require('util');
var common = require('./common');
var debug = common.debug;
var verbose = common.verbose;
/*
* Runs an ssh command on the remote host
*... |
Change the Date format to String | package com.ice.av.sample.entity;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Info {
@SuppressWarnings("unused")
private static final Logger log = LoggerFactory.getLogger(Info.class);
private String info = "This is a test info...";
publ... | package com.ice.av.sample.entity;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Info {
@SuppressWarnings("unused")
private static final Logger log = LoggerFactory.getLogger(Info.class);
private String info = "This is a test info...";
publ... |
Change Autoload Third Party to Global Class | <?php
function ThirdPartyAutoload($class) {
$class_array = explode('\\', $class);
//if (count($class_array)>1) {
//if ($class_array[0] == 'ThirdParty') {
if (isset($class_array[1]))
$file_load = \Kecik\Config::get('path.third_party').'/'.$class_array[0].'/'.$class_array[1].'.php';
else
$file_load ... | <?php
class ThirdParty {
public static function init() {
spl_autoload_register(array(self, '::autoload'), true, true);
}
public static function autoload($class) {
$class_array = explode('\\', $class);
if (count($class_array)>1) {
if ($class_array[0] == 'ThirdParty') {
$file_load = Config::get('path.... |
Add content type text/html to response | import falcon
import template
def get_paragraphs(pathname: str) -> list:
result = []
with open(pathname) as f:
for line in f.readlines():
if line != '\n':
result.append(line[:-1])
return result
class BooksResource:
def on_get(self, req, resp):
resp.status ... | import falcon
import template
def get_paragraphs(pathname: str) -> list:
result = []
with open(pathname) as f:
for line in f.readlines():
if line != '\n':
result.append(line[:-1])
return result
class BooksResource:
def on_get(self, req, resp):
resp.status ... |
Fix the missing getter for proper Jackson desserialization of truffle compilation result | package org.adridadou.ethereum.propeller.solidity;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.adridadou.ethereum.propeller.solidity.abi.AbiEntry;
import org.adridadou.ethereum.propeller.values.EthData;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Truff... | package org.adridadou.ethereum.propeller.solidity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.adridadou.ethereum.propeller.solidity.abi.AbiEntry;
import org.adridadou.ethereum.propeller.values.EthData;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Truff... |
Set self.build_flow before calling the super __init__ method | from cumulusci.core.config import YamlGlobalConfig
from cumulusci.core.config import YamlProjectConfig
class MrbelvedereProjectConfig(YamlProjectConfig):
def __init__(self, global_config_obj, build_flow):
self.build_flow = build_flow
super(MrbelvedereProjectConfig, self).__init__(global_config_obj)... | from cumulusci.core.config import YamlGlobalConfig
from cumulusci.core.config import YamlProjectConfig
class MrbelvedereProjectConfig(YamlProjectConfig):
def __init__(self, global_config_obj, build_flow):
super(MrbelvedereProjectConfig, self).__init__(global_config_obj)
self.build_flow = build_flow... |
Add language support in assets helper | <?php
class Kwf_View_Helper_Assets
{
public function assets($assetsPackage, $language = null, $subroot = null)
{
if (!$language) $language = Kwf_Trl::getInstance()->getTargetLanguage();
$ev = new Kwf_Events_Event_CreateAssetsPackageUrls(get_class($this), $assetsPackage, $subroot);
Kwf_E... | <?php
class Kwf_View_Helper_Assets
{
public function assets($assetsPackage, $language = null, $subroot = null)
{
if (!$language) $language = Kwf_Trl::getInstance()->getTargetLanguage();
$ev = new Kwf_Events_Event_CreateAssetsPackageUrls(get_class($this), $assetsPackage, $subroot);
Kwf_E... |
Use .state instead of .is_online to keep internal state | import glib
import dbus
from dbus.mainloop.glib import DBusGMainLoop
from pyee import EventEmitter
import logbook
logger = logbook.Logger('connman-dispatcher')
__all__ = ['detector']
def property_changed(_, message):
if message.get_member() == "PropertyChanged":
_, state = message.get_args_list()
... | import glib
import dbus
from dbus.mainloop.glib import DBusGMainLoop
from pyee import EventEmitter
import logbook
logger = logbook.Logger('connman-dispatcher')
__all__ = ['detector']
def property_changed(_, message):
if message.get_member() == "PropertyChanged":
_, state = message.get_args_list()
... |
Change the way we retrieve statistics | 'use strict';
const config = require(`${__dirname}/../config/init`);
/**
* makeAllRowRequestBody(str)
* @param string field Field to query parameters from.
* @param string from Date to query results from.
* @param string to Date to query results to.
* @return object Request to be performed body.
*/
exports.make... | 'use strict';
const config = require(`${__dirname}/../config/init`);
/**
* makeAllRowRequestBody(str)
* @param string field Field to query parameters from.
* @param string from Date to query results from.
* @param string to Date to query results to.
* @return object Request to be performed body.
*/
exports.make... |
Use mv command instead of os.Rename because avoid invalid cross-device link error. | package main
import (
"os"
"os/exec"
"path"
"path/filepath"
)
func newFileStorage(params *params) storager {
return &fileStorage{params}
}
type fileStorage struct {
params *params
}
func (f fileStorage) isExist() bool {
if _, err := os.Stat(f.pathByParams()); err != nil {
return false
}
return true
}
fu... | package main
import (
"os"
"path"
"path/filepath"
)
func newFileStorage(params *params) storager {
return &fileStorage{params}
}
type fileStorage struct {
params *params
}
func (f fileStorage) isExist() bool {
if _, err := os.Stat(f.pathByParams()); err != nil {
return false
}
return true
}
func (f fileS... |
Fix pluralisation for missing keys | import i18next from 'i18next'
import t from './t'
// Formats a pluralized string
const tPlural = (messages, options = {}) => {
if (!Number.isInteger(options.count)) {
console.error('[react-globe] tPlural requires a integer "count" option')
return null
}
if (!messages.one || !messages.many) {
console... | import i18next from 'i18next'
import t from './t'
// Formats a pluralized string
const tPlural = (messages, options = {}) => {
if (!Number.isInteger(options.count)) {
console.error('[react-globe] tPlural requires a integer "count" option')
return null
}
if (!messages.one || !messages.many) {
console... |
Use copy instead of create | /*
Example usage:
var A = Class(function() {
var defaults = {
foo: 'cat',
bar: 'dum'
}
this.init = function(opts) {
opts = std.extend(opts, defaults)
this._foo = opts.foo
this._bar = opts.bar
}
this.getFoo = function() {
return this._foo
}
this.getBar = function() {
return th... | /*
Example usage:
var A = Class(function() {
var defaults = {
foo: 'cat',
bar: 'dum'
}
this.init = function(opts) {
opts = std.extend(opts, defaults)
this._foo = opts.foo
this._bar = opts.bar
}
this.getFoo = function() {
return this._foo
}
this.getBar = function() {
return th... |
Revert "Tweaked with header a bit"
This reverts commit b00daf557e643f477109164091778effed450b10. | <div class="bluewrap ue-header">
<div class="container" style="text-align: center;">
<div class="row">
<h1>
<span class="med-font" style="font-size: 72px;"><?php bloginfo("name") ?></span>
<br />
<?php bloginfo("description") ?>
</h1>
<... | <div class="bluewrap ue-header">
<div class="container" style="text-align: center;">
<div class="row">
<div>
<h1 class="med-font" style="font-size: 72px;">
<?php bloginfo("name") ?>
<br />
<small><?php bloginfo("description") ?></small>
... |
Reset landing page state only upon logout
This change prevents the signup and login page analytics events to be
fired erroneously. [Finishes #133219321] | 'use strict';
import { LOGOUT } from 'app/actions/auth';
import {
SET_PAGE_LOGIN_STATE,
SET_PAGE_SIGNUP_STATE,
SET_OVERRIDE_FRAME,
CLEAR_OVERRIDE_FRAME
} from 'app/actions/landingPage';
import { initialLPState } from 'app/constants';
export default function landingPageState(state = initialLPState, action) {
... | 'use strict';
import { API_LOGIN_SUCCESS, API_SIGNUP_SUCCESS } from 'app/actions/auth';
import {
SET_PAGE_LOGIN_STATE,
SET_PAGE_SIGNUP_STATE,
SET_OVERRIDE_FRAME,
CLEAR_OVERRIDE_FRAME
} from 'app/actions/landingPage';
import { initialLPState } from 'app/constants';
export default function landingPageState(stat... |
Add test for certain required locale keys | import test from "ava";
const fs = require("fs");
const path = require("path");
const localesPath = path.join(__dirname, "..", "locales");
const filenameRegex = /^[a-z][a-z](_[A-Z]+)*\.json$/;
test("locale files are valid", t => {
const filenames = fs.readdirSync(localesPath);
filenames.forEach(filename => {
... | import test from "ava";
const fs = require("fs");
const path = require("path");
const localesPath = path.join(__dirname, "..", "locales");
const filenameRegex = /^[a-z][a-z](_[A-Z]+)*\.json$/;
test("locale files are valid", t => {
const filenames = fs.readdirSync(localesPath);
filenames.forEach(filename => {
... |
Make allowSearch default to true | (function() {
'use strict';
var buttons = {
root: 'Home',
edit: 'Edit',
select: 'Select',
deselect: 'Deselect',
goToSubitems: 'Go to subitems',
addSubitems: 'Add subitems',
addNode: 'Add node',
remove: 'Delete',
done: 'Done',
search: '›',
searchClear: '×',
... | (function() {
'use strict';
var buttons = {
root: 'Home',
edit: 'Edit',
select: 'Select',
deselect: 'Deselect',
goToSubitems: 'Go to subitems',
addSubitems: 'Add subitems',
addNode: 'Add node',
remove: 'Delete',
done: 'Done',
search: '›',
searchClear: '×',
... |
Reorganize imports (and bump version) | version_info = (0, 21, 0)
__version__ = '.'.join(map(str, version_info))
try:
from . import greenpool
from . import queue
from .hubs.trampoline import gyield
from .greenthread import sleep, spawn, spawn_n, spawn_after, kill
from .greenpool import GreenPool, GreenPile
from .timeout import Timeou... | version_info = (0, 20, 0)
__version__ = '.'.join(map(str, version_info))
try:
from . import greenthread
from . import greenpool
from . import queue
from . import timeout
from . import patcher
from . import server
from .hubs.trampoline import gyield
import greenlet
import pyuv_cffi ... |
Revert "Updated docstring for the file (mostly to diagnose/solve a git branch/merge problem)"
This reverts commit 3bcc40305193f3a46de63f4345812c9c2ee4c27f [formerly e2fe152ba58cfa853637bc5bd805adf0ae9617eb] [formerly 8e549c3bfb3650f08aca2ba204d2904e53aa4ab4].
Former-commit-id: e783ac4d5946403a9d608fe9dffa42212796b40... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Author: CEF PNM Team
# License: TBD
# Copyright (c) 2012
#from __future__ import print_function
"""
module __GenericPhysics__: Base class to define pore scale physics
==================================================================
.. warning:: The classes of this m... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Author: CEF PNM Team
# License: TBD
# Copyright (c) 2012
#from __future__ import print_function
"""
module __GenericPhysics__: Base class to define pore scale physics
==================================================================
.. warning:: The classes of this m... |
Fix 401 error for requests that require authentication | import base64
from .models import Device
class BasicAuthRemote(object):
def __init__(self, get_response):
self.get_response = get_response
def get_user_token(self, email, token):
try:
device = Device.objects.get(token=token)
if device.user.email != email:
... | import base64
from .models import Device
class BasicAuthRemote(object):
def __init__(self, get_response):
self.get_response = get_response
def get_user_token(self, email, token):
try:
device = Device.objects.get(token=token).select_related('user')
if device.user.email ... |
Allow passing User directly to get_change_metadata | import sys
from datetime import datetime
from random import randint
def get_client_ip(request):
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded_for:
ip = x_forwarded_for.split(",")[-1].strip()
else:
ip = request.META.get("REMOTE_ADDR")
return ip
def create_v... | import sys
from datetime import datetime
from random import randint
def get_client_ip(request):
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded_for:
ip = x_forwarded_for.split(",")[-1].strip()
else:
ip = request.META.get("REMOTE_ADDR")
return ip
def create_v... |
Set default application name to folder name
Fixes #1 | 'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var AppengineGenerator = module.exports = function AppengineGenerator(args, options, config) {
yeoman.generators.Base.apply(this, arguments);
this.args = args;
this.pkg = JSON.parse(this.readFileAsStr... | 'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var AppengineGenerator = module.exports = function AppengineGenerator(args, options, config) {
yeoman.generators.Base.apply(this, arguments);
this.args = args;
this.pkg = JSON.parse(this.readFileAsStr... |
Add classes to run ./configure | #
# Copyright (c) 2004 Specifix, Inc.
# All rights reserved
#
import os
import shutil
import util
class ManualConfigure:
def doBuild(self, dir):
os.system("cd %s; ./configure %s" % (dir, self.extraflags))
def __init__(self, extraflags=""):
self.extraflags = extraflags
class Configure:
def doBu... | #
# Copyright (c) 2004 Specifix, Inc.
# All rights reserved
#
import os
import shutil
import util
class Make:
def doBuild(self, dir):
os.system("cd %s; make" % dir)
class MakeInstall:
def doInstall(self, dir, root):
os.system("cd %s; make %s=%s install" % (dir, self.rootVar, root))
def __init__(self,... |
Update with some boilerplate comment header | package org.ensembl.healthcheck.testcase.funcgen;
import java.sql.Connection;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
/**
* @author mnuhn
*
* Abstract class providing method "getSpeciesAssemblyDataFileBasePath". This
* can be used to write checks for ... | package org.ensembl.healthcheck.testcase.funcgen;
import java.sql.Connection;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
public abstract class AbstractExternalFileUsingTestcase extends AbstractCoreDatabaseUsingTestCase {
protected String getSpeciesAssemblyD... |
Improve comments in example 2 | package main
import (
"fmt"
sci "github.com/samuell/scipipe"
)
func main() {
// Init barReplacer task
barReplacer := sci.Sh("sed 's/foo/bar/g' {i:foo2} > {o:bar}")
// Init function for generating output file pattern
barReplacer.OutPathFuncs["bar"] = func() string {
return barReplacer.GetInPath("foo2") + ".bar... | package main
import (
"fmt"
sci "github.com/samuell/scipipe"
)
func main() {
// Init barReplacer task
barReplacer := sci.Sh("sed 's/foo/bar/g' {i:foo2} > {o:bar}")
// Init function for generating output file pattern
barReplacer.OutPathFuncs["bar"] = func() string {
return barReplacer.GetInPath("foo2") + ".bar... |
Test profiles manager filterting method | import json
from nose.tools import eq_, raises
from mock import MagicMock, patch
from buffer.managers.profiles import Profiles
from buffer.models.profile import Profile, PATHS
mocked_response = {
'name': 'me',
'service': 'twiter',
'id': 1
}
def test_profiles_manager_all_method():
'''
Test basic profiles... | import json
from nose.tools import eq_, raises
from mock import MagicMock, patch
from buffer.managers.profiles import Profiles
from buffer.models.profile import PATHS
mocked_response = {
'name': 'me',
'service': 'twiter',
'id': 1
}
def test_profiles_manager_all_method():
'''
Test basic profiles retrievi... |
Fix bug where supersamples would not run without a supersamples.opt file | var fs = require('fs');
var path = require('path');
var cjson = require('cjson');
var _ = require('lodash');
var data = null;
var OPTS_FILE = 'supersamples.opts';
var DEFAULTS = {
output: './tmp',
renderer: {
name: 'html',
options: {
title: 'API Documentation',
baseUrl: 'http://localh... | var fs = require('fs');
var path = require('path');
var cjson = require('cjson');
var _ = require('lodash');
var data = null;
var OPTS_FILE = 'supersamples.opts';
var DEFAULTS = {
output: './tmp',
renderer: {
name: 'html',
options: {
title: 'API Documentation',
baseUrl: 'http://localh... |
Add more objects to cache in the service worker. | /**
* Created by Alvaro on 18/03/2017.
*/
// use a cacheName for cache versioning
var CACHE_NAME = 'static-v0.0.1';
var urlsToCache = [
'./',
'./js/main.js',
'./js/build/ObjectivesList.js',
'./js/vendor/react.min.js',
'./js/vendor/react-com.min.js'
];
// during the install phase you usually want to cache ... | /**
* Created by Alvaro on 18/03/2017.
*/
// use a cacheName for cache versioning
var CACHE_NAME = 'static-v1';
var urlsToCache = [
'./',
'./js/main.js'
];
// during the install phase you usually want to cache static assets
self.addEventListener('install', function(event) {
// once the SW is installed, go ahe... |
Move back to 0.9.0 for prod PyPi upload | import os
from setuptools import setup
setup(
name='algorithmia',
version='0.9.0',
description='Algorithmia Python Client',
long_description='Algorithmia Python Client is a client library for accessing Algorithmia from python code. This library also gets bundled with any Python algorithms in Algorithm... | import os
from setuptools import setup
setup(
name='algorithmia',
version='0.9.2',
description='Algorithmia Python Client',
long_description='Algorithmia Python Client is a client library for accessing Algorithmia from python code. This library also gets bundled with any Python algorithms in Algorithm... |
Add a couple unittest helpers | package unittest
import (
"testing"
)
type Any interface{}
func Failure(t *testing.T, msg ...Any) {
t.Fail()
t.Log(msg)
}
func CheckEqual(t *testing.T, x, y Any) {
if x != y {
Failure(t, x, "!=", y)
}
}
func CheckNotEqual(t *testing.T, x, y Any) {
if x == y {
Failure(t, x, "... | package unittest
import (
"testing"
)
type Any interface{}
func Failure(t *testing.T, msg ...Any) {
t.Fail()
t.Log(msg)
}
func CheckEqual(t *testing.T, x, y Any) {
if x != y {
Failure(t, x, "!=", y)
}
}
func CheckNotEqual(t *testing.T, x, y Any) {
if x == y {
Failure(t, x, "... |
Add a test for sysdig | import pytest
@pytest.mark.parametrize("name", [
("apt-file"),
("apt-transport-https"),
("atom"),
("blktrace"),
("ca-certificates"),
("chromium-browser"),
("cron"),
("curl"),
("diod"),
("docker-ce"),
("fonts-font-awesome"),
("git"),
("gnupg"),
("gnupg2"),
("gnupg-agent"),
("handbrake"),... | import pytest
@pytest.mark.parametrize("name", [
("apt-file"),
("apt-transport-https"),
("atom"),
("blktrace"),
("ca-certificates"),
("chromium-browser"),
("cron"),
("curl"),
("diod"),
("docker-ce"),
("fonts-font-awesome"),
("git"),
("gnupg"),
("gnupg2"),
("gnupg-agent"),
("handbrake"),... |
Add requests to dep list | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
:bug: Fix bug that personFinder used unfiltered list | import { isFunction } from '../../utils/is';
export default function getList(data, orm, inputValue) {
let retVal = [];
if (Array.isArray(orm.groups)) {
orm.groups.forEach(({ key, show }) => {
if (!(isFunction(show) && !show(inputValue) && (!isFunction(orm.filter) || orm.filter(inputValue)))... | export default function getList(data, orm, inputValue) {
let retVal = [];
if (Array.isArray(orm.groups)) {
orm.groups.forEach(({ key, show }) => {
if (!(typeof show === 'function' && !show(inputValue))) {
const list = data[key];
retVal = retVal.concat(list);
... |
Allow queue xml path to be set by prior extensions | package com.voodoodyne.gstrap.gae.test;
import com.voodoodyne.gstrap.test.util.TestInfoContextAdapter;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.Ext... | package com.voodoodyne.gstrap.gae.test;
import com.voodoodyne.gstrap.test.util.TestInfoContextAdapter;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.Ext... |
Set date to NULL if not present or invalid | <?php
function convert_mysql_date_to_php_date($date) {
if ($date == "0000-00-00") {
$date = "N/A";
} else {
$date = date('d-M-y', strtotime($date));
}
return $date;
}
function convert_str_date_to_mysql_date($date) {
if ($date == "N/A" || $date == "0") {
$date = NULL;
} e... | <?php
function convert_mysql_date_to_php_date($date) {
if ($date == "0000-00-00") {
$date = "N/A";
} else {
$date = date('d-M-y', strtotime($date));
}
return $date;
}
function convert_str_date_to_mysql_date($date) {
if ($date == "N/A" || $date == "0") {
$date = "0";
} el... |
Use an example component without transparent background. | import React from 'react';
import { Button } from '@storybook/components';
export default {
title: 'Core/Layout',
parameters: {
layout: 'padded',
},
};
export const InheritedLayout = () => <Button primary>a button</Button>;
export const PaddedLayout = () => <Button primary>a button</Button>;
PaddedLayout.s... | import React from 'react';
import { Button } from '@storybook/components';
export default {
title: 'Core/Layout',
parameters: {
layout: 'padded',
},
};
export const InheritedLayout = () => <Button>a button</Button>;
export const PaddedLayout = () => <Button>a button</Button>;
PaddedLayout.story = {
param... |
Improve Worker resistance against external code exceptions | import queue
import threading
class Worker:
def __init__(self, name: str, work_queue: queue.Queue, error_handler: callable):
self.name = name
self.queue = work_queue
# using an event instead of a boolean flag to avoid race conditions between threads
self.end = threading.Event()
... | import queue
import threading
class Worker:
def __init__(self, name: str, work_queue: queue.Queue, error_handler: callable):
self.name = name
self.queue = work_queue
# using an event instead of a boolean flag to avoid race conditions between threads
self.end = threading.Event()
... |
[FIX] Add meta data to Serializer | from django.urls import reverse
from rest_framework import serializers
from .models import Tafseer, TafseerText
class TafseerSerializer(serializers.ModelSerializer):
class Meta:
model = Tafseer
fields = ['id', 'name', 'language', 'author', 'book_name']
class TafseerTextSerializer(serializers.... | from django.urls import reverse
from rest_framework import serializers
from .models import Tafseer, TafseerText
class TafseerSerializer(serializers.ModelSerializer):
class Meta:
model = Tafseer
fields = ['id', 'name']
class TafseerTextSerializer(serializers.ModelSerializer):
tafseer_id = ... |
Fix regexp for rpm-related RPMs | package main
import (
"bufio"
"fmt"
"os"
"strings"
"regexp"
)
func main() {
reader := bufio.NewReader(os.Stdin)
re := regexp.MustCompile(`[^/]+\.rpm`)
for true {
line, _ := reader.ReadString('\n')
parts := strings.Split(line, " ")
url := parts[0]
... | package main
import (
"bufio"
"fmt"
"os"
"strings"
"regexp"
)
func main() {
reader := bufio.NewReader(os.Stdin)
re := regexp.MustCompile("[^/]+.rpm")
for true {
line, _ := reader.ReadString('\n')
parts := strings.Split(line, " ")
url := parts[0]
... |
Fix Add MW Deployment not working
The correct variable holding the reference to the file is `filePath`
instead of just `file`. | ManageIQ.angular.app.controller('mwAddDeploymentController', MwAddDeploymentController);
MwAddDeploymentController.$inject = ['$scope', '$http', 'miqService'];
function MwAddDeploymentController($scope, $http, miqService) {
$scope.$on('mwAddDeploymentEvent', function(event, data) {
var fd = new FormData();
... | ManageIQ.angular.app.controller('mwAddDeploymentController', MwAddDeploymentController);
MwAddDeploymentController.$inject = ['$scope', '$http', 'miqService'];
function MwAddDeploymentController($scope, $http, miqService) {
$scope.$on('mwAddDeploymentEvent', function(event, data) {
var fd = new FormData();
... |
Use default host when not specified | import sys
import argparse
from elasticsearch import Elasticsearch
from annotator.reindexer import Reindexer
description = """
Reindex an elasticsearch index.
WARNING: Documents that are created while reindexing may be lost!
"""
def main(argv):
argparser = argparse.ArgumentParser(description=description)
a... | import sys
import argparse
from elasticsearch import Elasticsearch
from annotator.reindexer import Reindexer
description = """
Reindex an elasticsearch index.
WARNING: Documents that are created while reindexing may be lost!
"""
def main(argv):
argparser = argparse.ArgumentParser(description=description)
a... |
Normalize all to spinal-case before other convertions. Added toSpaceCase. | var p = String.prototype;
// normalize always returns the string in spinal-case
function normalize(str) {
var arr = str.split(/[\s-_.]/);
if(arr.length > 1)
return arr.map(function(part) { return part.toLowerCase(); }).join('-');
else
return (str.charAt(0).toLowerCase() + str.slice(1)).replace(/([A-Z])/, '-$&'... | var p = String.prototype;
// Converts spinal-case, snake_case or space case to camelCase
p.toCamelCase = function(pascalCase) {
var str = this.toLowerCase();
var arr = str.split(/[\s-_]/);
for(var i = pascalCase ? 0 : 1; i < arr.length; i++) {
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}
retu... |
Rename DELETE request route to reflect prepended /collection | const express = require('express'),
router = express.Router({mergeParams: true}),
db = require('../models');
router.get('/', function(req, res, next) {
db.Emoticon.find({}).then(function(emoticons) {
res.render('emoticons/index', {emoticons});
}).catch(function(err) {
console.log(err);
})... | const express = require('express'),
router = express.Router({mergeParams: true}),
db = require('../models');
router.get('/', function(req, res, next) {
db.Emoticon.find({}).then(function(emoticons) {
res.render('emoticons/index', {emoticons});
}).catch(function(err) {
console.log(err);
})... |
Move remaining writeas/nerds/store funcs to web-core
Finishes the work started in #8. | package id
import (
"crypto/rand"
"fmt"
)
// GenerateRandomString creates a random string of characters of the given
// length from the given dictionary of possible characters.
//
// This example generates a hexadecimal string 6 characters long:
// GenerateRandomString("0123456789abcdef", 6)
func GenerateRandom... | package id
import (
"fmt"
"crypto/rand"
)
// GenerateRandomString creates a random string of characters of the given
// length from the given dictionary of possible characters.
//
// This example generates a hexadecimal string 6 characters long:
// GenerateRandomString("0123456789abcdef", 6)
func GenerateRandom... |
Fix jsx-runtime props not unmangled in tests | module.exports = function(api) {
api.cache(true);
const minify = String(process.env.MINIFY) === 'true';
const rename = {};
const mangle = require('./mangle.json');
for (let prop in mangle.props.props) {
let name = prop;
if (name[0] === '$') {
name = name.slice(1);
}
rename[name] = mangle.props.props[... | module.exports = function(api) {
api.cache(true);
const minify = String(process.env.MINIFY) === 'true';
const rename = {};
const mangle = require('./mangle.json');
for (let prop in mangle.props.props) {
let name = prop;
if (name[0] === '$') {
name = name.slice(1);
}
rename[name] = mangle.props.props[... |
Change argument name to stop probable name clash. | from django.contrib.contenttypes.models import ContentType
# USEFUL FUNCTIONS FOR FLUENT CONTENTS #############################################################
# Fluent Contents Helper Functions #################################################################
def create_content_instance(content_plugin_class, test_p... | from django.contrib.contenttypes.models import ContentType
# USEFUL FUNCTIONS FOR FLUENT CONTENTS #############################################################
# Fluent Contents Helper Functions #################################################################
def create_content_instance(content_plugin_class, page, ... |
Fix linter issue with test describe path | describe('test/test-harness-test.js', function() {
describe('globals', function() {
it('should expose should as a global', function() {
should.exist(should);
});
it('should expose sinon as a global', function() {
should.exist(sinon);
});
});
describe('should-sinon plugin', functio... | describe('test-harness', function() {
describe('globals', function() {
it('should expose should as a global', function() {
should.exist(should);
});
it('should expose sinon as a global', function() {
should.exist(sinon);
});
});
describe('should-sinon plugin', function() {
it... |
pywrap: Fix the loaders extend context after API change. | from ..utils import extend, add_swig_getmethod, add_swig_setmethod
from . import loaders_c
def extend_context(_context):
"""
Extends _context class with loader module methods for calling convenience.
Called once on loaders module inicialization.
"""
@extend(_context, name='load')
@staticmethod
def Load(... | from ..utils import extend, add_swig_getmethod, add_swig_setmethod
from . import loaders_c
def extend_context(_context):
"""
Extends _context class with loader module methods for calling convenience.
Called once on loaders module inicialization.
"""
@extend(_context, name='load')
@staticmethod
def Load(... |
Correct exit code on help | #!/usr/bin/env node
"use strict";
process.title = "oui";
var arg = process.argv[2],
oui = require("./"),
spin = require("char-spinner");
if (arg === "--update") {
var interval = spin();
oui.update(true, function (err) {
clearInterval(interval);
if (err) process.stdout.write(err + "\... | #!/usr/bin/env node
"use strict";
process.title = "oui";
var arg = process.argv[2],
oui = require("./"),
spin = require("char-spinner");
if (arg === "--update") {
var interval = spin();
oui.update(true, function (err) {
clearInterval(interval);
if (err) process.stdout.write(err + "\... |
Sort the result list to eliminate test flakiness. | package util
import (
"reflect"
"sort"
"testing"
)
func doubleIt(v reflect.Value) reflect.Value {
return reflect.ValueOf(v.Int() * 2)
}
func TestMergeChannel(t *testing.T) {
chan1 := make(chan reflect.Value)
chan2 := make(chan reflect.Value)
go func() {
chan1 <- reflect.ValueOf(1)
close(chan1)
}()
go ... | package util
import (
"reflect"
"testing"
)
func doubleIt(v reflect.Value) reflect.Value {
return reflect.ValueOf(v.Int() * 2)
}
func TestMergeChannel(t *testing.T) {
chan1 := make(chan reflect.Value)
chan2 := make(chan reflect.Value)
go func() {
chan1 <- reflect.ValueOf(1)
close(chan1)
}()
go func() {... |
Update method of loading creds
Changed the way of loading credentials from config.ini file to a json credentials file. | #!/usr/bin/env python
import json
from twython import Twython
#These values are all pulled from a file called 'config.ini'
#You can call yours myawesomebotconfig.ini or whatever else!
#Just remember to change it here
with open('creds.json') as f:
credentials = json.loads(f.read())
#SECURE YOUR CONFIG FILE - Don'... | #!/usr/bin/env python
from ConfigParser import SafeConfigParser
from twython import Twython
#These values are all pulled from a file called 'config.ini'
#You can call yours myawesomebotconfig.ini or whatever else!
#Just remember to change it here
config_file_name = 'config.ini'
#SECURE YOUR CONFIG FILE - Don't put ... |
Tweak the ring to make it actually useful | package xyz.brassgoggledcoders.modularutilities.modules.baubles;
import baubles.api.BaubleType;
import baubles.api.IBauble;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
public class ItemBloodboundRing e... | package xyz.brassgoggledcoders.modularutilities.modules.baubles;
import baubles.api.BaubleType;
import baubles.api.IBauble;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
public class ItemBloodboundRing e... |
Disable double addFile as legacy code has not been verified yet. | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.filedistribution;
import com.yahoo.config.FileReference;
import com.yahoo.config.application.api.FileRegistry;
import java.util.List;
public class CombinedLegac... | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.filedistribution;
import com.yahoo.config.FileReference;
import com.yahoo.config.application.api.FileRegistry;
import java.util.List;
public class CombinedLegac... |
Enable filtering ProposalVotes by reviewer. | from django.contrib import admin
from conf_site.reviews.models import (
ProposalFeedback,
ProposalNotification,
ProposalResult,
ProposalVote,
)
class ProposalInline(admin.StackedInline):
model = ProposalNotification.proposals.through
@admin.register(ProposalFeedback)
class ProposalFeedbackAdmin... | from django.contrib import admin
from conf_site.reviews.models import (
ProposalFeedback,
ProposalNotification,
ProposalResult,
ProposalVote,
)
class ProposalInline(admin.StackedInline):
model = ProposalNotification.proposals.through
@admin.register(ProposalFeedback)
class ProposalFeedbackAdmin... |
Add icon that works for linux apps also | const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const Menu = electron.Menu;
var menu = require('./menu');
var argv = require('optimist').argv;
let mainWindow;
app.on('ready', function() {
mainWindow = new BrowserWindow({
center: true,
... | const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const Menu = electron.Menu;
var menu = require('./menu');
var argv = require('optimist').argv;
let mainWindow;
app.on('ready', function() {
mainWindow = new BrowserWindow({
center: true,
... |
Add checks to get_app_instance to avoid Resolver404 even if namespace does not exists | # -*- coding: utf-8 -*-
from app_data import AppDataContainer, app_registry
from cms.apphook_pool import apphook_pool
from django.core.urlresolvers import resolve, Resolver404
def get_app_instance(request):
"""
Returns a tuple containing the current namespace and the AppHookConfig instance
:param request... | # -*- coding: utf-8 -*-
from app_data import AppDataContainer, app_registry
from cms.apphook_pool import apphook_pool
from django.core.urlresolvers import resolve
def get_app_instance(request):
"""
Returns a tuple containing the current namespace and the AppHookConfig instance
:param request: request obj... |
Fix Random Chance of Exception w/ customs | package main
import "math/rand"
import "time"
const DEFAULT_AD_CHANCE = 95
type Plug struct {
ID int
S3ID string
Owner string
ViewsRemaining int
Approved bool
PresignedURL string
}
type PlugList struct {
Data []string `form:"plugs[]"`
}
func (p Plug) IsDefault() bool {... | package main
import "math/rand"
import "time"
const DEFAULT_AD_CHANCE = 95
type Plug struct {
ID int
S3ID string
Owner string
ViewsRemaining int
Approved bool
PresignedURL string
}
type PlugList struct {
Data []string `form:"plugs[]"`
}
func (p Plug) IsDefault() bool {... |
Add DendriticLayerBase to init to ease experimentation | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2021, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2021, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... |
Fix typo (nil instaed of null) | function BetterContentController(){
this.listeners = {};
}
BetterContentController.prototype.registerListener = function(client, func) {
this.listeners[client] = func;
}
BetterContentController.prototype.removeListener = function(client) {
this.listeners[client] = null;
}
BetterContentController.prototype... | function BetterContentController(){
this.listeners = {};
}
BetterContentController.prototype.registerListener = function(client, func) {
this.listeners[client] = func;
}
BetterContentController.prototype.removeListener = function(client) {
this.listeners[client] = nil;
}
BetterContentController.prototype.... |
Change default HTTP timeout to 10 seconds | <?php
require 'check_setup.php';
require 'vendor/password.php';
require 'vendor/PicoTools/Dependency_Injection.php';
require 'vendor/PicoTools/Translator.php';
require 'vendor/PicoDb/Database.php';
require 'vendor/PicoDb/Table.php';
require 'schema.php';
require 'model.php';
const DB_VERSION = 8;
const APP_VERSIO... | <?php
require 'check_setup.php';
require 'vendor/password.php';
require 'vendor/PicoTools/Dependency_Injection.php';
require 'vendor/PicoTools/Translator.php';
require 'vendor/PicoDb/Database.php';
require 'vendor/PicoDb/Table.php';
require 'schema.php';
require 'model.php';
const DB_VERSION = 8;
const APP_VERSIO... |
Use ADVISER_DIR instead of getcwd(). | <?php namespace Adviser\Utilities;
class CommandRunnerUtilityTest extends \Adviser\Testing\UtilityTestCase
{
/**
* @test
*/
public function it_runs_a_terminal_command()
{
$output = (new CommandRunnerUtility())->run(ADVISER_DIR."/testing/utility-command.sh");
$this->assertInterna... | <?php namespace Adviser\Utilities;
class CommandRunnerUtilityTest extends \Adviser\Testing\UtilityTestCase
{
/**
* @test
*/
public function it_runs_a_terminal_command()
{
$output = (new CommandRunnerUtility())->run(getcwd()."/testing/utility-command.sh");
$this->assertInternalTy... |
Fix a problem that coverage decreased | <?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App;
class LoginTest extends TestCase
{
use DatabaseMigrations;
public function testBasic... | <?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App;
class LoginTest extends TestCase
{
use DatabaseMigrations;
public function testBasic... |
Fix doctest - not sure why it was failing on the quotation marks | import re
import os
import contextlib
from . import pipeline
@contextlib.contextmanager
def maintained_selection():
comp = pipeline.get_current_comp()
previous_selection = comp.GetToolList(True).values()
try:
yield
finally:
flow = comp.CurrentFrame.FlowView
flow.Select() # No... | import re
import os
import contextlib
from . import pipeline
@contextlib.contextmanager
def maintained_selection():
comp = pipeline.get_current_comp()
previous_selection = comp.GetToolList(True).values()
try:
yield
finally:
flow = comp.CurrentFrame.FlowView
flow.Select() # No... |
Add new function for relative paths. | /*jslint node: true*/
"use strict";
var fs = require('fs');
var path = require('path');
var S = require('string');
var options = require('./options.js');
var logging = require('./logging.js');
module.exports.uriToFilename = function(uri) {
var filename = path.join(options.fileBase, uri);
// Make sure filenam... | /*jslint node: true*/
"use strict";
var fs = require('fs');
var path = require('path');
var S = require('string');
var options = require('./options.js');
var logging = require('./logging.js');
module.exports.uriToFilename = function(uri) {
var filename = path.join(options.fileBase, uri);
// Make sure filenam... |
Fix exception on missing options object
If the JumpPointFinder constructor was not passed the options object there
was a ReferenceError. | /**
* @author aniero / https://github.com/aniero
*/
var DiagonalMovement = require('../core/DiagonalMovement');
var JPFNeverMoveDiagonally = require('./JPFNeverMoveDiagonally');
var JPFAlwaysMoveDiagonally = require('./JPFAlwaysMoveDiagonally');
var JPFMoveDiagonallyIfNoObstacles = require('./JPFMoveDiagonallyIfNoObs... | /**
* @author aniero / https://github.com/aniero
*/
var DiagonalMovement = require('../core/DiagonalMovement');
var JPFNeverMoveDiagonally = require('./JPFNeverMoveDiagonally');
var JPFAlwaysMoveDiagonally = require('./JPFAlwaysMoveDiagonally');
var JPFMoveDiagonallyIfNoObstacles = require('./JPFMoveDiagonallyIfNoObs... |
Fix unresolvable /lib/rogue path leftover by fixing merge conflicts | 'use strict';
/* eslint-disable global-require */
function start() {
const config = require('../config');
const logger = require('./logger');
const app = require('../app');
// Setup Gateway client.
require('./gateway').getClient();
// Start mongoose connection
require('../config/mongoose')(config.dbUri... | 'use strict';
/* eslint-disable global-require */
function start() {
const config = require('../config');
const logger = require('./logger');
const app = require('../app');
// Setup rogue client.
require('./rogue').getClient();
// Start mongoose connection
require('../config/mongoose')(config.dbUri);
... |
Use key fixture in boto tests. | #!/usr/bin/env python
import os
from tempdir import TempDir
import pytest
boto = pytest.importorskip('boto')
from simplekv.net.botostore import BotoStore
from basic_store import BasicStore
from url_store import UrlStore
from bucket_manager import boto_credentials, boto_bucket
@pytest.fixture(params=boto_credentia... | #!/usr/bin/env python
import os
from tempdir import TempDir
import pytest
boto = pytest.importorskip('boto')
from simplekv.net.botostore import BotoStore
from basic_store import BasicStore
from url_store import UrlStore
from bucket_manager import boto_credentials, boto_bucket
@pytest.fixture(params=boto_credentia... |
Use skipIfExists instead of true | /*
* grunt-contrib-internal
* http://gruntjs.com/
*
* Copyright (c) 2016 Tyler Kellen, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
var path = require('path');
grunt.registerTask('contrib-ci', 'Normalizes AppVeyor and Travis CI configs.', function(skipIf... | /*
* grunt-contrib-internal
* http://gruntjs.com/
*
* Copyright (c) 2016 Tyler Kellen, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
var path = require('path');
grunt.registerTask('contrib-ci', 'Normalizes AppVeyor and Travis CI configs.', function(skipIf... |
FIx warning and remove use of preventDefault on checkbox | import React from 'react'
export default class Prefs extends React.Component {
static propTypes = {
prefs: React.PropTypes.object.isRequired,
setPrefs: React.PropTypes.func.isRequired,
providerRefresh: React.PropTypes.func.isRequired,
}
setEnabled = this.setEnabled.bind(this)
handleRefresh = this.... | import React from 'react'
export default class Prefs extends React.Component {
static propTypes = {
prefs: React.PropTypes.object.isRequired,
setPrefs: React.PropTypes.func.isRequired,
providerRefresh: React.PropTypes.func.isRequired,
}
toggleEnabled = this.toggleEnabled.bind(this)
handleRefresh =... |
Fix IndexLink component without href value can't be a link | import React, {Component} from 'react'
import {IndexLink, Link} from 'react-router'
import styles from '../sass/Navbar'
class Navbar extends Component {
constructor() {
super()
}
render() {
return (
<nav className={styles.navbar}>
<IndexLink className={styles.li... | import React, {Component} from 'react'
import {IndexLink, Link} from 'react-router'
import styles from '../sass/Navbar'
class Navbar extends Component {
constructor() {
super()
}
render() {
return (
<nav className={styles.navbar}>
<IndexLink className={styles.li... |
Use custom logger on gevent>=1.1 | '''
This module provides some function to make running a webserver a little easier
'''
def gevent_run(app):
from gevent.wsgi import WSGIServer
import gevent.monkey
from werkzeug.debug import DebuggedApplication
gevent.monkey.patch_socket()
run_app = app
if app.config['DEBUG']:
run_app ... | '''
This module provides some function to make running a webserver a little easier
'''
def gevent_run(app):
from gevent.wsgi import WSGIServer
import gevent.monkey
from werkzeug.debug import DebuggedApplication
gevent.monkey.patch_socket()
run_app = app
if app.config['DEBUG']:
run_app ... |
Fix error al pulsar creditos
Se añade errors en la ruta de creditos... | var express = require('express');
var router = express.Router();
var quizController = require('../controllers/quiz_controller');
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Quiz', errors: []});
});
router.get('/author', function(req, res) {
res.render('author', { title:... | var express = require('express');
var router = express.Router();
var quizController = require('../controllers/quiz_controller');
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Quiz', errors: []});
});
router.get('/author', function(req, res) {
res.render('author', { title:... |
Configure redux-logger to be a bit prettier. | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyMiddleware, combineReducers, compose, createStore } from 'redux';
import { initializeCurrentLocation } from 'redux-little-router';
import { createLogger } from 'redux-logger';
import thunk from 'redux-thun... | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyMiddleware, combineReducers, compose, createStore } from 'redux';
import { initializeCurrentLocation } from 'redux-little-router';
import logger from 'redux-logger';
import thunk from 'redux-thunk';
impor... |
Send computeWorkflow message when tag is deselected | 'use strict';
/**
* @ngdoc function
* @name tagrefineryGuiApp.controller:WorkflowCtrl
* @description
* # WorkflowCtrl
* Controller of the tagrefineryGuiApp
*/
angular.module('tagrefineryGuiApp')
.controller('WorkflowCtrl', ["$scope", "socket", function ($scope, socket) {
var that = this;
// State vari... | 'use strict';
/**
* @ngdoc function
* @name tagrefineryGuiApp.controller:WorkflowCtrl
* @description
* # WorkflowCtrl
* Controller of the tagrefineryGuiApp
*/
angular.module('tagrefineryGuiApp')
.controller('WorkflowCtrl', ["$scope", "socket", function ($scope, socket) {
var that = this;
// State vari... |
Update test to reflect changing git codebase | import unittest
from pylons import c, g
from ming.orm import ThreadLocalORMSession
from pyforge.tests import helpers
from pyforge.lib import helpers as h
class TestGitApp(unittest.TestCase):
def setUp(self):
helpers.setup_basic_test()
helpers.setup_global_objects()
h.set_context('test',... | import unittest
from pylons import c, g
from ming.orm import ThreadLocalORMSession
from pyforge.tests import helpers
from pyforge.lib import helpers as h
class TestGitApp(unittest.TestCase):
def setUp(self):
helpers.setup_basic_test()
helpers.setup_global_objects()
h.set_context('test',... |
Add balancing for cleaver scripts. | exports.listeners = {
wield: function (l10n) {
return function (location, player, players) {
player.say('You ready the weighty cleaver.');
player.combat.addToHitMod({
name: 'cleaver ' + this.getUuid(),
effect: toHit => toHit + 1
});
player.combat.addToDodgeMod({
na... | exports.listeners = {
wield: function (l10n) {
return function (location, player, players) {
player.say('You ready the weighty cleaver.');
player.combat.addToHitMod({
name: 'cleaver ' + this.getUuid(),
effect: toHit => toHit + 1
});
}
},
remove: function (l10n) {
re... |
Add comment to test settings to advice disabling search indexing | import logging
from {{ project_name }}.settings import * # noqa
logging.disable(logging.CRITICAL)
DEBUG = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '{{ project_name }}',
'USER': 'postgres'
},
}
# Add middleware to add a meta tag with the re... | import logging
from {{ project_name }}.settings import * # noqa
logging.disable(logging.CRITICAL)
DEBUG = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '{{ project_name }}',
'USER': 'postgres'
},
}
# Add middleware to add a meta tag with the re... |
Add xspress3 to step-scan detector list | # vim: sw=4 ts=4 sts expandtab smarttab
# HXN step-scan configuration
import hxntools.scans
from bluesky.global_state import get_gs
gs = get_gs()
hxntools.scans.setup()
ct = hxntools.scans.count
ascan = hxntools.scans.absolute_scan
dscan = hxntools.scans.relative_scan
fermat = hxntools.scans.relative_fermat
spiral =... | # vim: sw=4 ts=4 sts expandtab smarttab
# HXN step-scan configuration
import hxntools.scans
from bluesky.global_state import get_gs
gs = get_gs()
hxntools.scans.setup()
ct = hxntools.scans.count
ascan = hxntools.scans.absolute_scan
dscan = hxntools.scans.relative_scan
fermat = hxntools.scans.relative_fermat
spiral =... |
Fix bug in launch-instances subcommand of ami-publisher. | package main
import (
"fmt"
"github.com/Symantec/Dominator/imagepublishers/amipublisher"
"github.com/Symantec/Dominator/lib/awsutil"
"github.com/Symantec/Dominator/lib/log"
"os"
"path"
)
func launchInstancesSubcommand(args []string, logger log.Logger) {
domImage := ""
if len(args) > 1 {
domImage = args[1]
... | package main
import (
"fmt"
"github.com/Symantec/Dominator/imagepublishers/amipublisher"
"github.com/Symantec/Dominator/lib/awsutil"
"github.com/Symantec/Dominator/lib/log"
"os"
"path"
)
func launchInstancesSubcommand(args []string, logger log.Logger) {
domImage := ""
if len(args) > 1 {
domImage = args[1]
... |
Fix edge-case with blank user agent in FastBoot
* Call the isMobile class with the current context to avoid leaking the global. | import Service from '@ember/service';
import { computed, get, set } from '@ember/object';
import { getOwner } from '@ember/application';
import { isBlank } from '@ember/utils';
import isMobile from 'ismobilejs';
/**
* The attributes returned by isMobile are accessible. However, they should be
* accessed using the `g... | import Service from '@ember/service';
import { computed, get, getProperties, set } from '@ember/object';
import { getOwner } from '@ember/application';
import { isBlank } from '@ember/utils';
import isMobile from 'ismobilejs';
export default Service.extend({
fastboot: computed(function() {
return getOwner(this)... |
Correct for None appearing in requirements list | #!/usr/bin/env python
"""
Install the packages you have listed in the requirements file you input as
first argument.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
import fileinput
import subprocess
from pip.req import parse_requirements
... | #!/usr/bin/env python
"""
Install the packages you have listed in the requirements file you input as
first argument.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
import fileinput
import subprocess
from pip.req import parse_requirements
... |
Fix issue with 'who' lagging behind user typing | "use strict"
import React from "react"
import StatusMessage from "./status-message"
import PollTable from "./poll-table"
import PollReport from "./poll-report"
import Nav from "./nav"
import throttle from "lodash/function/throttle"
// Declare here for global throttling
const updateWho = throttle((flux, who) => flux.... | "use strict"
import React from "react"
import StatusMessage from "./status-message"
import PollTable from "./poll-table"
import PollReport from "./poll-report"
import Nav from "./nav"
import throttle from "lodash/function/throttle"
// Declare here for global throttling
const updateWho = throttle((flux, who) => flux.... |
Send actual output to standard out instead of error. | package main
import (
"log"
"os"
"fmt"
"go/ast"
"go/parser"
"go/token"
)
func validator(name string, s *ast.StructType) {
fmt.Println(name)
for _, fld := range(s.Fields.List) {
nam := fld.Names[0].Name
typ := fld.Type.(*ast.Ident)
fmt.Printf("%s %s\n", nam, typ)
}
}
func main() {
log.SetFlags(0)
f... | package main
import (
"log"
"os"
"go/ast"
"go/parser"
"go/token"
)
func validator(name string, s *ast.StructType) {
log.Print(name)
for _, fld := range(s.Fields.List) {
nam := fld.Names[0].Name
typ := fld.Type.(*ast.Ident)
log.Printf("%s %s", nam, typ)
}
}
func main() {
log.SetFlags(0)
fs := token.... |
Apply the empty promise to the promise class | PromiseAllSync = {
extend: function(PromiseClass) {
var emptyPromise = PromiseClass.resolve || PromiseClass.when;
PromiseClass.allSync = function(collection, fn, unfn) {
var stack = [];
return collection.reduce(function(promise, item) {
return promise.then(function() {
var nextPr... | PromiseAllSync = {
extend: function(PromiseClass) {
PromiseClass.allSync = function(collection, fn, unfn) {
var stack = [];
return collection.reduce(function(promise, item) {
return promise.then(function() {
var nextPromise = fn ? fn(item) : item;
return nextPromise.then(fu... |
Switch to using Eimann's mirror to resolve jamendo track ids, due to jamendo downtime. | <?php
function resolve_external_url($url) {
if (substr($url, 0, 10) == 'jamendo://') {
return process_jamendo_url($url);
}
return $url;
}
function process_jamendo_url($url) {
if (substr($url, 10, 13) == 'track/stream/') {
$id = substr($url, 23);
return 'http://gigue.rrbone.net/' . $id . '.ogg2';
}
if (su... | <?php
function resolve_external_url($url) {
if (substr($url, 0, 10) == 'jamendo://') {
return process_jamendo_url($url);
}
return $url;
}
function process_jamendo_url($url) {
if (substr($url, 10, 13) == 'track/stream/') {
$id = substr($url, 23);
return 'http://api.jamendo.com/get2/stream/track/redirect/?id=... |
Remove public getProfile method to base controller | <?php
namespace base;
class Controller{
private $_views = array();
private $_res = null;
private $_req = null;
public $currentPath = null;
protected function getRequest()
{
return Request::getInstance();
}
protected function getResponse()
{
if(empty($this->_res)){
$this->_res = new Response();
... | <?php
namespace base;
class Controller{
private $_views = array();
private $_res = null;
private $_req = null;
public $currentPath = null;
protected function getRequest()
{
return Request::getInstance();
}
protected function getResponse()
{
if(empty($this->_res)){
$this->_res = new Response();
... |
Test getComponentName() should throw when nothing passed in | import React, { Component } from 'react';
import getComponentName from '../getComponentName';
/* eslint-disable */
class Foo extends Component {
render() {
return <div />;
}
}
function Bar() {
return <div />;
}
const OldComp = React.createClass({
render: function() {
return <div />;
... | import React, { Component } from 'react';
import getComponentName from '../getComponentName';
/* eslint-disable */
class Foo extends Component {
render() {
return <div />;
}
}
function Bar() {
return <div />;
}
const OldComp = React.createClass({
render: function() {
return <div />;
... |
Add client side user detail permission | (function() {
'use strict';
var app = angular.module('radar.users');
app.factory('UserPermission', ['AdminPermission', function(AdminPermission) {
return AdminPermission;
}]);
app.factory('UserInfoController', ['ModelDetailController', '$injector', 'UserPermission', function(ModelDetailController, $inj... | (function() {
'use strict';
var app = angular.module('radar.users');
app.factory('UserInfoController', ['ModelDetailController', '$injector', function(ModelDetailController, $injector) {
function UserInfoController($scope) {
var self = this;
$injector.invoke(ModelDetailController, self, {
... |
Remove run_hook from list of imported commands. | # -*- coding: utf-8 -*-
# Copyright (c) 2014-2019 Dontnod Entertainment
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use,... | # -*- coding: utf-8 -*-
# Copyright (c) 2014-2019 Dontnod Entertainment
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use,... |
Change from MySQL to SQLite3 | import os
import peewee
APP_DIR = os.path.dirname(__file__)
try:
import urlparse
import psycopg2
urlparse.uses_netloc.append('postgres')
url = urlparse.urlparse(os.environ["DATABASE_URL"])
database = peewee.PostgresqlDatabase(database=url.path[1:],
user=ur... | import os
import peewee
APP_DIR = os.path.dirname(__file__)
try:
import urlparse
import psycopg2
urlparse.uses_netloc.append('postgres')
url = urlparse.urlparse(os.environ["DATABASE_URL"])
database = peewee.PostgresqlDatabase(database=url.path[1:],
user=ur... |
Fix for zero arg constructor | package org.gwtbootstrap3.extras.slider.client.ui;
/*
* #%L
* GwtBootstrap3
* %%
* Copyright (C) 2013 GwtBootstrap3
* %%
* 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
*
* htt... | package org.gwtbootstrap3.extras.slider.client.ui;
/*
* #%L
* GwtBootstrap3
* %%
* Copyright (C) 2013 GwtBootstrap3
* %%
* 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
*
* htt... |
Remove unreachable code per `go vet` | package main
import (
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
"time"
)
func RunPeriodically(c *cli.Context) error {
log.SetFormatter(_makeFormatter(c.String("format")))
log.WithFields(log.Fields{
"appName": c.App.Name,
}).Info("Running periodically")
period := time.Duration(c.Int("period"... | package main
import (
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
"time"
)
func RunPeriodically(c *cli.Context) error {
log.SetFormatter(_makeFormatter(c.String("format")))
log.WithFields(log.Fields{
"appName": c.App.Name,
}).Info("Running periodically")
period := time.Duration(c.Int("period"... |
Increment port number with each execution | var RSVP = require('rsvp');
var request = RSVP.denodeify(require('request'));
var jsdom = require("jsdom").jsdom;
var express = require('express');
var FastBootServer = require('ember-fastboot-server');
var server = new FastBootServer({
distPath: 'fastboot-dist',
ui: {
writeLine: function() {
consol... | var RSVP = require('rsvp');
var request = RSVP.denodeify(require('request'));
var jsdom = require("jsdom").jsdom;
var express = require('express');
var FastBootServer = require('ember-fastboot-server');
var server = new FastBootServer({
distPath: 'fastboot-dist',
ui: {
writeLine: function() {
consol... |
Use global.datadir to obtain package files | 'use strict';
const path = require('path');
const fs = require('fs');
const jsontolua = require('../jsontolua');
const registry = require('../registry');
module.exports = function(req, res) {
req.params.version = req.params.version.replace(/^latest$/, '>=0.0.0');
registry.wrap(req.params.package)
... | 'use strict';
const path = require('path');
const fs = require('fs');
const jsontolua = require('../jsontolua');
const registry = require('../registry');
module.exports = function(req, res) {
req.params.version = req.params.version.replace(/^latest$/, '>=0.0.0');
registry.wrap(req.params.package)
... |
Remove old comment that no longer applies | # Copyright 2011-2012 Michael Garski (mgarski@mac.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-2.0
#
# Unless required by ap... | # Copyright 2011-2012 Michael Garski (mgarski@mac.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-2.0
#
# Unless required by ap... |
Add utility methods for yesterday's date | """class to convert datetime values"""
import datetime
class DatetimeConverter(object):
"""stuff"""
_EPOCH_0 = datetime.datetime(1970, 1, 1)
def __init__(self):
"""stuff"""
pass
@staticmethod
def get_tomorrow():
"""stuff"""
return datetime.datetime.today() + da... | """class to convert datetime values"""
import datetime
class DatetimeConverter(object):
"""stuff"""
_EPOCH_0 = datetime.datetime(1970, 1, 1)
def __init__(self):
"""stuff"""
pass
@staticmethod
def get_tomorrow():
"""stuff"""
return datetime.datetime.today() + da... |
Fix product_id filter on content delivery repos
The value should be an integer.
JIRA: PDC-1104 | #
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
import django_filters as filters
from pdc.apps.common.filters import MultiValueFilter, MultiIntFilter
from . import models
class RepoFilter(filters.FilterSet):
arch = MultiValueFilter(name='variant_arch__... | #
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
import django_filters as filters
from pdc.apps.common.filters import MultiValueFilter
from . import models
class RepoFilter(filters.FilterSet):
arch = MultiValueFilter(name='variant_arch__arch__name')
... |
Streamline the filesystem looping code. | #!/usr/bin/env python
import os
import sys
import subprocess
import getopt
class Checker:
def __init__(self, path):
if not os.path.isdir(path):
sys.exit(1);
self.path = os.path.realpath(path)
self.jobs = self.getExecutableFiles(self.path)
def getExecutableFiles(self,path)... | #!/usr/bin/env python
import os
import sys
import subprocess
import getopt
class Chdir:
def __init__(self, newPath):
self.savedPath = os.getcwd()
os.chdir(newPath)
class Checker:
def __init__(self, path):
self.path = path
def get_jobs(self):
Chdir(self.path)
jobs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.