text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Replace newlines with spaces for readability | import logging
from functools import partial
from lala.util import command, msg
from twisted.internet.utils import getProcessOutput
@command
def fortune(user, channel, text):
"""Show a random, hopefully interesting, adage"""
_call_fortune(user, channel)
@command
def ofortune(user, channel, text):
"""Show... | import logging
from functools import partial
from lala.util import command, msg
from twisted.internet.utils import getProcessOutput
@command
def fortune(user, channel, text):
"""Show a random, hopefully interesting, adage"""
_call_fortune(user, channel)
@command
def ofortune(user, channel, text):
"""Show... |
Improve mapUrl filter. Replace whitespace with %20C. | '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... |
Use IRC style symbols instead of weird mix of IRC symbols and shell symbols. | <?php
function ircReport($stuff)
{
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock, Settings::pluginGet("host"), Settings::pluginGet("port"));
socket_write($sock, $stuff."\n");
socket_close($sock);
}
function ircUserColor($name, $gender, $power) {
$gColors = array(0 => 12, 1 => 13, 2 =... | <?php
function ircReport($stuff)
{
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock, Settings::pluginGet("host"), Settings::pluginGet("port"));
socket_write($sock, $stuff."\n");
socket_close($sock);
}
function ircUserColor($name, $gender, $power) {
$gColors = array(0 => 12, 1 => 13, 2 =... |
Complete alias list test case | package seedu.todo.guitests;
import static org.junit.Assert.*;
import org.junit.Test;
import seedu.todo.guitests.guihandles.AliasItemHandle;
import seedu.todo.models.Task;
// @@author A0139812A
public class AliasCommandTest extends GuiTest {
@Test
public void alias_view_success() {
console.runComma... | package seedu.todo.guitests;
import static org.junit.Assert.*;
import org.junit.Test;
import seedu.todo.guitests.guihandles.AliasItemHandle;
// @@author A0139812A
public class AliasCommandTest extends GuiTest {
@Test
public void alias_view_success() {
console.runCommand("alias");
assertTrue... |
Change hashing for ParticleFilter python class | import hoomd._hoomd as _hoomd
import numpy as np
class ParticleFilter:
def __init__(self, *args, **kwargs):
args_str = ''.join([repr(arg) if not isinstance(arg, np.ndarray)
else repr(list(arg)) for arg in args])
kwargs_str = ''.join([repr(value) if not isinstance(value... | import hoomd._hoomd as _hoomd
class ParticleFilterID:
def __init__(self, *args, **kwargs):
args_str = ''.join([str(arg) for arg in args])
kwargs_str = ''.join([str(value)for value in kwargs.values()])
self.args_str = args_str
self.kwargs_str = kwargs_str
_id = hash(self.__... |
Add link to Firefox’s I2P | /**
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law ... | /**
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law ... |
Change the name of the endpoint | /**
* Created by Neil on 29/09/13.
*/
function signin(mode, callback, clientID) { // clientID filled in by template, immediate = true because we should not need to ask permission again
gapi.auth.authorize({client_id: clientID,
scope: ["https://www.googleapis.com/auth/userinfo.email", "https://www.goog... | /**
* Created by Neil on 29/09/13.
*/
function signin(mode, callback, clientID) { // clientID filled in by template, immediate = true because we should not need to ask permission again
gapi.auth.authorize({client_id: clientID,
scope: ["https://www.googleapis.com/auth/userinfo.email", "https://www.goog... |
Change 'Address App' to Task Manager' | package seedu.address.commons.core;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.task.commons.core.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ConfigTe... | package seedu.address.commons.core;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.task.commons.core.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ConfigTe... |
Add call to random.seed() and change print statement to print function. | # -*- coding: utf-8 -*-
import random
import webbrowser
from pythonkc_meetups import PythonKCMeetups
from optparse import OptionParser
def raffle_time(api_key=None, event_id=None):
client = PythonKCMeetups(api_key=api_key)
attendees = client.get_event_attendees(event_id)
random.seed()
random.shuffle(... | # -*- coding: utf-8 -*-
import random
import webbrowser
from pythonkc_meetups import PythonKCMeetups
from optparse import OptionParser
def raffle_time(api_key=None, event_id=None):
client = PythonKCMeetups(api_key=api_key)
attendees = client.get_event_attendees(event_id)
random.shuffle(attendees)
win... |
Change navbar to be static at top of app. | import React from 'react';
import { Link } from 'react-router-dom';
import { Navbar, Nav, NavItem } from 'react-bootstrap';
const Navigation = (props) => {
return (
<Navbar>
<Navbar.Header>
<Navbar.Brand>
<Link to="/">
Recipeas
</Link>
</Navbar.Brand>
... | import React from 'react';
import { Link } from 'react-router-dom';
import { Navbar, Nav, NavItem } from 'react-bootstrap';
const Navigation = (props) => {
return (
<Navbar fixedTop={true}>
<Navbar.Header>
<Navbar.Brand>
<Link to="/">
Recipeas
</Link>
</Navba... |
Add methods for converting resolution independent pixels (dp) to real pixels and the other way round. | /*
* *
* * LayoutUtil.java
* * as part of mkcommons-android
* *
* * Created by michaelkuck, last updated on 7/25/14 1:00 PM
* * Unless otherwise stated in a separate LICENSE file for this project
* * or agreed via contract, all rights reserved by the author.
*
*/
package com.michael_kuck.android.mkcommo... | /*
* *
* * LayoutUtil.java
* * as part of mkcommons-android
* *
* * Created by michaelkuck, last updated on 7/25/14 1:00 PM
* * Unless otherwise stated in a separate LICENSE file for this project
* * or agreed via contract, all rights reserved by the author.
*
*/
package com.michael_kuck.android.mkcommo... |
Improve notifications around the remove package command | 'use babel';
import DependenciesView from '../views/DependenciesView';
import getDependencies from '../yarn/get-dependencies';
import yarnExec from '../yarn/exec';
import reportError from '../report-error';
import addProgressNotification from '../add-progress-notification';
import path from 'path';
export default asy... | 'use babel';
import DependenciesView from '../views/DependenciesView';
import getDependencies from '../yarn/get-dependencies';
import yarnExec from '../yarn/exec';
import reportError from '../report-error';
export default async function(projectFolder) {
const dependencies = await getDependencies(projectFolder);
... |
Change page target to unprotected sandbox | var Bot = require( 'nodemw' ),
readline = require( 'readline' ),
fs = require( 'fs' ),
c = require( 'ansicolors' ),
rl = readline.createInterface( {
input: process.stdin,
output: process.stdout
} ),
client = new Bot( {
protocol: 'https',
server: 'dev.fandom.com',
path: ''
} ),
params = {
action: 'sc... | var Bot = require( 'nodemw' ),
readline = require( 'readline' ),
fs = require( 'fs' ),
c = require( 'ansicolors' ),
rl = readline.createInterface( {
input: process.stdin,
output: process.stdout
} ),
client = new Bot( {
protocol: 'https',
server: 'dev.fandom.com',
path: ''
} ),
params = {
action: 'sc... |
Remove unneccessary attack action 'toggleFavorite' | import * as types from './types';
export const showAttack = (attackId) => {
return {
type: types.SHOW_ATTACK,
attackId
};
}
export const setAttacks = (attacks) => {
return {
type: types.SET_ATTACKS,
attacks
};
}
export const setPendingAttackEdits = (attack) => {
return {
type: types.SET... | import * as types from './types';
export const favoriteAttack = (attack) => {
return {
type: types.TOGGLE_FAVORITE,
attack
};
}
export const showAttack = (attackId) => {
return {
type: types.SHOW_ATTACK,
attackId
};
}
export const setAttacks = (attacks) => {
return {
type: types.SET_ATT... |
Revert "Changing this to a release candidate."
This reverts commit a9f8afbc1c5a40d0a35e3a9757f8c96da494d35a. | from setuptools import setup, find_packages
GITHUB_ALERT = """**NOTE**: These are the docs for the version of envbuilder in git. For
documentation on the last release, see the `pypi_page <http://pypi.python.org/pypi/envbuilder/>`_."""
readme = open('README.rst', 'r')
unsplit_readme_text = readme.read()
split_text =... | from setuptools import setup, find_packages
GITHUB_ALERT = """**NOTE**: These are the docs for the version of envbuilder in git. For
documentation on the last release, see the `pypi_page <http://pypi.python.org/pypi/envbuilder/>`_."""
readme = open('README.rst', 'r')
unsplit_readme_text = readme.read()
split_text =... |
Add coverage to some of log.py | import json
import logging
from unittest.mock import Mock, patch
from jsonrpcclient.log import _trim_string, _trim_values, _trim_message
def test_trim_string():
message = _trim_string("foo" * 100)
assert "..." in message
def test_trim_values():
message = _trim_values({"list": [0] * 100})
assert "..... | import json
import logging
from unittest.mock import Mock, patch
from jsonrpcclient.log import _trim_string, _trim_values
def test_trim_string():
message = _trim_string("foo" * 100)
assert "..." in message
def test_trim_values():
message = _trim_values({"list": [0] * 100})
assert "..." in message["... |
Use [] notation in wrapper module for task management | from t2activity import NestedWorkflow
from t2types import ListType, String
from t2flow import Workflow
class WrapperWorkflow(Workflow):
def __init__(self, flow):
self.flow = flow
Workflow.__init__(self, flow.title, flow.author, flow.description)
self.task[flow.name] = NestedWorkflow(flow)
nested = self.task[... | from t2activity import NestedWorkflow
from t2types import ListType, String
from t2flow import Workflow
class WrapperWorkflow(Workflow):
def __init__(self, flow):
self.flow = flow
Workflow.__init__(self, flow.title, flow.author, flow.description)
setattr(self.task, flow.name, NestedWorkflow(flow))
nested = ge... |
Remove debug print in test. | package scraper
import (
"os"
"os/exec"
"testing"
"time"
"github.com/pachyderm/pachyderm/src/client/pkg/require"
)
func TestScraper(t *testing.T) {
require.NoError(t, exec.Command("pachctl", "create-repo", "urls").Run())
require.NoError(t, exec.Command("pachctl", "start-commit", "urls", "master").Run())
putF... | package scraper
import (
"fmt"
"os"
"os/exec"
"testing"
"time"
"github.com/pachyderm/pachyderm/src/client/pkg/require"
)
func TestScraper(t *testing.T) {
wd, err := os.Getwd()
require.NoError(t, err)
fmt.Printf("wd: %s", wd)
require.NoError(t, exec.Command("pachctl", "create-repo", "urls").Run())
require.... |
Print player emails in migration script. | import store
rstore = store.RedisStore()
def populate_terminations():
for game in rstore.all_games():
rstore.set_game(game["game_id"], game["game"])
def populate_game_ids():
keys = rstore.rconn.keys("chess:games:*:game")
game_ids = [k.split(":")[-2] for k in keys]
rstore.rconn.sadd("chess:gam... | import store
rstore = store.RedisStore()
def populate_terminations():
for game in rstore.all_games():
rstore.set_game(game["game_id"], game["game"])
def populate_game_ids():
keys = rstore.rconn.keys("chess:games:*:game")
game_ids = [k.split(":")[-2] for k in keys]
rstore.rconn.sadd("chess:gam... |
Use string resource instead of hardcoded string | package fr.free.nrw.commons.nearby;
import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.ViewHolder;
import fr.free.nrw.commons.ut... | package fr.free.nrw.commons.nearby;
import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.ViewHolder;
import fr.free.nrw.commons.ut... |
Add cors whitelist configuration to api | const express = require('express');
const morganLogger = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const RateLimit = require('express-rate-limit');
const cors = require('cors');
const log = require('./config/logger');
const { blogPostRoute, healthCheckRoute } =... | const express = require('express');
const morganLogger = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const RateLimit = require('express-rate-limit');
const cors = require('cors');
const log = require('./config/logger');
const { blogPostRoute, healthCheckRoute } =... |
Change iOS back button color to white | /**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
import React, {
AppRegistry,
Component,
NavigatorIOS,
StyleSheet
} from 'react-native';
import ContestListScreen from './ContestListScreen';
import { PRIMARY_COLOR } from './Constants';
import moment from 'mo... | /**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
import React, {
AppRegistry,
Component,
NavigatorIOS,
StyleSheet
} from 'react-native';
import ContestListScreen from './ContestListScreen';
import { PRIMARY_COLOR } from './Constants';
import moment from 'mo... |
Make test runner work with blank mysql password | import os
import os.path
import configparser
import shutil
import subprocess
# Setup
print("Setting up...")
if os.path.isfile("../halite.ini"):
shutil.copyfile("../halite.ini", "temp.ini")
shutil.copyfile("tests.ini", "../halite.ini")
parser = configparser.ConfigParser()
parser.read("../halite.ini")
# Website te... | import os
import os.path
import configparser
import shutil
import subprocess
# Setup
print("Setting up...")
if os.path.isfile("../halite.ini"):
shutil.copyfile("../halite.ini", "temp.ini")
shutil.copyfile("tests.ini", "../halite.ini")
parser = configparser.ConfigParser()
parser.read("../halite.ini")
# Website te... |
Make `initial` argument to `accumulate` optional | from functools import partial
from itertools import accumulate as accumulate_, chain, tee
MYPY = False
if MYPY:
from typing import Callable, Iterable, Iterator, Optional, Tuple, TypeVar
T = TypeVar('T')
filter_ = partial(filter, None) # type: Callable[[Iterator[Optional[T]]], Iterator[T]]
flatten = chain.fr... | from functools import partial
from itertools import accumulate as accumulate_, chain, tee
MYPY = False
if MYPY:
from typing import Callable, Iterable, Iterator, Optional, Tuple, TypeVar
T = TypeVar('T')
filter_ = partial(filter, None) # type: Callable[[Iterator[Optional[T]]], Iterator[T]]
flatten = chain.fr... |
Disable random test for Jenkins | /*
* Copyright (c) 2014, Cloudera, Inc. All Rights Reserved.
*
* Cloudera, Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICE... | /*
* Copyright (c) 2014, Cloudera, Inc. All Rights Reserved.
*
* Cloudera, Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICE... |
Modify parseErrorResponse to return JSON API compatible array | import Ember from 'ember';
import DS from 'ember-data';
const VALIDATION_ERROR_STATUSES = [400, 422];
export default DS.RESTAdapter.extend({
namespace: 'api',
isInvalid: function(status) {
return VALIDATION_ERROR_STATUSES.indexOf(status) >= 0;
},
// Override the parseErrorResponse method from RESTAdapte... | import DS from 'ember-data';
const VALIDATION_ERROR_STATUSES = [400, 422];
export default DS.RESTAdapter.extend({
namespace: 'api',
isInvalid: function(status) {
return VALIDATION_ERROR_STATUSES.indexOf(status) >= 0;
},
// Override the parseErrorResponse method from RESTAdapter
// so that we can munge... |
Allow Fake Backend to take an image as the screen | import numpy as np
from ..core import Location
class GeistFakeBackend(object):
def __init__(self, image=None, w=800, h=600):
if image is None:
self.image = np.zeros((h, w, 3))
self.locations = [Location(0, 0, w=w, h=h, image=self.image)]
else:
if isinstance(imag... | import numpy as np
from ..core import Location
class GeistFakeBackend(object):
def __init__(self, w=800, h=600):
self.image = np.zeros((h, w, 3))
self.locations = [Location(0, 0, w=w, h=h, image=self.image)]
def create_process(self, command):
pass
def actions_transaction(self):
... |
Improve module definition generation script
The script no longer produces unnecessary module declarations. | 'use strict';
var fs = require('fs');
var mkdirp = require('mkdirp');
var path = require('path');
var banner = require('./banner');
var dest = path.resolve(__dirname, '../dist/event-station.d.ts');
var dist = path.resolve(__dirname, '../dist');
var src = path.resolve(__dirname, '../build/dts/main.d.ts');
mkdirp(dis... | 'use strict';
var fs = require('fs');
var mkdirp = require('mkdirp');
var path = require('path');
var banner = require('./banner');
var dest = path.resolve(__dirname, '../dist/event-station.d.ts');
var dist = path.resolve(__dirname, '../dist');
var src = path.resolve(__dirname, '../build/dts/main.d.ts');
mkdirp(dis... |
Use only android and ios browser for autoprefixer | var ExtractText = require('extract-text-webpack-plugin');
var LessClean = require('less-plugin-clean-css');
var HtmlFile = require('html-webpack-plugin');
var webpack = require('webpack');
var config = {
cache: true,
entry: {
android: './src/android/main.less',
ios: './src/ios/main.less'
},
output: {
... | var ExtractText = require('extract-text-webpack-plugin');
var LessClean = require('less-plugin-clean-css');
var HtmlFile = require('html-webpack-plugin');
var webpack = require('webpack');
var config = {
cache: true,
entry: {
android: './src/android/main.less',
ios: './src/ios/main.less'
},
output: {
... |
Add some output to let users know what is about to be scraped. | package main
import (
"flag"
"fmt"
"log"
"strings"
"github.com/PuerkitoBio/goquery"
)
type user struct {
name string
email string
url string
username string
}
func main() {
url := flag.String("github_url", "", "github url you want to scrape")
flag.Parse()
githubURL := *url
doc, err := goque... | package main
import (
"flag"
"fmt"
"log"
"strings"
"github.com/PuerkitoBio/goquery"
)
type user struct {
name string
email string
url string
username string
}
func main() {
url := flag.String("github_url", "", "github url you want to scrape")
flag.Parse()
githubURL := *url
doc, err := goque... |
Fix implied_group, it still refers to the old module name | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public ... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public ... |
Change a bracelet to new line | <?php
namespace Juy\CharacterSolver;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Http\Kernel;
class CharacterSolverServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @param \Illuminate\Contracts\Http\Kernel $kernel
* @return void
... | <?php
namespace Juy\CharacterSolver;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Http\Kernel;
class CharacterSolverServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @param \Illuminate\Contracts\Http\Kernel $kernel
* @return void
... |
Fix compatibility with Phalcon 2 | <?php
/**
* @author Patsura Dmitry https://github.com/ovr <talk@dmtry.me>
*/
namespace User;
use Phalcon\DiInterface;
class Module implements \Phalcon\Mvc\ModuleDefinitionInterface
{
public function registerAutoloaders(DiInterface $dependencyInjector = null)
{
$loader = new \Phalcon\Loader();
... | <?php
/**
* @author Patsura Dmitry https://github.com/ovr <talk@dmtry.me>
*/
namespace User;
class Module implements \Phalcon\Mvc\ModuleDefinitionInterface
{
public function registerAutoloaders()
{
$loader = new \Phalcon\Loader();
$loader->registerNamespaces(array(
'User\Controll... |
Add project to hook table so it's a little more clear what it's a global one. | import django_tables2 as tables
from fabric_bolt.core.mixins.tables import ActionsColumn, PaginateTable
from fabric_bolt.web_hooks import models
class HookTable(PaginateTable):
"""Table used to show the configurations
Also provides actions to edit and delete"""
actions = ActionsColumn([
{'titl... | import django_tables2 as tables
from fabric_bolt.core.mixins.tables import ActionsColumn, PaginateTable
from fabric_bolt.web_hooks import models
class HookTable(PaginateTable):
"""Table used to show the configurations
Also provides actions to edit and delete"""
actions = ActionsColumn([
{'titl... |
Fix bug with registering local methods that got garbage collected due to django's weakref handling in signals. | def set_defaults(app, *defaults):
"Installs a set of default values during syncdb processing"
from django.core.exceptions import ImproperlyConfigured
from django.db.models import signals
from dbsettings.loading import get_setting_storage, set_setting_value
if not defaults:
raise Impr... | def set_defaults(app, *defaults):
"Installs a set of default values during syncdb processing"
from django.core.exceptions import ImproperlyConfigured
from django.db.models import signals
from dbsettings.loading import get_setting_storage, set_setting_value
if not defaults:
raise Impr... |
Fix range error in randomColor test | var lodash = require('lodash');
var expect = require('chai').expect;
var testPath = require('path').join(__dirname, '../../src/colors/randomColor');
var _ = require(testPath)(lodash);
module.exports = function() {
describe('randomColor', function() {
it('exists', function() {
expect(_.randomCol... | var lodash = require('lodash');
var expect = require('chai').expect;
var testPath = require('path').join(__dirname, '../../src/colors/randomColor');
var _ = require(testPath)(lodash);
module.exports = function() {
describe('randomColor', function() {
it('exists', function() {
expect(_.randomCol... |
Split out the dependencies of client and server. | from setuptools import setup
setup(
name="rotterdam",
version="0.3.2",
description=(
"Simple asynchronous job queue via redis."
),
author="William Glass",
author_email="william.glass@gmail.com",
url="http://github.com/wglass/rotterdam",
packages=["rotterdam"],
include_packag... | from setuptools import setup
setup(
name="rotterdam",
version="0.3.2",
description=(
"Simple distributed job queue via redis."
),
author="William Glass",
author_email="william.glass@gmail.com",
url="http://github.com/wglass/rotterdam",
packages=["rotterdam"],
include_package... |
Use simple name iso full class name to choose a port | package be.bagofwords.web;
import be.bagofwords.application.MainClass;
import be.bagofwords.application.annotations.BowConfiguration;
import be.bagofwords.util.HashUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
@BowConfiguration
public class W... | package be.bagofwords.web;
import be.bagofwords.application.MainClass;
import be.bagofwords.application.annotations.BowConfiguration;
import be.bagofwords.util.HashUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
@BowConfiguration
public class W... |
Tweak formatting of argparse section to minimize lines extending past 80 chars. | #!/usr/bin/env python
# CLI frontend to Arris modem stat scraper library arris_scraper.py
import argparse
import arris_scraper
import json
import pprint
default_url = 'http://192.168.100.1/cgi-bin/status_cgi'
parser = argparse.ArgumentParser(description='CLI tool to scrape information from Arris cable modem status ... | #!/usr/bin/env python
# CLI frontend to Arris modem stat scraper library arris_scraper.py
import argparse
import arris_scraper
import json
import pprint
default_url = 'http://192.168.100.1/cgi-bin/status_cgi'
parser = argparse.ArgumentParser(description='CLI tool to scrape information from Arris cable modem status ... |
Add workaround for atomic writes in watch mode | let chokidar = require('chokidar');
class Task {
/**
* Create a new task instance.
*
* @param {Object} data
*/
constructor(data) {
this.data = data;
this.assets = [];
this.isBeingWatched = false;
}
/**
* Watch all relevant files for changes.
*
... | let chokidar = require('chokidar');
class Task {
/**
* Create a new task instance.
*
* @param {Object} data
*/
constructor(data) {
this.data = data;
this.assets = [];
this.isBeingWatched = false;
}
/**
* Watch all relevant files for changes.
*
... |
Fix bug where homepage only displayed once.
Resolves #383 | //
// Gistbook
// A model representing a new Gistbook
//
import * as _ from 'underscore';
import { BaseModel, BaseCollection } from 'base/entities';
export default BaseModel.extend({
initialize() {
this._dirty = false;
this.on('change', this._markDirty, this);
this.listenTo(this.get('pages'), 'change', ... | //
// Gistbook
// A model representing a new Gistbook
//
import { BaseModel, BaseCollection } from 'base/entities';
export default BaseModel.extend({
initialize() {
this._dirty = false;
this.on('change', this._markDirty, this);
this.listenTo(this.get('pages'), 'change', this._markDirty);
},
// Crea... |
:key: Change dir to serve resources from public dir | <?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that... | <?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that... |
Change fixture upload task to json serializer | from __future__ import absolute_import, unicode_literals
from celery.task import task
from soil import DownloadBase
from corehq.apps.fixtures.upload import upload_fixture_file
@task
def fixture_upload_async(domain, download_id, replace):
task = fixture_upload_async
DownloadBase.set_progress(task, 0, 100)
... | from __future__ import absolute_import
from __future__ import unicode_literals
from corehq.apps.fixtures.upload import upload_fixture_file
from soil import DownloadBase
from celery.task import task
@task(serializer='pickle')
def fixture_upload_async(domain, download_id, replace):
task = fixture_upload_async
D... |
Fix typo in latest change for Base Controller Autoload. | <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Authenticated Controller
*
* Provides a base class for all controllers that must check user login
* status.
*
* @package Bonfire\Core\Controllers
* @category Controllers
* @author Bonfire Dev Team
* @link http://guid... | <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Authenticated Controller
*
* Provides a base class for all controllers that must check user login
* status.
*
* @package Bonfire\Core\Controllers
* @category Controllers
* @author Bonfire Dev Team
* @link http://guid... |
Add wait before switching iframe. This will stablize the e2e tests. | /**
* Copyright 2019 The Subscribe with Google Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* U... | /**
* Copyright 2019 The Subscribe with Google Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* U... |
Upgrade to Keras 2 API | from keras.layers import Conv2D
from keras.models import Sequential
from toolbox.metrics import psnr
def compile_srcnn(input_shape, c=1, f1=9, f2=1, f3=5, n1=64, n2=32):
"""Compile an SRCNN model.
See https://arxiv.org/abs/1501.00092.
"""
model = Sequential()
model.add(Conv2D(n1, f1, kernel_init... | from keras.layers import Conv2D
from keras.models import Sequential
from toolbox.metrics import psnr
def compile_srcnn(input_shape, c=1, f1=9, f2=1, f3=5, n1=64, n2=32):
"""Compile an SRCNN model.
See https://arxiv.org/abs/1501.00092.
"""
model = Sequential()
model.add(Conv2D(nb_filter=n1, nb_ro... |
Make sure __setitem__ is available for site.register() | from django.contrib.admin.sites import AdminSite as DjangoAdminSite
from django.contrib.admin.sites import site as django_site
class HatbandAndDjangoRegistry(object):
def __init__(self, site, default_site=None):
if default_site is None:
default_site = django_site
super(HatbandAndDjango... | from django.contrib.admin.sites import AdminSite as DjangoAdminSite
from django.contrib.admin.sites import site as django_site
class HatbandAndDjangoRegistry(object):
def __init__(self, site, default_site=None):
if default_site is None:
default_site = django_site
super(HatbandAndDjango... |
Rename prop for image source to imageSource instead of text | import React, { Component } from 'react';
import { TouchableOpacity, Image, View } from 'react-native';
// import styles from './styles/ClickableImageStyle';
import PropTypes from 'prop-types';
import { StackNagivator } from 'react-navigation';
import FadeInView from '../animations/FadeInView';
export default class Cl... | import React, { Component } from 'react';
import { TouchableOpacity, Image, View } from 'react-native';
// import styles from './styles/ClickableImageStyle';
import PropTypes from 'prop-types';
import { StackNagivator } from 'react-navigation';
import FadeInView from '../animations/FadeInView';
export default class Cl... |
Revert "util: make DeflateRaw Checksum hook into _transform so that it mimicks the norms."
This reverts commit cf22d920b48c3c320b0a7a75577b082901db07a6. | var zlib = require('zlib');
var inherits = require('util').inherits;
var util = require('./');
function DeflateRawChecksum(options) {
zlib.DeflateRaw.call(this, options);
this.checksum = util.crc32.createCRC32();
this.digest = null;
this.rawSize = 0;
this.compressedSize = 0;
this.on('data', function(ch... | var zlib = require('zlib');
var inherits = require('util').inherits;
var util = require('./');
function DeflateRawChecksum(options) {
zlib.DeflateRaw.call(this, options);
this.checksum = util.crc32.createCRC32();
this.digest = null;
this.rawSize = 0;
this.compressedSize = 0;
this.on('data', function(ch... |
Test line end carriages redo. | import moment from 'moment';
import { Paginator } from '../../../utils';
import template from './outdated-queries.html';
function OutdatedQueriesCtrl($scope, Events, $http, $timeout) {
Events.record('view', 'page', 'admin/outdated_queries');
$scope.autoUpdate = true;
this.queries = new Paginator([], { itemsPer... |
import moment from 'moment';
import { Paginator } from '../../../utils';
import template from './outdated-queries.html';
function OutdatedQueriesCtrl($scope, Events, $http, $timeout) {
Events.record('view', 'page', 'admin/outdated_queries');
$scope.autoUpdate = true;
this.queries = new Paginator([], { itemsPe... |
Allow for root-level domains like localhost | /**
* Expose `sni`.
* @type Function
*/
module.exports = sni;
/**
* RegEx for finding a domain name.
* @type {RegExp}
*/
var regex = /^(?:[a-z0-9-]+\.)*[a-z]+$/i;
/**
* Extract the SNI from a Buffer.
* @param {Buffer} buf
* @return {String|null}
*/
function sni(buf) {
var sni = null;
for(var b = ... | /**
* Expose `sni`.
* @type Function
*/
module.exports = sni;
/**
* RegEx for finding a domain name.
* @type {RegExp}
*/
var regex = /^(?:[a-z0-9-]+\.)+[a-z]+$/i;
/**
* Extract the SNI from a Buffer.
* @param {Buffer} buf
* @return {String|null}
*/
function sni(buf) {
var sni = null;
for(var b = ... |
[SYN5-294] Hide the user_profile data class | export default {
list() {
this.NewLibConnection
.Class
.please()
.list()
.ordering('desc')
.then((classes) => {
const classesList = classes.filter((item) => item.name !== 'user_profile');
this.completed(classesList);
})
.catch(this.failure);
},
get(n... | export default {
list() {
this.NewLibConnection
.Class
.please()
.list()
.ordering('desc')
.then(this.completed)
.catch(this.failure);
},
get(name) {
this.NewLibConnection
.Class
.please()
.get({ name })
.then(this.completed)
.catch(this.f... |
Fix bug where page stops updating by forcing it to reload after a minute
of no activity | #!/bin/env python
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from time import sleep
from getpass import getpass
if __name__ == '__main__':
driver = webdriver.phantomjs.webdriver.WebDriver()
driver.get('https://facebook.com')
driver.find_element_by_... | #!/bin/env python
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from time import sleep
from getpass import getpass
if __name__ == '__main__':
driver = webdriver.phantomjs.webdriver.WebDriver()
driver.get('https://facebook.com')
driver.find_element_by_... |
Include only fields that a component needs | var Appbase = require('appbase-js');
module.exports = {
getRequestObject: function (config, fieldName, boundingBoxCoordinates, streaming) {
var geo_bounding_box = JSON.parse(`{"${fieldName}":` + JSON.stringify(boundingBoxCoordinates) + '}');
var _source = !streaming ? `${fieldName}` : null;
return ({
type... | var Appbase = require('appbase-js');
module.exports = {
getRequestObject: function (config, fieldName, boundingBoxCoordinates) {
var geo_bounding_box = JSON.parse(`{"${fieldName}":` + JSON.stringify(boundingBoxCoordinates) + '}');
return ({
type: config.appbase.type,
body: {
"size": 1000,
"query":... |
Add dollar sign to fares, sort by fare type |
import tornado.web
import ipy_table
from transperth.location import Location
class BaseRequestHandler(tornado.web.RequestHandler):
@property
def args(self):
args = self.request.arguments
return {
k: [sv.decode() for sv in v]
for k, v in args.items()
}
def... |
import tornado.web
import ipy_table
from transperth.location import Location
class BaseRequestHandler(tornado.web.RequestHandler):
@property
def args(self):
args = self.request.arguments
return {
k: [sv.decode() for sv in v]
for k, v in args.items()
}
def... |
Fix SoundCloud embed width/height replacement.
SoundCloud embeds aren't always 500x500.
Also, don't set the "width" embed dict key to '100%':
"width"/"height" keys expect integers only. | from urllib.parse import urlparse
from django.conf import settings
from wagtail.wagtailembeds.finders.embedly import embedly
from wagtail.wagtailembeds.finders.oembed import oembed
def get_default_finder():
if hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'):
return embedly
return oembed
def finder(... | from urllib.parse import urlparse
from django.conf import settings
from wagtail.wagtailembeds.finders.embedly import embedly
from wagtail.wagtailembeds.finders.oembed import oembed
def get_default_finder():
if hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'):
return embedly
return oembed
def finder(... |
Update bootstrapped package.json to use Webpack and Karma CLIs | import { join } from 'path'
import json from '../util/json'
const saguiScripts = {
'start': 'npm run develop',
'test': 'NODE_ENV=test karma start',
'test:watch': 'npm test -- --no-single-run --auto-watch',
'develop': 'webpack-dev-server --port 3000 --host 0.0.0.0',
'build': 'webpack',
'dist': 'NODE_ENV=pro... | import { join } from 'path'
import json from '../util/json'
const saguiScripts = {
'start': 'npm run develop',
'test': 'NODE_ENV=test sagui test',
'test-watch': 'NODE_ENV=test sagui test --watch',
'develop': 'sagui develop',
'build': 'sagui build',
'dist': 'NODE_ENV=production sagui dist'
}
export default... |
Use ugettext_lazy instead of ugettext to support Django 1.7 migrations | from django.db import models
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
class Feedback(models.Model):
site = models.ForeignKey(Site, verbose_name=_('site'))
url = models.CharField(max_length=255, verbose_name=_('url'))
urlhash = models.TextField(ve... | from django.db import models
from django.contrib.sites.models import Site
from django.utils.translation import ugettext as _
class Feedback(models.Model):
site = models.ForeignKey(Site, verbose_name=_('site'))
url = models.CharField(max_length=255, verbose_name=_('url'))
urlhash = models.TextField(verbose... |
Split replacement pattern over multiple lines
This makes it a little more readable and maintainable. | /*
* Pattern matching the prefix of at least one stripped query string
* parameter. We'll search the query string portion of the URL for this
* pattern to determine if there's any stripping work to do.
*/
var searchPattern = new RegExp('utm_|clid|mkt_tok', 'i');
/*
* Pattern matching the query string parameters (... | /*
* Pattern matching the prefix of at least one stripped query string
* parameter. We'll search the query string portion of the URL for this
* pattern to determine if there's any stripping work to do.
*/
var searchPattern = new RegExp('utm_|clid|mkt_tok', 'i');
/*
* Pattern matching the query string parameters (... |
Hide dirs on Windows only | import Promise from 'bluebird'
import childProcess from 'child_process'
import logger from '../logger'
Promise.promisifyAll(childProcess)
const log = logger({
component: 'FS'
})
// Hides a directory on Windows.
// Errors are logged, not thrown.
export async function hideOnWindows (path: string): Promise<void> {
... | import Promise from 'bluebird'
import childProcess from 'child_process'
import logger from '../logger'
Promise.promisifyAll(childProcess)
const log = logger({
component: 'FS'
})
// Hides a directory on Windows.
// Errors are logged, not thrown.
export async function hideOnWindows (path: string): Promise<void> {
... |
Introduce a `render` method that generates content without beeing forced to put the result in a file. | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\GeneratorBundle\Generator;
/**
* Generator is the base c... | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\GeneratorBundle\Generator;
/**
* Generator is the base c... |
Order and comment
Organizar y comentar | angular.module('wi.bar.mainGridBar', [])
/**
* Grid Bar Ctrlr | Controlador de la Barra del Grid
*/
.controller('GridBarCtrl', ['$scope',
function ($scope) {
// *** CREATE | CREAR ***
// Create button click event | Evento clic en el botón Crear
$scope.createClk = function() {
console.log('Create... | angular.module('wi.bar.mainGridBar', [])
/**
* Grid Bar Ctrlr | Controlador de la Barra del Grid
*/
.controller('GridBarCtrl', ['$scope',
function ($scope) {
// Search String | String de búsqueda
$scope.searchString = '';
// Create Event
$scope.createClk = function() {
console.log('Create Clic... |
Fix click handler in MaterialTextInputSpec
Summary: For litho component click event handler to work in this case, we need to pass the clickhandler to the underling EditTextWithEventHandlers from TextInputSpec.
Reviewed By: adityasharat
Differential Revision: D25946471
fbshipit-source-id: 07e5b5455ed2a736f030aedc8dc... | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... |
Make single byte matchers throw an indexoutofboundsexception if an attempt is made to get a singlebytematcher other than in position zero. | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.domesdaybook.matcher.singlebyte;
import net.domesdaybook.matcher.sequence.SequenceMatcher;
/**
*
* @author matt
*/
public abstract class AbstractSingleByteSequence implements SingleByteMatcher {
/*... | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.domesdaybook.matcher.singlebyte;
import net.domesdaybook.matcher.sequence.SequenceMatcher;
/**
*
* @author matt
*/
public abstract class AbstractSingleByteSequence implements SingleByteMatcher {
/*... |
Update some popover in BCBProcess |
class BCBProcess extends CommonProcess {
constructor() {
super({
name: `${Project.NAME} Process`
});
this.initProcess();
}
initProcess() {
this.initPopover();
}
initPopover() {
{
new PopoverController({
name: 'ID Popover',
selector: '#login-id-help',... |
class BCBProcess extends CommonProcess {
constructor() {
super({
name: `${Project.NAME} Process`
});
this.initProcess();
}
initProcess() {
this.initPopover();
}
initPopover() {
{
new PopoverController({
name: 'ID Popover',
selector: '#login-id-help',... |
Set speech rates to 1.0/0.8 | /*
* Copyright (c) 2016 Reto Inderbitzin (mail@indr.ch)
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
package ch.indr.threethreefive.services;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;... | /*
* Copyright (c) 2016 Reto Inderbitzin (mail@indr.ch)
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
package ch.indr.threethreefive.services;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;... |
Add comments to Singleton about usage. |
class Singleton(object):
"""
This is a class that implements singleton for its subclasses.
The technique is based on a variant of other techniques found in:
http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
https://gist.github.com/werediver/4396488
The technique is simp... | """
File: singleton.py
Purpose: Defines a class whose subclasses will act like the singleton pattern.
"""
class Singleton(object):
"""
This is a class that implements singleton for its subclasses.
The technique is based on a variant of other techniques found in:
http://stackoverflow.com/questions/6... |
Add LayoutContainer to route root | /**
* Route definitions
*/
import React from 'react'
import { IndexRedirect, IndexRoute, Route } from 'react-router'
// Layout
import { LayoutContainer } from 'components/Layout'
// Pages
import Home from 'client/pages/Home'
import Terms from 'client/pages/Terms'
import BikeshedViewer from 'client/pages/BikeshedVie... | /**
* Route definitions
*/
import React from 'react'
import { IndexRedirect, IndexRoute, Route } from 'react-router'
// Pages
import Home from 'client/pages/Home'
import Terms from 'client/pages/Terms'
import BikeshedViewer from 'client/pages/BikeshedViewer'
// Queries
import ViewerQueries from 'client/queries/View... |
Set `canRetransform` flag to `false` in instrumentation.
We do not need to retransform classes once they are loaded.
All instrumentation byte-code is pushed at loading time.
This fixes a problem with Java 7 that was failing to add
a transformer because we did not declare retransformation
capability in `MANIFEST.MF` f... | /* NEST (New Scala Test)
* Copyright 2007-2013 LAMP/EPFL
* @author Grzegorz Kossakowski
*/
package scala.tools.partest.javaagent;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
/**
* Profiling agent that instruments byte-code to insert calls to
* {@link scal... | /* NEST (New Scala Test)
* Copyright 2007-2013 LAMP/EPFL
* @author Grzegorz Kossakowski
*/
package scala.tools.partest.javaagent;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
/**
* Profiling agent that instruments byte-code to insert calls to
* {@link scal... |
Load config from executing directory | const syrup = require('../../');
syrup.config(`./config.yaml`);
syrup.scenario('example.org1', `${__dirname}/test-example.org`, [], 'IEBrowser');
syrup.scenario('example.org2', `${__dirname}/test-example.org`, [], 'IEBrowser');
syrup.scenario('example.org3', `${__dirname}/test-example.org`, [], 'IEBrowser');
syrup.sc... | const syrup = require('../../');
syrup.config(`${__dirname}/config.yaml`);
syrup.scenario('example.org1', `${__dirname}/test-example.org`, [], 'IEBrowser');
syrup.scenario('example.org2', `${__dirname}/test-example.org`, [], 'IEBrowser');
syrup.scenario('example.org3', `${__dirname}/test-example.org`, [], 'IEBrowser'... |
Fix shell syntax for non bash shells
The custom make command in mono.py is executed with the default shell,
which on some systems doesn't support the fancy for loop syntax, like
dash on Ubuntu. | class MonoPackage (Package):
def __init__ (self):
Package.__init__ (self, 'mono', '2.10',
sources = [
'http://ftp.novell.com/pub/%{name}/sources/%{name}/%{name}-%{version}.tar.bz2',
'patches/mono-runtime-relocation.patch'
],
configure_flags = [
'--with-jit=yes',
'--with-ikvm=no',
'--with... | class MonoPackage (Package):
def __init__ (self):
Package.__init__ (self, 'mono', '2.10',
sources = [
'http://ftp.novell.com/pub/%{name}/sources/%{name}/%{name}-%{version}.tar.bz2',
'patches/mono-runtime-relocation.patch'
],
configure_flags = [
'--with-jit=yes',
'--with-ikvm=no',
'--with... |
Fix publishing the current tag | #!/usr/bin/env node
'use strict'
var childProcess = require('child_process')
, fs = require('fs')
, packageJson = JSON.parse(fs.readFileSync('./package.json'))
, version = packageJson.version
, parts = version.split('.')
, last = +parts[parts.length - 1]
, bumped = last + 1
, nextParts = parts.slice(0, ... | #!/usr/bin/env node
'use strict'
var childProcess = require('child_process')
, fs = require('fs')
, packageJson = JSON.parse(fs.readFileSync('./package.json'))
, version = packageJson.version
, parts = version.split('.')
, last = +parts[parts.length - 1]
, bumped = last + 1
, nextParts = parts.slice(0, ... |
Remove controller view from view (redundant) | package editor;
import javax.swing.*;
import java.awt.*;
/**
* The NewRootView is used to create the GUI that is used to create a new root
* XML element.
*/
public class NewRootView extends JFrame {
private JTextField rootTagField;
/**
* Create the view and set up the look of the GUI
* @param ne... | package editor;
import javax.swing.*;
import java.awt.*;
/**
* The NewRootView is used to create the GUI that is used to create a new root
* XML element.
*/
public class NewRootView extends JFrame {
private NewRootController controller;
private JTextField rootTagField;
/**
* Create the view and s... |
Fix encoding issues with open()
Traceback (most recent call last):
File "setup.py", line 7, in <module>
readme = f.read()
File "/usr/lib/python3.5/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 4... | #!/usr/bin/env python
import os
from io import open
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst'), encoding='utf-8') as f:
readme = f.read()
setup(
name='ctop',
version='1.0.0',
description='A lightweight top like monitor for linux CGroups',
long_des... | #!/usr/bin/env python
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as f:
readme = f.read()
setup(
name='ctop',
version='1.0.0',
description='A lightweight top like monitor for linux CGroups',
long_description=readme,
author='Jean-Tiar... |
Use `Localization.getCurrentDeviceCountryAsync` if its version of expo is over 26 since it's deprecated.
ref:https://github.com/expo/expo-docs/tree/master/versions/v26.0.0/sdk | let RNVersionCheck;
if (process.env.RNVC_ENV === 'test') {
RNVersionCheck = {
country: 'ko',
packageName: 'com.reactnative.versioncheck',
currentBuildNumber: 1,
currentVersion: '0.0.1',
};
} else {
const { Platform } = require('react-native');
const { Constants, Localization, Util } = require('e... | let RNVersionCheck;
if (process.env.RNVC_ENV === 'test') {
RNVersionCheck = {
country: 'ko',
packageName: 'com.reactnative.versioncheck',
currentBuildNumber: 1,
currentVersion: '0.0.1',
};
} else {
const { Platform } = require('react-native');
const { Constants, Util } = require('expo');
cons... |
Remove not needed bean declaration | /*
* MIT Licence
* Copyright (c) 2017 Simon Frankenberger
*
* Please see LICENCE.md for complete licence text.
*/
package eu.fraho.spring.example;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.boot.SpringApplication;
import org.springframew... | /*
* MIT Licence
* Copyright (c) 2017 Simon Frankenberger
*
* Please see LICENCE.md for complete licence text.
*/
package eu.fraho.spring.example;
import eu.fraho.spring.securityJwt.CryptPasswordEncoder;
import eu.fraho.spring.securityJwt.config.CryptConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.bou... |
Fix bug: Call speedDrop too many times
Use a boolean to record if it is speedDroping | var ai = ai || {}; //!< @namespace ai
ai.init = function(){
setInterval("ai._mainLoop();", 1000 / 120);
setInterval("api.keepPlay();", 1000 / 60);
ai.speedDroping = false;
}
ai._mainLoop = function(){
obs = api.getObstacles();
if (obs.length != 0){
var bound = 280 * (api.getCurrentSpeed() / Runner.con... | var ai = ai || {}; //!< @namespace ai
ai.init = function(){
setInterval("ai._mainLoop();", 1000 / 120);
setInterval("api.keepPlay();", 1000 / 60);
}
ai._mainLoop = function(){
obs = api.getObstacles();
if (obs.length != 0){
var bound = 280 * (api.getCurrentSpeed() / Runner.config.MAX_SPEED);
var dis... |
Update demo list for popover to add row of hyperlink button | import React from 'react';
import { action } from '@storybook/addon-actions';
import Button from '@ichef/gypcrete/src/Button';
import List from '@ichef/gypcrete/src/List';
import ListRow from '@ichef/gypcrete/src/ListRow';
function ButtonRow(props) {
return (
<ListRow>
<Button
... | import React from 'react';
import { action } from '@storybook/addon-actions';
import Button from '@ichef/gypcrete/src/Button';
import List from '@ichef/gypcrete/src/List';
import ListRow from '@ichef/gypcrete/src/ListRow';
function DemoButton(props) {
return (
<Button
bold
minified... |
Fix exception pattern matching for internal unicode strings | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: vraj@reciprocitylabs.com
# Maintained By: vraj@reciprocitylabs.com
import re
from sqlalchemy.exc import IntegrityError
def translate_message(excep... | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: vraj@reciprocitylabs.com
# Maintained By: vraj@reciprocitylabs.com
import re
from sqlalchemy.exc import IntegrityError
def translate_message(excep... |
Test that returned result is a str instance | #!/usr/bin/env python
# Copyright 2020 The StackStorm Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | #!/usr/bin/env python
# Copyright 2020 The StackStorm Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
Change how we detect gifs for production data. | import React from 'react'
class ImageRegion extends React.Component {
isGif() {
const optimized = this.attachment.optimized
if (optimized && optimized.metadata) {
return optimized.metadata.type === 'image/gif'
}
return false
}
renderAttachment() {
const { content } = this.props
le... | import React from 'react'
class ImageRegion extends React.Component {
renderAttachment() {
const { content } = this.props
let size = 'optimized'
if (!this.attachment[size].metadata.type.match('gif')) {
size = window.innerWidth > 375 ? 'hdpi' : 'mdpi'
}
return (
<img className="ImageR... |
Set the Gaussian threshold to 0. | import scipy.ndimage as ndim
from skimage.filters import gaussian
from skimage.morphology import convex_hull_image
def patch_up_roi(roi, sigma=0.5, truncate=2):
"""
After being non-linearly transformed, ROIs tend to have holes in them.
We perform a couple of computational geometry operations on the ROI to
... | import scipy.ndimage as ndim
from skimage.filters import gaussian
from skimage.morphology import convex_hull_image
def patch_up_roi(roi, sigma=0.5, truncate=2):
"""
After being non-linearly transformed, ROIs tend to have holes in them.
We perform a couple of computational geometry operations on the ROI to
... |
Update database connection to 7.1
Update database connection. Refactor variables with visibility constant. | <?php
class Connection
{
private const HOST = "LOCALHOST";
private const DATABASE = "...";
private const USERNAME = "...";
private const PASSWORD = "...";
public function getDatabase() {
$dbh = NULL;
try {
$dbh = new PDO('mysql:host=' . SELF::HOST . ';dbname=' . SE... | <?php
class Connection
{
public function getDatabase() {
$dbh = NULL;
$host = "localhost";
$dbname = "test";
$username = "root";
$password = "";
try {
$dbh = new PDO('mysql:host=' . $host . ';dbname=' . $dbname, $username, $password);
$dbh->... |
Make sure user can also change is_presynopsis_seminar. | <?php
include_once 'header.php';
include_once 'database.php';
$_POST[ 'speaker' ] = $_SESSION[ 'user' ];
$res = insertIntoTable( 'aws_requests'
, array( 'speaker', 'title', 'abstract', 'supervisor_1', 'supervisor_2'
, 'tcm_member_1', 'tcm_member_2', 'tcm_member_3', 'tcm_member_4'
, 'date', ... | <?php
include_once 'header.php';
include_once 'database.php';
$_POST[ 'speaker' ] = $_SESSION[ 'user' ];
$res = insertIntoTable( 'aws_requests'
, array( 'speaker', 'title', 'abstract', 'supervisor_1', 'supervisor_2'
, 'tcm_member_1', 'tcm_member_2', 'tcm_member_3', 'tcm_member_4'
, 'date', ... |
Use correct header height for scrolling back up. | Zepto(function($) {
prettyPrint();
var $frameLines = $('[id^="frame-line-"]');
var $activeLine = $('.frames-container .active');
var $activeFrame = $('.active[id^="frame-code-"]').show();
var $container = $('.details-container');
var headerHeight = $('header').height();
var highlightCurrentLine = fu... | Zepto(function($) {
prettyPrint();
var $frameLines = $('[id^="frame-line-"]');
var $activeLine = $('.frames-container .active');
var $activeFrame = $('.active[id^="frame-code-"]').show();
var $container = $('.details-container');
var headerHeight = $('header').css('height');
var highlightCurrentLine... |
Fix sentence index shifting with empty sentences | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from itertools import combinations
from operator import itemgetter
from distance import jaccard
from networkx import Graph, pagerank
from nltk import tokenize
from .utils import get_stopwords, get_words
def summarize(text, sentence_count=5, language='... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from itertools import combinations
from operator import itemgetter
from distance import jaccard
from networkx import Graph, pagerank
from nltk import tokenize
from .utils import get_stopwords, get_words
def summarize(text, sentence_count=5, language='... |
Rename out.js to main.js to reflect README | const dir = __dirname
const webpack = require('webpack')
module.exports = {
entry: "./build/main.js",
output: {
filename: "build/out/main.js"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|forge.bundle.js)/,
l... | const dir = __dirname
const webpack = require('webpack')
module.exports = {
entry: "./build/main.js",
output: {
filename: "build/out/out.js"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|forge.bundle.js)/,
lo... |
Modify model and add polyfill of promise.catch |
var mongoose = require('mongoose');
// polyfill of catch
// https://github.com/aheckmann/mpromise/pull/14
require('mongoose/node_modules/mpromise').prototype.catch = function (onReject) {
return this.then(undefined, onReject);
};
mongoose.connect(process.env.MONGO_URI);
/**
* Saves the model and returns a prom... |
var mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI);
mongoose.Model.prototype.psave = function () {
var that = this;
return new Promise(function (resolve) {
that.save(function (err) {
if (err) {
throw err
}
resolve();
... |
Use tabs instead of spaces | "use strict";
function getImagesFromDom() {
return _.chain($("img").toArray())
.map(function (element) {
return element.src;
})
.value();
}
function endsWith(str, suffix) {
return str.substr(str.length - suffix.length, str.length) === suffix;
}
var interval = Bacon.fromPoll(3000, function () {
return "tick";... | "use strict";
function getImagesFromDom() {
return _.chain($("img").toArray())
.map(function (element) {
return element.src;
})
.value();
}
function endsWith(str, suffix) {
return str.substr(str.length - suffix.length, str.length) === suffix;
}
var interval = Bacon.fromPoll(3000, function... |
Make the color for stderr red (i.e. the standard warning/danger/stop
color) rather than green. Suggested by Sam Schulenburg. | # Color Prefs for idle
class ColorPrefs:
CNormal = "black", "white" # "purple", "white"
CKeyword = "#ff7700", None
CComment = "#dd0000", None
CString = "#00aa00", None
CDefinition = "#0000ff", None
CHilite = "#000068", "#006868"
CSync = None, None # N... | # Color Prefs for idle
class ColorPrefs:
CNormal = "black", "white" # "purple", "white"
CKeyword = "#ff7700", None
CComment = "#dd0000", None
CString = "#00aa00", None
CDefinition = "#0000ff", None
CHilite = "#000068", "#006868"
CSync = None, None # N... |
Fix count of column in align in header | var Immutable = require('immutable');
var Draft = require('draft-js');
var TYPES = require('./TYPES');
var createRow = require('./createRow');
/**
* Create a new table header
*
* @param {String} tableKey
* @param {Number} countColumns
* @return {OrderedMap<String:Draft.ContentBlock>}
*/
function createHeader(ta... | var Immutable = require('immutable');
var Draft = require('draft-js');
var TYPES = require('./TYPES');
var createRow = require('./createRow');
/**
* Create a new table header
*
* @param {String} tableKey
* @param {Number} countColumns
* @return {OrderedMap<String:Draft.ContentBlock>}
*/
function createHeader(ta... |
Change ropsten gas price to 20 gwei | const yargs = require('yargs');
if (yargs.argv.network == 'ropsten' || yargs.argv.network == 'mainnet') {
var providerURL = `https://${yargs.argv.network}.infura.io`
var HDWalletProvider = require('truffle-hdwallet-provider');
// todo: Think about more secure way
var mnemonic = yargs.argv.mnemonic
provider... | const yargs = require('yargs');
if (yargs.argv.network == 'ropsten' || yargs.argv.network == 'mainnet') {
var providerURL = `https://${yargs.argv.network}.infura.io`
var HDWalletProvider = require('truffle-hdwallet-provider');
// todo: Think about more secure way
var mnemonic = yargs.argv.mnemonic
provider... |
Remove some unecessary @property doc comments | <?php
namespace PhpParser\Node\Expr;
use PhpParser\Node\Expr;
abstract class AssignOp extends Expr
{
/** @var Expr Variable */
public $var;
/** @var Expr Expression */
public $expr;
/**
* Constructs a compound assignment operation node.
*
* @param Expr $var Variable
*... | <?php
namespace PhpParser\Node\Expr;
use PhpParser\Node\Expr;
/**
* @property Expr $var Variable
* @property Expr $expr Expression
*/
abstract class AssignOp extends Expr
{
/** @var Expr Variable */
public $var;
/** @var Expr Expression */
public $expr;
/**
* Constructs a compound assig... |
Use app secret for prod app | package de.bowstreet.testandroidapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.microsoft.azure.mobile.MobileCenter;
import com.microsoft.azure.mobile.analytics.Analytics;
import com.microsoft.azure.mobile.crashes.Crash... | package de.bowstreet.testandroidapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.microsoft.azure.mobile.MobileCenter;
import com.microsoft.azure.mobile.analytics.Analytics;
import com.microsoft.azure.mobile.crashes.Crash... |
Modify get-status option in file | <?php
function send_email($to_email,$subject,$message1)
{
require_once 'Mandrill.php';
$apikey = '%API_key%'; // use this to encrypt your api key
$mandrill = new Mandrill($apikey);
$message = new stdClass();
$message->html = $message1;
$message->text = $message1;
$message->subject = $subject;
>>> function typescri... | <?php
function send_email($to_email,$subject,$message1)
{
require_once 'Mandrill.php';
$apikey = '%API_key%'; // use this to encrypt your api key
$mandrill = new Mandrill($apikey);
$message = new stdClass();
$message->html = $message1;
$message->text = $message1;
$message->subject = $subject;
>>> function typescri... |
Set default to be light mode | import React, { useEffect } from "react";
import { RoutingApp } from "./modules/RoutingApp";
import store from "./store";
import { Provider } from "react-redux";
import { STUY_SPEC_API_URL } from "./constants";
import { ApolloProvider } from "react-apollo";
import { ApolloClient } from "apollo-client";
import { HttpLi... | import React from "react";
import { RoutingApp } from "./modules/RoutingApp";
import store from "./store";
import { Provider } from "react-redux";
import { STUY_SPEC_API_URL } from "./constants";
import { ApolloProvider } from "react-apollo";
import { ApolloClient } from "apollo-client";
import { HttpLink } from "apol... |
Add tokens and seconds as private members
These members shouldn't be accessible other than being specified in the
constructor. If they were updated after the fact then the rate wouldn't
represent the chnage. | <?
namespace iFixit\TokenBucket;
use \InvalidArgumentException;
/**
* Defines a rate of tokens per second. Specify the tokens you want to
* allow for a given number of seconds.
*/
class TokenRate {
private $rate;
private $tokens;
private $seconds;
public function __construct($tokens, $seconds) {
... | <?
namespace iFixit\TokenBucket;
use \InvalidArgumentException;
/**
* Defines a rate of tokens per second. Specify the tokens you want to
* allow for a given number of seconds.
*/
class TokenRate {
private $rate;
public function __construct($tokens, $seconds) {
if (!is_int($tokens)) {
throw ... |
Change static reference to self | <?php namespace PhilipBrown\WorldPay;
use Assert\Assertion;
class Currency {
/**
* @var string
*/
private $name;
/**
* @var array
*/
private static $currencies;
/**
* @param string $name
*/
private function __construct($name)
{
if ( ! isset(self::$currencies))
{
self::... | <?php namespace PhilipBrown\WorldPay;
use Assert\Assertion;
class Currency {
/**
* @var string
*/
private $name;
/**
* @var array
*/
private static $currencies;
/**
* @param string $name
*/
private function __construct($name)
{
if ( ! isset(static::$currencies))
{
stat... |
Update message when account is not enabled | <?php
/*
* This file is part of By Night.
* (c) 2013-2020 Guillaume Sainthillier <guillaume.sainthillier@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Security;
use App\Entity\User;
use Symfony\Component\Security\Core... | <?php
/*
* This file is part of By Night.
* (c) 2013-2020 Guillaume Sainthillier <guillaume.sainthillier@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Security;
use App\Entity\User;
use Symfony\Component\Security\Core... |
Add orderId to initPayment method | <?php namespace professionalweb\payment\contracts\recurring;
use professionalweb\payment\contracts\PayService;
/**
* Interface for payment systems have recurring payments
* @package professionalweb\payment\contracts\recurring
*/
interface RecurringPayment
{
/**
* Get payment token
*
* @return st... | <?php namespace professionalweb\payment\contracts\recurring;
use professionalweb\payment\contracts\PayService;
/**
* Interface for payment systems have recurring payments
* @package professionalweb\payment\contracts\recurring
*/
interface RecurringPayment
{
/**
* Get payment token
*
* @return st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.