text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Adjust post-stimulus waiting period setting | /**
* Settings configuration for jsPASAT
*/
var jsPASAT = {
// Pace of PASAT trial presentation
'TIMING_STIM_DISPLAY': 1000,
'TIMING_POST_STIM': 4000,
// Practice block stimuli
'PRACTICE_BLOCK_1_STIMULI': [9, 1, 3, 5, 2, 6],
'PRACTICE_BLOCK_2_STIMULI': [6, 4, 5, 7, 2, 8, 4, 5, 9, 3, 6, 9, 2, 7, 3, 8],
... | /**
* Settings configuration for jsPASAT
*/
var jsPASAT = {
// Pace of PASAT trial presentation
'TIMING_STIM_DISPLAY': 1000,
'TIMING_POST_STIM': 3000,
// Practice block stimuli
'PRACTICE_BLOCK_1_STIMULI': [9, 1, 3, 5, 2, 6],
'PRACTICE_BLOCK_2_STIMULI': [6, 4, 5, 7, 2, 8, 4, 5, 9, 3, 6, 9, 2, 7, 3, 8],
... |
Remove extra character from whitespace replacement | 'use strict';
/* Filters */
angular.module('myApp.filters', []).
filter('interpolate', ['version', function(version) {
return function(text) {
return String(text).replace(/\%VERSION\%/mg, version);
}
}])
.filter('mapUrl', function() {
return function(e) {
var str = "";
fo... | 'use strict';
/* Filters */
angular.module('myApp.filters', []).
filter('interpolate', ['version', function(version) {
return function(text) {
return String(text).replace(/\%VERSION\%/mg, version);
}
}])
.filter('mapUrl', function() {
return function(e) {
var str = "";
fo... |
Connect <Header /> to the router to subscribe to location updates | import { connect } from 'react-redux';
import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router';
import { loggedOut } from '~client/actions/login';
import { getLoggedIn } from '~client/selectors/app';
import { getUnsaved } from '~client/selectors/api';
import AppLogo fro... | import { connect } from 'react-redux';
import React from 'react';
import PropTypes from 'prop-types';
import { loggedOut } from '~client/actions/login';
import { getLoggedIn } from '~client/selectors/app';
import { getUnsaved } from '~client/selectors/api';
import AppLogo from '~client/components/AppLogo';
import Navb... |
Add filters to snapshot preview | #!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var chalk = require('chalk')
var filter = process.argv[2]
function show (result) {
Object.keys(result).sort().reverse().forEach(file => {
var test = file.replace(/\.test\.js\.snap$/, '')
result[file].split('exports[`')
.filter(str ... | #!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var chalk = require('chalk')
function show (result) {
Object.keys(result).sort().reverse().forEach(file => {
var test = file.replace(/\.test\.js\.snap$/, '')
result[file].split('exports[`')
.filter(str => str.indexOf('// ') !== 0)
... |
Bz1178769: Fix JBDS import errors for greeter quickstart | /*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* y... | /*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* y... |
Fix a bad reference value in the Internal Note model. | var keystone = require('keystone'),
Types = keystone.Field.Types;
// Create model. Additional options allow menu name to be used what auto-generating URLs
var InternalNotes = new keystone.List('Internal Note', {
track: true,
autokey: { path: 'key', from: 'slug', unique: true },
defaultSort: 'date'
});
... | var keystone = require('keystone'),
Types = keystone.Field.Types;
// Create model. Additional options allow menu name to be used what auto-generating URLs
var InternalNotes = new keystone.List('Internal Note', {
track: true,
autokey: { path: 'key', from: 'slug', unique: true },
defaultSort: 'date'
});
... |
Add debug console root logging handler. | # Case Conductor is a Test Case Management system.
# Copyright (C) 2011-2012 Mozilla
#
# This file is part of Case Conductor.
#
# Case Conductor is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3... | # Case Conductor is a Test Case Management system.
# Copyright (C) 2011-2012 Mozilla
#
# This file is part of Case Conductor.
#
# Case Conductor is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3... |
Test the only untested line | from json import loads
from os import close, unlink
from tempfile import mkstemp
from unittest import TestCase
from cunhajacaiu import app
class FlaskTestCase(TestCase):
def setUp(self):
# set a test db
self.db_handler, self.db_path = mkstemp()
app.config['SQLALCHEMY_DATABASE_URI'] = 'sq... | from json import loads
from os import close, unlink
from tempfile import mkstemp
from unittest import TestCase
from cunhajacaiu import app
class FlaskTestCase(TestCase):
def setUp(self):
# set a test db
self.db_handler, self.db_path = mkstemp()
app.config['SQLALCHEMY_DATABASE_URI'] = 'sq... |
Improve how variables are output. Remove useless php tag. Switch to associative arrays for decoded json. | <html>
<head>
<title>dcs-get package listing</title>
</head>
<body>
<h1>Package Listing</h1>
<p>This is an up to date list of all packages available for dcs-get, along with their dependencies.</p>
<h2>Packages</h2>
<?php
//error_reporting(0);
error_reporting(E_ALL);
define('BASE_URL', 'http://backus.uwcs.co.uk/dcs-g... | <html>
<head>
<title>dcs-get package listing</title>
</head>
<body>
<h1>Package Listing</h1>
<p>This is an up to date list of all packages available for dcs-get, along with their dependencies.</p>
<h2>Packages</h2>
<?php
error_reporting(0);
//error_reporting(E_ALL);
define('BASE_URL', 'http://backus.uwcs.co.uk/dcs-g... |
Nit: Fix statement exceeding 100-character line limit | enum BeamType {
FAR(1.0f, 0.1f, 3.0f, 0.5f, 5.0f),
MIDDLE(2.0f, 0.2f, 6.0f, 0.7f, 7.0f),
NEAR(3.0f, 0.3f, 9.0f, 0.9f, 9.0f);
final float velocity;
final float acceleration;
final float terminalVelocity;
final float opacity;
final float size;
BeamType(float velocity, float accelera... | enum BeamType {
FAR(1.0f, 0.1f, 3.0f, 0.5f, 5.0f),
MIDDLE(2.0f, 0.2f, 6.0f, 0.7f, 7.0f),
NEAR(3.0f, 0.3f, 9.0f, 0.9f, 9.0f);
final float velocity;
final float acceleration;
final float terminalVelocity;
final float opacity;
final float size;
BeamType(float velocity, float accelera... |
Remove flags that drastically slow down writes | #!/usr/bin/python3
import argparse
import os
import icon_lib
parser = argparse.ArgumentParser(description='iconograph persistent')
parser.add_argument(
'--chroot-path',
dest='chroot_path',
action='store',
required=True)
FLAGS = parser.parse_args()
def main():
module = icon_lib.IconModule(FLAGS.c... | #!/usr/bin/python3
import argparse
import os
import icon_lib
parser = argparse.ArgumentParser(description='iconograph persistent')
parser.add_argument(
'--chroot-path',
dest='chroot_path',
action='store',
required=True)
FLAGS = parser.parse_args()
def main():
module = icon_lib.IconModule(FLAGS.c... |
Read template str as UTF-8 string | var browserify = require('browserify');
var brfs = require('brfs');
var through = require('through');
require('browserify/lib/builtins').fs = 'create-webfs.js'; // TODO: find a better way to replace this module
var b = browserify();
// directly include rfile TODO: use brfs, but it replaces fs.readFileSync
b.transfor... | var browserify = require('browserify');
var brfs = require('brfs');
var through = require('through');
require('browserify/lib/builtins').fs = 'create-webfs.js'; // TODO: find a better way to replace this module
var b = browserify();
// directly include rfile TODO: use brfs, but it replaces fs.readFileSync
b.transfor... |
Allow both -m and --message | from argparse import ArgumentParser
from dodo_commands.framework import Dodo
from dodo_commands.framework.config import Paths
import os
def _args():
parser = ArgumentParser()
parser.add_argument(
'--message', '-m', dest='message', help='The commit message')
args = Dodo.parse_args(parser)
retur... | from argparse import ArgumentParser
from dodo_commands.framework import Dodo
from dodo_commands.framework.config import Paths
import os
def _args():
parser = ArgumentParser()
parser.add_argument('-m', dest='message')
args = Dodo.parse_args(parser)
return args
if Dodo.is_main(__name__, safe=True):
... |
Use striptags from genshi for striphtml, since we have to have genshi anyway | # -*- coding: utf-8 -*-
"""WebHelpers used in SAUCE.
@author: moschlar
"""
from datetime import datetime
from tg import url as tgurl
#from webhelpers import date, feedgenerator, html, number, misc, text
import webhelpers as w
from webhelpers.html.tags import link_to
from webhelpers.text import truncate
from webhel... | # -*- coding: utf-8 -*-
"""WebHelpers used in SAUCE.
@author: moschlar
"""
from datetime import datetime
from tg import url as tgurl
#from webhelpers import date, feedgenerator, html, number, misc, text
import webhelpers as w
from webhelpers.html.tags import link_to
from webhelpers.text import truncate
from webhel... |
Use less strict condition to avoid problems with concurrency
In latest go versions TestWatcher fails pretty often, because it is
"more concurrent" now. Reproducible with go master:
while go test github.com/mholt/caddy/middleware/markdown; do :; done
Signed-off-by: Alexander Morozov <4efb7da3e38416208b41d8021a942884d8... | package markdown
import (
"fmt"
"strings"
"sync"
"testing"
"time"
)
func TestWatcher(t *testing.T) {
expected := "12345678"
interval := time.Millisecond * 100
i := 0
out := ""
stopChan := TickerFunc(interval, func() {
i++
out += fmt.Sprint(i)
})
// wait little more because of concurrency
time.Sleep(i... | package markdown
import (
"fmt"
"strings"
"sync"
"testing"
"time"
)
func TestWatcher(t *testing.T) {
expected := "12345678"
interval := time.Millisecond * 100
i := 0
out := ""
stopChan := TickerFunc(interval, func() {
i++
out += fmt.Sprint(i)
})
time.Sleep(interval * 8)
stopChan <- struct{}{}
if exp... |
Refactor and tie in configurable options | (function ( $ ) {
$.fn.goodtree = function( options ) {
// Default Settings
var settings = $.extend({
'expandIconClass' : 'closed',
'contractIconClass' : 'open',
'classPrefix' : 'goodtree_',
}, options);
return this.each(function() {
// Hide all of the children Elements
$(this).find('ul').hid... | (function ( $ ) {
$.fn.goodtree = function( options ) {
// Default Settings
var settings = $.extend({
'expand_icon' : 'images/tree/expand.png',
'contract_icon' : 'images/tree/contract.png',
'class_prefix' : 'goodtree_',
}, options);
return this.each(function() {
// Hide all of the children Eleme... |
Add option to shovel output files to a particular directory | package main
import (
"github.com/alecthomas/kingpin"
_ "github.com/cockroachdb/pq"
"github.com/npotts/arduino/WxShield2/wxplot"
"os"
)
var (
app = kingpin.New("wxPlot", "Plot data pulled from postgres/cockroachdb")
dataSourceName = app.Flag("dataSource", "Where should we connect to and yank data fro... | package main
import (
"github.com/alecthomas/kingpin"
_ "github.com/cockroachdb/pq"
"github.com/npotts/arduino/WxShield2/wxplot"
"os"
)
var (
app = kingpin.New("wxPlot", "Plot data pulled from postgres/cockroachdb")
dataSourceName = app.Flag("dataSource", "Where should we connect to and yank data fro... |
Update eslint config to allow 2 spaces
- happy to discuss and revert this. | module.exports = {
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"i... | module.exports = {
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"i... |
Refactor api test to setup test client in setup +review PLAT-127 DCORE-1109 | from nose.tools import eq_
import mock
from lcp import api
class TestApiClient(object):
def setup(self):
self.client = api.Client('BASE_URL')
def test_request_does_not_alter_absolute_urls(self):
for absolute_url in [
'http://www.points.com',
'https://www.point... | from nose.tools import eq_
import mock
from lcp import api
@mock.patch('lcp.api.requests.request')
def _assert_calls_requests_with_url(original_url, expected_url, request_mock):
api.Client('BASE_URL').request('METHOD', original_url)
expected_headers = {'Content-Type': 'application/json'}
eq_(request_mock... |
Remove assert in error-rasing test | from pytest import raises
from nirum.validate import (validate_boxed_type, validate_record_type,
validate_union_type)
def test_validate_boxed_type():
assert validate_boxed_type(3.14, float)
with raises(TypeError):
validate_boxed_type('hello', float)
def test_validate_rec... | from pytest import raises
from nirum.validate import (validate_boxed_type, validate_record_type,
validate_union_type)
def test_validate_boxed_type():
assert validate_boxed_type(3.14, float)
with raises(TypeError):
validate_boxed_type('hello', float)
def test_validate_rec... |
Make preprints url replacement absolute url | import Ember from 'ember';
import ResetScrollMixin from '../mixins/reset-scroll';
import AnalyticsMixin from '../mixins/analytics-mixin';
export default Ember.Route.extend(AnalyticsMixin, ResetScrollMixin, {
model(params) {
return this.store.findRecord('preprint', params.preprint_id);
},
setupContr... | import Ember from 'ember';
import ResetScrollMixin from '../mixins/reset-scroll';
import AnalyticsMixin from '../mixins/analytics-mixin';
export default Ember.Route.extend(AnalyticsMixin, ResetScrollMixin, {
model(params) {
return this.store.findRecord('preprint', params.preprint_id);
},
setupContr... |
Move Index import to the top to fix css order issue | /** DO NOT MODIFY **/
import React, { Component } from "react";
import { render } from "react-dom";
// Make sure that webpack considers new dependencies introduced in the Index
// file
import "../../Index.js";
import { Root } from "gluestick-shared";
import { match } from "react-router";
import routes from "./routes"... | /** DO NOT MODIFY **/
import React, { Component } from "react";
import { render } from "react-dom";
import { Root } from "gluestick-shared";
import { match } from "react-router";
import routes from "./routes";
import store from "./.store";
import { StyleRoot } from "radium";
// Make sure that webpack considers new de... |
Clarify use of 'debug' option | 'use strict';
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
//var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');
gulp.task('default', function() {
... | 'use strict';
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
//var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');
gulp.task('default', function() {
... |
Add defensive check to program arguments | package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Usage:\n\tmain region_name")
os.Exit(-1)
}
region := os.Args[1]
if region == "" {
fmt.Println("Usage:\n\... | package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
func main() {
svc := ec2.New(session.New(), &aws.Config{Region: aws.String("us-west-2")})
resp, err := svc.DescribeInstances(nil)
if err != nil {
panic(err)
}
fmt... |
Switch side of shrinking bar | AFRAME.registerComponent('hit-listener', {
schema: {
characterId: { default: undefined },
barWidth: { default: 1 },
maxLife: { default: 100 }
},
init: function () {
const el = this.el;
const data = this.data;
const position = el.getAttribute('position');
window.addEventListener('charac... | AFRAME.registerComponent('hit-listener', {
schema: {
characterId: { default: undefined },
barWidth: { default: 1 },
maxLife: { default: 100 }
},
init: function () {
const el = this.el;
const data = this.data;
const position = el.getAttribute('position');
window.addEventListener('charac... |
Return the simple response header and response body. | package org.yukung.sandbox.http;
import static org.yukung.sandbox.http.HttpRequest.*;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author yukung
*/
public class Main {
publi... | package org.yukung.sandbox.http;
import static org.yukung.sandbox.http.HttpRequest.CRLF;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author yukung
*/
public class Main {
pu... |
Remove closing PHP tag from end of file | <?php
//require_once( config_get( 'plugin_path' ) . 'SourceGithub/SourceGithub.php' );
auth_reauthenticate();
layout_page_header( plugin_lang_get( 'title' ) );
layout_page_begin();
print_manage_menu();
$f_repo_id = gpc_get_int( 'id' );
$f_code = gpc_get_string( 'code' );
$t_repo = SourceRepo::load( $f_repo_id );
... | <?php
//require_once( config_get( 'plugin_path' ) . 'SourceGithub/SourceGithub.php' );
auth_reauthenticate();
layout_page_header( plugin_lang_get( 'title' ) );
layout_page_begin();
print_manage_menu();
$f_repo_id = gpc_get_int( 'id' );
$f_code = gpc_get_string( 'code' );
$t_repo = SourceRepo::load( $f_repo_id );
... |
Establish connection only when needed | import xmlrpclib
import cPickle
import subprocess
from time import sleep
p = None
s = None
def start_plot_server():
global p
if p is None:
p = subprocess.Popen(["python", "plot_server.py"])
def stop_plot_server():
if p is not None:
p.terminate()
sleep(0.01)
p.kill()
def p... | import xmlrpclib
import cPickle
import subprocess
from time import sleep
p = None
s = None
def start_plot_server():
global p
if p is None:
p = subprocess.Popen(["python", "plot_server.py"])
def stop_plot_server():
if p is not None:
p.terminate()
sleep(0.01)
p.kill()
def p... |
Switch Login to use formsyFIeld | import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { browserHistory } from 'react-router';
import { Form, Button, Input } from 'semantic-ui-react';
import Formsy from 'formsy-react';
import { FormsyField } from '../formsy-semantic-ui';
import { createSession } from '../a... | import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { browserHistory } from 'react-router';
import { Form, Button } from 'semantic-ui-react';
import Formsy from 'formsy-react';
import { FormsyInput } from '../formsy-semantic-ui';
import { createSession } from '../actions/... |
Install typing module for older python versions. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
from setuptools import setup
setup(
name='django-brotli',
version='0.1.0',
description="""Middleware that compresses response using brotli algorithm.""",
long_description=io.open("README.rst", 'r', encoding="utf-8").read(),
url='https://gith... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
from setuptools import setup
setup(
name='django-brotli',
version='0.1.0',
description="""Middleware that compresses response using brotli algorithm.""",
long_description=io.open("README.rst", 'r', encoding="utf-8").read(),
url='https://gith... |
Print a message if method reflection returns null. | package com.twitter.diagnostics;
import java.lang.reflect.Method;
import java.lang.NoSuchMethodException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
class Tracepoints {
@PerfTracepoint static native void tracepoint0();
};
public class PerfTracepointTest exten... | package com.twitter.diagnostics;
import java.lang.reflect.Method;
import java.lang.NoSuchMethodException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
class Tracepoints {
@PerfTracepoint static native void tracepoint0();
};
public class PerfTracepointTest exten... |
Add Python 3.7 to the list of supported versions | from setuptools import setup
from os import path
with open(path.join(path.abspath(path.dirname(__file__)), 'README.rst')) as f:
readme = f.read()
setup(
name='ghstats',
version='1.2.0',
packages=['ghstats'],
description='GitHub Release download count and other statistics.',
long_description=re... | from setuptools import setup
from os import path
with open(path.join(path.abspath(path.dirname(__file__)), 'README.rst')) as f:
readme = f.read()
setup(
name='ghstats',
version='1.2.0',
packages=['ghstats'],
description='GitHub Release download count and other statistics.',
long_description=re... |
Remove all .pager instances after each test | var pager;
var items = 100;
var itemsOnPage = 10;
var pageCount = items/itemsOnPage;
beforeEach(function() {
$('<div id="pager" class="pager"></div>').appendTo('body').pagination({
items: items,
itemsOnPage: itemsOnPage
});
pager = $('#pager');
this.addMatchers({
toBePaged: f... | var pager;
var items = 100;
var itemsOnPage = 10;
var pageCount = items/itemsOnPage;
beforeEach(function() {
$('<div id="pager"></div>').appendTo('body').pagination({
items: items,
itemsOnPage: itemsOnPage
});
pager = $('#pager');
this.addMatchers({
toBePaged: function() {
... |
Add test of defining a signal with a return type.
svn path=/trunk/; revision=233 | #!/usr/bin/env seed
// Returns: 0
// STDIN:
// STDOUT:2 Weathermen\n\[object GtkWindow\]
// STDERR:
Seed.import_namespace("GObject");
Seed.import_namespace("Gtk");
Gtk.init(null, null);
HelloWindowType = {
parent: Gtk.Window,
name: "HelloWindow",
class_init: function(klass, prototype)
{
var He... | #!/usr/bin/env seed
// Returns: 0
// STDIN:
// STDOUT:2 Weathermen
// STDERR:
Seed.import_namespace("GObject");
Seed.import_namespace("Gtk");
Gtk.init(null, null);
HelloWindowType = {
parent: Gtk.Window,
name: "HelloWindow",
class_init: function(klass, prototype)
{
var HelloSignalDefinition = ... |
Update environment test to have cross platform support | """Test the checkers"""
from nose.tools import ok_, eq_
from preflyt import check
CHECKERS = [
{"checker": "env", "name": "PATH"}
]
BAD_CHECKERS = [
{"checker": "env", "name": "PATH1231342dhkfgjhk2394dv09324jk12039csdfg01231"}
]
def test_everything():
"""Test the check method."""
good, results = c... | """Test the checkers"""
from nose.tools import ok_, eq_
from preflyt import check
CHECKERS = [
{"checker": "env", "name": "USER"}
]
BAD_CHECKERS = [
{"checker": "env", "name": "USER1231342dhkfgjhk2394dv09324jk12039csdfg01231"}
]
def test_everything():
"""Test the check method."""
good, results = che... |
Use ioutil for reduce code line | package file_storage
import (
"github.com/photoshelf/photoshelf-storage/domain/model"
"io/ioutil"
"os"
"path"
)
type FileStorage struct {
baseDir string
}
func NewFileStorage(baseDir string) *FileStorage {
return &FileStorage{baseDir}
}
func (storage *FileStorage) Save(photo model.Photo) (*model.Identifier, e... | package file_storage
import (
"github.com/photoshelf/photoshelf-storage/domain/model"
"io/ioutil"
"os"
"path"
)
type FileStorage struct {
baseDir string
}
func NewFileStorage(baseDir string) *FileStorage {
return &FileStorage{baseDir}
}
func (storage *FileStorage) Save(photo model.Photo) (*model.Identifier, e... |
Work on older Python without assertIn method. | #!/usr/bin/env python
# vim: set ts=4 sw=4 et sts=4 ai:
#
# Test some basic functionality.
#
import unittest
import os
import sys
sys.path.append('..')
class TestQBasic(unittest.TestCase):
def setUp(self):
if os.path.exists('/tmp/q'):
os.remove('/tmp/q')
def tearDown(self):
self... | #!/usr/bin/env python
# vim: set ts=4 sw=4 et sts=4 ai:
#
# Test some basic functionality.
#
import unittest
import os
import sys
sys.path.append('..')
class TestQBasic(unittest.TestCase):
def setUp(self):
if os.path.exists('/tmp/q'):
os.remove('/tmp/q')
def tearDown(self):
self... |
Update API to look at one folder and return processor | """
This module provides a simplified API for invoking the Geneways input processor
, which converts extracted information collected with Geneways into INDRA
statements.
See publication:
Rzhetsky, Andrey, Ivan Iossifov, Tomohiro Koike, Michael Krauthammer, Pauline
Kra, Mitzi Morris, Hong Yu et al. "GeneWays: a system ... | """
This module provides a simplified API for invoking the Geneways input processor
, which converts extracted information collected with Geneways into INDRA
statements.
See publication:
Rzhetsky, Andrey, Ivan Iossifov, Tomohiro Koike, Michael Krauthammer, Pauline
Kra, Mitzi Morris, Hong Yu et al. "GeneWays: a system ... |
Revert "Properly cast dates to y-m-d format"
This reverts commit 7910dace9fc93ab5d5494e68cdee21867ad4558b partially. | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Timeline extends Model
{
use HasFactory;
protected $table = 'timeline';
protected $fillable = ['date', 'item_id', 'item_type'];
public function item() {
return $t... | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Timeline extends Model
{
use HasFactory;
protected $table = 'timeline';
protected $fillable = ['date', 'item_id', 'item_type'];
protected $dates = ['date'];
protected... |
Remove message traits from Signup controller | SignupController = Space.accountsUi.SignupController;
SignupController.extend(Donations, 'OrgRegistrationsController', {
dependencies: {
orgRegStore: 'Donations.OrgRegistrationsStore',
signupsStore: 'Space.accountsUi.SignupsStore'
},
requestSignupEvent: 'Donations.OrgRegistrationRequested',
initiateS... | SignupController = Space.accountsUi.SignupController;
SignupController.extend(Donations, 'OrgRegistrationsController', {
mixin: [
Space.messaging.EventSubscribing,
Space.messaging.EventPublishing
],
dependencies: {
orgRegStore: 'Donations.OrgRegistrationsStore',
signupsStore: 'Space.accountsUi.... |
Fix the identifier-ness test in maybe_quote. | function quote(s) {
return "\"" + s.replace(/([\\\"])/, "\\$1") + "\"";
}
function maybe_quote(s) {
if (/^[_A-Za-z][_A-Za-z0-9]*$/.test(s))
return s;
else
return quote(s);
}
function repr(x, max_depth) {
if (max_depth == undefined)
max_depth = 1;
if (x === null) {
return "null";
} else if (x instanceof... | function quote(s) {
return "\"" + s.replace(/([\\\"])/, "\\$1") + "\"";
}
function maybe_quote(s) {
if (/[\\\"]/.test(s))
return quote(s);
else
return s;
}
function repr(x, max_depth) {
if (max_depth == undefined)
max_depth = 1;
if (x === null) {
return "null";
} else if (x instanceof java.lang.Iterabl... |
Remove shebang line from non-script. | from twisted.protocols import amp
from twisted.cred.error import UnauthorizedLogin
# commands to server side
class Login(amp.Command):
arguments = [("username", amp.String()), ("password", amp.String())]
response = []
errors = {UnauthorizedLogin: "UnauthorizedLogin"}
# If we set requiresAnswer = False... | #!/usr/bin/env python
from twisted.protocols import amp
from twisted.cred.error import UnauthorizedLogin
# commands to server side
class Login(amp.Command):
arguments = [("username", amp.String()), ("password", amp.String())]
response = []
errors = {UnauthorizedLogin: "UnauthorizedLogin"}
# If we set... |
Fix retry for experiment group | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
from api.settings import CeleryTasks, Intervals
from api.celery_api import app as celery_app
from experiments.tasks import build_experiment
from projects.models import ExperimentGroup
logger = logging.getLogger('p... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
from api.settings import CeleryTasks, Intervals
from api.celery_api import app as celery_app
from experiments.tasks import build_experiment
from projects.models import ExperimentGroup
logger = logging.getLogger('p... |
Allow user code to call the addinfo() method on the profiler object. | """High-perfomance logging profiler, mostly written in C."""
import _hotshot
from _hotshot import ProfilerError
class Profile:
def __init__(self, logfn, lineevents=0, linetimings=1):
self.lineevents = lineevents and 1 or 0
self.linetimings = (linetimings and lineevents) and 1 or 0
self._... | """High-perfomance logging profiler, mostly written in C."""
import _hotshot
from _hotshot import ProfilerError
class Profile:
def __init__(self, logfn, lineevents=0, linetimings=1):
self.lineevents = lineevents and 1 or 0
self.linetimings = (linetimings and lineevents) and 1 or 0
self._... |
Fix unicode string syntax for Python 3 | from os.path import abspath, join, dirname
import random
__title__ = 'names'
__version__ = '0.2'
__author__ = 'Trey Hunner'
__license__ = 'MIT'
full_path = lambda filename: abspath(join(dirname(__file__), filename))
FILES = {
'first:male': full_path('dist.male.first'),
'first:female': full_path('dist.fema... | from os.path import abspath, join, dirname
import random
__title__ = 'names'
__version__ = '0.2'
__author__ = 'Trey Hunner'
__license__ = 'MIT'
full_path = lambda filename: abspath(join(dirname(__file__), filename))
FILES = {
'first:male': full_path('dist.male.first'),
'first:female': full_path('dist.fema... |
Bump up version to 0.3 | # -*- coding: utf-8 -*-
from distutils.core import setup
from setuptools import find_packages
setup(
name = 'djiki',
version = '0.3',
description = 'Django Wiki Application',
url = 'https://github.com/emesik/djiki/',
long_description = open('README.rst').read(),
author = 'Michał Sałaban',
author_email = 'michal... | # -*- coding: utf-8 -*-
from distutils.core import setup
from setuptools import find_packages
setup(
name = 'djiki',
version = '0.2',
description = 'Django Wiki Application',
url = 'https://github.com/emesik/djiki/',
long_description = open('README.rst').read(),
author = 'Michał Sałaban',
author_email = 'michal... |
Increase test timeout for Gitter beforeEach tests | /* jshint mocha: true */
'use strict';
const assert = require('assert');
const gitter = require('../lib/gitter');
const jsonist = require('jsonist');
let nodes;
let post = jsonist.post;
beforeEach(function() {
this.timeout(10000);
jsonist.post = function() {};
nodes = [
{
name: 'foo',
offline:... | /* jshint mocha: true */
'use strict';
const assert = require('assert');
const gitter = require('../lib/gitter');
const jsonist = require('jsonist');
let nodes;
let post = jsonist.post;
beforeEach(function() {
jsonist.post = function() {};
nodes = [
{
name: 'foo',
offline: true,
},{
nam... |
Add support for models that have .account | module.exports = function(app) {
var Role = app.models.Role;
Role.registerResolver('teamMember', function(role, context, cb) {
function reject(msg) {
console.log(msg);
process.nextTick(function() {
cb(null, false);
});
}
var userId = context.accessToken.userId;
if (!user... | module.exports = function(app) {
var Role = app.models.Role;
Role.registerResolver('teamMember', function(role, context, cb) {
function reject(msg) {
console.log(msg);
process.nextTick(function() {
cb(null, false);
});
}
var userId = context.accessToken.userId;
if (!use... |
Revert "Only ask for public privileges"
This reverts commit 47b95cb58a00364fd3146c10e12ba4b93ed45f60. | import * as ACTION_TYPES from '../constants/action_types'
function extractToken(hash, oldToken) {
const match = hash.match(/access_token=([^&]+)/)
let token = !!match && match[1]
if (!token) {
token = oldToken
}
return token
}
export function checkAuth(dispatch, oldToken, location) {
const token = ext... | import * as ACTION_TYPES from '../constants/action_types'
function extractToken(hash, oldToken) {
const match = hash.match(/access_token=([^&]+)/)
let token = !!match && match[1]
if (!token) {
token = oldToken
}
return token
}
export function checkAuth(dispatch, oldToken, location) {
const token = ext... |
Change assertGet body check from StringType to str | import unittest
import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
hosts = []
def assertGet(self, endpoint="", status_code=200, body=""):
"""
Asserts GET requests on a given endpoint
"""
for host in self.hosts:
... | import types
import unittest
import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
hosts = []
def assertGet(self, endpoint="", status_code=200, body=""):
"""
Asserts GET requests on a given endpoint
"""
for host in self... |
Update to stream bytes to checksum algo. | package bagutil
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"errors"
"fmt"
"hash"
"io"
"os"
)
// Takes a filepath as a string and produces a checksum.
func FileChecksum(filepath string, algo string) string {
hsh, err := newHash(algo)
if err != nil {
panic(err)
}
file, err := os.... | package bagutil
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"errors"
"fmt"
"hash"
"io/ioutil"
"os"
)
// Takes a filepath as a string and produces a checksum.
func FileChecksum(filepath string, algo string) string {
hsh, err := newHash(algo)
if err != nil {
panic(err)
}
file, err... |
Set user for core app service correctly | <?php
namespace SimplyTestable\WebClientBundle\Controller;
class TestNotificationController extends TestViewController
{
public function urlLimitAction($test_id, $website) {
$this->getTestService()->setUser($this->getUser());
$testRetrievalOutcome = $this->getTestRetrievalOutcome($website... | <?php
namespace SimplyTestable\WebClientBundle\Controller;
class TestNotificationController extends TestViewController
{
public function urlLimitAction($test_id, $website) {
$testRetrievalOutcome = $this->getTestRetrievalOutcome($website, $test_id);
if ($testRetrievalOutcome->hasResponse()) {
... |
Add missing numpy import, and cleanup the rest | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import print_function
import numpy as np
from astropy.tests.helper import remote_data
from astropy.table import Table
import astropy.units as u
from ... import nist
@remote_data
class TestNist:
def test_query_async(self):
... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import print_function
from astropy.tests.helper import remote_data
from astropy.table import Table
import astropy.units as u
import requests
import imp
from ... import nist
imp.reload(requests)
@remote_data
class TestNist:
def tes... |
Fix return type in DocBlock. | <?php
/**
* ExtReferenceConverterInterface class file
*/
namespace Graviton\DocumentBundle\Service;
/**
* Extref converter interface
*
* @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @... | <?php
/**
* ExtReferenceConverterInterface class file
*/
namespace Graviton\DocumentBundle\Service;
/**
* Extref converter interface
*
* @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @... |
Update EntityContentRevisions to use es6 class. | /*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2015 Canonical Ltd.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License vers... | /*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2015 Canonical Ltd.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License vers... |
Allow tests to be run with Python <2.6. | # -*- coding: latin-1 -*-
import unittest
from github2.issues import Issue
from github2.client import Github
class ReprTests(unittest.TestCase):
"""__repr__ must return strings, not unicode objects."""
def test_issue(self):
"""Issues can have non-ASCII characters in the title."""
i = Issue(t... | # -*- coding: latin-1 -*-
import unittest
from github2.issues import Issue
from github2.client import Github
class ReprTests(unittest.TestCase):
"""__repr__ must return strings, not unicode objects."""
def test_issue(self):
"""Issues can have non-ASCII characters in the title."""
i = Issue(t... |
FIX: Use another port number because this port is already bound by another test somewhere. | /**
* Modules dependencies
*/
var mocha = require('mocha'),
assert = require('chai').assert,
libPath = process.env['SCRAPINODE_COV'] ? '../lib-cov' : '../lib',
scrapinode = require( libPath + '/scrapinode'),
ScrapinodeError = require(libPath + '/error/scrapinode-error'),
express = require('express'),
filed = r... | /**
* Modules dependencies
*/
var mocha = require('mocha'),
assert = require('chai').assert,
libPath = process.env['SCRAPINODE_COV'] ? '../lib-cov' : '../lib',
scrapinode = require( libPath + '/scrapinode'),
ScrapinodeError = require(libPath + '/error/scrapinode-error'),
express = require('express'),
filed = r... |
Fix stubs not being served correctly | 'use strict';
var path = require('path');
var parseBundle = require('nodecg-bundle-parser');
var express = require('express');
var app = express();
var injectScripts = require('./script_injector');
module.exports = function(bundlePath) {
var bundle = parseBundle(path.resolve(bundlePath));
app.listen(9999);
... | 'use strict';
var path = require('path');
var parseBundle = require('nodecg-bundle-parser');
var express = require('express');
var app = express();
var injectScripts = require('./script_injector');
module.exports = function(bundlePath) {
var bundle = parseBundle(path.resolve(bundlePath));
app.listen(9999);
... |
Add id and key props | import React from 'react'
import Table from '../Table'
import TableRow from '../Table/TableRow/index'
import PropTypes from 'prop-types'
const InventoryTable = ({tableRows, addRow, setEditing, saveTableRow}) => {
const columns = [
{name: "Name", type: "text"},
{name: "Amount", type: "number"}
]
const t... | import React from 'react'
import Table from '../Table'
import PropTypes from 'prop-types'
const InventoryTable = ({tableRows, addRow, setEditing, saveTableRow}) => {
const columns = [
{name: "Name", type: "text"},
{name: "Amount", type: "number"}
]
const tableRowComponents = tableRows.map((tableRow) =>... |
Add 'watch property descriptor' action
Review URL: https://chromiumcodereview.appspot.com/9391018
git-svn-id: 1dc80909446f7a7ee3e21dd4d1b8517df524e9ee@927 fc8a088e-31da-11de-8fef-1f5ae417a2df | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.sdk;
import java.util.List;
import org.chromium.sdk.util.MethodIsBlockingException;
/**
* An object that represents a scope i... | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.sdk;
import java.util.List;
import org.chromium.sdk.util.MethodIsBlockingException;
/**
* An object that represents a scope i... |
Handle tuple error formatting same as list |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... |
Remove trailing comma from json | module.exports = {
port: 3000,
public_url: 'http://127.0.0.1:3000/',
expire_minutes: 15,
db: {
host: 'localhost',
user: 'root',
password: '',
database: 'nappikauppa2'
},
email: {
mailgun: {
api_key: '###',
domain: ''
},
from: '',
errors_to: '',
err... | module.exports = {
port: 3000,
public_url: 'http://127.0.0.1:3000/',
expire_minutes: 15,
db: {
host: 'localhost',
user: 'root',
password: '',
database: 'nappikauppa2'
},
email: {
mailgun: {
api_key: '###',
domain: ''
},
from: '',
errors_to: '',
err... |
Return the original file if SVGO fails | 'use strict';
var isSvg = require('is-svg');
var SVGO = require('svgo');
var through = require('through2');
module.exports = function (opts) {
opts = opts || {};
return through.ctor({objectMode: true}, function (file, enc, cb) {
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
... | 'use strict';
var isSvg = require('is-svg');
var SVGO = require('svgo');
var through = require('through2');
module.exports = function (opts) {
opts = opts || {};
return through.ctor({objectMode: true}, function (file, enc, cb) {
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
... |
[chore] Add bower.json and package.json to jshint checks | module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['*.js', 'client/app/*.js', 'server/**/*.js', 'database/**/*.js', '*.json'],
options: {
ignores: [
// (TODO: add lib files here)
]
}
},
uglify: {
my_target: {
files: {
... | module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['*.js', 'client/app/*.js', 'server/**/*.js', 'database/**/*.js'],
options: {
ignores: [
// (TODO: add lib files here)
]
}
},
uglify: {
my_target: {
files: {
'client... |
Use correct variable name when logging a less error | Package.describe({
summary: "The dynamic stylesheet language."
});
var less = require('less');
var fs = require('fs');
Package.register_extension(
"less", function (bundle, source_path, serve_path, where) {
serve_path = serve_path + '.css';
var contents = fs.readFileSync(source_path);
try {
le... | Package.describe({
summary: "The dynamic stylesheet language."
});
var less = require('less');
var fs = require('fs');
Package.register_extension(
"less", function (bundle, source_path, serve_path, where) {
serve_path = serve_path + '.css';
var contents = fs.readFileSync(source_path);
try {
le... |
Reset file as no changes were made. Just formatting | const router = require('../router')
const urls = require('../../../lib/urls')
describe('Company router', () => {
it('should define all routes', () => {
const paths = router.stack.filter(r => r.route).map(r => r.route.path)
expect(paths).to.deep.equal([
'/',
'/export',
'/:companyId/archive',... | const router = require('../router')
const urls = require('../../../lib/urls')
describe('Company router', () => {
it('should define all routes', () => {
const paths = router.stack.filter(r => r.route).map(r => r.route.path)
expect(paths).to.deep.equal(
[
'/',
'/export',
'/:compan... |
Fix typo in url to github repo inside footer | <footer>
<div class="container">
<div class="row">
<div class="column-1-4">
<div class="footer-div">
<h2 class="orange-border">FOCUS</h2>
<ul>
<li><a href="/contact.php">Contact Us</a></li>
<li><a href="https://github.com/svceglug/focus" target="_blank">So... | <footer>
<div class="container">
<div class="row">
<div class="column-1-4">
<div class="footer-div">
<h2 class="orange-border">FOCUS</h2>
<ul>
<li><a href="/contact.php">Contact Us</a></li>
<li><a href="https://github.com/scveglug" target="_blank">Source C... |
Enable twopoint in Tuvero Basic | /**
* Basic presets: swiss direct matchings, round similar to chess, and ko
* with a matched cadrage. Simple rankings
*
* @return Presets
* @author Erik E. Lorenz <erik@tuvero.de>
* @license MIT License
* @see LICENSE
*/
define(function() {
var Presets;
Presets = {
target: 'basic',
systems: {
... | /**
* Basic presets: swiss direct matchings, round similar to chess, and ko
* with a matched cadrage. Simple rankings
*
* @return Presets
* @author Erik E. Lorenz <erik@tuvero.de>
* @license MIT License
* @see LICENSE
*/
define(function() {
var Presets;
Presets = {
target: 'basic',
systems: {
... |
Optimize and classify only res.locals.scripts as not found | /*
* Ensures something has been found during the request. Returns 404 if
* res.template is unset, res.locals is empty and statusCode has not been set
* to 204.
*
* Should be placed at the very end of the middleware pipeline,
* after all project specific routes but before the error handler & responder.
*
* @mod... | /*
* Ensures something has been found during the request. Returns 404 if
* res.template is unset, res.locals is empty and statusCode has not been set
* to 204.
*
* Should be placed at the very end of the middleware pipeline,
* after all project specific routes but before the error handler & responder.
*
* @mod... |
Increment version number now that 0.1.5 release out. | import os
from os.path import relpath, join
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def find_package_data(data_root, package_root):
files = []
for root, dirnames, filenames in os.walk(data_root):
for fn in filenames:
... | import os
from os.path import relpath, join
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def find_package_data(data_root, package_root):
files = []
for root, dirnames, filenames in os.walk(data_root):
for fn in filenames:
... |
Add user id param to getUserSettings | package com.hubspot.singularity.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.hubspot.singularity.SingularityService;
import c... | package com.hubspot.singularity.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.hubspot.singularity.SingularityService;
import com.hubspot.singularity.Singula... |
Fix bug with incorrect case in path, damn you HFS | <?php
namespace Pheasant\Tests;
class EnumeratorTest extends \Pheasant\Tests\MysqlTestCase
{
public function setUp()
{
parent::setUp();
}
public function testEnumerating()
{
$dir = __DIR__.'/Examples';
$files = array_map(function($f) { return substr(basename($f),0,-4); },
... | <?php
namespace Pheasant\Tests;
class EnumeratorTest extends \Pheasant\Tests\MysqlTestCase
{
public function setUp()
{
parent::setUp();
}
public function testEnumerating()
{
$dir = __DIR__.'/examples';
$files = array_map(function($f) { return substr(basename($f),0,-4); },
... |
Make showLog and deleteLog admin commands | package com.oldterns.vilebot.handlers.admin;
import ca.szc.keratin.bot.annotation.HandlerContainer;
import ca.szc.keratin.core.event.message.recieve.ReceivePrivmsg;
import com.oldterns.vilebot.db.GroupDB;
import com.oldterns.vilebot.db.LogDB;
import com.oldterns.vilebot.util.Sessions;
import net.engio.mbassy.listener.... | package com.oldterns.vilebot.handlers.admin;
import ca.szc.keratin.bot.annotation.HandlerContainer;
import ca.szc.keratin.core.event.message.recieve.ReceivePrivmsg;
import com.oldterns.vilebot.db.LogDB;
import net.engio.mbassy.listener.Handler;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* C... |
Remove extra call to recalculateVisibility | var viewModel = null;
var LogError = null;
// This function is run when the app is ready to start interacting with the host application.
// It ensures the DOM is ready before updating the span elements with values from the current message.
$(document).ready(function () {
LogError = window.parent.LogError;
$(w... | var viewModel = null;
var LogError = null;
// This function is run when the app is ready to start interacting with the host application.
// It ensures the DOM is ready before updating the span elements with values from the current message.
$(document).ready(function () {
LogError = window.parent.LogError;
$(w... |
Fix nearest stops on iOS | <?php
require_once __DIR__.'/../../config.inc.php';
use TPGwidget\Data\Stops;
$file = 'https://prod.ivtr-od.tpg.ch/v1/GetStops.xml?key='.getenv('TPG_API_KEY').'&latitude='.($_GET['latitude'] ?? '').'&longitude='.($_GET['longitude'] ?? '');
$stops = @simplexml_load_file($file);
$output = [];
if ($stops) {
foreach ... | <?php
require_once __DIR__.'/../../config.inc.php';
use TPGwidget\Data\Stops;
$file = 'https://prod.ivtr-od.tpg.ch/v1/GetStops.xml?key='.getenv('TPG_API_KEY').'&latitude='.($_GET['latitude'] ?? '').'&longitude='.($_GET['longitude'] ?? '');
$stops = @simplexml_load_file($file);
$output = [];
if ($stops) {
foreach ... |
Implement results action in town controller | <?php
namespace Listabierta\Bundle\MunicipalesBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Listabierta\Bundle\MunicipalesBundle\Form\Type\TownStep1Type;
class TownController extends Controller
{
public function indexAction(Request $re... | <?php
namespace Listabierta\Bundle\MunicipalesBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Listabierta\Bundle\MunicipalesBundle\Form\Type\TownStep1Type;
class TownController extends Controller
{
public function indexAction(Request $re... |
Change :id to :username for more clarity | const express = require('express'),
router = express.Router(),
db = require('../models');
router.get('/', function(req, res, next) {
res.render('index');
});
router.get('/new', function(req, res, next) {
res.render('users/new');
});
router.get('/:username', function(req, res, next) {
// db.User.fin... | const express = require('express'),
router = express.Router(),
db = require('../models');
router.get('/', function(req, res, next) {
res.render('index');
});
router.get('/new', function(req, res, next) {
res.render('users/new');
});
router.get('/:id/edit', function(req, res, next) {
db.User.findByI... |
Fix tags_fts table create migration. | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Owl\Repositories\Eloquent\Models\Tag;
use Owl\Repositories\Eloquent\Models\TagFts;
class CreateTagsFts extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::stat... | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Owl\Models\Tag;
use Owl\Models\TagFts;
class CreateTagsFts extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::statement('CREATE VIRTUAL TABLE tags_fts USING f... |
Use new AccountCreate component for setup. | /**
* Analytics common components.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2... | /**
* Analytics common components.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2... |
Allow to get up to 100 issues at once | from __future__ import print_function
import urllib, json, sys
def generate(milestone):
# Find the milestone number for the given name
milestones_json = json.loads(urllib.urlopen('https://api.github.com/repos/CoolProp/CoolProp/milestones').read())
# Map between name and number
title_to_number_map... | from __future__ import print_function
import urllib, json, sys
def generate(milestone):
# Find the milestone number for the given name
milestones_json = json.loads(urllib.urlopen('https://api.github.com/repos/CoolProp/CoolProp/milestones').read())
# Map between name and number
title_to_number_map... |
Use a workerpool for configuration file updates
Co-Authored-By: Jakob <0708d49e9b6eea40f2835438410a265908e17890@users.noreply.github.com> | package server
import (
"github.com/gammazero/workerpool"
"runtime"
)
// Parent function that will update all of the defined configuration files for a server
// automatically to ensure that they always use the specified values.
func (s *Server) UpdateConfigurationFiles() {
pool := workerpool.New(runtime.GOMAXPROCS... | package server
import (
"github.com/pterodactyl/wings/parser"
"sync"
)
// Parent function that will update all of the defined configuration files for a server
// automatically to ensure that they always use the specified values.
func (s *Server) UpdateConfigurationFiles() {
wg := new(sync.WaitGroup)
files := s.P... |
Revert "Use Meteor.wrapAsync instead of Fibers."
This reverts commit b7e5328913c05a016ec760dc47431c7320af514a. | // Get our NPM stuff.
var Future = Npm.require("fibers/future");
request = Npm.require("request");
// This is our main wrapping function, using Fibers.
var requestSync = function(uri, options) {
var future = new Future();
request(uri, options, function(error, response, body) {
if (error) {
console.log(error);
... | // Get our NPM stuff.
request = Npm.require("request");
// Wrap request with something that can be `Meteor.wrapAsync`ed.
var requestAsync = function(uri, options, callback) {
request(uri, options, function(error, response, body) {
if (error) {
console.log(error);
callback(error);
} else {
callback(null, ... |
Include the dyno identifier, if available, in the metric key | var Graphite = require('graphite');
var Measured = require('measured');
var reportInterval = 5000;
var graphiteHost = process.env.GRAPHITE_HOST || null;
var graphitePort = process.env.GRAPHITE_PORT || 2003;
var envName = process.env.NODE_ENV || "unknown";
var processIdentifier = process.env.DYNO || "unknown-process";
... | var Graphite = require('graphite');
var Measured = require('measured');
var reportInterval = 5000;
var graphiteHost = process.env.GRAPHITE_HOST || null;
var graphitePort = process.env.GRAPHITE_PORT || 2003;
var envName = process.env.NODE_ENV || "unknown";
var timer = null;
var graphite = null;
var data = Measured.cre... |
Fix bug in read tracking system | def update_read_tracking(topic, user):
tracking = user.readtracking
#if last_read > last_read - don't check topics
if tracking.last_read and tracking.last_read > (topic.last_post.updated or
topic.last_post.created):
return
if isinstance(track... | def update_read_tracking(topic, user):
tracking = user.readtracking
#if last_read > last_read - don't check topics
if tracking.last_read and tracking.last_read > (topic.last_post.updated or
topic.last_post.created):
return
if isinstance(track... |
Use full URI for build failure reasons | from __future__ import absolute_import
from jinja2 import Markup
from changes.buildfailures.base import BuildFailure
from changes.utils.http import build_uri
class TestFailure(BuildFailure):
def get_html_label(self, build):
link = build_uri('/projects/{0}/builds/{1}/tests/?result=failed'.format(build.pr... | from __future__ import absolute_import
from jinja2 import Markup
from changes.buildfailures.base import BuildFailure
class TestFailure(BuildFailure):
def get_html_label(self, build):
link = '/projects/{0}/builds/{1}/tests/?result=failed'.format(build.project.slug, build.id.hex)
try:
... |
Use append mode in case other hooks want to write to build-extras.gradle | #!/usr/bin/env node
// add additional build-extras.gradle file to instruct android's lint to ignore translation errors
// v0.1.c
// causing error in the build --release
// Issue: https://github.com/phonegap/phonegap-plugin-barcodescanner/issues/80
//
// Warning: This solution does not solve the problem only makes it p... | #!/usr/bin/env node
// add additional build-extras.gradle file to instruct android's lint to ignore translation errors
// v0.1.c
// causing error in the build --release
// Issue: https://github.com/phonegap/phonegap-plugin-barcodescanner/issues/80
//
// Warning: This solution does not solve the problem only makes it p... |
Fix link to the tagged release. | from setuptools import setup
setup(
name = 'PyFVCOM',
packages = ['PyFVCOM'],
version = '1.3.4',
description = ("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."),
author = 'Pierre Cazenave',
author_email =... | from setuptools import setup
setup(
name = 'PyFVCOM',
packages = ['PyFVCOM'],
version = '1.3.4',
description = ("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."),
author = 'Pierre Cazenave',
author_email =... |
Fix typo in Famo.us require in test | 'use strict';
window.Famous = require('famous');
var test = require('tape');
var BEST = require('../lib/index');
var DataStore = require('../lib/data-store/data-store');
test('---- BEST', function(t) {
t.plan(2);
t.test('exports', function(st) {
st.plan(4);
st.ok(BEST, 'BEST exports');
... | 'use strict';
window.Famous = require('../node_modules/famous');
var test = require('tape');
var BEST = require('../lib/index');
var DataStore = require('../lib/data-store/data-store');
test('---- BEST', function(t) {
t.plan(2);
t.test('exports', function(st) {
st.plan(4);
st.ok(BEST, 'BEST e... |
Remove Extra EJS Routes Handler and Add Caching Process to AccessToken | 'use strict'
var loopback = require('loopback')
var boot = require('loopback-boot')
var path = require('path')
var bodyParser = require('body-parser')
var app = module.exports = loopback()
// configure body parser
app.use(bodyParser.urlencoded({extended: true}))
app.use(loopback.token({
model: app.models.access... | 'use strict';
var loopback = require('loopback');
var boot = require('loopback-boot');
var path = require('path');
var bodyParser = require('body-parser');
var app = module.exports = loopback();
// configure view handler
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// configure bo... |
Update test to use ?state | 'use strict';
require('should');
var request = require('supertest');
var app = require('../app.js');
var helpers = require('./helpers.js');
var config = require('../config/configuration.js');
describe('Auth handlers', function() {
describe('GET /init/connect', function() {
it("should redirect to the AnyFetch ... | 'use strict';
require('should');
var request = require('supertest');
var app = require('../app.js');
var helpers = require('./helpers.js');
var config = require('../config/configuration.js');
describe('Auth handlers', function() {
describe('GET /init/connect', function() {
it("should redirect to the AnyFetch ... |
Allow extensions to be sent as well - maybe we should consider just allowing opts.browserifyOpts | var browserify = require('browserify'),
path = require('path');
module.exports = function(opts){
var routerPath;
if (typeof opts.getLocation === 'function') {
var router = opts;
routerPath = router.getLocation();
}else if(opts.router && typeof opts.router.getLocation === 'function'){
var router ... | var browserify = require('browserify'),
path = require('path');
module.exports = function(opts){
var routerPath;
if (typeof opts.getLocation === 'function') {
var router = opts;
routerPath = router.getLocation();
}else if(opts.router && typeof opts.router.getLocation === 'function'){
var router ... |
Add onConnect and onDisconnect callbacks and return 'connection' object with disconnect option | var WebSocket = require('ws');
var debug = require('debug')('signalk:ws');
function connectDelta(hostname, callback, onConnect, onDisconnect) {
debug("Connecting to " + hostname);
var url = "ws://" + hostname + "/signalk/stream?stream=delta&context=self";
if (typeof Primus != 'undefined') {
debug("Using Pri... | var WebSocket = require('ws');
var debug = require('debug')('signalk:ws');
function connectDelta(hostname, callback) {
var url = "ws://" + hostname + "/signalk/stream?stream=delta&context=self";
if (typeof Primus != 'undefined') {
var signalKStream = Primus.connect(url, {
reconnect: {
maxDelay: ... |
Use relative paths for includes. | <?php if ( ! defined('BASEPATH')) exit('Invalid file request.');
/**
* OmniLog module tests.
*
* @author Stephen Lewis <stephen@experienceinternet.co.uk>
* @copyright Experience Internet
* @package Omnilog
*/
require_once dirname(__FILE__) .'/../mcp.omnilog.php';
require_once dirname(__FILE__) ... | <?php if ( ! defined('BASEPATH')) exit('Invalid file request.');
/**
* OmniLog module tests.
*
* @author Stephen Lewis <stephen@experienceinternet.co.uk>
* @copyright Experience Internet
* @package Omnilog
*/
require_once PATH_THIRD .'omnilog/mcp.omnilog.php';
require_once PATH_THIRD .'om... |
Fix the trailing slash bug. | from django.conf.urls import include, url
from django.contrib import admin
from visualize import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'state', views.StateViewSet)
urlpatterns = [
url(r'^$', ... | from django.conf.urls import include, url
from django.contrib import admin
from visualize import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'state', views.StateViewSet)
urlpatterns = [
url(r'^$', ... |
Handle response with 0 results | var apiKey = "AIzaSyAj9GGrBLnNPImKnl7MKAuD737t1MHnMT8";
var geocoder = require('node-geocoder') ("google", "https", { apiKey: apiKey });
var csv = require('csv');
process.stdin
.pipe(csv.parse())
.pipe(csv.transform(function(data, callback){
setImmediate(function(){
geocoder.geocode(data[1])
.then(functio... | var apiKey = "AIzaSyAj9GGrBLnNPImKnl7MKAuD737t1MHnMT8";
var geocoder = require('node-geocoder') ("google", "https", { apiKey: apiKey });
var csv = require('csv');
process.stdin
.pipe(csv.parse())
.pipe(csv.transform(function(data, callback){
setImmediate(function(){
geocoder.geocode(data[1])
.then(functio... |
Use -1 for hashCode, since 0 has the same effect as "no object" in typical cases (e.g. sequences/sets) | package org.bouncycastle.asn1;
import java.io.IOException;
/**
* A NULL object.
*/
public abstract class ASN1Null
extends ASN1Object
{
public ASN1Null()
{
}
public int hashCode()
{
return -1;
}
boolean asn1Equals(
DERObject o)
{
if (!(o instanceof ASN1Nu... | package org.bouncycastle.asn1;
import java.io.IOException;
/**
* A NULL object.
*/
public abstract class ASN1Null
extends ASN1Object
{
public ASN1Null()
{
}
public int hashCode()
{
return 0;
}
boolean asn1Equals(
DERObject o)
{
if (!(o instanceof ASN1Nul... |
Allow unpacking selected fields in specific order | <?php
class SodaTuple {
public function __construct($fields = array()) {
foreach($fields as $field => $value) {
$this->{$field} = $value;
}
}
public function __call($name, $args) {
if(count($args)) return $this->{$name} = $args[0]; // set method
return $this->{$na... | <?php
class SodaTuple {
public function __construct($fields = array()) {
foreach($fields as $field => $value) {
$this->{$field} = $value;
}
}
public function __call($name, $args) {
if(count($args)) return $this->{$name} = $args[0]; /* set method */
return $this->{... |
chromium: Make login name detection more strict
Check that the login name is inside a link pointing to something under
https://profiles.google.com/ | console.log("goa: GOA content script for GMail loading");
function detectLoginInfo() {
console.log("goa: Scraping for login info");
var selector = '//*[@role="navigation"]//*[starts-with(@href, "https://profiles.google.com/")]//text()[contains(.,"@")]';
var r = document.evaluate(selector, document.body, null, XP... | console.log("goa: GOA content script for GMail loading");
function detectLoginInfo() {
console.log("goa: Scraping for login info");
var r = document.evaluate('//*[@role="navigation"]//text()[contains(.,"@")]', document.body, null, XPathResult.STRING_TYPE, null);
var loginName = r.stringValue;
if (!loginName)
... |
Add initializaton of Cloud Firestore instance for use accross all scripts. | // Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | // Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
Copy the main paragraph 3x | <!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>teodizzo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=... | <!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>teodizzo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.