text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use duck typing when creating a RangeSet | from itertools import chain
from typing import Container, Iterable, Sized
class RangeSet(Sized, Iterable, Container):
def __init__(self, *ranges):
self.ranges = []
for r in ranges:
if isinstance(r, range):
self.ranges.append(r)
continue
try:
element = list(r.ranges)
except AttributeError:
element = None
try:
element = element or [range(*r)]
except:
msg = "RangeSet argument must be a range, RangeSet or an Iterable, not {}"
raise ValueError(msg.format(type(r)))
self.ranges.extend(element)
def __iter__(self):
return chain.from_iterable(r for r in self.ranges)
def __contains__(self, elem):
return any(elem in r for r in self.ranges)
def __len__(self):
return sum(len(r) for r in self.ranges)
| from itertools import chain
from typing import Sized, Iterable, Container, Set
class RangeSet(Sized, Iterable, Container):
def __init__(self, *ranges):
self.ranges = []
for r in ranges:
if isinstance(r, range):
r = [r]
elif isinstance(r, RangeSet):
r = list(r.ranges)
elif isinstance(r, Iterable) and not isinstance(r, Set):
r = [range(*r)]
else:
msg = "RangeSet argument must be a range, RangeSet or an Iterable, not {}"
raise ValueError(msg.format(type(r)))
self.ranges.extend(r)
def __iter__(self):
return chain.from_iterable(r for r in self.ranges)
def __contains__(self, elem):
return any(elem in r for r in self.ranges)
def __len__(self):
return sum(len(r) for r in self.ranges)
|
Remove redundant colons and superfluous hyphens | from django import forms
class BugReportForm(forms.Form):
bug = forms.CharField(label="Bug (required)", required=True)
description = forms.CharField(
label="Description (required)",
widget=forms.Textarea(attrs={'rows': 4, 'cols': 50}), required=True)
reproduce = forms.CharField(
label="How to reproduce the error",
widget=forms.Textarea(attrs={'rows': 4, 'cols': 50}), required=False)
expected = forms.CharField(
label="The expected result",
widget=forms.Textarea(attrs={'rows': 4, 'cols': 50}), required=False)
actual = forms.CharField(
label="The actual result",
widget=forms.Textarea(attrs={'rows': 4, 'cols': 50}), required=False)
session_data = forms.CharField(widget=forms.HiddenInput())
| from django import forms
class BugReportForm(forms.Form):
bug = forms.CharField(label="Bug: - (required)", required=True)
description = forms.CharField(
label="Description: - (required)",
widget=forms.Textarea(attrs={'rows': 4, 'cols': 50}), required=True)
reproduce = forms.CharField(
label="How to reproduce the error",
widget=forms.Textarea(attrs={'rows': 4, 'cols': 50}), required=False)
expected = forms.CharField(
label="The expected result",
widget=forms.Textarea(attrs={'rows': 4, 'cols': 50}), required=False)
actual = forms.CharField(
label="The actual result",
widget=forms.Textarea(attrs={'rows': 4, 'cols': 50}), required=False)
session_data = forms.CharField(widget=forms.HiddenInput())
|
Use getToolbar() to get the toolbar object. | <?php
/**
* @version $Id: html.php 628 2011-03-20 01:49:53Z johanjanssens $
* @category Nooku
* @package Nooku_Server
* @subpackage Cache
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Cache Groups Html View
*
* @author Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
* @category Nooku
* @package Nooku_Server
* @subpackage Cache
*/
class ComCacheViewHtml extends ComDefaultViewHtml
{
public function __construct(KConfig $config)
{
$config->views = array(
'groups' => JText::_('Groups'),
'keys' => JText::_('Keys'),
);
parent::__construct($config);
}
public function display()
{
$this->getToolbar()
->setTitle('Cache Manager')
->reset()
->append('delete')
->append('purge');
return parent::display();
}
} | <?php
/**
* @version $Id: html.php 628 2011-03-20 01:49:53Z johanjanssens $
* @category Nooku
* @package Nooku_Server
* @subpackage Cache
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Cache Groups Html View
*
* @author Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
* @category Nooku
* @package Nooku_Server
* @subpackage Cache
*/
class ComCacheViewHtml extends ComDefaultViewHtml
{
public function __construct(KConfig $config)
{
$config->views = array(
'groups' => JText::_('Groups'),
'keys' => JText::_('Keys'),
);
parent::__construct($config);
}
public function display()
{
KFactory::get('admin::com.cache.toolbar.'.$this->getName(), array('title' => 'Cache Manager'))
->reset()
->append('delete')
->append('purge');
return parent::display();
}
} |
Handle error code METHOD_NOT_FOUND_CODE in InspectorServiceWorker.StopAllWorkers()
DevTools method ServiceWorker.stopAllWorkers is supported from M63, so
calling this can return METHOD_NOT_FOUND_CODE error in previous browser.
This CL make InspectorServiceWorker.StopAllWorkers() handle this error.
If it receives this error, it raises NotImplementedError.
This is implemented in the same way with memory_backend.py does.
https://cs.chromium.org/chromium/src/third_party/catapult/telemetry/telemetry/internal/backends/chrome_inspector/memory_backend.py?type=cs&q=warn+file:%5Esrc/third_party/catapult/telemetry/telemetry/internal/backends/chrome_inspector/+package:%5Echromium$&l=84
BUG=chromium:736697
Review-Url: https://chromiumcodereview.appspot.com/3013263002 | # Copyright 2017 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.
from telemetry.internal.backends.chrome_inspector import inspector_websocket
from telemetry.core import exceptions
class InspectorServiceWorker(object):
def __init__(self, inspector_socket, timeout):
self._websocket = inspector_socket
self._websocket.RegisterDomain('ServiceWorker', self._OnNotification)
# ServiceWorker.enable RPC must be called before calling any other methods
# in ServiceWorker domain.
res = self._websocket.SyncRequest(
{'method': 'ServiceWorker.enable'}, timeout)
if 'error' in res:
raise exceptions.StoryActionError(res['error']['message'])
def _OnNotification(self, msg):
# TODO: track service worker events
# (https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker/)
pass
def StopAllWorkers(self, timeout):
res = self._websocket.SyncRequest(
{'method': 'ServiceWorker.stopAllWorkers'}, timeout)
if 'error' in res:
code = res['error']['code']
if code == inspector_websocket.InspectorWebsocket.METHOD_NOT_FOUND_CODE:
raise NotImplementedError(
'DevTools method ServiceWorker.stopAllWorkers is not supported by '
'this browser.')
raise exceptions.StoryActionError(res['error']['message'])
| # Copyright 2017 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.
from telemetry.core import exceptions
class InspectorServiceWorker(object):
def __init__(self, inspector_websocket, timeout):
self._websocket = inspector_websocket
self._websocket.RegisterDomain('ServiceWorker', self._OnNotification)
# ServiceWorker.enable RPC must be called before calling any other methods
# in ServiceWorker domain.
res = self._websocket.SyncRequest(
{'method': 'ServiceWorker.enable'}, timeout)
if 'error' in res:
raise exceptions.StoryActionError(res['error']['message'])
def _OnNotification(self, msg):
# TODO: track service worker events
# (https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker/)
pass
def StopAllWorkers(self, timeout):
res = self._websocket.SyncRequest(
{'method': 'ServiceWorker.stopAllWorkers'}, timeout)
if 'error' in res:
raise exceptions.StoryActionError(res['error']['message'])
|
Document "../../" in example as being "express-state" | var express = require('express'),
exphbs = require('express3-handlebars'),
state = require('../../'), // "express-state"
app = express();
app.engine('hbs', exphbs());
app.set('view engine', 'hbs');
app.expose({
flickr_api: 'asdf'
});
app.get('/', function (req, res, next) {
res.expose({
user : {id: '1234'},
flickr_api: 'fdsa'
});
res.expose('Eric', 'user.name');
res.render('index');
});
app.get('/foo', function (req, res, next) {
res.expose({
user: {id: '1234'}
});
res.render('index');
});
app.expose('MY APP', 'title', 'app');
app.listen(3000);
| var express = require('express'),
exphbs = require('express3-handlebars'),
state = require('../../'),
app = express();
app.engine('hbs', exphbs());
app.set('view engine', 'hbs');
app.expose({
flickr_api: 'asdf'
});
app.get('/', function (req, res, next) {
res.expose({
user : {id: '1234'},
flickr_api: 'fdsa'
});
res.expose('Eric', 'user.name');
res.render('index');
});
app.get('/foo', function (req, res, next) {
res.expose({
user: {id: '1234'}
});
res.render('index');
});
app.expose('MY APP', 'title', 'app');
app.listen(3000);
|
Add test test tag 4 to the item tags | package info.u_team.u_team_test.init;
import info.u_team.u_team_core.util.TagUtil;
import info.u_team.u_team_test.TestMod;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.tags.ITag.INamedTag;
public class TestTags {
public static class Blocks {
public static INamedTag<Block> TEST_TAG_1 = TagUtil.createBlockTag(TestMod.MODID, "test_1");
public static INamedTag<Block> TEST_TAG_2 = TagUtil.createBlockTag(TestMod.MODID, "test_2");
}
public static class Items {
public static INamedTag<Item> TEST_TAG_1 = TagUtil.fromBlockTag(Blocks.TEST_TAG_1);
public static INamedTag<Item> TEST_TAG_2 = TagUtil.fromBlockTag(Blocks.TEST_TAG_2);
public static INamedTag<Item> TEST_TAG_3 = TagUtil.createItemTag(TestMod.MODID, "test_3");
public static INamedTag<Item> TEST_TAG_4 = TagUtil.createItemTag(TestMod.MODID, "test_4");
}
}
| package info.u_team.u_team_test.init;
import info.u_team.u_team_core.util.TagUtil;
import info.u_team.u_team_test.TestMod;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.tags.ITag.INamedTag;
public class TestTags {
public static class Blocks {
public static INamedTag<Block> TEST_TAG_1 = TagUtil.createBlockTag(TestMod.MODID, "test_1");
public static INamedTag<Block> TEST_TAG_2 = TagUtil.createBlockTag(TestMod.MODID, "test_2");
}
public static class Items {
public static INamedTag<Item> TEST_TAG_1 = TagUtil.fromBlockTag(Blocks.TEST_TAG_1);
public static INamedTag<Item> TEST_TAG_2 = TagUtil.fromBlockTag(Blocks.TEST_TAG_2);
public static INamedTag<Item> TEST_TAG_3 = TagUtil.createItemTag(TestMod.MODID, "test_3");
}
}
|
2016-03.py: Sort triples in separate step | from __future__ import annotations
from typing import List, Tuple
from aoc_common import load_puzzle_input, report_solution
def parse_horizontal(string: str) -> List[Tuple[int, int, int]]:
"""Parse the instruction lines into triples of side lengths."""
sides = [[int(x) for x in line.split()] for line in string.splitlines()]
return [(s[0], s[1], s[2]) for s in sides]
def filter_valid_triangles(
triples: List[Tuple[int, int, int]]
) -> List[Tuple[int, int, int]]:
triples = sort_sides(triples)
return [triple for triple in triples if triple[0] + triple[1] > triple[2]]
def sort_sides(triples: List[Tuple[int, int, int]]) -> List[Tuple[int, int, int]]:
return [(t[0], t[1], t[2]) for t in [sorted(sides) for sides in triples]]
if __name__ == "__main__":
horizontal_triples = parse_horizontal(load_puzzle_input(day=3))
valid_horizontal = filter_valid_triangles(horizontal_triples)
report_solution(
puzzle_title="Day 3: Squares With Three Sides",
part_one_solution=len(valid_horizontal),
)
| from __future__ import annotations
from typing import List, Tuple
from aoc_common import load_puzzle_input, report_solution
def parse_horizontal(string: str) -> List[Tuple[int, int, int]]:
"""Parse the instruction lines into sorted triples of side lengths."""
sorted_sides = [
sorted(int(x) for x in line.split()) for line in string.splitlines()
]
triples = [(sides[0], sides[1], sides[2]) for sides in sorted_sides]
return triples
def filter_valid_triangles(
triples: List[Tuple[int, int, int]]
) -> List[Tuple[int, int, int]]:
return [triple for triple in triples if triple[0] + triple[1] > triple[2]]
if __name__ == "__main__":
horizontal_triples = parse_horizontal(load_puzzle_input(day=3))
valid_horizontal = filter_valid_triangles(horizontal_triples)
report_solution(
puzzle_title="Day 3: Squares With Three Sides",
part_one_solution=len(valid_horizontal),
)
|
Fix game screen missing parameter | package com.geniusclone.screens;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.geniusclone.game.GameplayClassic;
public class GameScreen implements Screen {
private Game myGame;
private GameplayClassic gameplay;
public GameScreen(Game g) {
myGame = g;
gameplay = new GameplayClassic(myGame);
Gdx.input.setInputProcessor(gameplay);
}
@Override
public void render(float delta) {
gameplay.render();
}
@Override
public void resize(int width, int height) {
}
@Override
public void show() {
}
@Override
public void hide() {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void dispose() {
gameplay.dispose();
}
} | package com.geniusclone.screens;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.geniusclone.game.GameplayClassic;
public class GameScreen implements Screen {
private Game myGame;
private GameplayClassic gameplay;
public GameScreen(Game g) {
myGame = g;
gameplay = new GameplayClassic();
Gdx.input.setInputProcessor(gameplay);
}
@Override
public void render(float delta) {
gameplay.render();
}
@Override
public void resize(int width, int height) {
}
@Override
public void show() {
}
@Override
public void hide() {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void dispose() {
gameplay.dispose();
}
} |
Update for new React types, context, forwardRef, etc | import React from 'react';
import createChainableTypeChecker from './utils/createChainableTypeChecker';
function elementType(props, propName, componentName, location, propFullName) {
const propValue = props[propName];
const propType = typeof propValue;
if (React.isValidElement(propValue)) {
return new Error(
`Invalid ${location} \`${propFullName}\` of type ReactElement ` +
`supplied to \`${componentName}\`, expected an element type (a string ` +
'or a ReactClass).'
);
}
const isSpecial = propValue && propValue.$$typeof;
if (propType !== 'function' && propType !== 'string' && !isSpecial) {
return new Error(
`Invalid ${location} \`${propFullName}\` of value \`${propValue}\` ` +
`supplied to \`${componentName}\`, expected an element type (a string ` +
', component class, or function component).'
);
}
return null;
}
export default createChainableTypeChecker(elementType);
| import React from 'react';
import createChainableTypeChecker from './utils/createChainableTypeChecker';
function elementType(props, propName, componentName, location, propFullName) {
const propValue = props[propName];
const propType = typeof propValue;
if (React.isValidElement(propValue)) {
return new Error(
`Invalid ${location} \`${propFullName}\` of type ReactElement ` +
`supplied to \`${componentName}\`, expected an element type (a string ` +
'or a ReactClass).'
);
}
if (propType !== 'function' && propType !== 'string') {
return new Error(
`Invalid ${location} \`${propFullName}\` of value \`${propValue}\` ` +
`supplied to \`${componentName}\`, expected an element type (a string ` +
'or a ReactClass).'
);
}
return null;
}
export default createChainableTypeChecker(elementType);
|
Remove closure wrapping around script injector
It turns out that content scripts and JS in the document cannot affect
each others state. | const isURLAvailable = url => {
const req = new Request(url, {
method: "HEAD",
redirect: "follow"
});
return fetch(req).then(resp => resp.ok).catch(() => false);
};
const getHostname = () => {
const u = new URL(document.URL);
return `${u.protocol}//${u.hostname}`;
};
const reportCouldNotConnect = url => {
/* eslint-disable no-console */
console.error(`livereloaded: could not find livereload script at ${url}`);
console.error(`livereloaded: check that livereload server is running`);
/* eslint-enable no-console */
};
const injectLivereload = port => {
const host = getHostname();
const url = `${host}:${port}/livereload.js`;
return isURLAvailable(url).then(isAvailable => {
if (!isAvailable) {
reportCouldNotConnect(url);
return false;
}
const script = document.createElement("script");
script.setAttribute("src", url);
document.head.appendChild(script);
return true;
});
};
browser.runtime.onMessage.addListener(msg => {
switch (msg.command) {
case "inject":
return injectLivereload(msg.port);
default:
return false;
}
});
| (() => {
const isURLAvailable = url => {
const req = new Request(url, {
method: "HEAD",
redirect: "follow"
});
return fetch(req).then(resp => resp.ok).catch(() => false);
};
const getHostname = () => {
const u = new URL(document.URL);
return `${u.protocol}//${u.hostname}`;
};
const reportCouldNotConnect = url => {
/* eslint-disable no-console */
console.error(`livereloaded: could not find livereload script at ${url}`);
console.error(`livereloaded: check that livereload server is running`);
/* eslint-enable no-console */
};
const injectLivereload = port => {
const host = getHostname();
const url = `${host}:${port}/livereload.js`;
return isURLAvailable(url).then(isAvailable => {
if (!isAvailable) {
reportCouldNotConnect(url);
return false;
}
const script = document.createElement("script");
script.setAttribute("src", url);
document.head.appendChild(script);
return true;
});
};
browser.runtime.onMessage.addListener(msg => {
switch (msg.command) {
case "inject":
return injectLivereload(msg.port);
default:
return false;
}
});
})();
|
Work around quirk of POS tagger |
from jargonprofiler.util import tag_proper_nouns
from jargonprofiler.munroe import munroe_score
def test_proper_noun_in_sentence():
assert tag_proper_nouns("My name is Eilis.") == set(["Eilis"])
def test_proper_noun_begins_sentence():
assert tag_proper_nouns("Eilis is a girl") == set(["Eilis"])
def test_proper_noun_middle_sentence():
assert tag_proper_nouns("Today, Eilis is at CW17.") == set(["Eilis"])
def test_proper_noun_missing():
assert tag_proper_nouns("Today is cloudy at CW17.") == set()
def test_two_proper_nouns():
assert tag_proper_nouns("Eilis Hannon is a girl.") == set(["Eilis",
"Hannon"])
def test_munroe_with_proper_noun():
result = munroe_score("Eilis is a small girl")
assert result["score"] == 1.0
def test_munroe_with_proper_noun_and_complex_words():
result = munroe_score("Jonathan and Eilis are at a workshop")
assert result['score'] == 1 / 3
|
from jargonprofiler.util import tag_proper_nouns
from jargonprofiler.munroe import munroe_score
def test_proper_noun_in_sentence():
assert tag_proper_nouns("My name is Eilis.") == set(["Eilis"])
def test_proper_noun_begins_sentence():
assert tag_proper_nouns("Eilis is a girl") == set(["Eilis"])
def test_proper_noun_middle_sentence():
assert tag_proper_nouns("Today, Eilis is at CW17.") == set(["Eilis"])
def test_proper_noun_missing():
assert tag_proper_nouns("Today is cloudy at CW17.") == set()
def test_two_proper_nouns():
assert tag_proper_nouns("Eilis Hannon is a girl.") == set(["Eilis",
"Hannon"])
def test_munroe_with_proper_noun():
result = munroe_score("Eilis is a small girl")
assert result["score"] == 1.0
def test_munroe_with_proper_noun_and_complex_words():
result = munroe_score("Eilis and Jonathan at a workshop")
assert result['score'] == 0.5
|
Add catch for google login and clean up google login file | import React, { Component } from 'react'
import firebase from 'firebase'
import { googleAuthProvider } from '../config/constants'
import googleLogo from '../images/auth_service_google.svg'
export default class GoogleAuth extends Component {
authenticate() {
firebase.auth().signInWithPopup(googleAuthProvider)
.then(() => {
this.authHandler();
})
.catch(() => {
alert('There was a problem signing in with Google. Please check your credentials and try again.')
})
}
authHandler(err, authData) { //eslint-disable-line
if (err) {
console.log('error', err)
return
}
console.log('authData', authData)
}
render() {
return (
<div className="text-center">
<p>or</p>
<button className="btn google-auth-button" onClick={() => { this.authenticate() }} >
<img src={googleLogo} alt="Google" />
Login with Google
</button>
</div>
)
}
}
| import React, { Component } from 'react'
import firebase from 'firebase'
import { googleAuthProvider } from '../config/constants'
import googleLogo from '../images/auth_service_google.svg'
export default class GoogleAuth extends Component {
authenticate() {
firebase.auth().signInWithPopup(googleAuthProvider)
.then(() => {
this.authHandler();
});
}
authHandler(err, authData) {
console.log(authData)
}
render() {
return (
<div className="text-center">
<p>or</p>
<button className="btn google-auth-button" onClick={() => { this.authenticate() }} >
<img src={googleLogo} alt="Google"/>
Login with Google
</button>
</div>
)
}
}
|
Remove try/catch around compile call
This prevents errors being thrown when someone breaks something in compiler. | 'use strict';
var _ = require('underscore');
// It should be given:
// - t: a function that will translate a key into the correct language depending
// on the locale selected.
// - compiler: a function which will compile the string using the context provided
module.exports = function (t, compiler) {
compiler = compiler || _.identity;
/**
* Given an array of keys and a context iterate through
* each of the keys until (1) the translated key is different
* from the non-translated key, and (2) a template containing the
* data from the context compiles successfully.
*/
return function (keys, context) {
if (typeof keys === 'string') {
keys = [keys];
}
return _.reduce(keys, function (message, token) {
if (!message && t(token) !== token) {
message = compiler(t(token), context || {});
}
return message;
}, null);
};
};
| 'use strict';
var _ = require('underscore');
// It should be given:
// - t: a function that will translate a key into the correct language depending
// on the locale selected.
// - compiler: a function which will compile the string using the context provided
module.exports = function (t, compiler) {
compiler = compiler || _.identity;
/**
* Given an array of keys and a context iterate through
* each of the keys until (1) the translated key is different
* from the non-translated key, and (2) a template containing the
* data from the context compiles successfully.
*/
return function (keys, context) {
if (typeof keys === 'string') {
keys = [keys];
}
return _.reduce(keys, function (message, token) {
if (!message && t(token) !== token) {
try {
message = compiler(t(token), context || {});
} catch (e) {}
}
return message;
}, null);
};
};
|
Change mentor to mentorBio to fix bug | app.factory('BioFactory', ['$http', function($http){
console.log('BioFactory running');
var mentors = {};
var mentorBio = {};
// gets all the mentors that match the newSearch selected fields
function getMentors(newSearch){
console.log("NEW SEARCH:", newSearch);
var newSearchString = JSON.stringify(newSearch);
return $http({
method: 'GET',
url: '/mentor-search/search',
headers: {
newSearchString: newSearchString
}
})
.then(function(response) {
mentors.info = response.data;
console.log("Mentors list:", mentors);
}),
function(err) {
console.log("Error with search get request ", err);
};
};
// Attach the chosen mentor object to the info property on mentorBio.
// This will be accessed by the profile controller
function setMentor(mentor){
mentorBio.info = mentor;
console.log("MENTOR:", mentorBio.info);
}
var publicApi = {
mentors: mentors,
mentorBio: mentorBio,
getMentors: function(newSearch){
return getMentors(newSearch);
},
setMentor: function(mentor){
return setMentor(mentor);
},
// getMentorId: function(){
// return getMentorId();
// }
};
return publicApi;
}]);
| app.factory('BioFactory', ['$http', function($http){
console.log('BioFactory running');
var mentorInfo = {};
var mentors = {};
var mentor = {};
function getMentors(newSearch){
console.log("NEW SEARCH:", newSearch);
var newSearchString = JSON.stringify(newSearch);
return $http({
method: 'GET',
url: '/mentor-search/search',
headers: {
newSearchString: newSearchString
}
})
.then(function(response) {
console.log("--------------------------------------");
mentors.info = response.data;
console.log("Mentors list:", mentors);
}),
function(err) {
console.log("Error with search get request ", err);
};
};
function setMentorId(mentorId){
mentor.id = mentorId;
}
var publicApi = {
mentors: mentors,
mentor: mentor,
getMentors: function(newSearch){
return getMentors(newSearch);
},
setMentorId: function(mentorId){
return setMentorId(mentorId);
},
// getMentorId: function(){
// return getMentorId();
// }
};
return publicApi;
}]);
|
Remove es5 option to make travis happy | define(function (require, exports, module) {
var playlist = require("text!../playlist.json");
// TODO: we need wraparound for the case that we run out of tracks
var currentTrack = playlist.pop();
var audio = new Audio();
function playUrl(url) {
function canplay() {
audio.removeEventListener("canplay", canplay);
audio.play();
}
audio.addEventListener("canplay", canplay);
audio.src = url;
}
// When the current track ends, start another
audio.addEventListener("ended", function() {
currentTrack = playlist.pop();
if(!currentTrack) {
// TODO: No more trackS! We should bubble up error handling to UI somehow...
console.error("[brackets-wavelength] No more tracks");
return;
}
playUrl(currentTrack.url);
});
return {
play: function() {
if(!audio.src) {
playUrl(currentTrack.url);
} else {
audio.play();
}
},
pause: function() {
audio.pause();
},
get paused() {
return audio.paused;
},
get trackInfo() {
return currentTrack;
}
};
});
| /*jshint es5:true */
define(function (require, exports, module) {
var playlist = require("text!../playlist.json");
// TODO: we need wraparound for the case that we run out of tracks
var currentTrack = playlist.pop();
var audio = new Audio();
function playUrl(url) {
function canplay() {
audio.removeEventListener("canplay", canplay);
audio.play();
}
audio.addEventListener("canplay", canplay);
audio.src = url;
}
// When the current track ends, start another
audio.addEventListener("ended", function() {
currentTrack = playlist.pop();
if(!currentTrack) {
// TODO: No more trackS! We should bubble up error handling to UI somehow...
console.error("[brackets-wavelength] No more tracks");
return;
}
playUrl(currentTrack.url);
});
return {
play: function() {
if(!audio.src) {
playUrl(currentTrack.url);
} else {
audio.play();
}
},
pause: function() {
audio.pause();
},
get paused() {
return audio.paused;
},
get trackInfo() {
return currentTrack;
}
};
});
|
Test for valid output price pass | /*
* nupricer
* https://github.com/ramseydsilva/nupricer
*
* Copyright (c) 2014 Ramsey D'silva
* Licensed under the MIT license.
*/
'use strict';
var errors = require('./errors');
(function(nupricer) {
var basePrice,
basePriceInt,
baseCurrency,
outputPriceInt;
var checkPriceFormat = function(price) {
var currency = price.match(/^\D{0,}/g)[0];
var priceInt = price.match(/\d*\.?\d*$/g)[0];
if (typeof currency != 'string' || isNaN(parseFloat(priceInt)) || !isFinite(priceInt) || priceInt == '') {
throw (errors.InvalidPriceError);
}
baseCurrency = currency;
outputPriceInt = priceInt; // output price is atleast >= input price
return true;
};
var checkWorkersFormat = function(workers) {
var match = workers.match(/\d+/g);
if (!match || match.length > 1) {
throw (errors.InvalidWorkersError);
}
};
nupricer.calculate = function(price, workers, material) {
checkPriceFormat(price);
checkWorkersFormat(workers);
return baseCurrency + outputPriceInt;
};
nupricer.checkPriceFormat = checkPriceFormat;
}(exports));
| /*
* nupricer
* https://github.com/ramseydsilva/nupricer
*
* Copyright (c) 2014 Ramsey D'silva
* Licensed under the MIT license.
*/
'use strict';
var errors = require('./errors');
(function(nupricer) {
nupricer.checkPriceFormat = function(price) {
var currency = price.match(/^\D{0,}/g)[0];
var priceInt = price.match(/\d*\.?\d*$/g)[0];
if (typeof currency != 'string' || isNaN(parseFloat(priceInt)) || !isFinite(priceInt) || priceInt == '') {
throw (errors.InvalidPriceError);
}
return;
};
var checkWorkersFormat = function(workers) {
var match = workers.match(/\d+/g);
if (!match || match.length > 1) {
throw (errors.InvalidWorkersError);
}
};
nupricer.calculate = function(price, workers, material) {
this.checkPriceFormat(price);
checkWorkersFormat(workers);
return "string";
};
}(exports));
|
Refactor user credentials as a prototyped object. | var md5= require('./md5');
/*
* Hide the password. Uses the password to form authorization strings,
* but provides no interface for exporting it.
*/
function user_credentials(username,password) {
if (username.is_user_credentials &&
typeof username.basic === 'function' &&
typeof username.digest === 'function'
) {
return username;
}
var basic_string= !password && password !== '' ?
new Buffer(username, "ascii").toString("base64")
:
new Buffer(username+':'+password, "ascii").toString("base64")
;
function Credentials()
{
this.username= username;
}
Credentials.prototype.basic= function()
{
return basic_string;
}
Credentials.prototype.digest= function(realm)
{
return !password && password !== '' ?
md5(username+':'+realm)
:
md5(username+':'+realm+':'+password)
}
Credentials.prototype.is_user_credentials= function()
{
return true;
}
return new Credentials;
}
module.exports= user_credentials;
| var md5= require('./md5');
/*
* Hide the password. Uses the password to form authorization strings,
* but provides no interface for exporting it.
*/
function user_credentials(username,password) {
if (username.is_user_credentials &&
typeof username.basic === 'function' &&
typeof username.digest === 'function'
) {
return username;
}
var basic_string= !password && password !== '' ?
new Buffer(username, "ascii").toString("base64")
:
new Buffer(username+':'+password, "ascii").toString("base64")
;
function basic()
{
return basic_string;
}
function digest(realm) {
return !password && password !== '' ?
md5(username+':'+realm)
:
md5(username+':'+realm+':'+password)
}
return {
basic: basic, // basic() returns a hash of username:password
digest: digest, // digest(realm) returns a u & p hash for that realm
username: username,
is_user_credentials: true
}
}
module.exports= user_credentials;
|
Use "dots" karma reporter (for Travis CI web UI) | var webpack = require('webpack');
module.exports = function (config) {
config.set({
browsers: [ process.env.CONTINUOUS_INTEGRATION ? 'Firefox' : 'Chrome' ],
singleRun: process.env.CONTINUOUS_INTEGRATION === 'true',
frameworks: [ 'mocha' ],
files: [
'tests.webpack.js'
],
preprocessors: {
'tests.webpack.js': [ 'webpack', 'sourcemap' ]
},
reporters: [ 'dots' ],
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [
{ test: /\.js$/, loader: 'jsx-loader?harmony' }
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('test')
})
]
},
webpackServer: {
noInfo: true
}
});
};
| var webpack = require('webpack');
module.exports = function (config) {
config.set({
browsers: [ process.env.CONTINUOUS_INTEGRATION ? 'Firefox' : 'Chrome' ],
singleRun: process.env.CONTINUOUS_INTEGRATION === 'true',
frameworks: [ 'mocha' ],
files: [
'tests.webpack.js'
],
preprocessors: {
'tests.webpack.js': [ 'webpack', 'sourcemap' ]
},
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [
{ test: /\.js$/, loader: 'jsx-loader?harmony' }
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('test')
})
]
},
webpackServer: {
noInfo: true
}
});
};
|
Save one line of code | var lastField = null;
var currentFillColor = ''; // ???
var changeCounter = 0; // ???
function setField(element) {
// element contains the current html element
if (element.style.backgroundColor !== currentFillColor) {
element.style.backgroundColor = currentFillColor;
} else {
element.style.backgroundColor = '#eee';
}
if (++changeCounter === 10) {
alert('You have clicked 10 times on the field!');
// Should the counter be reset after the alert?
// changeCounter = 0;
}
}
function setFillColor(color) {
// color should be a string
var logEntry = document.createElement('p');
logEntry.appendChild(document.createTextNode('Color changed'));
logEntry.style.color = currentFillColor = color;
document.getElementById('Log').appendChild(logEntry);
}
| var lastField = null;
var currentFillColor = ''; // ???
var changeCounter = 0; // ???
function setField(element) {
// element contains the current html element
if (element.style.backgroundColor !== currentFillColor) {
element.style.backgroundColor = currentFillColor;
} else {
element.style.backgroundColor = '#eee';
}
if (++changeCounter === 10) {
alert('You have clicked 10 times on the field!');
// Should the counter be reset after the alert?
// changeCounter = 0;
}
}
function setFillColor(color) {
// color should be a string
currentFillColor = color;
var logEntry = document.createElement('p');
logEntry.appendChild(document.createTextNode('Color changed'));
logEntry.style.color = currentFillColor;
document.getElementById('Log').appendChild(logEntry);
}
|
Update podcast list when Remove All is pressed | function updatePodcastList() {
var podcastListElement = $('#podcastList');
var bgPage = chrome.extension.getBackgroundPage();
var listHTML = '';
bgPage.podcastManager.podcastList.forEach(function(podcast) {
listHTML += renderPodcast(podcast);
});
podcastListElement.html(listHTML);
}
function storageChanged(changes, areaName) {
if(areaName === 'sync')
{
updatePodcastList();
}
}
$( document ).ready( function() {
var bgPage = chrome.extension.getBackgroundPage();
$('#addRSS').click( function() {
// addRSS($('#entryBox').val());
bgPage.podcastManager.addPodcast($('#entryBox').val(), updatePodcastList);
});
$('#removeAllRSS').click( function() {
bgPage.podcastManager.deleteAllPodcasts();
updatePodcastList();
});
// chrome.storage.onChanged.addListener(storageChanged)
updatePodcastList();
});
| function updatePodcastList() {
var podcastListElement = $('#podcastList');
var bgPage = chrome.extension.getBackgroundPage();
var listHTML = '';
bgPage.podcastManager.podcastList.forEach(function(podcast) {
listHTML += renderPodcast(podcast);
});
podcastListElement.html(listHTML);
}
function storageChanged(changes, areaName) {
if(areaName === 'sync')
{
updatePodcastList();
}
}
$( document ).ready( function() {
var bgPage = chrome.extension.getBackgroundPage();
$('#addRSS').click( function() {
// addRSS($('#entryBox').val());
bgPage.podcastManager.addPodcast($('#entryBox').val(), updatePodcastList);
});
$('#removeAllRSS').click( function() {
// removeAllRSS();
bgPage.podcastManager.deleteAllPodcasts();
});
// chrome.storage.onChanged.addListener(storageChanged)
updatePodcastList();
});
|
Remove headline from create view | # from django.shortcuts import render
from django.views.generic import ListView, CreateView, DetailView, TemplateView
from django.core.urlresolvers import reverse
from braces.views import OrderableListMixin
from .models import Signature
from .forms import SignatureForm
class SignatureList(OrderableListMixin, ListView):
model = Signature
orderable_columns = ("pk", "name", "city")
orderable_columns_default = "created_on"
ordering = 'desc'
paginate_by = 10
def get_context_data(self, **kwargs):
context = super(SignatureList, self).get_context_data(**kwargs)
context['count'] = Signature.objects.visible().count()
context['form'] = SignatureForm()
return context
def get_queryset(self, *args, **kwargs):
qs = super(SignatureList, self).get_queryset(*args, **kwargs)
return qs.visible()
class SignatureCreate(CreateView):
model = Signature
form_class = SignatureForm
def get_success_url(self):
return reverse('petition:thank-you')
class SignatureDetail(DetailView):
model = Signature
class SignatureCreateDone(TemplateView):
template_name = 'petition/signature_thank_you.html'
| # from django.shortcuts import render
from django.views.generic import ListView, CreateView, DetailView, TemplateView
from django.core.urlresolvers import reverse
from braces.views import SetHeadlineMixin
from braces.views import OrderableListMixin
from .models import Signature
from .forms import SignatureForm
class SignatureList(OrderableListMixin, ListView):
model = Signature
orderable_columns = ("pk", "name", "city")
orderable_columns_default = "created_on"
ordering = 'desc'
paginate_by = 10
def get_context_data(self, **kwargs):
context = super(SignatureList, self).get_context_data(**kwargs)
context['count'] = Signature.objects.visible().count()
context['form'] = SignatureForm()
return context
def get_queryset(self, *args, **kwargs):
qs = super(SignatureList, self).get_queryset(*args, **kwargs)
return qs.visible()
class SignatureCreate(SetHeadlineMixin, CreateView):
model = Signature
form_class = SignatureForm
def get_success_url(self):
return reverse('petition:thank-you')
class SignatureDetail(DetailView):
model = Signature
class SignatureCreateDone(TemplateView):
template_name = 'petition/signature_thank_you.html'
|
Change Var to Const in Seed.js | const userData = require('./mockdata/exampleUsers');
const templateData = require('./mockdata/exampleTemplate');
const activityData = require('./mockdata/exampleActivity');
const historyData = require('./mockdata/exampleHistory');
const { User, Template, Activity, History } = require('./db/mongoose-schemas.js')
//MAKE SURE TABLES ARE CLEAR
User.remove({}, function(err) {
if (err) console.log(err);
console.log('User Table Cleared');
})
Template.remove({}, function(err) {
if (err) console.log(err);
console.log('Template Table Cleared');
})
Activity.remove({}, function(err) {
if (err) console.log(err);
console.log('Activity Table Cleared');
})
History.remove({}, function(err) {
if (err) console.log(err);
console.log('History Table Cleared');
})
//ADD DATA
userData.forEach(function(element) {
User.create(element);
});
templateData.forEach(function(element) {
Template.create(element);
});
activityData.forEach(function(element) {
Activity.create(element);
});
historyData.forEach(function(element) {
History.create(element);
});
| var userData = require('./mockdata/exampleUsers');
var templateData = require('./mockdata/exampleTemplate');
var activityData = require('./mockdata/exampleActivity');
var historyData = require('./mockdata/exampleHistory');
const { User, Template, Activity, History } = require('./db/mongoose-schemas.js')
//MAKE SURE TABLES ARE CLEAR
User.remove({}, function(err) {
if (err) console.log(err);
console.log('User Table Cleared');
})
Template.remove({}, function(err) {
if (err) console.log(err);
console.log('Template Table Cleared');
})
Activity.remove({}, function(err) {
if (err) console.log(err);
console.log('Activity Table Cleared');
})
History.remove({}, function(err) {
if (err) console.log(err);
console.log('History Table Cleared');
})
//ADD DATA
userData.forEach(function(element) {
User.create(element);
});
templateData.forEach(function(element) {
Template.create(element);
});
activityData.forEach(function(element) {
Activity.create(element);
});
historyData.forEach(function(element) {
History.create(element);
});
|
Add a description to the extension | package net.sf.openrocket.example;
import net.sf.openrocket.simulation.SimulationConditions;
import net.sf.openrocket.simulation.exception.SimulationException;
import net.sf.openrocket.simulation.extension.AbstractSimulationExtension;
/**
* The actual simulation extension. A new instance is created for
* each simulation it is attached to.
*
* This class contains the configuration and is called before the
* simulation is run. It can do changes to the simulation, such
* as add simulation listeners.
*
* All configuration should be stored in the config variable, so that
* file storage will work automatically.
*/
public class ThrustScaler extends AbstractSimulationExtension {
@Override
public String getName() {
return "Thrust scaling \u00D7" + getMultiplier();
}
@Override
public String getDescription() {
// This description is shown when the user clicks the info-button on the extension
return "This extension multiplies the thrust of motors by a user-defined multiplier.";
}
@Override
public void initialize(SimulationConditions conditions) throws SimulationException {
conditions.getSimulationListenerList().add(new ThrustScalerSimulationListener(getMultiplier()));
}
public double getMultiplier() {
return config.getDouble("multiplier", 1.0);
}
public void setMultiplier(double multiplier) {
config.put("multiplier", multiplier);
fireChangeEvent();
}
}
| package net.sf.openrocket.example;
import net.sf.openrocket.simulation.SimulationConditions;
import net.sf.openrocket.simulation.exception.SimulationException;
import net.sf.openrocket.simulation.extension.AbstractSimulationExtension;
/**
* The actual simulation extension. A new instance is created for
* each simulation it is attached to.
*
* This class contains the configuration and is called before the
* simulation is run. It can do changes to the simulation, such
* as add simulation listeners.
*
* All configuration should be stored in the config variable, so that
* file storage will work automatically.
*/
public class ThrustScaler extends AbstractSimulationExtension {
@Override
public String getName() {
return "Thrust scaling \u00D7" + getMultiplier();
}
@Override
public void initialize(SimulationConditions conditions) throws SimulationException {
conditions.getSimulationListenerList().add(new ThrustScalerSimulationListener(getMultiplier()));
}
public double getMultiplier() {
return config.getDouble("multiplier", 1.0);
}
public void setMultiplier(double multiplier) {
config.put("multiplier", multiplier);
fireChangeEvent();
}
}
|
Use closed rescue in unit test in order to test access control | 'use strict'
module.exports = {
randomRescue: function () {
let randomName = (Date.now() - parseInt((Math.random() * Math.random()) * 1000000)).toString(36)
return {
active: true,
client: randomName,
codeRed: !!Math.round(Math.random()),
data: { foo: ['test'] },
epic: false,
open: false,
notes: 'test',
platform: Math.round(Math.random()) ? 'pc' : 'xb', // Randomly decide if the client is PC or Xbox
quotes: ['test'],
successful: !!Math.round(Math.random()),
system: 'Eravate',
title: 'Operation Unit Test',
unidentifiedRats: ['TestRat']
}
},
randomRat: function () {
let randomName = (Date.now() - parseInt((Math.random() * Math.random()) * 1000000)).toString(36)
return {
CMDRname: 'Test Rat ' + randomName,
data: { foo: ['test'] },
platform: Math.round(Math.random()) ? 'pc' : 'xb' // Randomly decide if the rat is PC or Xbox
}
}
}
| 'use strict'
module.exports = {
randomRescue: function () {
let randomName = (Date.now() - parseInt((Math.random() * Math.random()) * 1000000)).toString(36)
return {
active: true,
client: randomName,
codeRed: !!Math.round(Math.random()),
data: { foo: ['test'] },
epic: false,
open: true,
notes: 'test',
platform: Math.round(Math.random()) ? 'pc' : 'xb', // Randomly decide if the client is PC or Xbox
quotes: ['test'],
successful: !!Math.round(Math.random()),
system: 'Eravate',
title: 'Operation Unit Test',
unidentifiedRats: ['TestRat']
}
},
randomRat: function () {
let randomName = (Date.now() - parseInt((Math.random() * Math.random()) * 1000000)).toString(36)
return {
CMDRname: 'Test Rat ' + randomName,
data: { foo: ['test'] },
platform: Math.round(Math.random()) ? 'pc' : 'xb' // Randomly decide if the rat is PC or Xbox
}
}
}
|
Fix id source and ajax url | !function($) {
'use strict';
/**
* Soooooooo dirty ;_;
* add the "detach from post" link
*/
$(document).on('click', '.attachments-browser .attachment', function() {
var html = '<a class="remove-post-attachment" href="#">Detach from the post</a>'
$('.attachment-details').find('.delete-attachment').parent().append(html)
})
/**
* Remove the media from the post
*/
$(document).on('click', '.remove-post-attachment', function(e) {
e.preventDefault()
// get the attachment id
var datas = $(this).closest('.media-sidebar').find('.edit-attachment').attr('href')
, regex = /post=([0-9]*)&/g
, match = regex.exec(datas)
if (match !== null) {
var id = match[1]
$.ajax({
url: '/wp-content/plugins/wordpress-remove-post-attachment/ajax.php'
, type: 'post'
, dataType: 'json'
, data: { id: id }
})
.done(function() {
// quick and dirty: deselect the attachment and remove it from the list
var attachment = $('.attachments').find('.attachment.selected')
attachment.find('.check').click()
attachment.remove()
})
}
})
}(window.jQuery);
| !function($) {
'use strict';
/**
* Soooooooo dirty ;_;
* add the "detach from post" link
*/
$(document).on('click', '.attachments-browser .attachment', function() {
var html = '<a class="remove-post-attachment" href="#">Detach from the post</a>'
$('.attachment-details').find('.delete-attachment').parent().append(html)
})
/**
* Remove the media from the post
*/
$(document).on('click', '.remove-post-attachment', function(e) {
e.preventDefault()
// get the attachment id
var datas = $(this).closest('.media-sidebar').find('input[type=hidden]').attr('name')
, regex = /\[([0-9]*)\]/
, match = regex.exec(datas)
if (match !== null) {
var id = match[1]
$.ajax({
url: '/wp-content/plugins/remove-post-attachment/ajax.php'
, type: 'post'
, dataType: 'json'
, data: { id: id }
})
.done(function() {
// quick and dirty: deselect the attachment and remove it from the list
var attachment = $('.attachments').find('.attachment.selected')
attachment.find('.check').click()
attachment.remove()
})
}
})
}(window.jQuery);
|
Add no-ops for Meteor.publish, methods, and onConnection if no webapp | // Only create a server if we are in an environment with a HTTP server
// (as opposed to, eg, a command-line tool).
//
if (Package.webapp) {
if (process.env.DDP_DEFAULT_CONNECTION_URL) {
__meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL =
process.env.DDP_DEFAULT_CONNECTION_URL;
}
Meteor.server = new Server;
Meteor.refresh = function (notification) {
DDPServer._InvalidationCrossbar.fire(notification);
};
// Proxy the public methods of Meteor.server so they can
// be called directly on Meteor.
_.each(['publish', 'methods', 'call', 'apply', 'onConnection'],
function (name) {
Meteor[name] = _.bind(Meteor.server[name], Meteor.server);
});
} else {
// No server? Make these empty/no-ops.
Meteor.server = null;
Meteor.refresh = function (notification) {
};
// Make these empty/no-ops too, so that non-webapp apps can still
// depend on/use packages that use those functions.
_.each(['publish', 'methods', 'onConnection'],
function (name) {
Meteor[name] = function () { };
});
}
// Meteor.server used to be called Meteor.default_server. Provide
// backcompat as a courtesy even though it was never documented.
// XXX COMPAT WITH 0.6.4
Meteor.default_server = Meteor.server;
| // Only create a server if we are in an environment with a HTTP server
// (as opposed to, eg, a command-line tool).
//
if (Package.webapp) {
if (process.env.DDP_DEFAULT_CONNECTION_URL) {
__meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL =
process.env.DDP_DEFAULT_CONNECTION_URL;
}
Meteor.server = new Server;
Meteor.refresh = function (notification) {
DDPServer._InvalidationCrossbar.fire(notification);
};
// Proxy the public methods of Meteor.server so they can
// be called directly on Meteor.
_.each(['publish', 'methods', 'call', 'apply', 'onConnection'],
function (name) {
Meteor[name] = _.bind(Meteor.server[name], Meteor.server);
});
} else {
// No server? Make these empty/no-ops.
Meteor.server = null;
Meteor.refresh = function (notification) {
};
}
// Meteor.server used to be called Meteor.default_server. Provide
// backcompat as a courtesy even though it was never documented.
// XXX COMPAT WITH 0.6.4
Meteor.default_server = Meteor.server;
|
Check if file exists before making new one | package filehandler
import (
"fmt"
"os"
"path/filepath"
)
// SetUp will create the needed directories
func SetUp() error {
errMsg := "Cannot create resources dir. Consider -checkdir=false.\n"
// get current path
path, error := filepath.Abs(filepath.Dir(os.Args[0]))
if error != nil {
return fmt.Errorf(errMsg + "[error] : " + error.Error())
}
if err := os.MkdirAll(path+"/resources", 0711); err != nil {
return fmt.Errorf(errMsg + "[error] : " + err.Error())
}
if err := os.MkdirAll(path+"/resources/json", 0711); err != nil {
return fmt.Errorf(errMsg + "[error] : " + err.Error())
}
if _, err := os.Stat(path + "/resources/index.html"); os.IsNotExist(err) {
f, err := os.Create(path + "/resources/index.html")
if err != nil {
return fmt.Errorf(errMsg + "[error] : " + err.Error())
}
f.Write([]byte("<h1>Hello simple world!</h1>"))
}
return nil
}
| package filehandler
import (
"fmt"
"os"
"path/filepath"
)
// SetUp will create the needed directories
func SetUp() error {
errMsg := "Cannot create resources dir. Consider -checkdir=false.\n"
// get current path
path, error := filepath.Abs(filepath.Dir(os.Args[0]))
if error != nil {
return fmt.Errorf(errMsg + "[error] : " + error.Error())
}
if err := os.MkdirAll(path+"/resources", 0711); err != nil {
return fmt.Errorf(errMsg + "[error] : " + err.Error())
}
if err := os.MkdirAll(path+"/resources/json", 0711); err != nil {
return fmt.Errorf(errMsg + "[error] : " + err.Error())
}
f, err := os.Create(path + "/resources/index.html")
if err != nil {
return fmt.Errorf(errMsg + "[error] : " + err.Error())
}
f.Write([]byte("<h1>Hello simple world!</h1>"))
return nil
}
|
Add additional note to the callback throttle. | package com.novoda.downloadmanager;
/**
* Controls the rate at which a {@link DownloadFile} calls back to
* a {@link DownloadBatch}. Essentially controls the rate of notifications
* during a download of a file.
* <p>
* Note: This does not control the overall emissions of {@link DownloadBatchStatus} between the client and this library.
*/
public interface FileCallbackThrottle {
/**
* Set the callback that should be notified of {@link DownloadBatchStatus}
* changes.
*
* @param callback to notify.
*/
void setCallback(DownloadBatchStatusCallback callback);
/**
* The throttle logic that will forward events to the {@link DownloadBatchStatusCallback}.
*
* @param downloadBatchStatus the latest status to emit.
*/
void update(DownloadBatchStatus downloadBatchStatus);
/**
* Disable the callback or the throttling logic to
* prevent further emissions of {@link DownloadBatchStatus}.
*/
void stopUpdates();
}
| package com.novoda.downloadmanager;
/**
* Controls the rate at which a {@link DownloadFile} calls back to
* a {@link DownloadBatch}. Essentially controls the rate of notifications
* during a download of a file.
*/
public interface FileCallbackThrottle {
/**
* Set the callback that should be notified of {@link DownloadBatchStatus}
* changes.
*
* @param callback to notify.
*/
void setCallback(DownloadBatchStatusCallback callback);
/**
* The throttle logic that will forward events to the {@link DownloadBatchStatusCallback}.
*
* @param downloadBatchStatus the latest status to emit.
*/
void update(DownloadBatchStatus downloadBatchStatus);
/**
* Disable the callback or the throttling logic to
* prevent further emissions of {@link DownloadBatchStatus}.
*/
void stopUpdates();
}
|
Fix linter complaint and append rather than cat lists. | import django.contrib.auth.views as auth_views
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles import views
admin.autodiscover()
urlpatterns = [
url(r'^login/*$', auth_views.LoginView, name='login'),
url(r'^logout/$', auth_views.logout_then_login, name='logout_then_login'),
url(r'^changepassword/$', auth_views.PasswordChangeView, name='password_change'),
url(r'^changepassword/done/$', auth_views.PasswordChangeDoneView, name='password_change_done'),
url(r'^', include('server.urls')),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', admin.site.urls),
url(r'^api/', include('api.v1.urls')),
url(r'^api/v1/', include('api.v1.urls')),
url(r'^api/v2/', include('api.v2.urls')),
url(r'^inventory/', include('inventory.urls')),
url(r'^search/', include('search.urls')),
url(r'^licenses/', include('licenses.urls')),
url(r'^catalog/', include('catalog.urls')),
url(r'^profiles/', include('profiles.urls')),
]
if settings.DEBUG:
urlpatterns.append(url(r'^static/(?P<path>.*)$', views.serve))
| import django.contrib.auth.views as auth_views
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles import views
admin.autodiscover()
urlpatterns = [
url(r'^login/*$', auth_views.LoginView, name='login'),
url(r'^logout/$', auth_views.logout_then_login, name='logout_then_login'),
url(r'^changepassword/$', auth_views.PasswordChangeView, name='password_change'),
url(r'^changepassword/done/$', auth_views.PasswordChangeDoneView, name='password_change_done'),
url(r'^', include('server.urls')),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', admin.site.urls),
url(r'^api/', include('api.v1.urls')),
url(r'^api/v1/', include('api.v1.urls')),
url(r'^api/v2/', include('api.v2.urls')),
url(r'^inventory/', include('inventory.urls')),
url(r'^search/', include('search.urls')),
url(r'^licenses/', include('licenses.urls')),
url(r'^catalog/', include('catalog.urls')),
url(r'^profiles/', include('profiles.urls')),
]
if settings.DEBUG:
urlpatterns += [url(r'^static/(?P<path>.*)$', views.serve),]
|
Use environment defined port if available | var locomotive = require('locomotive')
, bootable = require('bootable');
// Create a new application and initialize it with *required* support for
// controllers and views. Move (or remove) these lines at your own peril.
var app = new locomotive.Application();
app.phase(locomotive.boot.controllers(__dirname + '/app/controllers'));
app.phase(locomotive.boot.views());
// Add phases to configure environments, run initializers, draw routes, and
// start an HTTP server. Additional phases can be inserted as neeeded, which
// is particularly useful if your application handles upgrades from HTTP to
// other protocols such as WebSocket.
app.phase(require('bootable-environment')(__dirname + '/config/environments'));
app.phase(bootable.initializers(__dirname + '/config/initializers'));
app.phase(locomotive.boot.routes(__dirname + '/config/routes'));
app.phase(locomotive.boot.httpServer(process.env.PORT || 3000, '0.0.0.0'));
// Boot the application. The phases registered above will be executed
// sequentially, resulting in a fully initialized server that is listening
// for requests.
app.boot(function(err) {
if (err) {
console.error(err.message);
console.error(err.stack);
return process.exit(-1);
}
});
| var locomotive = require('locomotive')
, bootable = require('bootable');
// Create a new application and initialize it with *required* support for
// controllers and views. Move (or remove) these lines at your own peril.
var app = new locomotive.Application();
app.phase(locomotive.boot.controllers(__dirname + '/app/controllers'));
app.phase(locomotive.boot.views());
// Add phases to configure environments, run initializers, draw routes, and
// start an HTTP server. Additional phases can be inserted as neeeded, which
// is particularly useful if your application handles upgrades from HTTP to
// other protocols such as WebSocket.
app.phase(require('bootable-environment')(__dirname + '/config/environments'));
app.phase(bootable.initializers(__dirname + '/config/initializers'));
app.phase(locomotive.boot.routes(__dirname + '/config/routes'));
app.phase(locomotive.boot.httpServer(3000, '0.0.0.0'));
// Boot the application. The phases registered above will be executed
// sequentially, resulting in a fully initialized server that is listening
// for requests.
app.boot(function(err) {
if (err) {
console.error(err.message);
console.error(err.stack);
return process.exit(-1);
}
});
|
Fix error when password is missing | 'use strict'
const tokens = require('../database/tokens')
const config = require('../utils/config')
const KnownError = require('../utils/KnownError')
const ignoreCookie = require('../utils/ignoreCookie')
const response = (entry) => ({
id: entry.id,
created: entry.created,
updated: entry.updated,
})
module.exports = {
Mutation: {
createToken: async (parent, { input }, { setCookies }) => {
const { username, password } = input
if (config.username == null) throw new KnownError('Ackee username missing in environment')
if (config.password == null) throw new KnownError('Ackee password missing in environment')
if (username !== config.username) throw new KnownError('Username or password incorrect')
if (password !== config.password) throw new KnownError('Username or password incorrect')
const entry = await tokens.add()
// Set cookie to avoid reporting your own visits
setCookies.push(ignoreCookie.on)
return {
success: true,
payload: response(entry),
}
},
deleteToken: async (parent, { id }, { setCookies }) => {
await tokens.del(id)
// Remove cookie to report your own visits, again
setCookies.push(ignoreCookie.off)
return {
success: true,
}
},
},
} | 'use strict'
const tokens = require('../database/tokens')
const config = require('../utils/config')
const KnownError = require('../utils/KnownError')
const ignoreCookie = require('../utils/ignoreCookie')
const response = (entry) => ({
id: entry.id,
created: entry.created,
updated: entry.updated,
})
module.exports = {
Mutation: {
createToken: async (parent, { input }, { setCookies }) => {
const { username, password } = input
if (config.username == null) throw new KnownError('Ackee username missing in environment')
if (config.password == null) throw new KnownError('Ackee username missing in environment')
if (username !== config.username) throw new KnownError('Username or password incorrect')
if (password !== config.password) throw new KnownError('Username or password incorrect')
const entry = await tokens.add()
// Set cookie to avoid reporting your own visits
setCookies.push(ignoreCookie.on)
return {
success: true,
payload: response(entry),
}
},
deleteToken: async (parent, { id }, { setCookies }) => {
await tokens.del(id)
// Remove cookie to report your own visits, again
setCookies.push(ignoreCookie.off)
return {
success: true,
}
},
},
} |
Add assertion for flagbit_currency.twig Twig extension service | <?php
namespace Flagbit\Bundle\CurrencyBundle\Tests;
use Flagbit\Bundle\CurrencyBundle\DependencyInjection\FlagbitCurrencyExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class FlagbitCurrencyExtensionTest extends \PHPUnit_Framework_TestCase
{
public function testCurrencyServiceIntegration()
{
$container = new ContainerBuilder();
$config = array();
$extension = new FlagbitCurrencyExtension();
$extension->load($config, $container);
$definition = $container->findDefinition('flagbit_currency.twig');
$definition->setPublic(true);
$container->compile();
$currencyBundle = $container->get('flagbit_currency.intl_bundle');
$currency = $container->get('flagbit_currency');
$currencyExtension = $container->get('flagbit_currency.twig');
$this->assertInstanceOf('Symfony\Component\Intl\ResourceBundle\CurrencyBundleInterface', $currencyBundle);
$this->assertInstanceOf('Flagbit\Bundle\CurrencyBundle\Service\Currency', $currency);
$this->assertInstanceOf('Flagbit\Bundle\CurrencyBundle\Twig\FlagbitCurrencyExtension', $currencyExtension);
}
}
| <?php
namespace Flagbit\Bundle\CurrencyBundle\Tests;
use Flagbit\Bundle\CurrencyBundle\DependencyInjection\FlagbitCurrencyExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class FlagbitCurrencyExtensionTest extends \PHPUnit_Framework_TestCase
{
public function testCurrencyServiceIntegration()
{
$container = new ContainerBuilder();
$config = array();
$extension = new FlagbitCurrencyExtension();
$extension->load($config, $container);
$container->compile();
$currencyBundle = $container->get('flagbit_currency.intl_bundle');
$currency = $container->get('flagbit_currency');
$this->assertInstanceOf('Symfony\Component\Intl\ResourceBundle\CurrencyBundleInterface', $currencyBundle);
$this->assertInstanceOf('Flagbit\Bundle\CurrencyBundle\Service\Currency', $currency);
}
}
|
Remove commented out, unused code. | import dateUtil from './date-util';
const dateMap = {
days: 1,
weeks: 7
};
export default function({ referenceDate, back, forward, scale = 'days' }) {
// The "1" here accounts for the referenceDate itself.
var length = back + forward + 1;
// The number of days that we add for the scale
var diffUnit = dateMap[scale];
var dates = [];
var potentialDate, toAdd;
var i = 0;
var index = 0;
// Create the starting date from our reference date
var start = dateUtil.cloneDate(referenceDate);
// This assumes that the `back` is right, but it is not. It needs
// to take into account weekends when in day mode
var method = scale === 'days' ? 'subtractWeekDays' : 'subtractDays';
var amount = diffUnit * back;
start = dateUtil[method](start, amount);
while (i < length) {
toAdd = index * diffUnit;
potentialDate = dateUtil.cloneDate(start);
// Update our date appropriately.
potentialDate.setDate(start.getDate() + toAdd);
// Ignore weekends
var isDays = scale === 'days';
var isAWeekend = dateUtil.isWeekendDay(potentialDate);
if (!isDays || (isDays && !isAWeekend)) {
dates.push({time: potentialDate});
i++;
}
index++;
}
return dates;
};
| import dateUtil from './date-util';
const dateMap = {
days: 1,
weeks: 7
};
export default function({ referenceDate, back, forward, scale = 'days' }) {
// The "1" here accounts for the referenceDate itself.
var length = back + forward + 1;
// The number of days that we add for the scale
var diffUnit = dateMap[scale];
var dates = [];
var potentialDate, toAdd;
var i = 0;
var index = 0;
// Create the starting date from our reference date
var start = dateUtil.cloneDate(referenceDate);
// This assumes that the `back` is right, but it is not. It needs
// to take into account weekends when in day mode
var method = scale === 'days' ? 'subtractWeekDays' : 'subtractDays';
var amount = diffUnit * back;
start = dateUtil[method](start, amount);
// start.setDate(referenceDate.getDate() - diffUnit * back);
while (i < length) {
toAdd = index * diffUnit;
potentialDate = dateUtil.cloneDate(start);
// Update our date appropriately.
potentialDate.setDate(start.getDate() + toAdd);
// Ignore weekends
var isDays = scale === 'days';
var isAWeekend = dateUtil.isWeekendDay(potentialDate);
if (!isDays || (isDays && !isAWeekend)) {
dates.push({time: potentialDate});
i++;
}
index++;
}
return dates;
};
|
Revert "bootstrap file changed to reflect new kernel" | // Copyright 2015, EMC, Inc.
'use strict';
module.exports = {
friendlyName: 'Bootstrap Ubuntu',
injectableName: 'Task.Linux.Bootstrap.Ubuntu',
implementsTask: 'Task.Base.Linux.Bootstrap',
options: {
kernelFile: 'vmlinuz-3.16.0-25-generic',
initrdFile: 'initrd.img-3.16.0-25-generic',
kernelUri: '{{ api.server }}/common/{{ options.kernelFile }}',
initrdUri: '{{ api.server }}/common/{{ options.initrdFile }}',
basefs: 'common/base.trusty.3.16.0-25-generic.squashfs.img',
overlayfs: 'common/discovery.overlay.cpio.gz',
profile: 'linux.ipxe',
comport: 'ttyS0'
},
properties: {
os: {
linux: {
distribution: 'ubuntu',
release: 'trusty',
kernel: '3.16.0-25-generic'
}
}
}
};
| // Copyright 2015, EMC, Inc.
'use strict';
module.exports = {
friendlyName: 'Bootstrap Ubuntu',
injectableName: 'Task.Linux.Bootstrap.Ubuntu',
implementsTask: 'Task.Base.Linux.Bootstrap',
options: {
kernelVersion: '3.19.0-56-generic',
kernelFile: 'vmlinuz-{{ options.kernelVersion }}',
initrdFile: 'initrd.img-{{ options.kernelVersion }}',
kernelUri: '{{ api.server }}/common/{{ options.kernelFile }}',
initrdUri: '{{ api.server }}/common/{{ options.initrdFile }}',
basefs: 'common/base.trusty.{{ options.kernelVersion }}.squashfs.img',
overlayfs: 'common/discovery.{{ options.kernelVersion }}.overlay.cpio.gz',
profile: 'linux.ipxe',
comport: 'ttyS0'
},
properties: {
os: {
linux: {
distribution: 'ubuntu',
release: 'trusty',
kernel: '3.19.0-56-generic'
}
}
}
};
|
Revert "Export with UMD as 'clappr' and 'Clappr'" | /* eslint-disable no-var */
var path = require('path')
var webpack = require('webpack')
var Clean = require('clean-webpack-plugin')
var webpackConfig = require('./webpack-base-config')
webpackConfig.entry = path.resolve(__dirname, 'src/main.js')
if (process.env.npm_lifecycle_event === 'release') {
webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({
compress: {warnings: false},
output: {comments: false}
}))
} else {
webpackConfig.plugins.push(new Clean(['dist'], {verbose: false}))
}
webpackConfig.output = {
path: path.resolve(__dirname, 'dist'),
publicPath: '<%=baseUrl%>/',
filename: 'clappr.js',
library: 'Clappr',
libraryTarget: 'umd'
}
module.exports = webpackConfig
| /* eslint-disable no-var */
var path = require('path')
var webpack = require('webpack')
var Clean = require('clean-webpack-plugin')
var webpackConfig = require('./webpack-base-config')
webpackConfig.entry = path.resolve(__dirname, 'src/main.js')
if (process.env.npm_lifecycle_event === 'release') {
webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({
compress: {warnings: false},
output: {comments: false}
}))
} else {
webpackConfig.plugins.push(new Clean(['dist'], {verbose: false}))
}
webpackConfig.output = {
path: path.resolve(__dirname, 'dist'),
publicPath: '<%=baseUrl%>/',
filename: 'clappr.js',
library: ['clappr', 'Clappr'],
libraryTarget: 'umd'
}
module.exports = webpackConfig
|
Split up the HTTP security config for readability. | package hello.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class Security extends WebSecurityConfigurerAdapter {
public static final String ADMIN_ROLE = "ADMINISTRATOR";
@Override
protected void configure(HttpSecurity http) throws Exception {
// Allow all requests and we use method security in the controllers.
http.authorizeRequests().anyRequest().permitAll();
// Use form login/logout for the Web.
http.formLogin().loginPage("/sign-in").permitAll();
http.logout().logoutUrl("/sign-out").logoutSuccessUrl("/").permitAll();
// Use HTTP basic for the API.
http.httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("Rob").password("Haines").roles(ADMIN_ROLE).and().withUser("Caroline")
.password("Jay").roles(ADMIN_ROLE).and().withUser("Markel").password("Vigo").roles(ADMIN_ROLE);
}
}
| package hello.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class Security extends WebSecurityConfigurerAdapter {
public static final String ADMIN_ROLE = "ADMINISTRATOR";
@Override
protected void configure(HttpSecurity http) throws Exception {
// Use form login for the Web, and HTTP basic for the API.
http.authorizeRequests().anyRequest().permitAll().and().formLogin().loginPage("/sign-in").permitAll().and()
.logout().logoutUrl("/sign-out").logoutSuccessUrl("/").permitAll().and().httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("Rob").password("Haines").roles(ADMIN_ROLE).and().withUser("Caroline")
.password("Jay").roles(ADMIN_ROLE).and().withUser("Markel").password("Vigo").roles(ADMIN_ROLE);
}
}
|
Update version number to 0.6 | // Copyright 2017-2018 Auburn University and others. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The godoctor command refactors Go code.
package main
import (
"fmt"
"os"
"github.com/godoctor/godoctor/engine/cli"
)
// Name of the refactoring tool (Go Doctor). This can be overridden using:
// go build -ldflags "-X main.name 'Go Doctor'" github.com/godoctor/godoctor
var name string = "Go Doctor"
// Go Doctor version number. This can be overridden using:
// go build -ldflags "-X main.version 0.6" github.com/godoctor/godoctor
var version string = "0.6 (Beta)"
func main() {
aboutText := fmt.Sprintf("%s %s", name, version)
os.Exit(cli.Run(aboutText, os.Stdin, os.Stdout, os.Stderr, os.Args))
}
| // Copyright 2017 Auburn University and others. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The godoctor command refactors Go code.
package main
import (
"fmt"
"os"
"github.com/godoctor/godoctor/engine/cli"
)
// Name of the refactoring tool (Go Doctor). This can be overridden using:
// go build -ldflags "-X main.name 'Go Doctor'" github.com/godoctor/godoctor
var name string = "Go Doctor"
// Go Doctor version number. This can be overridden using:
// go build -ldflags "-X main.version 0.5" github.com/godoctor/godoctor
var version string = "0.5 (Beta)"
func main() {
aboutText := fmt.Sprintf("%s %s", name, version)
os.Exit(cli.Run(aboutText, os.Stdin, os.Stdout, os.Stderr, os.Args))
}
|
Update analysis definitions on update | var _ = require('underscore');
var Backbone = require('backbone');
var syncAbort = require('./backbone/sync-abort');
/**
* Analysis definition model.
* Points to a node that is the head of the particular analysis.
*/
module.exports = Backbone.Model.extend({
/**
* @override {Backbone.prototype.sync} abort ongoing request if there is any
*/
sync: syncAbort,
initialize: function (attrs, opts) {
if (!opts.analysisDefinitionNodesCollection) throw new Error('analysisDefinitionNodesCollection is required');
this._analysisDefinitionNodesCollection = opts.analysisDefinitionNodesCollection;
},
parse: function (r, opts) {
// If parse is called on a new model it have not yet called initialize and thus don't have the collection
var nodesCollection = this._analysisDefinitionNodesCollection || opts.analysisDefinitionNodesCollection;
nodesCollection.add(r.analysis_definition, {silent: true, merge: true, parse: true});
var attrs = _.omit(r, 'analysis_definition');
attrs.node_id = r.analysis_definition.id;
return attrs;
},
toJSON: function () {
return {
id: this.id,
analysis_definition: this.getNodeDefinitionModel().toJSON()
};
},
containsNode: function (other) {
var nodeDefModel = this.getNodeDefinitionModel();
return !!(nodeDefModel && nodeDefModel.containsNode(other));
},
getNodeDefinitionModel: function () {
return this._analysisDefinitionNodesCollection.get(this.get('node_id'));
}
});
| var _ = require('underscore');
var Backbone = require('backbone');
var syncAbort = require('./backbone/sync-abort');
/**
* Analysis definition model.
* Points to a node that is the head of the particular analysis.
*/
module.exports = Backbone.Model.extend({
/**
* @override {Backbone.prototype.sync} abort ongoing request if there is any
*/
sync: syncAbort,
initialize: function (attrs, opts) {
if (!opts.analysisDefinitionNodesCollection) throw new Error('analysisDefinitionNodesCollection is required');
this._analysisDefinitionNodesCollection = opts.analysisDefinitionNodesCollection;
},
parse: function (r, opts) {
// If parse is called on a new model it have not yet called initialize and thus don't have the collection
var nodesCollection = this._analysisDefinitionNodesCollection || opts.analysisDefinitionNodesCollection;
nodesCollection.add(r.analysis_definition, {silent: true});
var attrs = _.omit(r, 'analysis_definition');
attrs.node_id = r.analysis_definition.id;
return attrs;
},
toJSON: function () {
return {
id: this.id,
analysis_definition: this.getNodeDefinitionModel().toJSON()
};
},
containsNode: function (other) {
var nodeDefModel = this.getNodeDefinitionModel();
return !!(nodeDefModel && nodeDefModel.containsNode(other));
},
getNodeDefinitionModel: function () {
return this._analysisDefinitionNodesCollection.get(this.get('node_id'));
}
});
|
Change order of the menu imems | 'use strict';
const ipcRenderer = global.require('electron').ipcRenderer;
const remote = require('electron').remote;
const app = remote.app;
const Menu = remote.Menu;
const MenuItem = remote.MenuItem;
let keepAspectRatio = false;
let menu = new Menu();
menu.append(new MenuItem({
label: 'ファイルを開く...',
click: () => ipcRenderer.send('open')
}));
menu.append(new MenuItem({
label: 'アスペクト比を維持',
type: 'checkbox',
checked: keepAspectRatio,
click: () => {
keepAspectRatio = !keepAspectRatio;
console.log("@keepAspectRatio", keepAspectRatio);
}
}));
menu.append(new MenuItem({type: 'separator'}));
menu.append(new MenuItem({
label: 'yamadaを終了',
click: () => app.quit()
}));
const getInlineImageStyle = () => {
const maxOption = keepAspectRatio ? 'max-' : '';
return `style="${maxOption}width: 100%; ${maxOption}height: 100%"`
};
window.addEventListener('contextmenu', e => {
e.preventDefault();
menu.popup(remote.getCurrentWindow());
}, false);
document.addEventListener('DOMContentLoaded', () => {
const mainEl = document.querySelector('.main');
ipcRenderer.on('image', (ev, data) => {
mainEl.innerHTML = `<img src='${JSON.parse(data)}' ${getInlineImageStyle()}>`;
});
});
| 'use strict';
const ipcRenderer = global.require('electron').ipcRenderer;
const remote = require('electron').remote;
const app = remote.app;
const Menu = remote.Menu;
const MenuItem = remote.MenuItem;
let keepAspectRatio = false;
let menu = new Menu();
menu.append(new MenuItem({
label: 'ファイルを開く...',
click: () => ipcRenderer.send('open')
}));
menu.append(new MenuItem({type: 'separator'}));
menu.append(new MenuItem({
label: 'yamadaを終了',
click: () => app.quit()
}));
menu.append(new MenuItem({
label: 'アスペクト比を維持',
type: 'checkbox',
checked: keepAspectRatio,
click: () => {
keepAspectRatio = !keepAspectRatio;
console.log("@keepAspectRatio", keepAspectRatio);
}
}));
const getInlineImageStyle = () => {
const maxOption = keepAspectRatio ? 'max-' : '';
return `style="${maxOption}width: 100%; ${maxOption}height: 100%"`
};
window.addEventListener('contextmenu', e => {
e.preventDefault();
menu.popup(remote.getCurrentWindow());
}, false);
document.addEventListener('DOMContentLoaded', () => {
const mainEl = document.querySelector('.main');
ipcRenderer.on('image', (ev, data) => {
mainEl.innerHTML = `<img src='${JSON.parse(data)}' ${getInlineImageStyle()}>`;
});
});
|
Fix blending issue with armours above level 128 | package ganymedes01.etfuturum.core.handlers;
import ganymedes01.etfuturum.EtFuturum;
import ganymedes01.etfuturum.client.OpenGLHelper;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.client.event.RenderPlayerEvent.SetArmorModel;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
public class ClientEventHandler {
@SubscribeEvent
public void renderPlayerEventPre(RenderPlayerEvent.Pre event) {
if (EtFuturum.enableTransparentAmour) {
OpenGLHelper.enableBlend();
OpenGLHelper.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
}
@SubscribeEvent
public void renderPlayerSetArmour(SetArmorModel event) {
if (EtFuturum.enableTransparentAmour) {
OpenGLHelper.enableBlend();
OpenGLHelper.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
}
@SubscribeEvent
public void renderPlayerEventPost(RenderPlayerEvent.Post event) {
if (EtFuturum.enableTransparentAmour)
OpenGLHelper.disableBlend();
}
} | package ganymedes01.etfuturum.core.handlers;
import ganymedes01.etfuturum.EtFuturum;
import ganymedes01.etfuturum.client.OpenGLHelper;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.client.event.RenderPlayerEvent.SetArmorModel;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
public class ClientEventHandler {
@SubscribeEvent
public void renderPlayerEventPre(RenderPlayerEvent.Pre event) {
if (EtFuturum.enableTransparentAmour)
OpenGLHelper.enableBlend();
}
@SubscribeEvent
public void renderPlayerSetArmour(SetArmorModel event) {
if (EtFuturum.enableTransparentAmour)
OpenGLHelper.enableBlend();
}
@SubscribeEvent
public void renderPlayerEventPost(RenderPlayerEvent.Post event) {
if (EtFuturum.enableTransparentAmour)
OpenGLHelper.disableBlend();
}
} |
Rename _shotNum to _right in DoubleShot | package edu.stuy.starlorn.upgrades;
public class DoubleShotUpgrade extends GunUpgrade {
private boolean _right;
public DoubleShotUpgrade() {
super();
_right = true;
}
@Override
public int getNumShots() {
return 2;
}
@Override
public double getAimAngle() {
int direction = 0;
if (_right) {
_right = !_right;
direction = 1;
} else if (!_right) {
_right = !_right;
direction = -1;
}
return direction * Math.PI/8;
}
}
| package edu.stuy.starlorn.upgrades;
public class DoubleShotUpgrade extends GunUpgrade {
private boolean _shotNum;
public DoubleShotUpgrade() {
super();
_shotNum = false;
}
@Override
public int getNumShots() {
return 2;
}
@Override
public double getAimAngle() {
int direction = 0;
if (_shotNum) {
_shotNum = !_shotNum;
direction = 1;
} else if (!_shotNum) {
_shotNum = !_shotNum;
direction = -1;
}
return direction * Math.PI/8;
}
}
|
Add params to recurring interface | <?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 string
*/
public function getRecurringPayment(): string;
/**
* Initialize recurring payment
*
* @param string $token
* @param string $accountId
* @param float $amount
* @param string $description
* @param string $currency
*
* @param array $extraParams
*
* @return bool
*/
public function initPayment(string $token, string $accountId, float $amount, string $description, string $currency = PayService::CURRENCY_RUR_ISO, array $extraParams = []): bool;
/**
* Remember payment fo recurring payments
*
* @return RecurringPayment
*/
public function makeRecurring(): self;
/**
* Set user id payment will be assigned
*
* @param string $id
*
* @return RecurringPayment
*/
public function setUserId(string $id): self;
} | <?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 string
*/
public function getRecurringPayment(): string;
/**
* Initialize recurring payment
*
* @param string $token
* @param float $amount
* @param string $description
* @param string $currency
*
* @return bool
*/
public function initPayment(string $token, float $amount, string $description, string $currency = PayService::CURRENCY_RUR_ISO): bool;
/**
* Remember payment fo recurring payments
*
* @return RecurringPayment
*/
public function makeRecurring(): self;
/**
* Set user id payment will be assigned
*
* @param string $id
*
* @return RecurringPayment
*/
public function setUserId(string $id): self;
} |
Fix bug in resizing images module | <?php
$id = Router::$parameters['{id}'];
$image = Image::ROW($id);
if (null == $image) {
exit();
}
$parts = Router::$parts;
if (0 == count($parts)) {
$path = Rack::Path('img', md5($image->getId()));
} elseif (1 == count($parts)) {
$transformation = $parts[0];
$hash = md5(Router::$url);
$path = Rack::Path('img.cache', $hash);
if (!file_exists($path)) {
Rack::Make('img.cache', $hash);
$prim = Prim::transform($image);
$prim->setRules($transformation);
$prim->saveTo($path);
}
} else {
exit;
}
header("Expires: ".date("r", time()+9999999));
header("Content-type: ".$image->getMime());
header("Content-Length: ". filesize($path));
readfile($path);
| <?php
$id = Router::$parameters['{id}'];
$image = Image::ROW($id);
if (null == $image) {
exit();
}
$parts = Router::$parts;
if (0 == count($parts)) {
$path = Rack::Path('img', md5($image->getId()));
} elseif (1 == count($parts)) {
$transformation = $parts[0];
$hash = md5($transformation);
$path = Rack::Path('img.cache', $hash);
if (!file_exists($path)) {
Rack::Make('img.cache', $hash);
$prim = Prim::transform($image);
$prim->setRules($transformation);
$prim->saveTo($path);
}
} else {
exit;
}
header("Expires: ".date("r", time()+9999999));
header("Content-type: ".$image->getMime());
header("Content-Length: ". filesize($path));
readfile($path);
|
[REFACTOR] Remove "final" keyword on getItems and getDefaultId methods in dynamic list services. | <?php
/**
* @package module.twitterconnect
*/
class twitterconnect_ListAuthorizedaccountsbywebsiteService extends BaseService
{
/**
* @var twitterconnect_ListAccountsbywebsiteService
*/
private static $instance;
private $items = null;
/**
* @return twitterconnect_ListAccountsbywebsiteService
*/
public static function getInstance()
{
if (is_null(self::$instance))
{
self::$instance = self::getServiceClassInstance(get_class());
}
return self::$instance;
}
/**
* @return array<list_Item>
*/
public function getItems()
{
try
{
$request = Controller::getInstance()->getContext()->getRequest();
$websiteId = intval($request->getParameter('websiteId', 0));
$website = DocumentHelper::getDocumentInstance($websiteId);
}
catch (Exception $e)
{
if (Framework::isDebugEnabled())
{
Framework::debug(__METHOD__ . ' EXCEPTION: ' . $e->getMessage());
}
return array();
}
$items = array();
foreach (twitterconnect_AccountService::getInstance()->getAuthorizedByWebsite($website) as $account)
{
$items[] = new list_Item(
$account->getLabel(),
$account->getId()
);
}
return $items;
}
} | <?php
/**
* @package module.twitterconnect
*/
class twitterconnect_ListAuthorizedaccountsbywebsiteService extends BaseService
{
/**
* @var twitterconnect_ListAccountsbywebsiteService
*/
private static $instance;
private $items = null;
/**
* @return twitterconnect_ListAccountsbywebsiteService
*/
public static function getInstance()
{
if (is_null(self::$instance))
{
self::$instance = self::getServiceClassInstance(get_class());
}
return self::$instance;
}
/**
* @return array<list_Item>
*/
public final function getItems()
{
try
{
$request = Controller::getInstance()->getContext()->getRequest();
$websiteId = intval($request->getParameter('websiteId', 0));
$website = DocumentHelper::getDocumentInstance($websiteId);
}
catch (Exception $e)
{
if (Framework::isDebugEnabled())
{
Framework::debug(__METHOD__ . ' EXCEPTION: ' . $e->getMessage());
}
return array();
}
$items = array();
foreach (twitterconnect_AccountService::getInstance()->getAuthorizedByWebsite($website) as $account)
{
$items[] = new list_Item(
$account->getLabel(),
$account->getId()
);
}
return $items;
}
} |
Use self when refering to the closure's execution context | quail.aLinkTextDoesNotBeginWithRedundantWord = function (quail, test, Case) {
test.get('$scope').find('a').each(function () {
var self = this;
var $link = $(this);
var text = '';
var $img = $link.find('img[alt]');
if ($img.length) {
text = text + $img.eq(0).attr('alt');
}
text = text + $link.text();
text = text.toLowerCase();
var _case;
// Search the text for redundant words. Break as soon as one is detected.
for (var i = 0, il = quail.strings.redundant.link.length; i < il; ++i) {
var phrase = quail.strings.redundant.link[i];
if (text.search(phrase) > -1) {
_case = test.add(Case({
element: self,
status: 'failed'
}));
break;
}
}
// If the case didn't fail, then it passed.
if (!_case) {
test.add(Case({
element: self,
status: 'passed'
}));
}
});
};
| quail.aLinkTextDoesNotBeginWithRedundantWord = function (quail, test, Case) {
test.get('$scope').find('a').each(function () {
var link = this;
var $link = $(this);
var text = '';
var $img = $link.find('img[alt]');
if ($img.length) {
text = text + $img.eq(0).attr('alt');
}
text = text + $link.text();
text = text.toLowerCase();
var _case;
// Search the text for redundant words. Break as soon as one is detected.
for (var i = 0, il = quail.strings.redundant.link.length; i < il; ++i) {
var phrase = quail.strings.redundant.link[i];
if (text.search(phrase) > -1) {
_case = test.add(Case({
element: link,
status: 'failed'
}));
break;
}
}
// If the case didn't fail, then it passed.
if (!_case) {
test.add(Case({
element: link,
status: 'passed'
}));
}
});
};
|
Build: Make Promises/A+ tests use the dot reporter instead of the default
The default reporter is very verbose as it prints all the test names it
encounters. We already use the dot reporter for Karma tests.
Closes gh-4313 | "use strict";
module.exports = grunt => {
const timeout = 2000;
const spawnTest = require( "./lib/spawn_test.js" );
grunt.registerTask( "promises_aplus_tests",
[ "promises_aplus_tests:deferred", "promises_aplus_tests:when" ] );
grunt.registerTask( "promises_aplus_tests:deferred", function() {
spawnTest( this.async(),
"\"" + __dirname + "/../../node_modules/.bin/promises-aplus-tests\"" +
" test/promises_aplus_adapters/deferred.js" +
" --reporter dot" +
" --timeout " + timeout
);
} );
grunt.registerTask( "promises_aplus_tests:when", function() {
spawnTest( this.async(),
"\"" + __dirname + "/../../node_modules/.bin/promises-aplus-tests\"" +
" test/promises_aplus_adapters/when.js" +
" --reporter dot" +
" --timeout " + timeout
);
} );
};
| module.exports = function( grunt ) {
"use strict";
var timeout = 2000,
spawnTest = require( "./lib/spawn_test.js" );
grunt.registerTask( "promises_aplus_tests",
[ "promises_aplus_tests:deferred", "promises_aplus_tests:when" ] );
grunt.registerTask( "promises_aplus_tests:deferred", function() {
spawnTest( this.async(),
"\"" + __dirname + "/../../node_modules/.bin/promises-aplus-tests\"" +
" test/promises_aplus_adapters/deferred.js" +
" --timeout " + timeout
);
} );
grunt.registerTask( "promises_aplus_tests:when", function() {
spawnTest( this.async(),
"\"" + __dirname + "/../../node_modules/.bin/promises-aplus-tests\"" +
" test/promises_aplus_adapters/when.js" +
" --timeout " + timeout
);
} );
};
|
Initialize array store with an empty array |
var SimpleStore = require('fh-wfm-simple-store'),
config = require('./config.js');
/**
* Creates and initializes a store to be used by the app modules.
* @param {String} dataSetId String used as an identifier for the store
* @param {Object|null} seedData Object to be saved in the store initially
* @param {Object} mediator Object used for listening to a topic.
*/
function initStore(dataSetId, seedData, mediator) {
var dataStore = new SimpleStore(dataSetId);
/**
* Check if existing data exists. If no existing data is found, initialize with the given seed data. Otherwise,
* continue to listen to topic.
*
* TODO: Check for existing data may be removed in production as applications are likely to start with no
* initial data. Instead, initialize store with: dataStore.init();
*/
dataStore.list().then(function(storeData) {
if (!storeData || storeData.length === 0) {
//Check if seed data is given, otherwise initialize store with no initial data.
//array store needs to be initialized with an empty array if there is no seed data given.
if (!seedData && process.env.WFM_USE_MEMORY_STORE === "true") {
seedData = [];
}
dataStore.init(seedData).then(function() {
dataStore.listen(config.get('dataTopicPrefix'), mediator);
});
} else {
dataStore.listen(config.get('dataTopicPrefix'), mediator);
}
});
}
module.exports = {
init: initStore
};
|
var SimpleStore = require('fh-wfm-simple-store'),
config = require('./config.js');
/**
* Creates and initializes a store to be used by the app modules.
* @param {String} dataSetId String used as an identifier for the store
* @param {Object|null} seedData Object to be saved in the store initially
* @param {Object} mediator Object used for listening to a topic.
*/
function initStore(dataSetId, seedData, mediator) {
var dataStore = new SimpleStore(dataSetId);
/**
* Check if existing data exists. If no existing data is found, initialize with the given seed data. Otherwise,
* continue to listen to topic.
*
* TODO: Check for existing data may be removed in production as applications are likely to start with no
* initial data. Instead, initialize store with: dataStore.init();
*/
dataStore.list().then(function(storeData) {
if (!storeData || storeData.length === 0) {
//Check if seed data is given, otherwise initialize store with no initial data.
if (seedData) {
dataStore.init(seedData).then(function() {
dataStore.listen(config.get('dataTopicPrefix'), mediator);
});
} else {
dataStore.init().then(function() {
dataStore.listen(config.get('dataTopicPrefix'), mediator);
});
}
} else {
dataStore.listen(config.get('dataTopicPrefix'), mediator);
}
});
}
module.exports = {
init: initStore
};
|
Adjust function name for setLoginAttributeName.
This is not my fault, cause sentry changed this name. | <?php namespace Shanhaijing\SentryExt;
use Shanhaijing\SentryExt\Users\Eloquent\Provider as UserProvider;
use Cartalyst\Sentry\SentryServiceProvider;
class SentryExtServiceProvider extends SentryServiceProvider {
protected function registerUserProvider()
{
$this->app['sentry.user'] = $this->app->share(function($app)
{
$model = $app['config']['cartalyst/sentry::users.model'];
// We will never be accessing a user in Sentry without accessing
// the user provider first. So, we can lazily setup our user
// model's login attribute here. If you are manually using the
// attribute outside of Sentry, you will need to ensure you are
// overriding at runtime.
if (method_exists($model, 'setLoginAttributeName')) {
$loginAttribute = $app['config']['cartalyst/sentry::users.login_attribute'];
forward_static_call_array(
array($model, 'setLoginAttributeName'),
array($loginAttribute)
);
}
return new UserProvider($app['sentry.hasher'], $model);
});
}
}
| <?php namespace Shanhaijing\SentryExt;
use Shanhaijing\SentryExt\Users\Eloquent\Provider as UserProvider;
use Cartalyst\Sentry\SentryServiceProvider;
class SentryExtServiceProvider extends SentryServiceProvider {
protected function registerUserProvider()
{
$this->app['sentry.user'] = $this->app->share(function($app)
{
$model = $app['config']['cartalyst/sentry::users.model'];
// We will never be accessing a user in Sentry without accessing
// the user provider first. So, we can lazily setup our user
// model's login attribute here. If you are manually using the
// attribute outside of Sentry, you will need to ensure you are
// overriding at runtime.
if (method_exists($model, 'setLoginAttribute'))
{
$loginAttribute = $app['config']['cartalyst/sentry::users.login_attribute'];
forward_static_call_array(
array($model, 'setLoginAttribute'),
array($loginAttribute)
);
}
return new UserProvider($app['sentry.hasher'], $model);
});
}
}
|
Add the decoratable behavior to the dispatcher and add the document controller as decorator | <?php
/**
* Kodekit Platform - http://www.timble.net/kodekit
*
* @copyright Copyright (C) 2011 - 2016 Johan Janssens and Timble CVBA. (http://www.timble.net)
* @license MPL v2.0 <https://www.mozilla.org/en-US/MPL/2.0>
* @link https://github.com/timble/kodekit-platform for the canonical source repository
*/
use Kodekit\Library;
return array(
'priority' => Library\ObjectBootstrapperInterface::PRIORITY_LOW,
'aliases' => array(
'application' => 'com:application.dispatcher',
'application.sites' => 'com:application.model.composite.sites',
'translator' => 'com:application.translator',
'lib:dispatcher.router.route' => 'com:application.dispatcher.router.route',
),
'identifiers' => array(
'dispatcher' => array(
'behaviors'=> array('decoratable' => array('decorators' => 'com:application.controller.document')),
)
)
);
| <?php
/**
* Kodekit Platform - http://www.timble.net/kodekit
*
* @copyright Copyright (C) 2011 - 2016 Johan Janssens and Timble CVBA. (http://www.timble.net)
* @license MPL v2.0 <https://www.mozilla.org/en-US/MPL/2.0>
* @link https://github.com/timble/kodekit-platform for the canonical source repository
*/
return array(
'aliases' => array(
'application' => 'com:application.dispatcher',
'application.sites' => 'com:application.model.composite.sites',
'translator' => 'com:application.translator',
'lib:dispatcher.router.route' => 'com:application.dispatcher.router.route',
),
'identifiers' => array(
'dispatcher' => array(
'behaviors' => array('com:application.dispatcher.behavior.documentable')
),
)
);
|
chore(pins): Update to point to release/horton
- Update to point to release/horton of gdcdictionary | from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'psqlgraph',
'gdcdictionary',
'cdisutils',
'python-dateutil==2.4.2',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@4a75cc05c7ba2174e70cca9c9ea7e93947f7a868#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@7b5de7d56aa3159a9526940eb273579ddbf084ca#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@release/horton#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
| from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'psqlgraph',
'gdcdictionary',
'cdisutils',
'python-dateutil==2.4.2',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@4a75cc05c7ba2174e70cca9c9ea7e93947f7a868#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@7b5de7d56aa3159a9526940eb273579ddbf084ca#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@86a4e6dd7b78d50ec17dc4bcdd1a3d25c658b88b#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
|
[FrameworkBundle] Fix built-in server when using query params in paths
$_SERVER['REQUEST_URI'] will contain the query params so is_file will fail.
Change it to use $_SERVER['SCRIPT_NAME'] instead which only contains the
relative filename of the the script. | <?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.
*/
/*
* This file implements rewrite rules for PHP built-in web server.
*
* See: http://www.php.net/manual/en/features.commandline.webserver.php
*
* If you have custom directory layout, then you have to write your own router
* and pass it as a value to 'router' option of server:run command.
*
* @author: Michał Pipa <michal.pipa.xsolve@gmail.com>
* @author: Albert Jessurum <ajessu@gmail.com>
*/
if (is_file($_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . $_SERVER['SCRIPT_NAME'])) {
return false;
}
$_SERVER['SCRIPT_FILENAME'] = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'app_dev.php';
require 'app_dev.php';
| <?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.
*/
/*
* This file implements rewrite rules for PHP built-in web server.
*
* See: http://www.php.net/manual/en/features.commandline.webserver.php
*
* If you have custom directory layout, then you have to write your own router
* and pass it as a value to 'router' option of server:run command.
*
* @author: Michał Pipa <michal.pipa.xsolve@gmail.com>
* @author: Albert Jessurum <ajessu@gmail.com>
*/
if (is_file($_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . $_SERVER['REQUEST_URI'])) {
return false;
}
$_SERVER['SCRIPT_FILENAME'] = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'app_dev.php';
require 'app_dev.php';
|
Clean intersection class. Moved method to Main class and not intersection | package city;
import utils.Helper;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Intersection {
public int calls = 0;
public int index;
public List<Integer> connections = new ArrayList<Integer>();
public Intersection(int index, List<Integer> connections) {
this.index = index;
this.connections = connections;
}
public Intersection() {
}
public void receiveCall() {
this.calls++;
}
@Override
public String toString() {
return "Intersection{" +
"nextTime=" + nextTime +
", calls=" + calls +
", index=" + index +
", connections=" + connections +
'}';
}
}
| package city;
import utils.Helper;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Intersection {
public Date nextTime;
public int calls = 0;
public int index;
final static int MAX_CALLS = 4;
public List<Integer> connections = new ArrayList<Integer>();
public Intersection(int index, List<Integer> connections) {
this.index = index;
this.connections = connections;
}
public Intersection() {
}
// public void nextTime(Date currentTime){
// if(calls < MAX_CALLS)
// this.nextTime = Helper.nextCall(currentTime);
// else
// this.nextTime = null;
// }
public void receiveCall() {
this.calls++;
}
@Override
public String toString() {
return "Intersection{" +
"nextTime=" + nextTime +
", calls=" + calls +
", index=" + index +
", connections=" + connections +
'}';
}
}
|
Add support for typescriptreact *.tsx files | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Anton Lavrenov
# Copyright (c) 2014 Anton Lavrenov
#
# License: MIT
#
"""This module exports the Tslint plugin class."""
from SublimeLinter.lint import Linter, util
class Tslint(Linter):
"""Provides an interface to tslint."""
syntax = ('typescript', 'typescriptreact')
cmd = ('tslint', '@')
regex = (
r'^.+?\[(?P<line>\d+), (?P<col>\d+)\]: '
r'(?P<message>.+)'
)
error_stream = util.STREAM_BOTH
config_file = ('--config', 'tslint.json', '~')
tempfile_suffix = {'typescript': 'ts', 'typescriptreact': 'tsx'}
version_args = '--version'
version_requirement = '>= 0.4.0'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Anton Lavrenov
# Copyright (c) 2014 Anton Lavrenov
#
# License: MIT
#
"""This module exports the Tslint plugin class."""
from SublimeLinter.lint import Linter, util
class Tslint(Linter):
"""Provides an interface to tslint."""
syntax = 'typescript'
cmd = ('tslint', '@')
regex = (
r'^.+?\[(?P<line>\d+), (?P<col>\d+)\]: '
r'(?P<message>.+)'
)
error_stream = util.STREAM_BOTH
config_file = ('--config', 'tslint.json', '~')
tempfile_suffix = 'ts'
version_args = '--version'
version_requirement = '>= 0.4.0'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
|
Change local variables names in graphs.FindCelebrity function
This change makes code more readable. | // Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package graphs
// FindCelebrity returns an index into 2D slice f that represents a celebrity
// on the party who doesn't know no one. -1 is returned if such a celebrity
// doesn't exists in f or if a person exists who doesn't know the celebrity.
// The time complexity is O(n), and O(1) additional space is needed.
func FindCelebrity(f [][]bool) int {
row, col := 0, 1 // col starts at 1 'cause it's after start of a diagonal (A<->A, B<->B, C<->C, ...)
for col < len(f) {
if f[row][col] {
row, col = col, col+1 // All candidates less then col are not celebrity candidates.
} else {
col++ // row is still a celebrity candidate but col is not.
}
}
for _, status := range f[row] { // Check if selected candidate is really a celebrity.
if status {
return -1
}
}
return row
}
| // Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package graphs
// FindCelebrity returns an index into 2D slice f that represents a celebrity
// on the party who doesn't know no one. -1 is returned if such a celebrity
// doesn't exists in f or if a person exists who doesn't know the celebrity.
// The time complexity is O(n), and O(1) additional space is needed.
func FindCelebrity(f [][]bool) int {
r, c := 0, 1 // c starts at 1 'cause it's after start of diagonal (A<->A, B<->B, C<->C, ...)
for c < len(f) {
if f[r][c] {
r, c = c, c+1 // All candidates less then c are not celebrity candidates.
} else {
c++ // r is still a celebrity candidate but c is not.
}
}
for _, status := range f[r] { // Check if selected candidate is really a celebrity.
if status {
return -1
}
}
return r
}
|
fix: Clean out dist and build before building
This should fix the problem with uploading old versions.
Fixes #86 | """PyPI
"""
from invoke import run
from semantic_release import ImproperConfigurationError
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:param dists: The dists string passed to setup.py. Default: 'bdist_wheel'
:param username: PyPI account username string
:param password: PyPI account password string
:param skip_existing: Continue uploading files if one already exists. (Only valid when
uploading to PyPI. Other implementations may not support this.)
"""
if username is None or password is None or username == "" or password == "":
raise ImproperConfigurationError('Missing credentials for uploading')
run('rm -rf build dist')
run('python setup.py {}'.format(dists))
run(
'twine upload -u {} -p {} {} {}'.format(
username,
password,
'--skip-existing' if skip_existing else '',
'dist/*'
)
)
run('rm -rf build dist')
| """PyPI
"""
from invoke import run
from semantic_release import ImproperConfigurationError
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:param dists: The dists string passed to setup.py. Default: 'bdist_wheel'
:param username: PyPI account username string
:param password: PyPI account password string
:param skip_existing: Continue uploading files if one already exists. (Only valid when
uploading to PyPI. Other implementations may not support this.)
"""
if username is None or password is None or username == "" or password == "":
raise ImproperConfigurationError('Missing credentials for uploading')
run('python setup.py {}'.format(dists))
run(
'twine upload -u {} -p {} {} {}'.format(
username,
password,
'--skip-existing' if skip_existing else '',
'dist/*'
)
)
run('rm -rf build dist')
|
Enable IA button only if cookie iabutton exists implemented | /* global menuJson:false */
window.addEventListener('WebComponentsReady', function() {
//original document
var firstElement = document.body.children[0];
// insert header after body-tag
var header = document.createElement('uq-minimal-header');
header.showIAButton = (document.cookie.indexOf("iabutton") >= 0);
header.showMenuButton = true;
header.showSearchButton = true;
document.body.insertBefore(header, firstElement);
// insert menu after header
var menu = document.createElement('uql-menu');
menu.menuJson = menuJson;
header.appendChild(menu);
header.addEventListener("menu-clicked", function(event) {
menu.toggleMenu();
});
// insert footer before body-tag
var subFooter = document.createElement('uql-connect-footer');
document.body.appendChild(subFooter);
subFooter.footerMenuUrl = menuJson;
subFooter.mainDomain = 'https://www.library.uq.edu.au';
var footer = document.createElement('uq-minimal-footer');
document.body.appendChild(footer);
}); | /* global menuJson:false */
window.addEventListener('WebComponentsReady', function() {
//original document
var firstElement = document.body.children[0];
// insert header after body-tag
var header = document.createElement('uq-minimal-header');
header.showIAButton = false;
header.showMenuButton = true;
header.showSearchButton = true;
document.body.insertBefore(header, firstElement);
// insert menu after header
var menu = document.createElement('uql-menu');
menu.menuJson = menuJson;
header.appendChild(menu);
header.addEventListener("menu-clicked", function(event) {
menu.toggleMenu();
});
// insert footer before body-tag
var subFooter = document.createElement('uql-connect-footer');
document.body.appendChild(subFooter);
subFooter.footerMenuUrl = menuJson;
subFooter.mainDomain = 'https://www.library.uq.edu.au';
var footer = document.createElement('uq-minimal-footer');
document.body.appendChild(footer);
}); |
Remove an unused variable from TestTests. | """
Tests for the :mod:`retdec.test` module.
:copyright: © 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
:license: MIT, see the ``LICENSE`` file for more details
"""
from retdec.exceptions import AuthenticationError
from retdec.test import Test
from tests.service_tests import BaseServiceTests
class TestTests(BaseServiceTests):
"""Tests for :class:`retdec.test.Test`."""
def test_auth_sends_correct_request(self):
test = Test(api_key='API-KEY')
test.auth()
self.APIConnectionMock.assert_called_once_with(
'https://retdec.com/service/api/test/echo',
'API-KEY'
)
self.conn_mock.send_get_request.assert_called_once_with()
def test_auth_raises_exception_when_authentication_fails(self):
self.conn_mock.send_get_request.side_effect = AuthenticationError(
code=401,
message='Unauthorized by API Key',
description='API key authentication failed.'
)
test = Test(api_key='INVALID-API-KEY')
with self.assertRaises(AuthenticationError):
test.auth()
| """
Tests for the :mod:`retdec.test` module.
:copyright: © 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
:license: MIT, see the ``LICENSE`` file for more details
"""
from retdec.exceptions import AuthenticationError
from retdec.test import Test
from tests.service_tests import BaseServiceTests
class TestTests(BaseServiceTests):
"""Tests for :class:`retdec.test.Test`."""
def test_auth_sends_correct_request(self):
test = Test(api_key='API-KEY')
test.auth()
self.APIConnectionMock.assert_called_once_with(
'https://retdec.com/service/api/test/echo',
'API-KEY'
)
self.conn_mock.send_get_request.assert_called_once_with()
def test_auth_raises_exception_when_authentication_fails(self):
self.conn_mock.send_get_request.side_effect = AuthenticationError(
code=401,
message='Unauthorized by API Key',
description='API key authentication failed.'
)
test = Test(api_key='INVALID-API-KEY')
with self.assertRaises(AuthenticationError) as cm:
test.auth()
|
Fix bug: Do not push if saga is undefined | import { createActions, handleActions } from 'redux-actions'
import { takeEvery } from 'redux-saga/effects'
export const createModule = (moduleName, definitions, defaultState) => {
const identityActions = []
const actionMap = {}
const reducerMap = {}
const sagas = []
for (const [type, definition] of Object.entries(definitions)) {
const ACTION_TYPE = `${moduleName}/${type}`
const { creator, reducer, saga } = typeof definition === 'function' ? { reducer: definition } : definition
creator ? actionMap[ACTION_TYPE] = creator : identityActions.push(ACTION_TYPE)
reducerMap[ACTION_TYPE] = reducer
saga && sagas.push(takeEvery(ACTION_TYPE, saga))
}
return {
reducer: handleActions(reducerMap, defaultState),
...sagas.length && { sagas },
...Object
.entries(createActions(actionMap, ...identityActions))
.reduce((prev, [key, value]) => ({ ...prev, [key.split('/', 1)[1]]: value }), {}),
}
}
| import { createActions, handleActions } from 'redux-actions'
import { takeEvery } from 'redux-saga/effects'
export const createModule = (moduleName, definitions, defaultState) => {
const identityActions = []
const actionMap = {}
const reducerMap = {}
const sagas = []
for (const [type, definition] of Object.entries(definitions)) {
const ACTION_TYPE = `${moduleName}/${type}`
const { creator, reducer, saga } = typeof definition === 'function' ? { reducer: definition } : definition
creator ? actionMap[ACTION_TYPE] = creator : identityActions.push(ACTION_TYPE)
reducerMap[ACTION_TYPE] = reducer
sagas.push(takeEvery(ACTION_TYPE, saga))
}
return {
reducer: handleActions(reducerMap, defaultState),
...sagas.length && { sagas },
...Object
.entries(createActions(actionMap, ...identityActions))
.reduce((prev, [key, value]) => ({ ...prev, [key.split('/', 1)[1]]: value }), {}),
}
}
|
Make sure query filter works with database prefix
Related to flarum/core#269. | <?php namespace Flarum\Subscriptions\Gambits;
use Flarum\Core\Search\Search;
use Flarum\Core\Search\RegexGambit;
use Illuminate\Database\Query\Expression;
class SubscriptionGambit extends RegexGambit
{
protected $pattern = 'is:(follow|ignor)(?:ing|ed)';
protected function conditions(Search $search, array $matches, $negate)
{
$actor = $search->getActor();
// might be better as `id IN (subquery)`?
$method = $negate ? 'whereNotExists' : 'whereExists';
$search->getQuery()->$method(function ($query) use ($actor, $matches) {
$query->select(app('flarum.db')->raw(1))
->from('users_discussions')
->where('discussions.id', new Expression('discussion_id'))
->where('user_id', $actor->id)
->where('subscription', $matches[1] === 'follow' ? 'follow' : 'ignore');
});
}
}
| <?php namespace Flarum\Subscriptions\Gambits;
use Flarum\Core\Search\Search;
use Flarum\Core\Search\RegexGambit;
class SubscriptionGambit extends RegexGambit
{
protected $pattern = 'is:(follow|ignor)(?:ing|ed)';
protected function conditions(Search $search, array $matches, $negate)
{
$actor = $search->getActor();
// might be better as `id IN (subquery)`?
$method = $negate ? 'whereNotExists' : 'whereExists';
$search->getQuery()->$method(function ($query) use ($actor, $matches) {
$query->select(app('flarum.db')->raw(1))
->from('users_discussions')
->whereRaw('discussion_id = discussions.id')
->where('user_id', $actor->id)
->where('subscription', $matches[1] === 'follow' ? 'follow' : 'ignore');
});
}
}
|
Fix classifier error while pishing to pypi | from setuptools import find_packages, setup
setup(
name='pyserializer',
version='0.0.1',
description='Simple python serialization library.',
author='LocalMed',
author_email='ecordell@localmed.com, pete@localmed.com, joel.james@localmed.com',
url='',
license='MIT',
packages=find_packages(exclude=['tests', 'tests.*']),
include_package_data=True,
install_requires=[
'six==1.8.0'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Internet :: WWW/HTTP',
],
)
| from setuptools import find_packages, setup
setup(
name='pyserializer',
version='0.0.1',
description='Simple python serialization library.',
author='LocalMed',
author_email='ecordell@localmed.com, pete@localmed.com, joel.james@localmed.com',
url='',
license='MIT',
packages=find_packages(exclude=['tests', 'tests.*']),
include_package_data=True,
install_requires=[
'six==1.8.0'
],
classifiers=[
'Development Status :: 1 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Internet :: WWW/HTTP',
],
)
|
Add className to join component | const Join = () => {
return (
<div className="component">
<h1>Bli med i linjeforeningen!</h1>
<p>Alle informatikere er med i linjeforeningen. Gå videre til <a href="https://online.ntnu.no/">hovedsiden</a> for å lage din brukerkonto på Online sine systemer.</p>
<p>Har du lyst til å gjøre studietiden til informatikere enda bedre? Som komitemedlem i Online blir du del av en familie du aldri vil glemme. Vi tilbyr utfordrende og spennende verv i et meget sosialt miljø med stor takhøyde.</p>
<p>Les mer om de ulike komiteene, linjeforeningen og mye mer på vår <a href="https://online.ntnu.no/wiki" target="_blank">Wiki</a>.</p>
</div>
);
};
export default Join;
| const Join = () => {
return (
<div>
<h1>Bli med i linjeforeningen!</h1>
<p>Alle informatikere er med i linjeforeningen. Gå videre til <a href="https://online.ntnu.no/">hovedsiden</a> for å lage din brukerkonto på Online sine systemer.</p>
<p>Har du lyst til å gjøre studietiden til informatikere enda bedre? Som komitemedlem i Online blir du del av en familie du aldri vil glemme. Vi tilbyr utfordrende og spennende verv i et meget sosialt miljø med stor takhøyde.</p>
<p>Les mer om de ulike komiteene, linjeforeningen og mye mer på vår <a href="https://online.ntnu.no/wiki" target="_blank">Wiki</a>.</p>
</div>
);
};
export default Join;
|
Adjust opt.splitter to compare against undefined for the default value. | var es = require('event-stream'),
clone = require('clone'),
path = require('path');
module.exports = function(opt){
// clone options
opt = opt ? clone(opt) : {};
if (typeof opt.splitter === 'undefined') opt.splitter = '\r\n';
if (!opt.fileName) throw new Error("Missing fileName option for gulp-concat");
var buffer = [];
function bufferContents(file){
// clone the file so we arent mutating stuff
buffer.push(clone(file));
}
function endStream(){
if (buffer.length === 0) return this.emit('end');
var joinedContents = buffer.map(function(file){
return file.contents;
}).join(opt.splitter);
var joinedPath = path.join(path.dirname(buffer[0].path), opt.fileName);
var joinedFile = {
shortened: opt.fileName,
path: joinedPath,
contents: joinedContents
};
this.emit('data', joinedFile);
this.emit('end');
}
return es.through(bufferContents, endStream);
};
| var es = require('event-stream'),
clone = require('clone'),
path = require('path');
module.exports = function(opt){
// clone options
opt = opt ? clone(opt) : {};
if (!opt.splitter && opt.splitter !== "") opt.splitter = '\r\n';
if (!opt.fileName) throw new Error("Missing fileName option for gulp-concat");
var buffer = [];
function bufferContents(file){
// clone the file so we arent mutating stuff
buffer.push(clone(file));
}
function endStream(){
if (buffer.length === 0) return this.emit('end');
var joinedContents = buffer.map(function(file){
return file.contents;
}).join(opt.splitter);
var joinedPath = path.join(path.dirname(buffer[0].path), opt.fileName);
var joinedFile = {
shortened: opt.fileName,
path: joinedPath,
contents: joinedContents
};
this.emit('data', joinedFile);
this.emit('end');
}
return es.through(bufferContents, endStream);
};
|
[fix] Remove buggy code from test suite | import supertest from 'supertest';
import app from '../index';
describe('PostIt Tests', () => {
describe('Authentication routes test', () => {
it('ensures proper response for successful user sign in', (done) => {
});
it('ensures proper response for incorrect auth details', (done) => {
});
it('ensures proper response for successful user sign up', (done) => {
});
it('ensures proper response for sign up with incorrect data', (done) => {
});
});
describe('Group CRUD operation routes', () => {
it('ensure proper response when group is created successfully', (done) => {
});
it('ensures proper response when messages are posted successfully', (done) => {
});
it('ensures all messages for a particular group can be read successfully', (done) => {
});
it('ensures all members of a particular group can be read successfully', (done) => {
});
});
});
| import supertest from 'supertest';
import app from '../index';
const request = supertest(app);
describe('PostIt Tests', () => {
describe('Authentication routes test', () => {
it('ensures proper response for successful user sign in', () => {
});
it('ensures proper response for incorrect auth details', () => {
});
it('ensures proper response for successful user sign up', () => {
});
it('ensures proper response for sign up with incorrect data', () => {
});
});
describe('Group CRUD operation routes', () => {
it('ensure proper response when group is created successfully', () => {
});
it('ensures proper response when messages are posted successfully', () => {
});
it('ensures all messages for a particular group can be read successfully', () => {
});
it('ensures all members of a particular group can be read successfully', () => {
});
});
});
|
Remove image name dependency on object ID | import os
import uuid
from django.db import models
# ------------------------------------------------------------------------------
# General utilities
# ------------------------------------------------------------------------------
def image_filename(instance, filename):
""" Make image filenames
"""
return 'images/%s_%s' % (uuid.uuid4(), os.path.basename(filename))
# ------------------------------------------------------------------------------
# Models
# ------------------------------------------------------------------------------
class Partner(models.Model):
short_name = models.CharField(max_length=200)
full_name = models.CharField(max_length=200)
physical_address = models.CharField(max_length=200)
contact_person = models.CharField(max_length=200)
telephone = models.CharField(max_length=200)
email_address = models.EmailField(max_length=200)
intro_title = models.CharField(max_length=200)
intro_statement = models.TextField(max_length=200)
intro_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
context_quote = models.CharField(max_length=200)
context_statement = models.TextField(max_length=200)
context_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
| import os
from django.db import models
# ------------------------------------------------------------------------------
# General utilities
# ------------------------------------------------------------------------------
def image_filename(instance, filename):
""" Make S3 image filenames
"""
return 'images/%s/%s' % (instance.id, os.path.basename(filename))
# ------------------------------------------------------------------------------
# Models
# ------------------------------------------------------------------------------
class Partner(models.Model):
short_name = models.CharField(max_length=200)
full_name = models.CharField(max_length=200)
physical_address = models.CharField(max_length=200)
contact_person = models.CharField(max_length=200)
telephone = models.CharField(max_length=200)
email_address = models.EmailField(max_length=200)
intro_title = models.CharField(max_length=200)
intro_statement = models.TextField(max_length=200)
intro_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
context_quote = models.CharField(max_length=200)
context_statement = models.TextField(max_length=200)
context_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
|
Update SQL for efficiency and semicolons. | from __future__ import unicode_literals, print_function
import sqlite3, os, random
_select = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_uncommon_select = 'select value from uncommons where key=?;'
def generate_name():
conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
cursor = conn.cursor()
adj = cursor.execute(_select.format('adjective', 'adjectives')).fetchone()[0]
anim = cursor.execute(_select.format('animal', 'animals')).fetchone()[0]
rare = cursor.execute(_select.format('name', 'rares')).fetchone()[0]
uncommon_anim = cursor.execute(_uncommon_select, [adj]).fetchone()
uncommon_adj = cursor.execute(_uncommon_select, [anim]).fetchone()
conn.close()
r = random.random()
if r < 0.001 or r >= 0.999:
return rare
elif r < 0.3 and uncommon_anim is not None:
return ' '.join((adj, uncommon_anim[0]))
elif r >= 0.7 and uncommon_adj is not None:
return ' '.join((uncommon_adj[0], anim))
return ' '.join((adj, anim))
if __name__ == '__main__':
print(generate_name())
| from __future__ import unicode_literals, print_function
import sqlite3, os, random
_select = 'select {} from {} order by random() limit 1'
_uncommon_select = 'select value from uncommons where key=?'
def generate_name():
conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
cursor = conn.cursor()
adj = cursor.execute(_select.format('adjective', 'adjectives')).fetchone()[0]
anim = cursor.execute(_select.format('animal', 'animals')).fetchone()[0]
rare = cursor.execute(_select.format('name', 'rares')).fetchone()[0]
uncommon_anim = cursor.execute(_uncommon_select, [adj]).fetchone()
uncommon_adj = cursor.execute(_uncommon_select, [anim]).fetchone()
conn.close()
r = random.random()
if r < 0.001 or r >= 0.999:
return rare
elif r < 0.3 and uncommon_anim is not None:
return ' '.join((adj, uncommon_anim[0]))
elif r >= 0.7 and uncommon_adj is not None:
return ' '.join((uncommon_adj[0], anim))
return ' '.join((adj, anim))
if __name__ == '__main__':
print(generate_name())
|
Update IndexFile model to have 'index' column instead of 'reference' | import enum
from sqlalchemy import Column, Integer, String, Enum
from virtool.pg.utils import Base, SQLEnum
class IndexType(str, SQLEnum):
"""
Enumerated type for index file types
"""
json = "json"
fasta = "fasta"
bowtie2 = "bowtie2"
class IndexFile(Base):
"""
SQL model to store new index files
"""
__tablename__ = "index_files"
id = Column(Integer, primary_key=True)
name = Column(String)
index = Column(String)
type = Column(Enum(IndexType))
size = Column(Integer)
def __repr__(self):
return f"<IndexFile(id={self.id}, name={self.name}, index={self.index}, type={self.type}, " \
f"size={self.size} "
| import enum
from sqlalchemy import Column, Integer, String, Enum
from virtool.pg.utils import Base, SQLEnum
class IndexType(str, SQLEnum):
"""
Enumerated type for index file types
"""
json = "json"
fasta = "fasta"
bowtie2 = "bowtie2"
class IndexFile(Base):
"""
SQL model to store new index files
"""
__tablename__ = "index_files"
id = Column(Integer, primary_key=True)
name = Column(String)
reference = Column(String)
type = Column(Enum(IndexType))
size = Column(Integer)
def __repr__(self):
return f"<IndexFile(id={self.id}, name={self.name}, reference={self.reference}, type={self.type}, " \
f"size={self.size} "
|
Fix /help - part 2 | package com.ForgeEssentials.permission.mcoverride;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
// Hopefully we can transform the stuff in and we won't need this class.
public class OverrideManager
{
public static void regOverrides(FMLServerStartingEvent e)
{
e.registerServerCommand(new CommandBanIp());
e.registerServerCommand(new CommandBanlist());
e.registerServerCommand(new CommandDebug());
e.registerServerCommand(new CommandDefaultGameMode());
e.registerServerCommand(new CommandDeop());
e.registerServerCommand(new CommandDifficulty());
e.registerServerCommand(new CommandGameRule());
e.registerServerCommand(new CommandKick());
e.registerServerCommand(new CommandMe());
e.registerServerCommand(new CommandOp());
e.registerServerCommand(new CommandPardonIp());
e.registerServerCommand(new CommandPublish());
e.registerServerCommand(new CommandSaveAll());
e.registerServerCommand(new CommandSaveOff());
e.registerServerCommand(new CommandSaveOn());
e.registerServerCommand(new CommandSay());
e.registerServerCommand(new CommandSeed());
e.registerServerCommand(new CommandSetSpawn());
e.registerServerCommand(new CommandStop());
e.registerServerCommand(new CommandToggleDownfall());
e.registerServerCommand(new CommandXP());
e.registerServerCommand(new CommandTestFor());
}
}
| package com.ForgeEssentials.permission.mcoverride;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
// Hopefully we can transform the stuff in and we won't need this class.
public class OverrideManager
{
public static void regOverrides(FMLServerStartingEvent e)
{
e.registerServerCommand(new CommandBanIp());
e.registerServerCommand(new CommandBanlist());
e.registerServerCommand(new CommandDebug());
e.registerServerCommand(new CommandDefaultGameMode());
e.registerServerCommand(new CommandDeop());
e.registerServerCommand(new CommandDifficulty());
e.registerServerCommand(new CommandGameRule());
e.registerServerCommand(new CommandHelp());
e.registerServerCommand(new CommandKick());
e.registerServerCommand(new CommandMe());
e.registerServerCommand(new CommandOp());
e.registerServerCommand(new CommandPardonIp());
e.registerServerCommand(new CommandPublish());
e.registerServerCommand(new CommandSaveAll());
e.registerServerCommand(new CommandSaveOff());
e.registerServerCommand(new CommandSaveOn());
e.registerServerCommand(new CommandSay());
e.registerServerCommand(new CommandSeed());
e.registerServerCommand(new CommandSetSpawn());
e.registerServerCommand(new CommandStop());
e.registerServerCommand(new CommandToggleDownfall());
e.registerServerCommand(new CommandXP());
e.registerServerCommand(new CommandTestFor());
}
}
|
Use correct field to get org from | from __future__ import unicode_literals
from datetime import datetime
from django.utils import timezone
from djcelery_transactions import task
from redis_cache import get_redis_connection
from .models import Campaign, EventFire
from django.conf import settings
import redis
from temba.msgs.models import HANDLER_QUEUE, HANDLE_EVENT_TASK, FIRE_EVENT
from temba.utils.queues import push_task
@task(track_started=True, name='check_campaigns_task') # pragma: no cover
def check_campaigns_task(sched_id=None):
"""
See if any event fires need to be triggered
"""
logger = check_campaigns_task.get_logger()
# get a lock
r = get_redis_connection()
key = 'check_campaigns'
# only do this if we aren't already checking campaigns
if not r.get(key):
with r.lock(key, timeout=3600):
# for each that needs to be fired
for fire in EventFire.objects.filter(fired=None, scheduled__lte=timezone.now()).select_related('contact', 'contact.org'):
try:
push_task(fire.contact.org, HANDLER_QUEUE, HANDLE_EVENT_TASK, dict(type=FIRE_EVENT, id=fire.id))
except: # pragma: no cover
logger.error("Error running campaign event: %s" % fire.pk, exc_info=True)
| from __future__ import unicode_literals
from datetime import datetime
from django.utils import timezone
from djcelery_transactions import task
from redis_cache import get_redis_connection
from .models import Campaign, EventFire
from django.conf import settings
import redis
from temba.msgs.models import HANDLER_QUEUE, HANDLE_EVENT_TASK, FIRE_EVENT
from temba.utils.queues import push_task
@task(track_started=True, name='check_campaigns_task') # pragma: no cover
def check_campaigns_task(sched_id=None):
"""
See if any event fires need to be triggered
"""
logger = check_campaigns_task.get_logger()
# get a lock
r = get_redis_connection()
key = 'check_campaigns'
# only do this if we aren't already checking campaigns
if not r.get(key):
with r.lock(key, timeout=3600):
# for each that needs to be fired
for fire in EventFire.objects.filter(fired=None, scheduled__lte=timezone.now()).select_related('event', 'event.org'):
try:
push_task(fire.event.org, HANDLER_QUEUE, HANDLE_EVENT_TASK, dict(type=FIRE_EVENT, id=fire.id))
except: # pragma: no cover
logger.error("Error running campaign event: %s" % fire.pk, exc_info=True)
|
Remove "<hr>" elements from homepage | import React from 'react'
import Page from '../../components/page'
import Header from './header'
import PreviousEpisodeSection from './sections/previous-episodes'
import EpisodesSection from './sections/episodes'
import PanelistsSection from './sections/panelists'
import SponsorsSection from '../../components/sponsors'
import LinksSection from './sections/links'
import SocialIconGroupSection from './sections/social-icon-group'
import FeatureShowScript from './scripts/feature-show'
export default Home
function Home(
{
futureEpisodes = [],
pastEpisodes = [],
sponsors,
panelists,
}
) {
return (
<Page>
<Header />
<EpisodesSection episodes={futureEpisodes} />
<PanelistsSection panelists={panelists} />
<div className="container">
<SponsorsSection {...sponsors} />
<PreviousEpisodeSection episodes={pastEpisodes} />
{pastEpisodes.length ? <hr /> : ''}
<SocialIconGroupSection />
<LinksSection />
<FeatureShowScript />
</div>
</Page>
)
}
| import React from 'react'
import Page from '../../components/page'
import Header from './header'
import PreviousEpisodeSection from './sections/previous-episodes'
import EpisodesSection from './sections/episodes'
import PanelistsSection from './sections/panelists'
import SponsorsSection from '../../components/sponsors'
import LinksSection from './sections/links'
import SocialIconGroupSection from './sections/social-icon-group'
import FeatureShowScript from './scripts/feature-show'
export default Home
function Home(
{
futureEpisodes = [],
pastEpisodes = [],
sponsors,
panelists,
}
) {
return (
<Page>
<Header />
<EpisodesSection episodes={futureEpisodes} />
<PanelistsSection panelists={panelists} />
<div className="container">
{futureEpisodes.length ? <hr /> : ''}
<SponsorsSection {...sponsors} />
<hr />
<PreviousEpisodeSection episodes={pastEpisodes} />
{pastEpisodes.length ? <hr /> : ''}
<hr />
<hr />
<SocialIconGroupSection />
<hr />
<LinksSection />
<FeatureShowScript />
</div>
</Page>
)
}
|
Update to use <span> instead of <input> for non-modifiable text.
--HG--
extra : convert_revision : svn%3A465e5836-af34-0410-8d6e-35500593c4db/trunk%40153 |
<!-- Sleep so users see the activity indicator -->
<?php sleep(2); ?>
<ul id="stats" title="Stats">
<li><a href="#usage">Usage</a></li>
<li><a href="#battery">Battery</a></li>
</ul>
<div id="usage" title="Usage" class="panel">
<h2>Play Time</h2>
<fieldset>
<div class="row">
<label>Years</label>
<span>2</span>
</div>
<div class="row">
<label>Months</label>
<span>8</span>
</div>
<div class="row">
<label>Days</label>
<span>27</span>
</div>
</fieldset>
</div>
<div id="battery" title="Battery" class="panel">
<h2>Better recharge soon!</h2>
</div>
|
<!-- Sleep so users see the activity indicator -->
<?php sleep(2); ?>
<ul id="stats" title="Stats">
<li><a href="#usage">Usage</a></li>
<li><a href="#battery">Battery</a></li>
</ul>
<div id="usage" title="Usage" class="panel">
<h2>Play Time</h2>
<fieldset>
<div class="row">
<label>Years</label>
<input type="text" value="2"/>
</div>
<div class="row">
<label>Months</label>
<input type="text" value="8"/>
</div>
<div class="row">
<label>Days</label>
<input type="text" value="27"/>
</div>
</fieldset>
</div>
<div id="battery" title="Battery" class="panel">
<h2>Better recharge soon!</h2>
</div>
|
Simplify default database setting, but allow it to be overridden | from os import getenv
class Config(object):
API_KEY = getenv('API_KEY')
DAEMON_SLEEP_INTERVAL = 6 # hours
MAIL_DEBUG = False
MAIL_DEFAULT_SENDER = getenv('SENDER_EMAIL', 'dynamite@example.com')
MAIL_PASSWORD = getenv('MAILGUN_SMTP_PASSWORD', None)
MAIL_PORT = getenv('MAILGUN_SMTP_PORT', 25)
MAIL_SERVER = getenv('MAILGUN_SMTP_SERVER', 'localhost')
MAIL_USERNAME = getenv('MAILGUN_SMTP_LOGIN', None)
MAIL_USE_SSL = False
NOTIFY_EMAIL = getenv('NOTIFY_EMAIL', 'dynamite@example.com')
SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL', 'sqlite:///app.db').replace('mysql2:', 'mysql:')
class ProductionConfig(Config):
DEBUG = False
TESTING = False
class DevelopmentConfig(Config):
DEBUG = True
MAIL_DEBUG = True
class TestingConfig(Config):
TESTING = True
| from os import getenv
class Config(object):
API_KEY = getenv('API_KEY')
DAEMON_SLEEP_INTERVAL = 6 # hours
MAIL_DEBUG = False
MAIL_DEFAULT_SENDER = getenv('SENDER_EMAIL', 'dynamite@example.com')
MAIL_PASSWORD = getenv('MAILGUN_SMTP_PASSWORD', None)
MAIL_PORT = getenv('MAILGUN_SMTP_PORT', 25)
MAIL_SERVER = getenv('MAILGUN_SMTP_SERVER', 'localhost')
MAIL_USERNAME = getenv('MAILGUN_SMTP_LOGIN', None)
MAIL_USE_SSL = False
NOTIFY_EMAIL = getenv('NOTIFY_EMAIL', 'dynamite@example.com')
SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL').replace('mysql2:', 'mysql:')
class ProductionConfig(Config):
DEBUG = False
TESTING = False
class DevelopmentConfig(Config):
DEBUG = True
MAIL_DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db'
class TestingConfig(Config):
TESTING = True
|
Remove global stream memoization to fix more tests
Memoizing into a local variable doesn't work well the tests since
the tests mutate the value of the global. In theory we could
define a test helper to work around this, but it doesn't seem
like its worth the effort since this path is deprecated and
has a simple upgrade path. | /**
@module ember
@submodule ember-htmlbars
*/
import Ember from "ember-metal/core";
import { isGlobal } from "ember-metal/path_cache";
import SimpleStream from "ember-metal/streams/simple-stream";
export default function getRoot(scope, key) {
if (key === 'this') {
return [scope.self];
} else if (isGlobal(key) && Ember.lookup[key]) {
return [getGlobal(key)];
} else if (scope.locals[key]) {
return [scope.locals[key]];
} else {
return [getKey(scope, key)];
}
}
function getKey(scope, key) {
if (key === 'attrs' && scope.attrs) {
return scope.attrs;
}
var self = scope.self || scope.locals.view;
if (scope.attrs && key in scope.attrs) {
Ember.deprecate("You accessed the `" + key + "` attribute directly. Please use `attrs." + key + "` instead.");
return scope.attrs[key];
} else if (self) {
return self.getKey(key);
}
}
function getGlobal(name) {
Ember.deprecate("Global lookup of " + name + " from a Handlebars template is deprecated")
// This stream should be memoized, but this path is deprecated and
// will be removed soon so it's not worth the trouble.
return new SimpleStream(Ember.lookup[name], name);
}
| /**
@module ember
@submodule ember-htmlbars
*/
import Ember from "ember-metal/core";
import { isGlobal } from "ember-metal/path_cache";
import SimpleStream from "ember-metal/streams/simple-stream";
export default function getRoot(scope, key) {
if (key === 'this') {
return [scope.self];
} else if (isGlobal(key) && Ember.lookup[key]) {
return [getGlobal(key)];
} else if (scope.locals[key]) {
return [scope.locals[key]];
} else {
return [getKey(scope, key)];
}
}
function getKey(scope, key) {
if (key === 'attrs' && scope.attrs) {
return scope.attrs;
}
var self = scope.self || scope.locals.view;
if (scope.attrs && key in scope.attrs) {
Ember.deprecate("You accessed the `" + key + "` attribute directly. Please use `attrs." + key + "` instead.");
return scope.attrs[key];
} else if (self) {
return self.getKey(key);
}
}
var globalStreams = {};
function getGlobal(name) {
Ember.deprecate("Global lookup of " + name + " from a Handlebars template is deprecated")
var globalStream = globalStreams[name];
if (globalStream === undefined) {
var global = Ember.lookup[name];
globalStream = new SimpleStream(global, name);
globalStreams[name] = globalStream;
}
return globalStream;
}
|
Update helper link when libraries are not found | // debugger;
;(function(Agent){
debug.log("Backbone agent is starting...");
console.log('Marionette Inspector: window.__agent = ', this);
Agent.sendAppComponentReport('start');
Agent.patchDefine(
Agent.patchBackbone,
Agent.patchMarionette
);
Agent.patchWindow(
Agent.patchBackbone,
Agent.patchMarionette
);
/* start is a manual way to start the agent if
* Backbone and Marionette are not set on the window or
* you're not using `define` to package your modules.
*/
Agent.start = function(Backbone, Marionette) {
Agent.patchBackbone(Backbone);
Agent.patchMarionette(Backbone, Marionette);
};
Agent.disableAnalytics = false;
Agent.startAnalytics();
Agent.lazyWorker = new Agent.LazyWorker();
setInterval(Agent.observeChanges, 500);
}(Agent));
window.setTimeout(function() {
if(window.__agent && window.__agent.patchedBackbone) {
return;
}
console.warn("Marionette Inspector: Hmmm... couldn't find yo Backbone");
console.log("Please peruse https://github.com/marionettejs/marionette.inspector#setup");
}, 5000);
| // debugger;
;(function(Agent){
debug.log("Backbone agent is starting...");
console.log('Marionette Inspector: window.__agent = ', this);
Agent.sendAppComponentReport('start');
Agent.patchDefine(
Agent.patchBackbone,
Agent.patchMarionette
);
Agent.patchWindow(
Agent.patchBackbone,
Agent.patchMarionette
);
/* start is a manual way to start the agent if
* Backbone and Marionette are not set on the window or
* you're not using `define` to package your modules.
*/
Agent.start = function(Backbone, Marionette) {
Agent.patchBackbone(Backbone);
Agent.patchMarionette(Backbone, Marionette);
};
Agent.disableAnalytics = false;
Agent.startAnalytics();
Agent.lazyWorker = new Agent.LazyWorker();
setInterval(Agent.observeChanges, 500);
}(Agent));
window.setTimeout(function() {
if(window.__agent && window.__agent.patchedBackbone) {
return;
}
console.warn("Marionette Inspector: Hmmm... couldn't find yo Backbone");
console.log("Please peruse https://github.com/marionettejs/marionette.inspector#caveats");
}, 5000);
|
Use setImmediate() to kick aggregate off. | /**
Provide mdb-aggregate, a MongoDB style aggregation pipeline, to NodeJS.
Copyright (C) 2014 Charles J. Ezell III
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
var _aggregate = require('bindings')('mdb-conduit.node');
function _aggregate_bare(docSrcs, documents, callback) {
setImmediate(_aggregate.aggregate(docSrcs, documents, callback));
}
function aggregate(docSrcs, documents, callback) {
//TODO: get rid of the JSON.parse() here. The implementation should be
//returning us native V8 objects or bson.
_aggregate_bare(docSrcs, documents, function fixupResults(err, results) {
if(err) return callback(err);
results = JSON.parse(results);
return callback(null, results.result);
});
}
module.exports = {
aggregate: aggregate,
_aggregate_bare: _aggregate_bare
};
| /**
Provide mdb-aggregate, a MongoDB style aggregation pipeline, to NodeJS.
Copyright (C) 2014 Charles J. Ezell III
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
var _aggregate = require('bindings')('mdb-conduit.node');
function _aggregate_bare(docSrcs, documents, callback) {
return _aggregate.aggregate(docSrcs, documents, callback);
}
function aggregate(docSrcs, documents, callback) {
//TODO: get rid of the JSON.parse() here. The implementation should be
//returning us native V8 objects or bson.
_aggregate_bare(docSrcs, documents, function fixupResults(err, results) {
if(err) return callback(err);
results = JSON.parse(results);
return callback(null, results.result);
});
}
module.exports = {
aggregate: aggregate,
_aggregate_bare: _aggregate_bare
};
|
Disable revision support for field collection items temporarily. | <?php
namespace AbleCore\Fields\FieldHandlerTypes;
use AbleCore\Fields\FieldValueHandler;
use AbleCore\Fields\FieldValueTypes\EntityReferenceFieldValue;
class EntityReference extends FieldValueHandler
{
public static $configuration = array(
'entityreference' => 'reference',
'node_reference' => 'nodeReference',
'field_collection' => 'fieldCollection',
);
public static function reference($type, $value, $name)
{
if (!self::checkFieldValue($value, 'target_id'))
return null;
$info = field_info_field($name);
if (!isset($info['settings']['target_type'])) {
trigger_error('Target type couldnt be found.', E_USER_WARNING);
return null;
}
$target_type = $info['settings']['target_type'];
return new EntityReferenceFieldValue($type, $value, $target_type);
}
public static function nodeReference($type, $value, $name)
{
if (!self::checkFieldValue($value, 'nid'))
return null;
return new EntityReferenceFieldValue($type, $value, 'node', 'nid');
}
public static function fieldCollection($type, $value, $name)
{
if (!self::checkFieldValue($value, 'value'))
return null;
// TODO: Enable revision support for this when https://www.drupal.org/node/2075325 is fixed.
return new EntityReferenceFieldValue($type, $value, 'field_collection_item', 'value');
}
}
| <?php
namespace AbleCore\Fields\FieldHandlerTypes;
use AbleCore\Fields\FieldValueHandler;
use AbleCore\Fields\FieldValueTypes\EntityReferenceFieldValue;
class EntityReference extends FieldValueHandler
{
public static $configuration = array(
'entityreference' => 'reference',
'node_reference' => 'nodeReference',
'field_collection' => 'fieldCollection',
);
public static function reference($type, $value, $name)
{
if (!self::checkFieldValue($value, 'target_id'))
return null;
$info = field_info_field($name);
if (!isset($info['settings']['target_type'])) {
trigger_error('Target type couldnt be found.', E_USER_WARNING);
return null;
}
$target_type = $info['settings']['target_type'];
return new EntityReferenceFieldValue($type, $value, $target_type);
}
public static function nodeReference($type, $value, $name)
{
if (!self::checkFieldValue($value, 'nid'))
return null;
return new EntityReferenceFieldValue($type, $value, 'node', 'nid');
}
public static function fieldCollection($type, $value, $name)
{
if (!self::checkFieldValue($value, 'value'))
return null;
return new EntityReferenceFieldValue($type, $value, 'field_collection_item', 'value', 'revision_id');
}
}
|
Add history subdirectory to the package | __author__ = 'karec'
import os
from setuptools import setup
from octbrowser import __version__
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
with open('README.rst') as f:
long_description = f.read()
setup(
name='octbrowser',
version=__version__,
author='Emmanuel Valette',
author_email='manu.valette@gmail.com',
packages=['octbrowser', 'octbrowser.history'],
description="A web scrapper based on lxml library.",
long_description=long_description,
url='https://github.com/karec/oct-browser',
download_url='https://github.com/karec/oct-browser/archive/master.zip',
keywords=['testing', 'mechanize', 'webscrapper', 'browser', 'web', 'lxml', 'html'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4'
],
install_requires=[
'argparse',
'requests',
'lxml',
'cssselect',
'tinycss',
'six'
]
)
| __author__ = 'karec'
import os
from setuptools import setup
from octbrowser import __version__
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
with open('README.rst') as f:
long_description = f.read()
setup(
name='octbrowser',
version=__version__,
author='Emmanuel Valette',
author_email='manu.valette@gmail.com',
packages=['octbrowser'],
description="A web scrapper based on lxml library.",
long_description=long_description,
url='https://github.com/karec/oct-browser',
download_url='https://github.com/karec/oct-browser/archive/master.zip',
keywords=['testing', 'mechanize', 'webscrapper', 'browser', 'web', 'lxml', 'html'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4'
],
install_requires=[
'argparse',
'requests',
'lxml',
'cssselect',
'tinycss',
'six'
]
)
|
Use sequence number instead of timestamp to avoid cache | var Pinger = {
seq: 0
};
// http://stackoverflow.com/a/573784
Pinger.getPing = function(target, callback) {
var start;
var client = Pinger.getClient(); // xmlhttprequest object
client.onreadystatechange = function() {
if (client.readyState >= 2) { // request received
lag_ms = Pinger.pingDone(start); //handle ping
client.onreadystatechange = null; //remove handler
callback(lag_ms);
}
}
Pinger.seq += 1;
start = new Date();
client.open("HEAD", target + "?" + Pinger.seq);
client.send();
}
Pinger.pingDone = function(start) {
done = new Date();
return done.valueOf() - start.valueOf();
}
Pinger.getClient = function() {
if (window.XMLHttpRequest)
return new XMLHttpRequest();
if (window.ActiveXObject)
return new ActiveXObject('MSXML2.XMLHTTP.3.0');
throw("No XMLHttpRequest Object Available.");
}
| var Pinger = {
};
// http://stackoverflow.com/a/573784
Pinger.getPing = function(target, callback) {
var start;
var client = Pinger.getClient(); // xmlhttprequest object
client.onreadystatechange = function() {
if (client.readyState >= 2) { // request received
lag_ms = Pinger.pingDone(start); //handle ping
client.onreadystatechange = null; //remove handler
callback(lag_ms);
}
}
start = new Date();
client.open("HEAD", target + "?" + start.valueOf());
client.send();
}
Pinger.pingDone = function(start) {
done = new Date();
return done.valueOf() - start.valueOf();
}
Pinger.getClient = function() {
if (window.XMLHttpRequest)
return new XMLHttpRequest();
if (window.ActiveXObject)
return new ActiveXObject('MSXML2.XMLHTTP.3.0');
throw("No XMLHttpRequest Object Available.");
}
|
Use the correct js comparator
Signed-off-by: Kenneth Myhra <0b608bd85f046792b19ad6fef49a3bfa8a0828b9@gmail.com> | $(document).ready(function ()
{
// initialize progress bar
var progress = 0;
$("#pbar").css("width", progress + "%").attr('aria-valuenow', progress);
// initialize the connection to the server
var progressNotifier = $.connection.initializerHub;
// client-side sendMessage function that will be called from the server-side
progressNotifier.client.sendMessage =
function (message)
{
UpdateProgress(message);
};
// establish the connection to the server and start server-side operation
$.connection.hub.start().done(
function ()
{
progressNotifier.server.loadData();
});
});
function UpdateProgress(message)
{
var output = $("#resultmessage");
n = parseInt(message.Progress);
output.html("Status: <b>" + n + "%</b> " + message.Message);
//var percetage = $("#percentage");
//percetage.html(message.Progress + "%");
$("#pbar").css("width", n + "%").attr('aria-valuenow', n);
if (n === 100)
{
$("#pbar").removeClass("progress-bar-striped");
}
} | $(document).ready(function ()
{
// initialize progress bar
var progress = 0;
$("#pbar").css("width", progress + "%").attr('aria-valuenow', progress);
// initialize the connection to the server
var progressNotifier = $.connection.initializerHub;
// client-side sendMessage function that will be called from the server-side
progressNotifier.client.sendMessage =
function (message)
{
UpdateProgress(message);
};
// establish the connection to the server and start server-side operation
$.connection.hub.start().done(
function ()
{
progressNotifier.server.loadData();
});
});
function UpdateProgress(message)
{
var output = $("#resultmessage");
n = parseInt(message.Progress);
output.html("Status: <b>" + n + "%</b> " + message.Message);
//var percetage = $("#percentage");
//percetage.html(message.Progress + "%");
$("#pbar").css("width", n + "%").attr('aria-valuenow', n);
if (n == 100)
{
$("#pbar").removeClass("progress-bar-striped");
}
} |
Apply modification from Feb 5 | import hashlib
import models
import os
import os.path
def init():
models.db.connect()
models.db.create_tables([models.Entry])
def digest(file_path):
h = hashlib.sha1()
file = open(file_path, 'rb')
buf = file.read(8192)
while len(buf) > 0:
h.update(buf)
buf = file.read(8192)
return h.hexdigest()
def traverse(path):
path = os.path.abspath(path)
for (dir_path, dirs, files) in os.walk(path):
buf = []
for file_name in sorted(files):
file_path = os.path.join(dir_path, file_name)
entry = {
'path': file_path,
'size': os.path.getsize(file_path),
'last_modified': os.path.getmtime(file_path),
'hash_str': digest(file_path)
}
buf.append(entry)
if len(buf) >= 256:
print('Writing chunks until', file_name)
models.Entry.insert_many(buf).execute()
buf.clear()
| import hashlib
import models
import os
import os.path
def init():
models.db.connect()
models.db.create_tables([models.Entry])
def digest(file_path):
h = hashlib.sha1()
file = open(file_path, 'rb')
buf = file.read(8192)
while len(buf) > 0:
h.update(buf)
buf = file.read(8192)
return h.hexdigest()
def traverse(path):
path = os.path.abspath(path)
for (dir_path, dirs, files) in os.walk(path):
for file_name in files:
file_path = os.path.join(dir_path, file_name)
entry = models.Entry(path=file_path)
entry.size = os.path.getsize(file_path)
entry.last_modified = os.path.getmtime(file_path)
entry.hash_str = digest(file_path)
entry.save()
|
Validate if user has already sigin | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import ReduxThunk from 'redux-thunk';
// Actions
import { authUser, setUserData } from './actions/auth-actions';
// Routes
import Routes from './routes/';
// Reducers
import RootReducers from './reducers/';
// APIs
import AuthAPI from './utils/api/auth-api';
// utils
import { verifyToken, getSession } from './utils/api/header-config';
// configure Redux extension
const componseEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
// default store
// const storeWithMiddlewares = applyMiddleware(
// ReduxThunk
// )(createStore);
// export const store = storeWithMiddlewares(RootReducers);
export const store = createStore(RootReducers, {}, componseEnhancers(
applyMiddleware(ReduxThunk.withExtraArgument({ AuthAPI }))
));
// validate session
const session = getSession();
if (session && verifyToken()) {
store.dispatch(authUser());
store.dispatch(setUserData(session));
}
// for debuggin
// window.store = store;
document.addEventListener('DOMContentLoaded', () => {
ReactDOM.render(
<Provider store={store}>
{ Routes }
</Provider>
, document.getElementById('app')
);
}); | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import ReduxThunk from 'redux-thunk';
// Routes
import Routes from './routes/';
// Reducers
import RootReducers from './reducers/';
// configure Redux extension
const componseEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_CHROME__ || compose;
// default store
// const storeWithMiddlewares = applyMiddleware(
// ReduxThunk
// )(createStore);
// export const store = storeWithMiddlewares(RootReducers);
export const store = createStore(RootReducers, {}, componseEnhancers(
applyMiddleware(ReduxThunk)
));
// for debuggin
// window.store = store;
document.addEventListener('DOMContentLoaded', () => {
ReactDOM.render(
<Provider store={store}>
{ Routes }
</Provider>
, document.getElementById('app')
);
}); |
Create chaptersync table for new databases | package eu.kanade.mangafeed.data.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;
import eu.kanade.mangafeed.data.database.tables.ChapterSyncTable;
import eu.kanade.mangafeed.data.database.tables.ChapterTable;
import eu.kanade.mangafeed.data.database.tables.MangaTable;
public class DbOpenHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "mangafeed.db";
public static final int DATABASE_VERSION = 2;
public DbOpenHelper(@NonNull Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(@NonNull SQLiteDatabase db) {
db.execSQL(MangaTable.getCreateTableQuery());
db.execSQL(ChapterTable.getCreateTableQuery());
db.execSQL(ChapterSyncTable.getCreateTableQuery());
}
@Override
public void onUpgrade(@NonNull SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1)
db.execSQL(ChapterSyncTable.getCreateTableQuery());
}
@Override
public void onConfigure(SQLiteDatabase db){
db.setForeignKeyConstraintsEnabled(true);
}
} | package eu.kanade.mangafeed.data.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;
import eu.kanade.mangafeed.data.database.tables.ChapterSyncTable;
import eu.kanade.mangafeed.data.database.tables.ChapterTable;
import eu.kanade.mangafeed.data.database.tables.MangaTable;
public class DbOpenHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "mangafeed.db";
public static final int DATABASE_VERSION = 2;
public DbOpenHelper(@NonNull Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(@NonNull SQLiteDatabase db) {
db.execSQL(MangaTable.getCreateTableQuery());
db.execSQL(ChapterTable.getCreateTableQuery());
}
@Override
public void onUpgrade(@NonNull SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1)
db.execSQL(ChapterSyncTable.getCreateTableQuery());
}
@Override
public void onConfigure(SQLiteDatabase db){
db.setForeignKeyConstraintsEnabled(true);
}
} |
Add ssa2, zp to baseline | # vim: sw=4 ts=4 sts expandtab smarttab
# HXN step-scan configuration
import hxntools.scans
from bluesky.global_state import get_gs
gs = get_gs()
hxntools.scans.setup()
ct = hxntools.scans.count
ascan = hxntools.scans.absolute_scan
dscan = hxntools.scans.relative_scan
fermat = hxntools.scans.relative_fermat
spiral = hxntools.scans.relative_spiral
mesh = hxntools.scans.absolute_mesh
dmesh = hxntools.scans.relative_mesh
d2scan = hxntools.scans.d2scan
a2scan = hxntools.scans.a2scan
gs.DETS = [zebra, sclr1, merlin1, xspress3, lakeshore2]
gs.TABLE_COLS = ['sclr1_ch2','sclr1_ch3', 'sclr1_ch4', 'sclr1_ch5_calc', 'ssx', 'ssy', 'ssz',
't_base', 't_sample', 't_vlens', 't_hlens']
# Plot this by default versus motor position:
gs.PLOT_Y = 'Det2_Cr'
gs.OVERPLOT = False
gs.BASELINE_DEVICES = [smll,vmll, hmll, ssa2, zp]
| # vim: sw=4 ts=4 sts expandtab smarttab
# HXN step-scan configuration
import hxntools.scans
from bluesky.global_state import get_gs
gs = get_gs()
hxntools.scans.setup()
ct = hxntools.scans.count
ascan = hxntools.scans.absolute_scan
dscan = hxntools.scans.relative_scan
fermat = hxntools.scans.relative_fermat
spiral = hxntools.scans.relative_spiral
mesh = hxntools.scans.absolute_mesh
dmesh = hxntools.scans.relative_mesh
d2scan = hxntools.scans.d2scan
a2scan = hxntools.scans.a2scan
gs.DETS = [zebra, sclr1, merlin1, xspress3, lakeshore2]
gs.TABLE_COLS = ['sclr1_ch2','sclr1_ch3', 'sclr1_ch4', 'sclr1_ch5_calc', 'ssx', 'ssy', 'ssz',
't_base', 't_sample', 't_vlens', 't_hlens']
# Plot this by default versus motor position:
gs.PLOT_Y = 'Det2_Pt'
gs.OVERPLOT = False
gs.BASELINE_DEVICES = [smll,vmll, hmll]
|
Use count() on queryset instead of len()
Ensure a fast query even for millions of rows. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import timedelta
from django.conf import settings
from django.utils import timezone
try:
from django.core.management.base import BaseCommand
except ImportError:
from django.core.management.base import NoArgsCommand as BaseCommand
from hitcount.models import Hit
class Command(BaseCommand):
help = "Can be run as a cronjob or directly to clean out old Hits objects from the database."
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
def handle(self, *args, **kwargs):
self.handle_noargs()
def handle_noargs(self, **options):
grace = getattr(settings, 'HITCOUNT_KEEP_HIT_IN_DATABASE', {'days': 30})
period = timezone.now() - timedelta(**grace)
qs = Hit.objects.filter(created__lt=period)
number_removed = qs.count()
qs.delete()
self.stdout.write('Successfully removed %s Hits' % number_removed)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import timedelta
from django.conf import settings
from django.utils import timezone
try:
from django.core.management.base import BaseCommand
except ImportError:
from django.core.management.base import NoArgsCommand as BaseCommand
from hitcount.models import Hit
class Command(BaseCommand):
help = "Can be run as a cronjob or directly to clean out old Hits objects from the database."
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
def handle(self, *args, **kwargs):
self.handle_noargs()
def handle_noargs(self, **options):
grace = getattr(settings, 'HITCOUNT_KEEP_HIT_IN_DATABASE', {'days': 30})
period = timezone.now() - timedelta(**grace)
qs = Hit.objects.filter(created__lt=period)
number_removed = len(qs)
qs.delete()
self.stdout.write('Successfully removed %s Hits' % number_removed)
|
Remove default format as it is now part of html-validator itself | var es = require('event-stream');
var path = require('path');
var htmlv = require('html-validator');
module.exports = function(options) {
if (!options) options = {};
function modifyContents(file, cb) {
if (file.isNull()) return cb(null, file); // pass along
if (file.isStream()) return cb(new Error('htmlv: Streaming not supported')); // pass error if streaming is not supported
options.data = file.contents.toString('utf8');
htmlv(options, function (err, data) {
if (err) return cb(err);
if (options.format === 'json') {
file.contents = new Buffer(JSON.stringify(data));
} else {
file.contents = new Buffer(String(data));
}
return cb(null, file);
});
}
// Return a stream
return es.map(modifyContents);
};
| var es = require('event-stream');
var path = require('path');
var htmlv = require('html-validator');
module.exports = function(options) {
if (!options) options = {};
if (!options.format) options.format = 'json';
function modifyContents(file, cb) {
if (file.isNull()) return cb(null, file); // pass along
if (file.isStream()) return cb(new Error('htmlv: Streaming not supported')); // pass error if streaming is not supported
options.data = file.contents.toString('utf8');
htmlv(options, function (err, data) {
if (err) return cb(err);
if (options.format === 'json') {
file.contents = new Buffer(JSON.stringify(data));
} else {
file.contents = new Buffer(String(data));
}
return cb(null, file);
});
}
// Return a stream
return es.map(modifyContents);
};
|
Add missing import to test to fix travis | import unittest
import os
import types
import time
from util import EC2
class TestEC2(unittest.TestCase):
def test_metadata(self):
# Skip this step on travis
if os.environ.get('TRAVIS', False): return
# Test gathering metadata from ec2
start = time.time()
d = EC2.get_metadata()
end = time.time()
assert type(d) == types.DictType
# Either we're on ec2 or we're not (at least 7 attributes expected)
assert len(d) == 0 or len(d) >= 7, d
if "instance-id" in d:
assert d["instance-id"].startswith("i-"), d
assert d["hostname"].startswith("i-") or d["hostname"].startswith("domU-"), d
assert end - start <= 1.1, "It took %s seconds to get ec2 metadata" % (end-start)
if __name__ == "__main__":
unittest.main()
| import unittest
import logging
import types
import time
from util import EC2
class TestEC2(unittest.TestCase):
def test_metadata(self):
# Skip this step on travis
if os.environ.get('TRAVIS', False): return
# Test gathering metadata from ec2
start = time.time()
d = EC2.get_metadata()
end = time.time()
assert type(d) == types.DictType
# Either we're on ec2 or we're not (at least 7 attributes expected)
assert len(d) == 0 or len(d) >= 7, d
if "instance-id" in d:
assert d["instance-id"].startswith("i-"), d
assert d["hostname"].startswith("i-") or d["hostname"].startswith("domU-"), d
assert end - start <= 1.1, "It took %s seconds to get ec2 metadata" % (end-start)
if __name__ == "__main__":
unittest.main()
|
Add TODOs to date time request parameter | /*
* Copyright 2015 Open mHealth
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openmhealth.shimmer.common.domain.parameters;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
/**
* @author Chris Schaefbauer
*/
public class DateTimeRequestParameter extends RequestParameter<OffsetDateTime> {
// TODO unix time?
// TODO how do we parse?
private DateTimeFormatter dateTimeFormat;
public DateTimeFormatter getDateTimeFormat() {
return dateTimeFormat;
}
public void setDateTimeFormat(DateTimeFormatter dateTimeFormat) {
this.dateTimeFormat = dateTimeFormat;
}
}
| /*
* Copyright 2015 Open mHealth
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openmhealth.shimmer.common.domain.parameters;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
/**
* @author Chris Schaefbauer
*/
public class DateTimeRequestParameter extends RequestParameter<OffsetDateTime> {
private DateTimeFormatter dateTimeFormat;
public DateTimeFormatter getDateTimeFormat() {
return dateTimeFormat;
}
public void setDateTimeFormat(DateTimeFormatter dateTimeFormat) {
this.dateTimeFormat = dateTimeFormat;
}
}
|
Fix how caller file was identified so that now uses stack knowledge | module.exports = new Wog;
// converts arguments to a string
function _argsToString () {
var argArray = Array.prototype.slice.call(arguments);
return argArray.join(', ');
}
function Wog () {}
// log to server
Wog.prototype.log = function(){
// get call stack
var callStack = new Error().stack;
// find the correct frame using the knowledge it is the first call following module compilation
callStack = callStack.split("Module._compile")[0];
callStack = callStack.split("\n");
var callIndex = callStack.length - 2;
var callFrame = callStack[callIndex];
var callInfoIndex = callFrame.indexOf("(");
var callInfo = callFrame.slice(callInfoIndex+1);
// split the call info by colons
var details = callInfo.split(":");
// first element will be the file
var callerFile = details[0];
// second will be the line number
var lineNum = details[1];
// pass arguments to converter to be treated as same array-like object
var output = _argsToString.apply(this, arguments);
// smart log
console.log(output + " ---logged from " + callerFile + " at line " + lineNum);
}
| module.exports = new Wog;
// converts arguments to a string
function _argsToString () {
var argArray = Array.prototype.slice.call(arguments);
return argArray.join(', ');
}
function Wog () {
}
// log for server
Wog.prototype.log = function(){
// get trace details
var callerFrame = new Error().stack.split("\n")[2];
var callerFile = process.argv[1];
// get exact line number
var lineNumIndex = callerFrame.indexOf(callerFile);
var dirtyLine = callerFrame.slice(lineNumIndex+callerFile.length+1);
var chopIndex = dirtyLine.indexOf(":");
var lineNum = dirtyLine.slice(0, chopIndex);
// pass arguments to converter to be treated as same array-like object
var output = _argsToString.apply(this, arguments);
// smart log
console.log(output + " ---logged from " + callerFile + " at line " + lineNum);
} |
Include php files in root of project in phpcs check. | #!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
passthru('./vendor/bin/phpcs --standard=' . __DIR__ . '/DWS --extensions=php -n tests DWS *.php', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
passthru('./vendor/bin/phpunit --coverage-clover clover.xml tests/DWS', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
$xml = new SimpleXMLElement(file_get_contents('clover.xml'));
foreach ($xml->xpath('//file/metrics') as $metric) {
if ((int)$metric['elements'] !== (int)$metric['coveredelements']) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(0); //TODO: Get code coverage to 100%
}
}
echo "Code coverage was 100%\n";
| #!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
passthru('./vendor/bin/phpcs --standard=' . __DIR__ . '/DWS --extensions=php -n tests DWS', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
passthru('./vendor/bin/phpunit --coverage-clover clover.xml tests/DWS', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
$xml = new SimpleXMLElement(file_get_contents('clover.xml'));
foreach ($xml->xpath('//file/metrics') as $metric) {
if ((int)$metric['elements'] !== (int)$metric['coveredelements']) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(0); //TODO: Get code coverage to 100%
}
}
echo "Code coverage was 100%\n";
|
Use 'input' instead of 'data' | 'use strict';
var gonzales = require('gonzales-pe');
var linters = [
require('./linters/space_before_brace')
];
exports.lint = function (input, path, config) {
var ast = this.parseAST(input);
var errors = [];
ast.map(function (node) {
var i;
for (i = 0; i < linters.length; i++) {
errors.push(linters[i].call(null, {
config: config,
node: node,
path: path
}));
}
});
// Remove empty errors
return errors.filter(function (error) {
return error !== null && error !== true;
});
};
exports.parseAST = function (input) {
return gonzales.parse(input, {
syntax: 'less'
});
};
| 'use strict';
var gonzales = require('gonzales-pe');
var linters = [
require('./linters/space_before_brace')
];
exports.lint = function (data, path, config) {
var ast = this.parseAST(data);
var errors = [];
ast.map(function (node) {
var i;
for (i = 0; i < linters.length; i++) {
errors.push(linters[i].call(null, {
config: config,
node: node,
path: path
}));
}
});
// Remove empty errors
return errors.filter(function (error) {
return error !== null && error !== true;
});
};
exports.parseAST = function (input) {
return gonzales.parse(input, {
syntax: 'less'
});
};
|
Fix Pi-hole docker tag (alpine was deprecated) | package pihole
type Service struct{}
func (s Service) UserData() string {
return `
- name: pihole-etc-host.service
command: start
content: |
[Unit]
Description=pihole /etc/hosts entry
ConditionFirstBoot=true
[Service]
User=root
Type=oneshot
ExecStart=/bin/sh -c "echo 1.1.1.1 pi.hole >> /etc/hosts"
- name: pihole.service
command: start
content: |
[Unit]
Description=pihole
After=docker.service,dummy-interface.service
[Service]
User=core
Restart=always
TimeoutStartSec=0
KillMode=none
EnvironmentFile=/etc/environment
ExecStartPre=-/usr/bin/docker kill pihole
ExecStartPre=-/usr/bin/docker rm pihole
ExecStartPre=/usr/bin/docker pull diginc/pi-hole:latest
ExecStart=/usr/bin/docker run --name pihole --net=host -e ServerIP=1.1.1.1 -e WEBPASSWORD=dosxvpn diginc/pi-hole:latest
ExecStop=/usr/bin/docker stop pihole`
}
| package pihole
type Service struct{}
func (s Service) UserData() string {
return `
- name: pihole-etc-host.service
command: start
content: |
[Unit]
Description=pihole /etc/hosts entry
ConditionFirstBoot=true
[Service]
User=root
Type=oneshot
ExecStart=/bin/sh -c "echo 1.1.1.1 pi.hole >> /etc/hosts"
- name: pihole.service
command: start
content: |
[Unit]
Description=pihole
After=docker.service,dummy-interface.service
[Service]
User=core
Restart=always
TimeoutStartSec=0
KillMode=none
EnvironmentFile=/etc/environment
ExecStartPre=-/usr/bin/docker kill pihole
ExecStartPre=-/usr/bin/docker rm pihole
ExecStartPre=/usr/bin/docker pull diginc/pi-hole:alpine
ExecStart=/usr/bin/docker run --name pihole --net=host -e ServerIP=1.1.1.1 -e WEBPASSWORD=dosxvpn diginc/pi-hole:alpine
ExecStop=/usr/bin/docker stop pihole`
}
|
Index con todas las rutinas | 'use strict'
const express = require ('express')
const api = express.Router()
const UserController = require ('../Controllers/UserController')
const MatchController = require ('../Controllers/MatchController')
const GunsController = require ('../Controllers/GunController')
const DisparoController = require ('../Controllers/DisparoController')
//DEFINED ROUTES TO API METHODS
//rutina de usuarios
api.get('/getUsers', UserController.getUsers)
api.get('/getUser', UserController.getUser)
api.post('/createUser', UserController.createUser)
//rutina de partida
api.get('/getMatchs', MatchController.getMatchs)
api.get('/getMatch', MatchController.getMatch)
api.post('/createMatch', MatchController.createMatch)
//rutina de pistolas
api.get('/getGuns', GunsController.getGuns)
api.get('/getGun', GunsController.getGun)
api.post('/createGun', GunsController.createGun)
//rutina de disparos
api.get('/getDisparo', DisparoController.getDisparo)
api.get('/getOneDisparo', DisparoController.getOneDisparo)
api.post('/createDisparo', DisparoController.createDisparo)
module.exports = api
| 'use strict'
const express = require ('express')
const api = express.Router()
const UserController = require ('../Controllers/UserController')
const MatchController = require ('../Controllers/MatchController')
const GunsController = require ('../Controllers/GunController')
const DisparoController = require ('../Controllers/DisparoController')
//DEFINED ROUTES TO API METHODS
//rutina de usuarios
api.get('/getUsers', UserController.getUsers)
api.get('/getUser', UserController.getUser)
api.post('/createUser', UserController.createUser)
//rutina de partida
api.get('/getMatchs', MatchController.getMatchs)
api.get('/getMatch', MatchController.getMatch)
api.post('/createMatch', MatchController.createMatch)
//rutina de pistolas
api.get('/getGuns', GunsController.getGuns)
//rutina de disparos
api.get('/getDisparo', DisparoController.getDisparo)
module.exports = api
|
Fix GUI main frame instantiation. | package com.github.aureliano.edocs.app;
import javax.swing.SwingUtilities;
import com.github.aureliano.edocs.app.gui.AppFrame;
public class EdocsApp {
private static EdocsApp instance;
private AppFrame frame;
public static void main(String[] args) {
final EdocsApp application = instance();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
application.getFrame().showFrame();
}
});
}
public static EdocsApp instance() {
if (instance == null) {
instance = new EdocsApp();
}
return instance;
}
public EdocsApp() {
this.frame = new AppFrame();
}
public AppFrame getFrame() {
return this.frame;
}
} | package com.github.aureliano.edocs.app;
import javax.swing.SwingUtilities;
import com.github.aureliano.edocs.app.gui.AppFrame;
public class EdocsApp {
private static EdocsApp instance;
private AppFrame frame;
public static void main(String[] args) {
final EdocsApp application = new EdocsApp();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
application.getFrame().showFrame();
}
});
}
public static EdocsApp instance() {
if (instance == null) {
instance = new EdocsApp();
}
return instance;
}
public EdocsApp() {
this.frame = new AppFrame();
}
public AppFrame getFrame() {
return this.frame;
}
} |
Make constructor for lifecycle subjects | 'use strict';
function LifecycleSubjects(createEventSubject) {
// Expose observables like properties
this.componentWillMount = createEventSubject();
this.componentDidMount = createEventSubject();
this.componentWillReceiveProps = createEventSubject();
this.componentWillUpdate = createEventSubject();
this.componentDidUpdate = createEventSubject();
this.componentWillUnmount = createEventSubject();
}
module.exports = {
digestDefinitionFnOutput: function digestDefinitionFnOutput(output) {
var vtree$;
var onMount;
var dispose;
var customEvents;
if (output && output.hasOwnProperty('view') &&
typeof output.view.subscribe === 'function')
{
vtree$ = output.view;
onMount = output.onMount;
dispose = output.dispose;
customEvents = output.events;
} else if (output && typeof output.subscribe === 'function') {
vtree$ = output;
} else {
throw new Error(
'definitionFn given to render or component must return an ' +
'Observable of React elements, or an object containing such ' +
'Observable named as `view`');
}
return {
vtree$: vtree$,
onMount: onMount,
dispose: dispose,
customEvents: customEvents || {}
};
},
createLifecycleSubjects: function createLifecycleSubjects(createEventSubject) {
return new LifecycleSubjects(createEventSubject);
}
};
| 'use strict';
module.exports = {
digestDefinitionFnOutput: function digestDefinitionFnOutput(output) {
var vtree$;
var onMount;
var dispose;
var customEvents;
if (output && output.hasOwnProperty('view') &&
typeof output.view.subscribe === 'function')
{
vtree$ = output.view;
onMount = output.onMount;
dispose = output.dispose;
customEvents = output.events;
} else if (output && typeof output.subscribe === 'function') {
vtree$ = output;
} else {
throw new Error(
'definitionFn given to render or component must return an ' +
'Observable of React elements, or an object containing such ' +
'Observable named as `view`');
}
return {
vtree$: vtree$,
onMount: onMount,
dispose: dispose,
customEvents: customEvents || {}
};
},
createLifecycleSubjects: function createLifecycleSubjects(createEventSubject) {
return {
componentWillMount: createEventSubject(),
componentDidMount: createEventSubject(),
componentWillReceiveProps: createEventSubject(),
componentWillUpdate: createEventSubject(),
componentDidUpdate: createEventSubject(),
componentWillUnmount: createEventSubject()
};
}
};
|
Make enemy move more unpredictable | var EnemyType = {};
EnemyType.Trash = function (game) {
Phaser.Group.call(this, game, game.world, 'Trash Enemy', false, true, Phaser.Physics.ARCADE);
this.enemySpeed = 200;
//Add 10 trash enemies into this group
for (var i = 0; i < 10; i++) {
this.add(new Enemy(game, 'enemy3'), true);
}
return this;
}
//EnemyType inherited from Phaser.Group
EnemyType.Trash.prototype = Object.create(Phaser.Group.prototype);
EnemyType.Trash.prototype.constructor = EnemyType.Trash;
EnemyType.Trash.prototype.launch = function() {
var enemy = this.getFirstExists(false);
enemy.body.drag.x = 100;
//Prevent sprite being cut off on the edges
var halfWidth = enemy.width / 2;
var x = this.game.rnd.integerInRange(0 + halfWidth, this.game.width - halfWidth);
var angle = this.game.rnd.integerInRange(45, 135);
//Launch the enemy starting on top of the screen
enemy.launch(x, 0, angle, this.enemySpeed, 0);
}
| var EnemyType = {};
EnemyType.Trash = function (game) {
Phaser.Group.call(this, game, game.world, 'Trash Enemy', false, true, Phaser.Physics.ARCADE);
this.enemySpeed = 200;
//Add 10 trash enemies into this group
for (var i = 0; i < 10; i++) {
this.add(new Enemy(game, 'enemy3'), true);
}
return this;
}
//EnemyType inherited from Phaser.Group
EnemyType.Trash.prototype = Object.create(Phaser.Group.prototype);
EnemyType.Trash.prototype.constructor = EnemyType.Trash;
EnemyType.Trash.prototype.launch = function() {
var enemy = this.getFirstExists(false);
//Prevent sprite being cut off on the edges
var halfWidth = enemy.width / 2;
var x = this.game.rnd.integerInRange(0 + halfWidth, this.game.width - halfWidth);
//Launch the enemy starting on top of the screen
enemy.launch(x, 0, 90, this.enemySpeed, 0);
}
|
Add new endpoints to turn lights on and off | var gpio = require('onoff').Gpio;
var red = new gpio(16, 'out');
var green = new gpio(12, 'out');
var blue = new gpio(21, 'out');
var button = new gpio(19, 'in', 'both');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
app.listen(3001, function () {
console.log('App listening on port 3001!');
});
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
app.get('/on', function (req, res) {
res.send('Lights on!');
red.writeSync(1);
green.writeSync(1);
blue.writeSync(1);
});
app.get('/off', function(req,res){
red.writeSync(0);
green.writeSync(0);
blue.writeSync(0)
})
// define the callback function
function light(err, state) {
console.log('Button pushed');
// check the state of the button
// 1 == pressed, 0 == not pressed
if (state == 1) {
// turn LED on
red.writeSync(1);
gree.writeSync(1);
blue.writeSync(1);
} else {
// turn LED off
red.writeSync(0);
gree.writeSync(0);
blue.writeSync(0);
}
}
// pass the callback function to the
// as the first argument to watch()
button.watch(light);
| var gpio = require('onoff').Gpio;
var red = new gpio(16, 'out');
var green = new gpio(12, 'out');
var blue = new gpio(21, 'out');
var button = new gpio(19, 'in', 'both');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
app.listen(3001, function(){
console.log('App listening on port 3001!');
});
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
// define the callback function
function light(err, state) {
console.log('Button pushed');
// check the state of the button
// 1 == pressed, 0 == not pressed
if(state == 1) {
// turn LED on
red.writeSync(1);
gree.writeSync(1);
blue.writeSync(1);
} else {
// turn LED off
red.writeSync(0);
gree.writeSync(0);
blue.writeSync(0)
}
}
// pass the callback function to the
// as the first argument to watch()
button.watch(light);
|
Handle SIGINT and SIGTERM to enable clean shutdown of Homebridge
For now we terminate the process, but in the future we may tell the
server to stop, which may possibly include some teardown logic.
Handling these signals also make it easier to put Homebridge inside
a docker container, as docker uses SIGTERM to tell a container process
to stop, and passes SIGINT when attached to the container and receiving
a Ctrl+C. | var program = require('commander');
var hap = require("hap-nodejs");
var version = require('./version');
var Server = require('./server').Server;
var Plugin = require('./plugin').Plugin;
var User = require('./user').User;
var log = require("./logger")._system;
'use strict';
module.exports = function() {
var insecureAccess = false;
program
.version(version)
.option('-P, --plugin-path [path]', 'look for plugins installed at [path] as well as the default locations ([path] can also point to a single plugin)', function(p) { Plugin.addPluginPath(p); })
.option('-U, --user-storage-path [path]', 'look for homebridge user files at [path] instead of the default location (~/.homebridge)', function(p) { User.setStoragePath(p); })
.option('-D, --debug', 'turn on debug level logging', function() { require('./logger').setDebugEnabled(true) })
.option('-I, --insecure', 'allow unauthenticated requests (for easier hacking)', function() { insecureAccess = true })
.parse(process.argv);
// Initialize HAP-NodeJS with a custom persist directory
hap.init(User.persistPath());
var server = new Server(insecureAccess);
var signals = { 'SIGINT': 2, 'SIGTERM': 15 };
Object.keys(signals).forEach(function (signal) {
process.on(signal, function () {
log.info("Got %s, shutting down Homebridge...", signal);
// FIXME: Shut down server cleanly
process.exit(128 + signals[signal]);
});
});
server.run();
}
| var program = require('commander');
var hap = require("hap-nodejs");
var version = require('./version');
var Server = require('./server').Server;
var Plugin = require('./plugin').Plugin;
var User = require('./user').User;
var log = require("./logger")._system;
'use strict';
module.exports = function() {
var insecureAccess = false;
program
.version(version)
.option('-P, --plugin-path [path]', 'look for plugins installed at [path] as well as the default locations ([path] can also point to a single plugin)', function(p) { Plugin.addPluginPath(p); })
.option('-U, --user-storage-path [path]', 'look for homebridge user files at [path] instead of the default location (~/.homebridge)', function(p) { User.setStoragePath(p); })
.option('-D, --debug', 'turn on debug level logging', function() { require('./logger').setDebugEnabled(true) })
.option('-I, --insecure', 'allow unauthenticated requests (for easier hacking)', function() { insecureAccess = true })
.parse(process.argv);
// Initialize HAP-NodeJS with a custom persist directory
hap.init(User.persistPath());
new Server(insecureAccess).run();
}
|
Fix Map to list problem. | package com.williamschris;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@RestController
public class CustomerController {
private HashMap<String, Customer> customerMap = new HashMap<>();
private long customerIdGenerator = 1;
@RequestMapping(value = "/customer", method = RequestMethod.POST)
public void addCustomer(@RequestBody Customer c) {
c.setId(customerIdGenerator);
customerMap.put(String.valueOf(customerIdGenerator++), c);
}
@RequestMapping("/customer/{id}")
public Customer getCustomer(@PathVariable String id){
return customerMap.get(id);
}
@RequestMapping("/customer")
public List<Customer> getCustomers(){
return new ArrayList<>(customerMap.values());
}
@RequestMapping(value = "/customer/{id}", method = RequestMethod.DELETE)
public void deleteCustomer(@PathVariable String id){
customerMap.remove(id);
}
} | package com.williamschris;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@RestController
public class CustomerController {
private HashMap<String, Customer> customerMap = new HashMap<>();
private long customerIdGenerator = 1;
@RequestMapping(value = "/customer", method = RequestMethod.POST)
public void addCustomer(@RequestBody Customer c) {
c.setId(customerIdGenerator);
customerMap.put(String.valueOf(customerIdGenerator++), c);
}
@RequestMapping("/customer/{id}")
public Customer getCustomer(@PathVariable String id){
return customerMap.get(id);
}
@RequestMapping("/customer")
public List<Customer> getCustomers(){
List<Customer> customers = new ArrayList<>();
for(long i = 1; i < customerIdGenerator; ++i){
Customer customer = customerMap.get(String.valueOf(i));
customers.add(customer);
}
return customers;
}
@RequestMapping(value = "/customer/{id}", method = RequestMethod.DELETE)
public void deleteCustomer(@PathVariable String id){
customerMap.remove(id);
}
} |
feat: Merge product reordered column with order ids | # importing modules/ libraries
import pandas as pd
import numpy as np
orders_prior_df = pd.read_csv('Data/orders_prior_sample.csv')
order_products_prior_df = pd.read_csv('Data/order_products_prior_sample.csv')
grouped = order_products_prior_df.groupby('order_id', as_index = False)
grouped_data = pd.DataFrame()
grouped_data['order_id'] = grouped['order_id'].aggregate(np.mean)
def product_ids(group):
l = []
for e in group['product_id']:
l.append(str(e))
return ' '.join(l)
grouped_data['product_ids'] = grouped.apply(product_ids)
def add_to_cart_orders(group):
l = []
for e in group['add_to_cart_order']:
l.append(str(e))
return ' '.join(l)
grouped_data['add_to_cart_orders'] = grouped.apply(add_to_cart_orders)
grouped_data['reordered'] = grouped['reordered'].aggregate(np.mean)['reordered'].round()
print('First five rows of grouped_data:\n', grouped_data.head())
orders_prior_merged = pd.merge(orders_prior_df, grouped_data, on='order_id')
print('First five rows of orders_prior_merged:\n', orders_prior_merged.head())
| # importing modules/ libraries
import pandas as pd
import numpy as np
orders_prior_df = pd.read_csv('Data/orders_prior_sample.csv')
order_products_prior_df = pd.read_csv('Data/order_products_prior_sample.csv')
grouped = order_products_prior_df.groupby('order_id', as_index = False)
grouped_data = pd.DataFrame()
grouped_data['order_id'] = grouped['order_id'].aggregate(np.mean)
def product_ids(group):
l = []
for e in group['product_id']:
l.append(str(e))
return ' '.join(l)
grouped_data['product_ids'] = grouped.apply(product_ids)
def add_to_cart_orders(group):
l = []
for e in group['add_to_cart_order']:
l.append(str(e))
return ' '.join(l)
grouped_data['add_to_cart_orders'] = grouped.apply(add_to_cart_orders)
print('First five rows of grouped_data:\n', grouped_data.head())
orders_prior_merged = pd.merge(orders_prior_df, grouped_data, on='order_id')
print('First five rows of orders_prior_merged:\n', orders_prior_merged.head())
|
Remove some object representation clobbering code | # -*- coding: utf-8 -*-
"""
Object layout.
"""
from __future__ import print_function, division, absolute_import
from numba2 import conversion
from pykit import types as ptypes
from pykit.utils import ctypes_support
#===------------------------------------------------------------------===
# Types
#===------------------------------------------------------------------===
def representation_type(ty):
"""
Get the low-level representation type for a high-level (user-defined) type.
Returns
=======
The pykit type for the object layout.
"""
# NOTE: special cases should be kept to an absolute minimum here. They
# should probably be introduced only if ctypes cannot represent the
# type
from numba2.lib import vectorobject
if ty.impl == vectorobject.Vector:
# Ctypes does not support vectors
base, count = ty.parameters
return ptypes.Vector(representation_type(base), count)
cty = conversion.ctype(ty)
result_type = ctypes_support.from_ctypes_type(cty)
if result_type.is_struct:
result_type = ptypes.Pointer(result_type)
return result_type
| # -*- coding: utf-8 -*-
"""
Object layout.
"""
from __future__ import print_function, division, absolute_import
from numba2 import conversion
from pykit import types as ptypes
from pykit.utils import ctypes_support
#===------------------------------------------------------------------===
# Types
#===------------------------------------------------------------------===
def representation_type(ty):
"""
Get the low-level representation type for a high-level (user-defined) type.
Returns
=======
The pykit type for the object layout.
"""
from numba2.lib import vectorobject
from numba2.lib import arrayobject
from numba2.runtime.obj import pointerobject
if ty.impl == pointerobject.Pointer:
(base,) = ty.parameters
return ptypes.Pointer(representation_type(base))
if ty.impl == vectorobject.Vector:
base, count = ty.parameters
return ptypes.Vector(representation_type(base), count)
if ty.impl == arrayobject.Array:
base, count = ty.parameters
return ptypes.Array(representation_type(base), count)
cty = conversion.ctype(ty)
result_type = ctypes_support.from_ctypes_type(cty)
if result_type.is_struct:
result_type = ptypes.Pointer(result_type)
return result_type
|
Remove installation of dev-requirements;they don't exist anymore | #!/usr/bin/env python
# encoding: utf-8
import os
from setuptools import setup, find_packages
setup(
name="bsAbstimmungen",
version="0.1.0",
packages=['bsAbstimmungen'],
author="Raphael Zimmermann",
author_email="dev@raphael.li",
url="https://github.com/raphiz/bsAbstimmungen",
description="",
long_description=open('./README.md').read(),
license="MIT",
platforms=["Linux", "BSD", "MacOS"],
include_package_data=True,
zip_safe=False,
install_requires=open('./requirements.txt').read(),
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
"Programming Language :: Python :: Implementation :: CPython",
'Development Status :: 4 - Beta',
],
)
| #!/usr/bin/env python
# encoding: utf-8
import os
from setuptools import setup, find_packages
setup(
name="bsAbstimmungen",
version="0.1.0",
packages=['bsAbstimmungen'],
author="Raphael Zimmermann",
author_email="dev@raphael.li",
url="https://github.com/raphiz/bsAbstimmungen",
description="",
long_description=open('./README.md').read(),
license="MIT",
platforms=["Linux", "BSD", "MacOS"],
include_package_data=True,
zip_safe=False,
install_requires=open('./requirements.txt').read(),
tests_require=open('./requirements-dev.txt').read(),
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
"Programming Language :: Python :: Implementation :: CPython",
'Development Status :: 4 - Beta',
],
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.