text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
[CDI] Fix some DTO arrays to lists | /*
* Copyright (c) OSGi Alliance (2017). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law 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.osgi.service.cdi.runtime.dto.template;
import java.util.List;
import org.osgi.dto.DTO;
import org.osgi.service.cdi.runtime.dto.template.ComponentTemplateDTO.Type;
/**
* Description of a CDI container.
*
* @NotThreadSafe
* @author $Id$
*/
public class ContainerTemplateDTO extends DTO {
/**
* The id of the CDI container.
*/
public String id;
/**
* The extension dependencies of this CDI container.
* <p>
* Must not be {@code null}
* <p>
* May be empty if the container does not require CDI extensions.
*/
public List<ExtensionTemplateDTO> extensions;
/**
* The components defined in this CDI container.
* <p>
* Must not be {@code null}
* <p>
* Has at lest one element for the {@link Type#APPLICATION application
* component}.
*/
public List<ComponentTemplateDTO> components;
}
| /*
* Copyright (c) OSGi Alliance (2017). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law 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.osgi.service.cdi.runtime.dto.template;
import org.osgi.dto.DTO;
/**
* Description of a CDI container.
*
* @NotThreadSafe
* @author $Id$
*/
public class ContainerTemplateDTO extends DTO {
/**
* The id of the CDI container.
*/
public String id;
/**
* The extension dependencies of this CDI container.
*/
public ExtensionTemplateDTO[] extensions;
/**
* The components defined in this CDI container.
*/
public ComponentTemplateDTO[] components;
}
|
Use pathlib to read ext.conf | import pathlib
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
| import os
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), "ext.conf")
return config.read(conf_file)
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
|
Add banner for js file | var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var rename = require('gulp-rename');
var header = require('gulp-header');
var bundleGulp = require('../util/bundleGulp');
var pkg = require('../../../package.json');
gulp.task('scripts', ['jshint'], function() {
var config = {
mangle: true
};
var headerConfig = {
pkg: pkg
};
return gulp.src('src/js/**/*.js')
.pipe(sourcemaps.init())
.pipe(concat('testimonial.js'))
.pipe(header(bundleGulp.getBanner(), headerConfig))
.pipe(gulp.dest('dist/js/'))
.pipe(uglify(config))
.pipe(rename('testimonial.min.js'))
.pipe(header(bundleGulp.getBanner(), headerConfig))
.pipe(gulp.dest('dist/js/'))
.pipe(rename('testimonial.min.map.js'))
.pipe(sourcemaps.write('maps'))
.pipe(gulp.dest('dist/js/'));
});
| var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var rename = require("gulp-rename");
gulp.task('scripts', ['jshint'], function() {
var config = {
mangle: true
};
return gulp.src('src/js/**/*.js')
.pipe(sourcemaps.init())
.pipe(concat('testimonial.js'))
.pipe(gulp.dest('dist/js/'))
.pipe(uglify(config))
.pipe(rename('testimonial.min.js'))
.pipe(gulp.dest('dist/js/'))
.pipe(rename('testimonial.min.map.js'))
.pipe(sourcemaps.write('maps'))
.pipe(gulp.dest('dist/js/'));
});
|
Update URL paths to be compatible with Retrofit 2. | package com.seatgeek.sixpack;
import com.seatgeek.sixpack.response.ConvertResponse;
import com.seatgeek.sixpack.response.ParticipateResponse;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface SixpackApi {
@GET("participate")
Call<ParticipateResponse> participate(
@Query("experiment") Experiment experiment,
@Query("alternatives") List<Alternative> alternatives,
@Query("force") Alternative forcedAlternative,
@Query("traffic_fraction") Double trafficFraction,
@Query("prefetch") Boolean prefetch
);
@GET("convert")
Call<ConvertResponse> convert(
@Query("experiment") Experiment experiment,
@Query("kpi") String kpi
);
}
| package com.seatgeek.sixpack;
import com.seatgeek.sixpack.response.ConvertResponse;
import com.seatgeek.sixpack.response.ParticipateResponse;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface SixpackApi {
@GET("/participate")
Call<ParticipateResponse> participate(
@Query("experiment") Experiment experiment,
@Query("alternatives") List<Alternative> alternatives,
@Query("force") Alternative forcedAlternative,
@Query("traffic_fraction") Double trafficFraction,
@Query("prefetch") Boolean prefetch
);
@GET("/convert")
Call<ConvertResponse> convert(
@Query("experiment") Experiment experiment,
@Query("kpi") String kpi
);
}
|
Use imgsrc plugin/snippet for background example. | <?php snippet_detect('html_head', array(
'criticalcss' => 'home',
'prev_next' => false,
'prerender' => false
)); ?>
<?php snippet('banner'); ?>
<div <?php echo imgsrc($page->images()->first(), array('bgimage' => true, 'class' => 'CoverImage FluidEmbed--3by2 FluidEmbed--large16by9 FluidEmbed--huge2by1')); ?>></div>
<div class="ContainPadding">
<main role="main" class="Copy u-spaceTrailerM">
<h1><?php echo $page->title()->smartypants()->widont(); ?></h1>
<?php echo $page->intro()->kirbytext(); ?>
<?php echo $page->text()->kirbytext(); ?>
</main>
<?php snippet('share_page'); ?>
</div>
<?php snippet_detect('footer'); ?>
| <?php snippet_detect('html_head', array(
'criticalcss' => 'home',
'prev_next' => false,
'prerender' => false
)); ?>
<?php snippet('banner'); ?>
<div class="CoverImage FluidEmbed FluidEmbed--3by2 FluidEmbed--compact16by9 FluidEmbed--medium2by1 FluidEmbed--large3by1"
style="background-image: url('<?php echo page('home')->images()->shuffle()->first()->url(); ?>')">
</div>
<div class="ContainPadding">
<main role="main" class="Copy u-spaceTrailerM">
<h1><?php echo $page->title()->smartypants()->widont(); ?></h1>
<?php echo $page->intro()->kirbytext(); ?>
<?php echo $page->text()->kirbytext(); ?>
</main>
<?php snippet('share_page'); ?>
</div>
<?php snippet_detect('footer'); ?>
|
Add watch option and make it default | var james = require('james');
var cssmin = require('james-cssmin');
var uglify = require('james-uglify');
var inputRoot = 'dev/';
var outputRoot = 'public/';
james.task('default', ['watch']);
james.task('build', build);
james.task('watch', watch);
james.task('minify_css', minifyCSS);
james.task('minify_js', minifyJS);
function build() {
minifyCSS();
minifyJS();
}
function watch() {
james.watch(inputRoot + '**/*.css', minifyCSS);
james.watch(inputRoot + '**/*.js', minifyJS);
}
function minifyCSS() {
var cssTarget = james.dest(outputRoot + 'css/all.css');
james.read(inputRoot + 'css/vendor/normalize.css').write(cssTarget);
james.read(inputRoot + 'css/vendor/foundation.css').write(cssTarget);
james.read(inputRoot + 'css/vendor/jquery.qtip.css').write(cssTarget);
james.list(inputRoot + 'css/*.css').forEach(process);
// TODO: figure out why the output doesn't work
//james.read(cssTarget).transform(cssmin).write(cssTarget);
function process(file) {
james.read(file).write(cssTarget);
}
}
function minifyJS() {
var jsTarget = james.dest(outputRoot + 'js/main.js');
james.list(inputRoot + 'js/**/*.js').forEach(function(file) {
james.read(file).transform(uglify).write(jsTarget);
});
}
| var james = require('james');
var cssmin = require('james-cssmin');
var uglify = require('james-uglify');
var inputRoot = 'dev/';
var outputRoot = 'public/';
james.task('minify_css', function() {
var cssTarget = james.dest(outputRoot + 'css/all.css');
james.read(inputRoot + 'css/vendor/normalize.css').write(cssTarget);
james.read(inputRoot + 'css/vendor/foundation.css').write(cssTarget);
james.read(inputRoot + 'css/vendor/jquery.qtip.css').write(cssTarget);
james.list(inputRoot + 'css/*.css').forEach(process);
// TODO: figure out why the output doesn't work
//james.read(cssTarget).transform(cssmin).write(cssTarget);
function process(file) {
james.read(file).write(cssTarget);
}
});
james.task('minify_js', function() {
var jsTarget = james.dest(outputRoot + 'js/main.js');
james.list(inputRoot + 'js/**/*.js').forEach(function(file) {
james.read(file).transform(uglify).write(jsTarget);
});
});
james.task('default', ['minify_css', 'minify_js']);
|
Fix points color and hover size | // Initial dot attributes
function dot_init (selection, scales, settings) {
selection
.style("fill", "rgb(31, 119, 180)");
// tooltips when hovering points
var tooltip = d3.select(".tooltip");
selection.on("mouseover", function(d, i){
d3.select(this)
.transition().duration(150)
.attr("d", d3.symbol().size(600));
tooltip.style("visibility", "visible")
.html(tooltip_content(d));
});
selection.on("mousemove", function(){
tooltip.style("top", (d3.event.pageY+15)+"px").style("left",(d3.event.pageX+15)+"px");
});
selection.on("mouseout", function(){
d3.select(this)
.transition().duration(150)
.attr("d", d3.symbol().size(settings.points_size));
tooltip.style("visibility", "hidden");
});
}
// Apply format to dot
function dot_formatting(selection, scales, settings) {
var sel = selection
.attr("transform", function(d) { return translation(d, scales); })
// fill color
.style("opacity", settings.points_opacity)
// symbol and size
.attr("d", d3.symbol().size(settings.points_size));
return sel;
}
| // Initial dot attributes
function dot_init (selection, scales) {
selection
.style("fill", "rgb(31, 119, 180)")
.attr("class", function(d,i) {
return "dot";
});
// tooltips when hovering points
var tooltip = d3.select(".tooltip");
selection.on("mouseover", function(d, i){
d3.select(this)
.transition().duration(150)
.attr("d", d3.symbol().size(450));
tooltip.style("visibility", "visible")
.html(tooltip_content(d));
});
selection.on("mousemove", function(){
tooltip.style("top", (d3.event.pageY+15)+"px").style("left",(d3.event.pageX+15)+"px");
});
selection.on("mouseout", function(){
d3.select(this)
.transition().duration(150)
.attr("d", d3.symbol().size(100));
tooltip.style("visibility", "hidden");
});
}
// Apply format to dot
function dot_formatting(selection, scales, settings) {
var sel = selection
.attr("transform", function(d) { return translation(d, scales); })
// fill color
.style("opacity", settings.points_opacity)
// symbol and size
.attr("d", d3.symbol().size(settings.points_size));
return sel;
}
|
Update test to match current behavior | # -*- coding: utf-8 -*-
from mock import Mock
from unittest2 import TestCase
from raven.events import Message
class MessageTest(TestCase):
def test_to_string(self):
unformatted_message = 'My message from %s about %s'
client = Mock()
message = Message(client)
message.logger = Mock()
data = {
'sentry.interfaces.Message': {
'message': unformatted_message,
}
}
self.assertEqual(message.to_string(data), unformatted_message)
data['sentry.interfaces.Message']['params'] = (1, 2)
self.assertEqual(message.to_string(data),
unformatted_message % (1, 2))
| # -*- coding: utf-8 -*-
from mock import Mock
from unittest2 import TestCase
from raven.events import Message
class MessageTest(TestCase):
def test_to_string(self):
unformatted_message = 'My message from %s about %s'
client = Mock()
message = Message(client)
message.logger = Mock()
data = {
'sentry.interfaces.Message': {
'message': unformatted_message,
}
}
self.assertEqual(message.to_string(data), unformatted_message)
self.assertEqual(message.logger.warn.call_count, 1)
args, kwargs = message.logger.warn.call_args
self.assertEqual(args, ('Unable to find params for message',))
self.assertEqual(kwargs,
{'extra': {'msg': {'message': unformatted_message}}})
data['sentry.interfaces.Message']['params'] = (1, 2)
self.assertEqual(message.to_string(data),
unformatted_message % (1, 2))
|
Fix toastr npm asset path | <?php
namespace CottaCush\Yii2\Assets;
/**
* Class ToastrAsset
* Asset for Toastr.js
* @author Olajide Oye <jide@cottacush.com>
* @package CottaCush\Yii2\Assets
*/
class ToastrAsset extends AssetBundle
{
public $sourcePath = '@npm/toastr/build';
public $css = [
'toastr.min.css'
];
public $js = [
'toastr.min.js'
];
public $productionCss = [
'https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.3/toastr.min.css'
];
public $productionJs = [
'https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.3/toastr.min.js'
];
public $depends = [
'yii\web\JqueryAsset'
];
}
| <?php
namespace CottaCush\Yii2\Assets;
/**
* Class ToastrAsset
* Asset for Toastr.js
* @author Olajide Oye <jide@cottacush.com>
* @package CottaCush\Yii2\Assets
*/
class ToastrAsset extends AssetBundle
{
public $sourcePath = '@npm/toastr';
public $css = [
'toastr.min.css'
];
public $js = [
'toastr.min.js'
];
public $productionCss = [
'https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.3/toastr.min.css'
];
public $productionJs = [
'https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.3/toastr.min.js'
];
public $depends = [
'yii\web\JqueryAsset'
];
}
|
Fix sorting issue that broke chrome and safari | import getTime from "date-fns/get_time";
import isAfter from "date-fns/is_after";
import React from "react";
const UPDATE_INTERVAL = 1000;
const getNextGame = (now, games) => {
return games
.filter((game) => { return isAfter(game.date, now); })
.sort((game1, game2) => { return getTime(game1.date) > getTime(game2.date); })
.shift();
};
const updateCurrentDate = (state) => {
state.today = new Date();
return state;
};
export default function (Component, gameData) {
return class extends React.Component {
constructor(props) {
super(props);
this.state = {
today: new Date()
};
}
componentDidMount() {
const updateDate = () => { this.setState(updateCurrentDate); };
this.timer = setInterval(updateDate.bind(this), UPDATE_INTERVAL);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return (
<Component
{...this.props}
nextGame={getNextGame(this.state.today, gameData)}
/>
);
}
};
}
| import getTime from "date-fns/get_time";
import isAfter from "date-fns/is_after";
import React from "react";
const UPDATE_INTERVAL = 1000;
const getNextGame = (now, games) => {
return games
.filter((game) => { return isAfter(game.date, now); })
.sort((game) => { return -getTime(game.date); })
.shift();
};
const updateCurrentDate = (state) => {
state.today = new Date();
return state;
};
export default function (Component, gameData) {
return class extends React.Component {
constructor(props) {
super(props);
this.state = {
today: new Date()
};
}
componentDidMount() {
const updateDate = () => { this.setState(updateCurrentDate); };
this.timer = setInterval(updateDate.bind(this), UPDATE_INTERVAL);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return (
<Component
{...this.props}
nextGame={getNextGame(this.state.today, gameData)}
/>
);
}
};
}
|
Rename entire repository as suggested by the Symphony team | <?php
Class extension_lang_german extends Extension {
/**
* Extension information
*/
public function about() {
return array(
'name' => 'Language: German',
'type' => 'Localisation',
'version' => '1.1',
'release-date' => '2010-02-01',
'author' => array(
'name' => 'Nils Hörrmann',
'website' => 'http://www.nilshoerrmann.de',
'email' => 'post@nilshoerrmann.de'
),
'description' => 'Official German translation for the Symphony backend',
'compatibility' => array(
'2.0.0' => false,
'2.0.1' => false,
'2.0.2' => false,
'2.0.3' => true,
'2.0.4' => true,
'2.0.5' => true,
'2.0.6' => true,
'2.0.7' => true
)
);
}
}
| <?php
Class extension_Symphony_German extends Extension {
/**
* Extension information
*/
public function about() {
return array(
'name' => 'German Localisation',
'type' => 'Interface',
'version' => '1.1',
'release-date' => '2010-02-01',
'author' => array(
'name' => 'Nils Hörrmann',
'website' => 'http://www.nilshoerrmann.de',
'email' => 'post@nilshoerrmann.de'
),
'description' => 'German translation for the Symphony backend',
'compatibility' => array(
'2.0.0' => false,
'2.0.1' => false,
'2.0.2' => false,
'2.0.3' => true,
'2.0.4' => true,
'2.0.5' => true,
'2.0.6' => true,
'2.0.7' => true
)
);
}
}
|
Add IP for dev mode | <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '31.32.220.167', 'fe80::1', '::1'))
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
| <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1'))
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
Add intelligent skip for missing secret info | import os
import unittest
import object_storage_tensorflow as obj_tf
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
class TestS3Connection(unittest.TestCase):
@unittest.skipUnless(os.environ.get("TRAVIS_PULL_REQUEST") == 'false',
"S3 tests will fail for Pull Requests due to lack of secrets.")
def test_buckets(self):
conn = obj_tf.s3.getConnection()
names = []
for bucket in conn.buckets.all():
names.append(bucket.name)
self.assertTrue(len(names) > 0)
if __name__ == '__main__':
unittest.main()
| import unittest
import object_storage_tensorflow as obj_tf
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
class TestS3Connection(unittest.TestCase):
def test_buckets(self):
conn = obj_tf.s3.getConnection()
names = []
for bucket in conn.buckets.all():
names.append(bucket.name)
self.assertTrue(len(names) > 0)
if __name__ == '__main__':
unittest.main()
|
Customize port to listen to | var express = require('express');
var http = require('http');
var path = require("path");
var fs = require('fs');
var _ = require('underscore');
var ldap = require('./modules/ldap');
var app = express();
var portNumber = process.env.PORT || 3001;
// app.use(express.static('public'));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get("/", function (request, response) { response.send({ status: 'OK' }); })
app.get('/employees', ldap.findAll);
app.get('/employees/:id([0-9]+)', ldap.findById);
app.get('/employees/:id([0-9]+)/team', ldap.team);
app.get('/employees/newcomers', ldap.newcomers);
app.get('/employees/apprentices', ldap.apprentices);
app.get('/employees/count', ldap.count);
app.use(express.static(__dirname));
app.listen(portNumber);
console.log("Responding server listening on port " + portNumber);
| var express = require('express');
var http = require('http');
var path = require("path");
var fs = require('fs');
var _ = require('underscore');
var ldap = require('./modules/ldap');
var app = express();
var portNumber = 3001;
// app.use(express.static('public'));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get("/", function (request, response) { response.send({ status: 'OK' }); })
app.get('/employees', ldap.findAll);
app.get('/employees/:id([0-9]+)', ldap.findById);
app.get('/employees/:id([0-9]+)/team', ldap.team);
app.get('/employees/newcomers', ldap.newcomers);
app.get('/employees/apprentices', ldap.apprentices);
app.get('/employees/count', ldap.count);
app.use(express.static(__dirname));
app.listen(portNumber);
console.log("Responding server listening on port " + portNumber);
|
Clean up option action creators | import {
SET_SPEED,
SET_PAUSE,
SET_PAUSE_HOVER,
SET_FALLOFF,
SET_RADII_SCALE,
SET_BOUNCE_BODIES,
SET_BOUNCE_SCREEN,
} from './types'
export function speed(speed) {
return {
type: SET_SPEED,
speed,
}
}
export function pause(paused) {
return {
type: SET_PAUSE,
paused,
}
}
export function pauseHover(pauseHover) {
return {
type: SET_PAUSE_HOVER,
pauseHover,
}
}
export function falloff(falloff) {
return {
type: SET_FALLOFF,
falloff,
}
}
export function radiiScale(radiiScale) {
return {
type: SET_RADII_SCALE,
radiiScale,
}
}
export function bounceBodies(bounceBodies) {
return {
type: SET_BOUNCE_BODIES,
bounceBodies,
}
}
export function bounceScreen(bounceScreen) {
return {
type: SET_BOUNCE_SCREEN,
bounceScreen,
}
}
| import {
SET_SPEED,
SET_PAUSE,
SET_PAUSE_HOVER,
SET_FALLOFF,
SET_RADII_SCALE,
SET_BOUNCE_BODIES,
SET_BOUNCE_SCREEN,
} from './types'
export function speed(s) {
return {
type: SET_SPEED,
speed: s,
}
}
export function pause(pause) {
return {
type: SET_PAUSE,
paused: pause,
}
}
export function pauseHover(pause) {
return {
type: SET_PAUSE_HOVER,
pauseHover: pause,
}
}
export function falloff(f) {
return {
type: SET_FALLOFF,
falloff: f,
}
}
export function radiiScale(scale) {
return {
type: SET_RADII_SCALE,
radiiScale: scale,
}
}
export function bounceBodies(b) {
return {
type: SET_BOUNCE_BODIES,
bounceBodies: b,
}
}
export function bounceScreen(b) {
return {
type: SET_BOUNCE_SCREEN,
bounceScreen: b,
}
}
|
Fix logout link on IE
Closes #213. | import 'babel-core/polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import { ReduxRouter } from 'redux-router';
import Immutable from 'seamless-immutable';
import rootReducer from 'reducers/index';
import configureStore from 'store/configureStore';
import 'assets/styles/app.less';
const initialStoreState = createStore(rootReducer, {}).getState();
const initialState = window.__INITIAL_STATE__;
const finalState = Immutable(initialStoreState).merge(initialState, { deep: true });
const store = configureStore(finalState);
render(
<Provider store={store}>
<ReduxRouter
components={[]}
location={{}}
params={{}}
routes={[]}
/>
</Provider>,
document.getElementById('root')
);
if (__DEVTOOLS__) {
require('./createDevToolsWindow')(store);
}
// Fix for IE
if (!window.location.origin) {
window.location.origin = (
window.location.protocol + '//' + window.location.hostname + (
window.location.port ? ':' + window.location.port : ''
)
);
}
| import 'babel-core/polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import { ReduxRouter } from 'redux-router';
import Immutable from 'seamless-immutable';
import rootReducer from 'reducers/index';
import configureStore from 'store/configureStore';
import 'assets/styles/app.less';
const initialStoreState = createStore(rootReducer, {}).getState();
const initialState = window.__INITIAL_STATE__;
const finalState = Immutable(initialStoreState).merge(initialState, { deep: true });
const store = configureStore(finalState);
render(
<Provider store={store}>
<ReduxRouter
components={[]}
location={{}}
params={{}}
routes={[]}
/>
</Provider>,
document.getElementById('root')
);
if (__DEVTOOLS__) {
require('./createDevToolsWindow')(store);
}
|
Set None instead of NoneType to SimEvent.sim_procedure to make pickle happy. | import itertools
event_id_count = itertools.count()
class SimEvent(object):
#def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None):
def __init__(self, state, event_type, **kwargs):
self.id = event_id_count.next()
self.type = event_type
self.ins_addr = state.scratch.ins_addr
self.bbl_addr = state.scratch.bbl_addr
self.stmt_idx = state.scratch.stmt_idx
self.sim_procedure = None if state.scratch.sim_procedure is None else state.scratch.sim_procedure.__class__
self.objects = dict(kwargs)
def __repr__(self):
return "<SimEvent %s %d, with fields %s>" % (self.type, self.id, self.objects.keys())
def _copy_event(self):
c = self.__class__.__new__(self.__class__)
c.id = self.id
c.type = self.type
c.bbl_addr = self.bbl_addr
c.stmt_idx = self.stmt_idx
c.sim_procedure = self.sim_procedure
c.objects = dict(self.objects)
return c
| import itertools
event_id_count = itertools.count()
class SimEvent(object):
#def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None):
def __init__(self, state, event_type, **kwargs):
self.id = event_id_count.next()
self.type = event_type
self.ins_addr = state.scratch.ins_addr
self.bbl_addr = state.scratch.bbl_addr
self.stmt_idx = state.scratch.stmt_idx
self.sim_procedure = state.scratch.sim_procedure.__class__
self.objects = dict(kwargs)
def __repr__(self):
return "<SimEvent %s %d, with fields %s>" % (self.type, self.id, self.objects.keys())
def _copy_event(self):
c = self.__class__.__new__(self.__class__)
c.id = self.id
c.type = self.type
c.bbl_addr = self.bbl_addr
c.stmt_idx = self.stmt_idx
c.sim_procedure = self.sim_procedure
c.objects = dict(self.objects)
return c
|
Create utilities for module generators
Summary:
There are two operations we do in every NativeModule generator:
- We convert the `SchemaType` into a map of NativeModule schemas
- If the type-annotation is a TypeAliasTypeAnnotation, we resolve it by doing a lookup on the NativeModuleAliasMap. This is usually followed by an invariant to assert that the lookup didn't fail.
Both procedures have been translated into utilities for use across our generators. I also deleted `getTypeAliasTypeAnnotation` which will no longer be used.
Changelog: [Internal]
Reviewed By: hramos
Differential Revision: D23667249
fbshipit-source-id: 4e34078980e2caa4daed77c38b1168bfc161c31c | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
'use strict';
import type {
SchemaType,
NativeModuleAliasMap,
Required,
NativeModuleObjectTypeAnnotation,
NativeModuleSchema,
} from '../../CodegenSchema';
const invariant = require('invariant');
export type AliasResolver = (
aliasName: string,
) => Required<NativeModuleObjectTypeAnnotation>;
function createAliasResolver(aliasMap: NativeModuleAliasMap): AliasResolver {
return (aliasName: string) => {
const alias = aliasMap[aliasName];
invariant(alias != null, `Unable to resolve type alias '${aliasName}'.`);
return alias;
};
}
function getModules(
schema: SchemaType,
): $ReadOnly<{|[moduleName: string]: NativeModuleSchema|}> {
return Object.keys(schema.modules)
.map<?{+[string]: NativeModuleSchema}>(
moduleName => schema.modules[moduleName].nativeModules,
)
.filter(Boolean)
.reduce<{+[string]: NativeModuleSchema}>(
(acc, modules) => ({...acc, ...modules}),
{},
);
}
module.exports = {
createAliasResolver,
getModules,
};
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
'use strict';
import type {ObjectTypeAliasTypeShape} from '../../CodegenSchema';
function getTypeAliasTypeAnnotation(
name: string,
aliases: $ReadOnly<{[aliasName: string]: ObjectTypeAliasTypeShape, ...}>,
): $ReadOnly<ObjectTypeAliasTypeShape> {
const typeAnnotation = aliases[name];
if (!typeAnnotation) {
throw Error(`No type annotation found for "${name}" in schema`);
}
if (typeAnnotation.type === 'ObjectTypeAnnotation') {
if (typeAnnotation.properties) {
return typeAnnotation;
}
throw new Error(
`Unsupported type for "${name}". Please provide properties.`,
);
}
// $FlowFixMe[incompatible-type]
if (typeAnnotation.type === 'TypeAliasTypeAnnotation') {
return getTypeAliasTypeAnnotation(typeAnnotation.name, aliases);
}
throw Error(
`Unsupported type annotation in alias "${name}", found: ${typeAnnotation.type}`,
);
}
module.exports = {
getTypeAliasTypeAnnotation,
};
|
Implement more TGT Shaman cards | from ..utils import *
##
# Hero Powers
# Lightning Jolt
class AT_050t:
play = Hit(TARGET, 2)
##
# Minions
# Tuskarr Totemic
class AT_046:
play = Summon(CONTROLLER, RandomTotem())
# Draenei Totemcarver
class AT_047:
play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM)
# Thunder Bluff Valiant
class AT_049:
inspire = Buff(FRIENDLY_MINIONS + TOTEM, "AT_049e")
# The Mistcaller
class AT_054:
# The Enchantment ID is correct
play = Buff(FRIENDLY + (IN_DECK | IN_HAND), "AT_045e")
##
# Spells
# Healing Wave
class AT_048:
play = JOUST & Heal(TARGET, 7) | Heal(TARGET, 14)
# Elemental Destruction
class AT_051:
play = Hit(ALL_MINIONS, RandomNumber(4, 5))
# Ancestral Knowledge
class AT_053:
play = Draw(CONTROLLER) * 2
##
# Weapons
# Charged Hammer
class AT_050:
deathrattle = Summon(CONTROLLER, "AT_050t")
| from ..utils import *
##
# Hero Powers
# Lightning Jolt
class AT_050t:
play = Hit(TARGET, 2)
##
# Minions
# Tuskarr Totemic
class AT_046:
play = Summon(CONTROLLER, RandomTotem())
# Draenei Totemcarver
class AT_047:
play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM)
# Thunder Bluff Valiant
class AT_049:
inspire = Buff(FRIENDLY_MINIONS + TOTEM, "AT_049e")
##
# Spells
# Healing Wave
class AT_048:
play = JOUST & Heal(TARGET, 7) | Heal(TARGET, 14)
# Elemental Destruction
class AT_051:
play = Hit(ALL_MINIONS, RandomNumber(4, 5))
# Ancestral Knowledge
class AT_053:
play = Draw(CONTROLLER) * 2
##
# Weapons
# Charged Hammer
class AT_050:
deathrattle = Summon(CONTROLLER, "AT_050t")
|
Add a safety check that newrelic_add_custom_parameter exists | <?php
/**
* @package New Relic Insights attributes for WordPress
* @version 0.1
*/
/*
Plugin Name: New Relic Insights attributes for WordPress
Plugin URI: http://newrelic.com
Description: This plugin adds Insights attributes for logged in users.
Author: New Relic
Version: 0.1
Author URI: http://newrelic.com
*/
function add_newrelic_insights_attributes() {
if (!function_exists("newrelic_add_custom_parameter")) {
return;
}
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
newrelic_add_custom_parameter("wp_logged_in", true);
newrelic_add_custom_parameter("wp_username", $current_user->user_login);
newrelic_add_custom_parameter("wp_user_id", $current_user->ID);
newrelic_add_custom_parameter("wp_user_email", $current_user->user_email);
} else {
newrelic_add_custom_parameter("wp_logged_in", false);
}
}
add_action( 'init', 'add_newrelic_insights_attributes' );
?>
| <?php
/**
* @package New Relic Insights attributes for WordPress
* @version 0.1
*/
/*
Plugin Name: New Relic Insights attributes for WordPress
Plugin URI: http://newrelic.com
Description: This plugin adds Insights attributes for logged in users.
Author: New Relic
Version: 0.1
Author URI: http://newrelic.com
*/
function add_newrelic_insights_attributes() {
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
newrelic_add_custom_parameter("wp_logged_in", true);
newrelic_add_custom_parameter("wp_username", $current_user->user_login);
newrelic_add_custom_parameter("wp_user_id", $current_user->ID);
newrelic_add_custom_parameter("wp_user_email", $current_user->user_email);
} else {
newrelic_add_custom_parameter("wp_logged_in", false);
}
}
add_action( 'init', 'add_newrelic_insights_attributes' );
?>
|
Add .py extension handling and more python keywords | import vx
import os.path
def mode_from_filename(file):
root, ext = os.path.splitext(file)
ext = ext if ext else root
mode = None
if ext == '.c':
return c_mode
elif ext == '.py':
return python_mode
class mode:
def __init__(self, window):
self.breaks = ('_', ' ', '\n', '\t')
self.keywords = ()
class python_mode(mode):
def __init__(self, window):
super().__init__(window)
self.breaks = ('_', ' ', '\n', '\t', '(', ')', '{', '}', '.', ',', '#')
self.keywords = ('class', 'return', 'for', 'while', 'break', 'continue', 'def', 'from', 'import')
class c_mode(mode):
def __init__(self, window):
super().__init__(window)
self.breaks = ('_', ' ', '\n', '\t', '(', ')', '<', '>', '.', ',', '#')
self.keywords = ('#include', '#define', 'if', 'else', 'return', 'goto', 'break', 'continue', r'"(?:[^"\\]|\\.)*"')
| import vx
import os.path
def mode_from_filename(file):
root, ext = os.path.splitext(file)
ext = ext if ext else root
mode = None
if ext == '.c':
return c_mode
class mode:
def __init__(self, window):
self.breaks = ('_', ' ', '\n', '\t')
self.keywords = ()
class python_mode(mode):
def __init__(self, window):
super().__init__(window)
self.breaks = ('_', ' ', '\n', '\t', '(', ')', '{', '}', '.', ',', '#')
self.keywords = ('return', 'for', 'while', 'break', 'continue', 'def')
class c_mode(mode):
def __init__(self, window):
super().__init__(window)
self.breaks = ('_', ' ', '\n', '\t', '(', ')', '<', '>', '.', ',', '#')
self.keywords = ('#include', '#define', 'if', 'else', 'return', 'goto', 'break', 'continue', r'"(?:[^"\\]|\\.)*"')
|
Fix galeginho si todo va bien | module.exports = (client) => {
var regex = require("./regexp");
var galeguinhos = 0;
client.on('message', message => {
if (regex.regexSiNo.test(message.content)) {
let response = Math.random() < 0.5 ? -1 : 1;
if (response > 0) {
response = "SI"
} else {
response = "NO"
}
message.reply(`PUES OBVIAMENTE, ${response}`).catch(console.log)
}
if (regex.regexCuantos.test(message.content)) {
if (message.guild.members.array().filter(each => regex.regexGale.test(each.user.username)).length > 0) {
galeguinhos = message.guild.members.array().filter(each => regex.regexGale.test(each.user.displayName)).length
}
let response = message.guild.memberCount - 1 + " DE LOS CUALES " + galeguinhos + " SON GALEGUINHO95 PORQUE ES PUTO TONTO. AH! Y YO, EL BOT, SOY EL BOT, YO ESTUVE, SÍ."
message.reply(response).then(() => galeguinhos = 0).catch(console.log)
}
})
}
| module.exports = (client) => {
var regex = require("./regexp");
var galeguinhos = 0;
client.on('message', message => {
if (regex.regexSiNo.test(message.content)) {
let response = Math.random() < 0.5 ? -1 : 1;
if (response > 0) {
response = "SI"
} else {
response = "NO"
}
message.reply(`PUES OBVIAMENTE, ${response}`).catch(console.log)
}
if (regex.regexCuantos.test(message.content)) {
if (message.guild.members.array().filter(each => regex.regexGale.test(each.user.username)).length > 0) {
galeguinhos = message.guild.members.array().filter(each => regex.regexGale.test(each.user.username)).length
}
let response = message.guild.memberCount - 1 + " DE LOS CUALES " + galeguinhos + " SON GALEGUINHO95 PORQUE ES PUTO TONTO. AH! Y YO, EL BOT, SOY EL BOT, YO ESTUVE, SÍ."
message.reply(response).then(() => galeguinhos = 0).catch(console.log)
}
})
}
|
Fix contract of block item provider by memoize the supplier for the
block item. | package info.u_team.u_team_core.block;
import java.util.function.Supplier;
import com.google.common.base.Suppliers;
import info.u_team.u_team_core.api.block.BlockItemProvider;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
public class UBlock extends Block implements BlockItemProvider {
protected final Supplier<Item> blockItem;
public UBlock(Properties properties) {
this(null, properties);
}
public UBlock(CreativeModeTab creativeTab, Properties properties) {
this(creativeTab, properties, null);
}
public UBlock(Properties properties, Item.Properties blockItemProperties) {
this(null, properties, blockItemProperties);
}
public UBlock(CreativeModeTab creativeTab, Properties properties, Item.Properties blockItemProperties) {
super(properties);
blockItem = Suppliers.memoize(() -> createBlockItem(blockItemProperties == null ? new Item.Properties().tab(creativeTab) : creativeTab == null ? blockItemProperties : blockItemProperties.tab(creativeTab)));
}
protected Item createBlockItem(Item.Properties blockItemProperties) {
return new BlockItem(this, blockItemProperties);
}
@Override
public Item blockItem() {
return blockItem.get();
}
}
| package info.u_team.u_team_core.block;
import java.util.function.Supplier;
import info.u_team.u_team_core.api.block.BlockItemProvider;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
public class UBlock extends Block implements BlockItemProvider {
protected final Supplier<Item> blockItem;
public UBlock(Properties properties) {
this(null, properties);
}
public UBlock(CreativeModeTab creativeTab, Properties properties) {
this(creativeTab, properties, null);
}
public UBlock(Properties properties, Item.Properties blockItemProperties) {
this(null, properties, blockItemProperties);
}
public UBlock(CreativeModeTab creativeTab, Properties properties, Item.Properties blockItemProperties) {
super(properties);
blockItem = () -> createBlockItem(blockItemProperties == null ? new Item.Properties().tab(creativeTab) : creativeTab == null ? blockItemProperties : blockItemProperties.tab(creativeTab));
}
protected Item createBlockItem(Item.Properties blockItemProperties) {
return new BlockItem(this, blockItemProperties);
}
@Override
public Item blockItem() {
return blockItem.get();
}
}
|
Connect to unix://data.sock by default | package main
import (
"github.com/codegangsta/cli"
. "github.com/tendermint/go-common"
"github.com/tendermint/tmsp/server"
"os"
application "github.com/tendermint/merkleeyes/app"
)
func main() {
app := cli.NewApp()
app.Name = "cli"
app.Usage = "cli [command] [args...]"
app.Commands = []cli.Command{
{
Name: "server",
Usage: "Run the MerkleEyes server",
Flags: []cli.Flag{
cli.StringFlag{
Name: "address",
Value: "unix://data.sock",
Usage: "MerkleEyes server listen address",
},
},
Action: func(c *cli.Context) {
cmdServer(app, c)
},
},
}
app.Run(os.Args)
}
//--------------------------------------------------------------------------------
func cmdServer(app *cli.App, c *cli.Context) {
addr := c.String("address")
mApp := application.NewMerkleEyesApp()
// Start the listener
_, err := server.StartListener(addr, mApp)
if err != nil {
Exit(err.Error())
}
// Wait forever
TrapSignal(func() {
// Cleanup
})
}
| package main
import (
"github.com/codegangsta/cli"
. "github.com/tendermint/go-common"
"github.com/tendermint/tmsp/server"
"os"
application "github.com/tendermint/merkleeyes/app"
)
func main() {
app := cli.NewApp()
app.Name = "cli"
app.Usage = "cli [command] [args...]"
app.Commands = []cli.Command{
{
Name: "server",
Usage: "Run the MerkleEyes server",
Flags: []cli.Flag{
cli.StringFlag{
Name: "address",
Value: "unix://test.sock",
Usage: "MerkleEyes server listen address",
},
},
Action: func(c *cli.Context) {
cmdServer(app, c)
},
},
}
app.Run(os.Args)
}
//--------------------------------------------------------------------------------
func cmdServer(app *cli.App, c *cli.Context) {
addr := c.String("address")
mApp := application.NewMerkleEyesApp()
// Start the listener
_, err := server.StartListener(addr, mApp)
if err != nil {
Exit(err.Error())
}
// Wait forever
TrapSignal(func() {
// Cleanup
})
}
|
Create session (catch the error) | package main
import (
"flag"
"fmt"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchevents"
)
func main() {
var apply bool
var dryrun bool
flag.BoolVar(&apply, "apply", false, "apply to CloudWatch Events")
flag.BoolVar(&dryrun, "dry-run", false, "dry-run")
flag.Parse()
fmt.Println(apply)
fmt.Println(dryrun)
sess, err := session.NewSession(nil)
if err != nil {
fmt.Errorf("Error %v", err)
}
cwe := cloudwatchevents.New(sess)
result, err := cwe.ListRules(nil)
if err != nil {
fmt.Println("Error", err)
} else {
fmt.Println("Success")
fmt.Println(result)
}
}
| package main
import (
"flag"
"fmt"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchevents"
)
func main() {
var apply bool
var dryrun bool
flag.BoolVar(&apply, "apply", false, "apply to CloudWatch Events")
flag.BoolVar(&dryrun, "dry-run", false, "dry-run")
flag.Parse()
fmt.Println(apply)
fmt.Println(dryrun)
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
cwe := cloudwatchevents.New(sess)
result, err := cwe.ListRules(nil)
if err != nil {
fmt.Println("Error", err)
} else {
fmt.Println("Success")
fmt.Println(result)
}
}
|
Fix protocol in tcp client | var assert = require('assert');
var baseErr = 'geteventstore-promise - TCP client - ';
module.exports = function(config) {
//Assert configuration
assert(config, baseErr + 'config not provided');
assert(config.hostname, baseErr + 'hostname property not provided');
assert(config.port, baseErr + 'port property not provided');
assert(config.credentials, baseErr + 'credentials property not provided');
assert(config.credentials.username, baseErr + 'credentials.username property not provided');
assert(config.credentials.password, baseErr + 'credentials.password property not provided');
//Add additional internal configuration properties
config = JSON.parse(JSON.stringify(config));
config.protocol = 'tcp';
config.auth = config.credentials.username + ':' + config.credentials.password;
return {
writeEvent: require('./writeEvent')(config),
writeEvents: require('./writeEvents')(config),
getAllStreamEvents: require('./getAllStreamEvents')(config),
getEvents: require('./getEvents')(config),
getEventsByType: require('./getEventsByType')(config),
eventEnumerator: require('./eventEnumerator')(config)
};
}; | var assert = require('assert');
var baseErr = 'geteventstore-promise - TCP client - ';
module.exports = function(config) {
//Assert configuration
assert(config, baseErr + 'config not provided');
assert(config.hostname, baseErr + 'hostname property not provided');
assert(config.port, baseErr + 'port property not provided');
assert(config.credentials, baseErr + 'credentials property not provided');
assert(config.credentials.username, baseErr + 'credentials.username property not provided');
assert(config.credentials.password, baseErr + 'credentials.password property not provided');
//Add additional internal configuration properties
config = JSON.parse(JSON.stringify(config));
config.protocol = 'http';
config.auth = config.credentials.username + ':' + config.credentials.password;
return {
writeEvent: require('./writeEvent')(config),
writeEvents: require('./writeEvents')(config),
getAllStreamEvents: require('./getAllStreamEvents')(config),
getEvents: require('./getEvents')(config),
getEventsByType: require('./getEventsByType')(config),
eventEnumerator: require('./eventEnumerator')(config)
};
}; |
Handle non-null falsey keys correctly | import ensureObject from './ensure-object.js';
import isArray from './is-array.js';
import isObject from './is-object.js';
import normalizeField from './normalize-field.js';
import normalizeRoot from './normalize-root.js';
const walk = ({ normalized = {}, data, getKey, query }) => {
if (isArray(data)) {
return data.map(data => walk({ normalized, data, getKey, query }));
}
if (!isObject(data) || data._type === undefined) return data;
const key = getKey?.(data);
const obj = key == null ? {} : (normalized[key] ??= {});
// eslint-disable-next-line no-unused-vars
const { _args, _field, ..._query } = ensureObject(query);
Object.assign(_query, _query[`_on_${data._type}`]);
for (const alias in _query) {
if (data[alias] === undefined) continue;
const query = ensureObject(_query[alias]);
const field = normalizeField({ alias, query });
const value = walk({ normalized, data: data[alias], getKey, query });
obj[field] =
isObject(value) && !isArray(value) && value._type !== 'ref'
? { ...obj[field], ...value }
: value;
}
return key == null ? obj : { _type: '_ref', key };
};
export default ({ data, getKey, query }) => {
const normalized = {};
normalized[normalizeRoot({ query })] = walk({
data,
getKey,
normalized,
query
});
return normalized;
};
| import ensureObject from './ensure-object.js';
import isArray from './is-array.js';
import isObject from './is-object.js';
import normalizeField from './normalize-field.js';
import normalizeRoot from './normalize-root.js';
const walk = ({ normalized = {}, data, getKey, query }) => {
if (isArray(data)) {
return data.map(data => walk({ normalized, data, getKey, query }));
}
if (!isObject(data) || data._type === undefined) return data;
const key = getKey && getKey(data);
const obj = key ? normalized[key] ?? (normalized[key] = {}) : {};
// eslint-disable-next-line no-unused-vars
const { _args, _field, ..._query } = ensureObject(query);
Object.assign(_query, _query[`_on_${data._type}`]);
for (const alias in _query) {
if (data[alias] === undefined) continue;
const query = ensureObject(_query[alias]);
const field = normalizeField({ alias, query });
const value = walk({ normalized, data: data[alias], getKey, query });
obj[field] =
isObject(value) && !isArray(value) && value._type !== 'ref'
? { ...obj[field], ...value }
: value;
}
return key ? { _type: '_ref', key } : obj;
};
export default ({ data, getKey, query }) => {
const normalized = {};
normalized[normalizeRoot({ query })] = walk({
data,
getKey,
normalized,
query
});
return normalized;
};
|
Disable StandardJS in Grunt to fix builds | module.exports = function (grunt) {
var standaloneFiles = [
'bower_components/sockjs-client/dist/sockjs.min.js',
'bower_components/stomp-websocket/lib/stomp.min.js',
'src/ng-stomp.js'
]
grunt.initConfig({
fileExists: {
scripts: standaloneFiles
},
uglify: {
main: {
options: {
preserveComments: 'some'
},
files: {
'dist/ng-stomp.min.js': ['src/ng-stomp.js'],
'dist/ng-stomp.standalone.min.js': standaloneFiles
}
}
}
})
grunt.loadNpmTasks('grunt-file-exists')
grunt.loadNpmTasks('grunt-contrib-uglify')
grunt.registerTask('default', ['fileExists', 'uglify'])
}
| module.exports = function (grunt) {
var standaloneFiles = [
'bower_components/sockjs-client/dist/sockjs.min.js',
'bower_components/stomp-websocket/lib/stomp.min.js',
'src/ng-stomp.js'
]
grunt.initConfig({
fileExists: {
scripts: standaloneFiles
},
uglify: {
main: {
options: {
preserveComments: 'some'
},
files: {
'dist/ng-stomp.min.js': ['src/ng-stomp.js'],
'dist/ng-stomp.standalone.min.js': standaloneFiles
}
}
},
standard: {
options: {
format: true
},
app: {
src: ['ng-stomp.js']
}
}
})
grunt.loadNpmTasks('grunt-file-exists')
grunt.loadNpmTasks('grunt-contrib-uglify')
grunt.loadNpmTasks('grunt-standard')
grunt.registerTask('default', ['standard', 'fileExists', 'uglify'])
}
|
Disable caching of identical images | import logging
import yorm
from yorm.types import List, Object
log = logging.getLogger(__name__)
@yorm.attr(items=List.of_type(Object))
@yorm.sync("data/images/cache.yml")
class Cache:
SIZE = 9
def __init__(self):
self.items = []
def add(self, **kwargs):
if kwargs['key'] == 'custom' or kwargs in self.items:
return
log.info("Caching: %s", kwargs)
self.items.insert(0, kwargs)
while len(self.items) > self.SIZE:
self.items.pop()
yorm.save(self)
def get(self, index):
log.info("Getting cache index: %s", index)
try:
data = self.items[index]
except IndexError:
data = {}
log.info("Retrieved cache: %s", data)
return data
| import logging
import yorm
from yorm.types import List, Object
log = logging.getLogger(__name__)
@yorm.attr(items=List.of_type(Object))
@yorm.sync("data/images/cache.yml")
class Cache:
SIZE = 9
def __init__(self):
self.items = []
def add(self, **kwargs):
if kwargs['key'] == 'custom':
return
log.info("Caching: %s", kwargs)
self.items.insert(0, kwargs)
while len(self.items) > self.SIZE:
self.items.pop()
yorm.save(self)
def get(self, index):
log.info("Getting cache index: %s", index)
try:
data = self.items[index]
except IndexError:
data = {}
log.info("Retrieved cache: %s", data)
return data
|
Add client part of package | from distutils.core import setup
setup(
name='xirvik-tools',
version='0.0.2',
author='Fa An',
author_email='2998784916@qq.com',
packages=['xirvik', 'xirvik.client'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
| from distutils.core import setup
setup(
name='xirvik-tools',
version='0.0.1',
author='Fa An',
author_email='2998784916@qq.com',
packages=['xirvik'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
|
Validate user exists before sending its info out | <?php
$u = new User();
if ($u->getUserID()) {
$ui = UserInfo::getByID($u->getUserID());
$userInfo = [
'name' => $u->getUserName(),
'firstName' => $ui->getAttribute('first_name')
];
}
// Capture renderable areas
ob_start();
(new GlobalArea('Left Header'))->display($c);
$LeftHeader = ['Left Header' => ob_get_clean()];
ob_start();
(new GlobalArea('Dropdown'))->display($c);
$Dropdown = ['Dropdown' => ob_get_clean()];
?>
<script>
JanesWalk.event.emit('user.receive', <?= json_encode($userInfo) ?>);
JanesWalk.event.emit('area.receive', <?= json_encode($LeftHeader) ?>);
JanesWalk.event.emit('area.receive', <?= json_encode($Dropdown) ?>);
</script>
<span id="navbar"></span>
| <?php
$u = new User();
$ui = UserInfo::getByID($u->getUserID());
if ($u) {
$userInfo = [
'name' => $u->getUserName(),
'firstName' => $ui->getAttribute('first_name')
];
}
// Capture renderable areas
ob_start();
(new GlobalArea('Left Header'))->display($c);
$LeftHeader = ['Left Header' => ob_get_clean()];
ob_start();
(new GlobalArea('Dropdown'))->display($c);
$Dropdown = ['Dropdown' => ob_get_clean()];
?>
<script>
JanesWalk.event.emit('user.receive', <?= json_encode($userInfo) ?>);
JanesWalk.event.emit('area.receive', <?= json_encode($LeftHeader) ?>);
JanesWalk.event.emit('area.receive', <?= json_encode($Dropdown) ?>);
</script>
<span id="navbar"></span>
|
Put the crawled link into the database | import requests
import re
import os
url = "https://www.autohome.com.cn/shanghai/"
urlBox = []
def catchURL(url):
file = requests.get(url,timeout=5)
data = file.content
links = re.findall(r'(https?://[^\s)";]+\.(\w|/)*)',str(data))
for i in links:
try:
currentURL = i[0]
if currentURL not in urlBox:
urlBox.append(currentURL)
sql = """
ssh pgadmin@10.211.55.8 psql test -U pgadmin << EOF
insert into url values(nextval(\'url_seq\'), \'"""+currentURL+"""\');
EOF
"""
print(sql)
os.popen(sql)
print(currentURL)
catchURL(currentURL)
except Exception as e:
pass
continue
catchURL(url) | import requests
import re
import os
url = "https://www.autohome.com.cn/shanghai/"
urlBox = []
def catchURL(url):
file = requests.get(url,timeout=2)
data = file.content
links = re.findall(r'(https?://[^\s)";]+\.(\w|/)*)',str(data))
for i in links:
try:
currentURL = i[0]
if currentURL not in urlBox:
urlBox.append(currentURL)
os.system("ssh pgadmin@10.211.55.8 psql test -c \
'insert into url values(nextval('url_seq'), '"+ currentURL +"')'")
print(currentURL)
catchURL(currentURL)
except Exception as e:
pass
continue
catchURL(url) |
Fix Python 3 incompatible super constructor invocation.
Summary: Python is a mess and requires all sorts of hacks to work :(
Reviewed By: philipjameson
fbshipit-source-id: 12f3f59a0d | from __future__ import absolute_import, division, print_function, with_statement
import collections
from json import JSONEncoder
# A JSONEncoder subclass which handles map-like and list-like objects.
class BuckJSONEncoder(JSONEncoder):
def __init__(self):
super(BuckJSONEncoder, self).__init__()
def default(self, obj):
if isinstance(obj, collections.Mapping) and isinstance(
obj, collections.Sized
): # nopep8
return dict(obj)
elif isinstance(obj, collections.Iterable) and isinstance(
obj, collections.Sized
):
return list(obj)
else:
return super(BuckJSONEncoder, self).default(obj)
| from __future__ import absolute_import, division, print_function, with_statement
import collections
from json import JSONEncoder
# A JSONEncoder subclass which handles map-like and list-like objects.
class BuckJSONEncoder(JSONEncoder):
def __init__(self):
super(BuckJSONEncoder, self).__init__(self)
def default(self, obj):
if isinstance(obj, collections.Mapping) and isinstance(
obj, collections.Sized
): # nopep8
return dict(obj)
elif isinstance(obj, collections.Iterable) and isinstance(
obj, collections.Sized
):
return list(obj)
else:
return super(BuckJSONEncoder, self).default(obj)
|
Format with tabs, add missing comma | package aws
import (
"testing"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccAWSBillingServiceAccount_basic(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccCheckAwsBillingServiceAccountConfig,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("data.aws_billing_service_account.main", "id", "386209384616"),
resource.TestCheckResourceAttr("data.aws_billing_service_account.main", "arn", "arn:aws:iam::386209384616:root"),
),
},
},
})
}
const testAccCheckAwsBillingServiceAccountConfig = `
data "aws_billing_service_account" "main" { }
`
| package aws
import (
"testing"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccAWSBillingServiceAccount_basic(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccCheckAwsBillingServiceAccountConfig,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("data.aws_billing_service_account.main", "id", "386209384616"),
resource.TestCheckResourceAttr("data.aws_billing_service_account.main", "arn", "arn:aws:iam::386209384616:root"),
),
}
},
})
}
const testAccCheckAwsBillingServiceAccountConfig = `
data "aws_billing_service_account" "main" { }
`
|
Make gunicorn log to stdout/stderr | import click
import os
from .app import app
from .server import StandaloneServer
@click.command()
@click.option(
'--port',
default=8000,
help='Port to listen on, default is 8000'
)
@click.option(
'--upload-dir',
default=os.getcwd(),
help='Directory where uploads are stored, if not specified the current working directory will be used'
)
@click.option(
'--baseurl',
default=None,
help='Base URL, e.g. http://example.com/'
)
def main(port, upload_dir, baseurl):
if baseurl is None:
baseurl = 'http://{host}:{port}/'.format(host='localhost', port=port)
click.echo(
click.style('You did not specify a Base URL, using default: ' + baseurl, fg='yellow')
)
app.config['UPLOAD_DIR'] = upload_dir
app.config['BASE_URL'] = baseurl
server_options = {
'bind': '{ip}:{port}'.format(
ip='0.0.0.0',
port=port
),
'workers': 4,
'accesslog': '-',
'errorlog': '-'
}
StandaloneServer(app, server_options).run()
if __name__ == '__main__':
main()
| import click
import os
from .app import app
from .server import StandaloneServer
@click.command()
@click.option(
'--port',
default=8000,
help='Port to listen on, default is 8000'
)
@click.option(
'--upload-dir',
default=os.getcwd(),
help='Directory where uploads are stored, if not specified the current working directory will be used'
)
@click.option(
'--baseurl',
default=None,
help='Base URL, e.g. http://example.com/'
)
def main(port, upload_dir, baseurl):
if baseurl is None:
baseurl = 'http://{host}:{port}/'.format(host='localhost', port=port)
click.echo(
click.style('You did not specify a Base URL, using default: ' + baseurl, fg='yellow')
)
app.config['UPLOAD_DIR'] = upload_dir
app.config['BASE_URL'] = baseurl
server_options = {
'bind': '{ip}:{port}'.format(
ip='0.0.0.0',
port=port
),
'workers': 4,
}
StandaloneServer(app, server_options).run()
if __name__ == '__main__':
main() |
Set webkit-appearance to none on submit button. | import React, { Component } from "react";
import styled from "styled-components";
class SubmitButton extends Component {
render() {
const {
isShowingPositive,
onNegativeClick,
onPositiveClick,
disabled,
positiveText,
negativeText
} = this.props;
return (
<StyledSubmitButton
disabled={disabled}
type="button"
value={isShowingPositive ? positiveText : negativeText}
onClick={isShowingPositive ? onPositiveClick : onNegativeClick}
/>
);
}
}
export const StyledSubmitButton = styled.input`
-webkit-appearance: none;
background-color: #00a8e2;
transition: background-color 0.25s ease-out, color 0.25s ease-out;
color: #fff;
border: none;
outline: none;
padding: 15px 45px;
font-size: 1.1em;
:hover {
cursor: pointer;
background-color: #0090c2;
}
:active {
background-color: #006b8f;
}
:disabled {
background-color: #c4c4c4;
}
`;
export default SubmitButton;
| import React, { Component } from "react";
import styled from "styled-components";
class SubmitButton extends Component {
render() {
const {
isShowingPositive,
onNegativeClick,
onPositiveClick,
disabled,
positiveText,
negativeText
} = this.props;
return (
<StyledSubmitButton
disabled={disabled}
type="button"
value={isShowingPositive ? positiveText : negativeText}
onClick={isShowingPositive ? onPositiveClick : onNegativeClick}
/>
);
}
}
export const StyledSubmitButton = styled.input`
background-color: #00a8e2;
transition: background-color 0.25s ease-out, color 0.25s ease-out;
color: #fff;
border: none;
outline: none;
padding: 15px 45px;
font-size: 1.1em;
:hover {
cursor: pointer;
background-color: #0090c2;
}
:active {
background-color: #006b8f;
}
:disabled {
background-color: #c4c4c4;
}
`;
export default SubmitButton;
|
Add some more startup logging | package pl.mkrystek.mkbot;
import static org.springframework.boot.Banner.Mode.OFF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
public class Main {
private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext ctx = new SpringApplicationBuilder().bannerMode(OFF).web(false).logStartupInfo(false)
.sources(BotApplicationConfiguration.class).headless(false).run(args);
LOGGER.debug("Application started!");
BotApplication application = ctx.getBean(BotApplication.class);
try {
application.init();
application.startApplication();
} catch (Exception e) {
LOGGER.error("Error : ", e);
} finally {
LOGGER.debug("Shutting down application");
if (application != null) application.shutdown();
}
}
}
| package pl.mkrystek.mkbot;
import static org.springframework.boot.Banner.Mode.OFF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
public class Main {
private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext ctx = new SpringApplicationBuilder().bannerMode(OFF).web(false).logStartupInfo(false)
.sources(BotApplicationConfiguration.class).headless(false).run(args);
BotApplication application = ctx.getBean(BotApplication.class);
try {
application.init();
application.startApplication();
} catch (Exception e) {
LOGGER.error("Error : ", e);
} finally {
if (application != null) application.shutdown();
}
}
}
|
Refactor selection sort w/ adding comments | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(ls):
"""Selection Sort algortihm.
Time complexity: O(n^2).
Space complexity: O(1).
"""
# Start from the last elemenet reversely: len(ls) - 1, ..., 0.
for i_max in reversed(range(len(ls))):
# Select the next max, and interchange it with corresponding element.
s = 0
for i in range(1, i_max + 1):
if ls[i] > ls[s]:
s = i
ls[s], ls[i_max] = ls[i_max], ls[s]
def main():
ls = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('List: {}'.format(ls))
print('By selection sort: ')
selection_sort(ls)
print(ls)
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(a_list):
"""Selection Sort algortihm.
Time complexity: O(n^2).
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
a_list[select_slot], a_list[max_slot] = (
a_list[max_slot], a_list[select_slot])
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
|
Check `instanceof Foo` instead of `instanceof Object`.
The latter is entirely equivalent to a null check. Thus, if the result
is `false`, tools may want to recognize that the value is `null`.
Perhaps there should be a sample that checks just that, but `instanceof
Object` is rare enough that recognizing it is more of a "nice to have"
than an essential. (We already try to avoid assuming most dataflow logic
in our samples, but we've made exceptions for common cases that we
expect ~every tool to want to recognize.)
Fixes https://github.com/jspecify/jspecify/issues/164 | /*
* Copyright 2020 The JSpecify Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by 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.
*/
import org.jspecify.annotations.DefaultNonNull;
import org.jspecify.annotations.Nullable;
import org.jspecify.annotations.NullnessUnspecified;
@DefaultNonNull
class InstanceOfCheck {
Object x0(Object o) {
if (o instanceof Foo) {
return o;
} else {
return o;
}
}
Object x1(@NullnessUnspecified Object o) {
if (o instanceof Foo) {
return o;
} else {
// jspecify_nullness_not_enough_information
return o;
}
}
Object x2(@Nullable Object o) {
if (o instanceof Foo) {
return o;
} else {
// jspecify_nullness_mismatch
return o;
}
}
class Foo {}
}
| /*
* Copyright 2020 The JSpecify Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by 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.
*/
import org.jspecify.annotations.DefaultNonNull;
import org.jspecify.annotations.Nullable;
import org.jspecify.annotations.NullnessUnspecified;
@DefaultNonNull
class InstanceOfCheck {
Object x0(Object o) {
if (o instanceof Object) {
return o;
} else {
return o;
}
}
Object x1(@NullnessUnspecified Object o) {
if (o instanceof Object) {
return o;
} else {
// jspecify_nullness_not_enough_information
return o;
}
}
Object x2(@Nullable Object o) {
if (o instanceof Object) {
return o;
} else {
// jspecify_nullness_mismatch
return o;
}
}
}
|
Add compat/ files in packaging | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from config import get_version
from distutils.command.install import INSTALL_SCHEMES
setup(name='datadog-agent',
version=get_version(),
description='Datatadog monitoring agent',
author='Datadog',
author_email='info@datadoghq.com',
url='http://datadoghq.com/',
packages=['checks', 'checks/db', 'resources', 'compat'],
package_data={'checks': ['libs/*']},
scripts=['agent.py', 'daemon.py', 'minjson.py', 'util.py', 'emitter.py', 'config.py'],
data_files=[('/etc/dd-agent/', ['datadog.conf.example']),
('/etc/init.d', ['redhat/datadog-agent'])]
)
| #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from config import get_version
from distutils.command.install import INSTALL_SCHEMES
setup(name='datadog-agent',
version=get_version(),
description='Datatadog monitoring agent',
author='Datadog',
author_email='info@datadoghq.com',
url='http://datadoghq.com/',
packages=['checks', 'checks/db', 'resources'],
package_data={'checks': ['libs/*']},
scripts=['agent.py', 'daemon.py', 'minjson.py', 'util.py', 'emitter.py', 'config.py'],
data_files=[('/etc/dd-agent/', ['datadog.conf.example']),
('/etc/init.d', ['redhat/datadog-agent'])]
)
|
Add new validity state for games unranked by host | package com.faforever.api.data.domain;
public enum Validity {
// Order is crucial
VALID,
TOO_MANY_DESYNCS,
WRONG_VICTORY_CONDITION,
NO_FOG_OF_WAR,
CHEATS_ENABLED,
PREBUILT_ENABLED,
NORUSH_ENABLED,
BAD_UNIT_RESTRICTIONS,
BAD_MAP,
TOO_SHORT,
BAD_MOD,
COOP_NOT_RANKED,
MUTUAL_DRAW,
SINGLE_PLAYER,
FFA_NOT_RANKED,
UNEVEN_TEAMS_NOT_RANKED,
UNKNOWN_RESULT,
TEAMS_UNLOCKED,
MULTIPLE_TEAMS,
HAS_AI,
CIVILIANS_REVEALED,
WRONG_DIFFICULTY,
EXPANSION_DISABLED,
SPAWN_NOT_FIXED,
OTHER_UNRANK,
UNRANKED_BY_HOST
}
| package com.faforever.api.data.domain;
public enum Validity {
// Order is crucial
VALID,
TOO_MANY_DESYNCS,
WRONG_VICTORY_CONDITION,
NO_FOG_OF_WAR,
CHEATS_ENABLED,
PREBUILT_ENABLED,
NORUSH_ENABLED,
BAD_UNIT_RESTRICTIONS,
BAD_MAP,
TOO_SHORT,
BAD_MOD,
COOP_NOT_RANKED,
MUTUAL_DRAW,
SINGLE_PLAYER,
FFA_NOT_RANKED,
UNEVEN_TEAMS_NOT_RANKED,
UNKNOWN_RESULT,
TEAMS_UNLOCKED,
MULTIPLE_TEAMS,
HAS_AI,
CIVILIANS_REVEALED,
WRONG_DIFFICULTY,
EXPANSION_DISABLED,
SPAWN_NOT_FIXED,
OTHER_UNRANK
}
|
Update mozci version to handle credentials in env variables | from setuptools import setup, find_packages
deps = [
'mozillapulse',
'mozci>=0.7.3',
'requests',
]
setup(name='pulse-actions',
version='0.1.4',
description='A pulse listener that acts upon messages with mozci.',
classifiers=['Intended Audience :: Developers',
'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
author='Alice Scarpa',
author_email='alicescarpa@gmail.com',
license='MPL 2.0',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=deps,
url='https://github.com/adusca/pulse_actions',
entry_points={
'console_scripts': [
'run-pulse-actions = pulse_actions.worker:main'
],
})
| from setuptools import setup, find_packages
deps = [
'mozillapulse',
'mozci>=0.7.0',
'requests',
]
setup(name='pulse-actions',
version='0.1.4',
description='A pulse listener that acts upon messages with mozci.',
classifiers=['Intended Audience :: Developers',
'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
author='Alice Scarpa',
author_email='alicescarpa@gmail.com',
license='MPL 2.0',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=deps,
url='https://github.com/adusca/pulse_actions',
entry_points={
'console_scripts': [
'run-pulse-actions = pulse_actions.worker:main'
],
})
|
Make all spacings consistent to all other files | const config = require('../config.js')
const routes = require('express').Router()
const uploadController = require('../controllers/uploadController')
const galleryController = require('../controllers/galleryController')
routes.get('/check', (req, res, next) => {
if(config.TOKEN === '')
return res.json({token: false})
return res.json({token: true})
})
routes.get('/info', (req, res, next) => {
if(config.TOKEN !== '')
if(req.headers.auth !== config.TOKEN)
return res.status(401).send('not-authorized')
return res.json({
maxFileSize: config.uploads.maxsize.slice(0, -2)
})
})
routes.post('/upload', (req, res, next) => uploadController.upload(req, res, next))
routes.get('/gallery', (req, res, next) => galleryController.list(req, res, next))
routes.get('/gallery/test', (req, res, next) => galleryController.test(req, res, next))
module.exports = routes
| const config = require('../config.js')
const routes = require('express').Router()
const uploadController = require('../controllers/uploadController')
const galleryController = require('../controllers/galleryController')
routes.get ('/check', (req, res, next) => {
if(config.TOKEN === '')
return res.json({token: false})
return res.json({token: true})
})
routes.get ('/info', (req, res, next) => {
if(config.TOKEN !== '')
if(req.headers.auth !== config.TOKEN)
return res.status(401).send('not-authorized')
return res.json({
maxFileSize: config.uploads.maxsize.slice(0, -2)
})
})
routes.post ('/upload', (req, res, next) => uploadController.upload(req, res, next))
routes.get ('/gallery', (req, res, next) => galleryController.list(req, res, next))
routes.get ('/gallery/test', (req, res, next) => galleryController.test(req, res, next))
module.exports = routes
|
Add colon to loggable URL pattern | export const PAUSE_STORAGE_KEY = 'is-logging-paused'
export function isLoggable({ url }) {
// Just remember http(s) pages, ignoring data uris, newtab, ...
const loggableUrlPattern = /^https?:\/\/\w+([-/.#=:$^@&%?+(),]\w*\/?)*$/
const urlEndings = ['.svg', '.jpg', '.png', '.jpeg', '.gif']
// Ignore all pages that are image files
for (let i = 0; i < urlEndings.length; i++) {
if (url.endsWith(urlEndings[i])) {
return false
}
}
return loggableUrlPattern.test(url)
}
export const getPauseState = async () => {
const state = (await browser.storage.local.get(PAUSE_STORAGE_KEY))[
PAUSE_STORAGE_KEY
]
switch (state) {
case 0:
case 1:
return true
case 2:
default:
return false
}
}
| export const PAUSE_STORAGE_KEY = 'is-logging-paused'
export function isLoggable({ url }) {
// Just remember http(s) pages, ignoring data uris, newtab, ...
const loggableUrlPattern = /^https?:\/\/\w+([-/.#=$^@&%?+(),]\w*\/?)*$/
const urlEndings = ['.svg', '.jpg', '.png', '.jpeg', '.gif']
// Ignore all pages that are image files
for (let i = 0; i < urlEndings.length; i++) {
if (url.endsWith(urlEndings[i])) {
return false
}
}
return loggableUrlPattern.test(url)
}
export const getPauseState = async () => {
const state = (await browser.storage.local.get(PAUSE_STORAGE_KEY))[
PAUSE_STORAGE_KEY
]
switch (state) {
case 0:
case 1:
return true
case 2:
default:
return false
}
}
|
Remove `tokens` and `upload` for now
until we figure out the problem with bower in `postinstall` as detailed
in #92 | 'use strict';
var inquirer = require('inquirer'),
_ = require('lodash');
// callback must be in form of function(results)
module.exports = function(options, callback) {
function required(value) {
return !!value.trim() || 'Required';
}
var questions = [{
type: 'input',
name: 'name',
message: 'What would you name your mean app?',
default: options.name,
validate: required
}, {
type: 'list',
name: 'taskrunner',
message: 'Do you prefer grunt or gulp as a taskrunner?',
default: 'grunt',
choices: ['grunt', 'gulp'],
validate: required
}, {
type: 'checkbox',
name: 'meanDeps',
message: 'Which mean packages would you like to install?',
choices: [
{
name: 'mean-admin',
checked: true
}
]
}];
inquirer.prompt(questions, function(results) {
_.assign(options, results);
callback(options);
});
};
| 'use strict';
var inquirer = require('inquirer'),
_ = require('lodash');
// callback must be in form of function(results)
module.exports = function(options, callback) {
function required(value) {
return !!value.trim() || 'Required';
}
var questions = [{
type: 'input',
name: 'name',
message: 'What would you name your mean app?',
default: options.name,
validate: required
}, {
type: 'list',
name: 'taskrunner',
message: 'Do you prefer grunt or gulp as a taskrunner?',
default: 'grunt',
choices: ['grunt', 'gulp'],
validate: required
}, {
type: 'checkbox',
name: 'meanDeps',
message: 'Which mean packages would you like to install?',
choices: [
{
name: 'mean-admin',
checked: true
}, {
name: 'tokens'
}, {
name: 'upload'
}
]
}];
inquirer.prompt(questions, function(results) {
_.assign(options, results);
callback(options);
});
};
|
Maintain aspect ratio of registered image | package httpimg_test
import (
"github.com/jung-kurt/gofpdf"
"github.com/jung-kurt/gofpdf/contrib/httpimg"
"github.com/jung-kurt/gofpdf/internal/example"
)
func ExampleRegister() {
pdf := gofpdf.New("L", "mm", "A4", "")
pdf.SetFont("Helvetica", "", 12)
pdf.SetFillColor(200, 200, 220)
pdf.AddPage()
url := "https://github.com/jung-kurt/gofpdf/raw/master/image/logo_gofpdf.jpg?raw=true"
httpimg.Register(pdf, url, "")
pdf.Image(url, 15, 15, 267, 0, false, "", 0, "")
fileStr := example.Filename("contrib_httpimg_Register")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
// Output:
// Successfully generated ../../pdf/contrib_httpimg_Register.pdf
}
| package httpimg_test
import (
"github.com/jung-kurt/gofpdf"
"github.com/jung-kurt/gofpdf/contrib/httpimg"
"github.com/jung-kurt/gofpdf/internal/example"
)
func ExampleRegister() {
pdf := gofpdf.New("", "", "", "")
pdf.SetFont("Helvetica", "", 12)
pdf.SetFillColor(200, 200, 220)
pdf.AddPage()
url := "https://github.com/jung-kurt/gofpdf/raw/master/image/logo_gofpdf.jpg?raw=true"
httpimg.Register(pdf, url, "")
pdf.Image(url, 100, 100, 20, 20, false, "", 0, "")
fileStr := example.Filename("contrib_httpimg_Register")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
// Output:
// Successfully generated ../../pdf/contrib_httpimg_Register.pdf
}
|
Add code explanation about baseDate variable | export default function getCalendarMonthWeeks(month, enableOutsideDays) {
// set utc offset to get correct dates in future (when timezone changes)
const baseDate = month.clone().utcOffset(month.utcOffset());
const firstOfMonth = baseDate.clone().startOf('month');
const lastOfMonth = baseDate.clone().endOf('month');
const currentDay = firstOfMonth.clone();
let currentWeek = [];
const weeksInMonth = [];
// days belonging to the previous month
for (let i = 0; i < currentDay.weekday(); i++) {
const prevDay = enableOutsideDays && currentDay.clone().subtract(i + 1, 'day');
currentWeek.unshift(prevDay);
}
while (currentDay < lastOfMonth) {
currentWeek.push(currentDay.clone());
currentDay.add(1, 'd');
if (currentDay.weekday() === 0) {
weeksInMonth.push(currentWeek);
currentWeek = [];
}
}
// days belonging to the next month
for (let k = currentDay.weekday(), count = 0; k < 7; k++, count++) {
const nextDay = enableOutsideDays && currentDay.clone().add(count, 'day');
currentWeek.push(nextDay);
}
weeksInMonth.push(currentWeek);
return weeksInMonth;
}
| export default function getCalendarMonthWeeks(month, enableOutsideDays) {
const baseDate = month.clone().utcOffset(month.utcOffset());
const firstOfMonth = baseDate.clone().startOf('month');
const lastOfMonth = baseDate.clone().endOf('month');
const currentDay = firstOfMonth.clone();
let currentWeek = [];
const weeksInMonth = [];
// days belonging to the previous month
for (let i = 0; i < currentDay.weekday(); i++) {
const prevDay = enableOutsideDays && currentDay.clone().subtract(i + 1, 'day');
currentWeek.unshift(prevDay);
}
while (currentDay < lastOfMonth) {
currentWeek.push(currentDay.clone());
currentDay.add(1, 'd');
if (currentDay.weekday() === 0) {
weeksInMonth.push(currentWeek);
currentWeek = [];
}
}
// days belonging to the next month
for (let k = currentDay.weekday(), count = 0; k < 7; k++, count++) {
const nextDay = enableOutsideDays && currentDay.clone().add(count, 'day');
currentWeek.push(nextDay);
}
weeksInMonth.push(currentWeek);
return weeksInMonth;
}
|
Fix name error in setting daemon | from threading import Timer
from . import track
_listeners = []
class TrackChecker():
def __init__(self, interval = 5):
self.listeners = []
self.CHECK_INTERVAL = interval
self.currentSong = ""
self.currentArtist = ""
self.currentAlbum = ""
self.timer = None
def checkSong(self):
song = track.getCurrentSong()
artist = track.getCurrentArtist()
album = track.getCurrentAlbum()
if (song != self.currentSong or artist != self.currentArtist
or album != self.currentAlbum):
self.currentSong = song
self.currentArtist = artist
self.currentAlbum = album
self._callListeners()
if self.timer != None:
self.startTimer()
def registerListener(self, function):
_listeners.append(function)
def _callListeners(self):
for listener in _listeners:
listener()
def startTimer(self):
self.timer = Timer(self.CHECK_INTERVAL, self.checkSong)
self.timer.daemon = True
self.timer.start()
def cancelTimer(self):
self.timer.cancel()
self.timer = None
| from threading import Timer
from . import track
_listeners = []
class TrackChecker():
def __init__(self, interval = 5):
self.listeners = []
self.CHECK_INTERVAL = interval
self.currentSong = ""
self.currentArtist = ""
self.currentAlbum = ""
self.timer = None
def checkSong(self):
song = track.getCurrentSong()
artist = track.getCurrentArtist()
album = track.getCurrentAlbum()
if (song != self.currentSong or artist != self.currentArtist
or album != self.currentAlbum):
self.currentSong = song
self.currentArtist = artist
self.currentAlbum = album
self._callListeners()
if self.timer != None:
self.startTimer()
def registerListener(self, function):
_listeners.append(function)
def _callListeners(self):
for listener in _listeners:
listener()
def startTimer(self):
self.timer = Timer(self.CHECK_INTERVAL, self.checkSong)
timer.daemon = True
self.timer.start()
def cancelTimer(self):
self.timer.cancel()
self.timer = None
|
Support Thunderbird 52 and later | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var AddHasAttachmentHeaderCompose = {
HEADER: 'X-Mozilla-Has-Attachment',
addHeader: function(aCompFields) {
// You don't need to remove old value (for mails generated by "edit as new",
// or edited from a draft) because custom header is automatically overridden
// with the latest value.
aCompFields.setHeader(this.HEADER, this.headerValue);
},
get headerValue() {
var attachmentsBacket = GetMsgAttachmentElement();
var attachmentsCount = attachmentsBacket.itemCount;
return attachmentsCount > 0 ? 'yes' : 'no';
}
};
(function() {
var originalRecipients2CompFields = window.Recipients2CompFields;
window.Recipients2CompFields = function Recipients2CompFields(aCompFields) {
var returnValue = originalRecipients2CompFields.apply(this, arguments);
AddHasAttachmentHeaderCompose.addHeader(aCompFields);
return returnValue;
};
})();
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var AddHasAttachmentHeaderCompose = {
HEADER: 'X-Mozilla-Has-Attachment',
addHeader: function(aCompFields) {
// You don't need to remove old value (for mails generated by "edit as new",
// or edited from a draft) because custom header is automatically overridden
// with the latest value.
aCompFields.otherRandomHeaders += this.HEADER + ': '+ this.headerValue + '\r\n';
},
get headerValue() {
var attachmentsBacket = GetMsgAttachmentElement();
var attachmentsCount = attachmentsBacket.itemCount;
return attachmentsCount > 0 ? 'yes' : 'no';
}
};
(function() {
var originalRecipients2CompFields = window.Recipients2CompFields;
window.Recipients2CompFields = function Recipients2CompFields(aCompFields) {
var returnValue = originalRecipients2CompFields.apply(this, arguments);
AddHasAttachmentHeaderCompose.addHeader(aCompFields);
return returnValue;
};
})();
|
Enable zip64 to store tracks larger than 2GB. | #!/usr/bin/env python
import zipfile
import cPickle
import numpy as np
"""
track_obj: {
frames: 1 by n numpy array,
anchors: 1 by n numpy array,
features: m by n numpy array,
scores: c by n numpy array,
boxes: 4 by n numpy array,
rois: 4 by n numpy array
}
"""
def save_track_proto_to_zip(track_proto, save_file):
zf = zipfile.ZipFile(save_file, 'w', allowZip64=True)
print "Writing to zip file {}...".format(save_file)
for track_id, track in enumerate(track_proto['tracks']):
track_obj = {}
for key in track[0]:
track_obj[key] = np.asarray([box[key] for box in track])
zf.writestr('{:06d}.pkl'.format(track_id),
cPickle.dumps(track_obj, cPickle.HIGHEST_PROTOCOL))
if (track_id + 1) % 1000 == 0:
print "\t{} tracks written.".format(track_id + 1)
print "\tTotally {} tracks written.".format(track_id + 1)
zf.close()
| #!/usr/bin/env python
import zipfile
import cPickle
import numpy as np
"""
track_obj: {
frames: 1 by n numpy array,
anchors: 1 by n numpy array,
features: m by n numpy array,
scores: c by n numpy array,
boxes: 4 by n numpy array,
rois: 4 by n numpy array
}
"""
def save_track_proto_to_zip(track_proto, save_file):
zf = zipfile.ZipFile(save_file, 'w')
print "Writing to zip file {}...".format(save_file)
for track_id, track in enumerate(track_proto['tracks']):
track_obj = {}
for key in track[0]:
track_obj[key] = np.asarray([box[key] for box in track])
zf.writestr('{:06d}.pkl'.format(track_id),
cPickle.dumps(track_obj, cPickle.HIGHEST_PROTOCOL))
if (track_id + 1) % 1000 == 0:
print "\t{} tracks written.".format(track_id + 1)
print "\tTotally {} tracks written.".format(track_id + 1)
zf.close()
|
Make the tested service configurable | // WikiPathways Java library,
// Copyright 2014-2015 WikiPathways
//
// 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.wikipathways.client.test.utils;
import java.net.URL;
import org.wikipathways.client.WikiPathwaysClient;
public class ConnectionSettings {
public static WikiPathwaysClient createClient() throws Exception {
String urlStr = System.getProperty("url", "https://rcbranch.wikipathways.org/wpi/webservicetest");
// URL url = new URL("http://webservice.wikipathways.org");
URL url = new URL(urlStr);
return new WikiPathwaysClient(url);
}
}
| // WikiPathways Java library,
// Copyright 2014-2015 WikiPathways
//
// 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.wikipathways.client.test.utils;
import java.net.URL;
import org.wikipathways.client.WikiPathwaysClient;
public class ConnectionSettings {
public static WikiPathwaysClient createClient() throws Exception {
// URL url = new URL("http://webservice.wikipathways.org");
URL url = new URL("https://rcbranch.wikipathways.org/wpi/webservicetest");
return new WikiPathwaysClient(url);
}
}
|
Add accessor for item on a note | <?php
namespace Scat;
class Note extends \Model implements \JsonSerializable {
public function txn() {
if ($this->kind == 'txn') {
return $this->belongs_to('Txn', 'attach_id')->find_one();
}
}
public function about() {
if ($this->kind == 'txn') {
return $this->belongs_to('Txn', 'attach_id')->find_one()->owner();
}
if ($this->kind == 'person') {
return $this->belongs_to('Person', 'attach_id')->find_one();
}
}
public function item() {
if ($this->kind == 'item') {
return $this->belongs_to('Item', 'attach_id')->find_one();
}
}
public function person() {
return $this->belongs_to('Person');
}
public function parent() {
return $this->belongs_to('Note', 'parent_id');
}
public function jsonSerialize() {
return $this->as_array();
}
}
| <?php
namespace Scat;
class Note extends \Model implements \JsonSerializable {
public function txn() {
if ($this->kind == 'txn') {
return $this->belongs_to('Txn', 'attach_id')->find_one();
}
}
public function about() {
if ($this->kind == 'txn') {
return $this->belongs_to('Txn', 'attach_id')->find_one()->owner();
}
if ($this->kind == 'person') {
return $this->belongs_to('Person', 'attach_id')->find_one();
}
}
public function person() {
return $this->belongs_to('Person');
}
public function parent() {
return $this->belongs_to('Note', 'parent_id');
}
public function jsonSerialize() {
return $this->as_array();
}
}
|
Mark dependencies on recent core and datamodel versions. | #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='example_ppp_module',
version='0.1',
description='Example python module for the PPP.',
url='https://github.com/ProjetPP',
author='Valentin Lorentz',
author_email='valentin.lorentz+ppp@ens-lyon.org',
license='MIT',
classifiers=[
'Environment :: No Input/Output (Daemon)',
'Development Status :: 1 - Planning',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
'Topic :: Software Development :: Libraries',
],
install_requires=[
'ppp_datamodel>=0.2',
'ppp_core>=0.2',
],
packages=[
'example_ppp_module',
],
)
| #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='example_ppp_module',
version='0.1',
description='Example python module for the PPP.',
url='https://github.com/ProjetPP',
author='Valentin Lorentz',
author_email='valentin.lorentz+ppp@ens-lyon.org',
license='MIT',
classifiers=[
'Environment :: No Input/Output (Daemon)',
'Development Status :: 1 - Planning',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
'Topic :: Software Development :: Libraries',
],
install_requires=[
'ppp_datamodel',
'ppp_core',
],
packages=[
'example_ppp_module',
],
)
|
Use local vars instead of global | package com.supinfo.jva.geocar;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class About extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
TextView version = (TextView) findViewById(R.id.version);
Button gitButton = (Button) findViewById(R.id.button_git);
Resources res = getResources();
String actualVersion = res.getString(R.string.version, "1.0.0");
version.setText(actualVersion);
gitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String urlProject = "https://github.com/Carmain/Geocar";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(urlProject));
startActivity(intent);
}
});
}
}
| package com.supinfo.jva.geocar;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class About extends ActionBarActivity {
private TextView version = null;
private Button gitButton = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
version = (TextView) findViewById(R.id.version);
gitButton = (Button) findViewById(R.id.button_git);
Resources res = getResources();
String actualVersion = res.getString(R.string.version, "1.0.0");
version.setText(actualVersion);
gitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String urlProject = "https://github.com/Carmain/Geocar";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(urlProject));
startActivity(intent);
}
});
}
}
|
Remove the usage of nargs to avoid different behaviors between chronograph and command line. | import logging
import docker
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
log = logging.getLogger()
class DockerExecutor(DjangoCmdBase):
def add_arguments(self, parser):
# Positional arguments
"""
:param: in the args it could be: /usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help
NO need to add '"' as "/usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help"
:return:
"""
# for using with chronograph, do not use nargs param, because chronograph seems do not support passing
# array, but using nargs will generate a list for the parameters
parser.add_argument('-c', '--container_id')
parser.add_argument('-w', '--work_dir', default=None)
parser.add_argument('path_and_params', nargs='+')
def msg_loop(self):
print(self.options["container_id"])
print(self.options["work_dir"])
print(self.options["path_and_params"])
client = docker.from_env()
container = client.containers.get(self.options["container_id"])
print(container.exec_run(" ".join(self.options["path_and_params"]), workdir=(self.options["work_dir"])))
Command = DockerExecutor
| import logging
import docker
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
log = logging.getLogger()
class DockerExecutor(DjangoCmdBase):
def add_arguments(self, parser):
# Positional arguments
"""
:param: in the args it could be: /usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help
NO need to add '"' as "/usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help"
:return:
"""
parser.add_argument('--container_id', nargs=1)
parser.add_argument('--work_dir', nargs='?', default=None)
parser.add_argument('path_and_params', nargs='+')
def msg_loop(self):
print(self.options["path_and_params"])
client = docker.from_env()
container = client.containers.get(self.options["container_id"][0])
print(container.exec_run(" ".join(self.options["path_and_params"]), workdir=self.options["work_dir"]))
Command = DockerExecutor
|
Make testing_log_file_path optional for now. | package com.twitter.mesos.scheduler.log.testing;
import java.io.File;
import com.google.common.base.Preconditions;
import com.google.inject.PrivateModule;
import com.google.inject.Singleton;
import com.twitter.common.args.Arg;
import com.twitter.common.args.CmdLine;
import com.twitter.mesos.scheduler.log.Log;
/**
* Binding module that uses a local log file, intended for testing.
*/
public class FileLogStreamModule extends PrivateModule {
// TODO(William Farner): Make this a required argument and ensure it is not included in production
// builds (MESOS-471).
//@NotNull
@CmdLine(name = "testing_log_file_path", help = "Path to a file to store local log file data in.")
private static final Arg<File> LOG_PATH = Arg.create(null);
@Override
protected void configure() {
Preconditions.checkNotNull(LOG_PATH.get());
bind(File.class).toInstance(LOG_PATH.get());
bind(Log.class).to(FileLog.class);
bind(FileLog.class).in(Singleton.class);
expose(Log.class);
}
}
| package com.twitter.mesos.scheduler.log.testing;
import java.io.File;
import com.google.inject.PrivateModule;
import com.google.inject.Singleton;
import com.twitter.common.args.Arg;
import com.twitter.common.args.CmdLine;
import com.twitter.common.args.constraints.NotNull;
import com.twitter.mesos.scheduler.log.Log;
/**
* Binding module that uses a local log file, intended for testing.
*/
public class FileLogStreamModule extends PrivateModule {
@NotNull
@CmdLine(name = "testing_log_file_path", help = "Path to a file to store local log file data in.")
private static final Arg<File> LOG_PATH = Arg.create(null);
@Override
protected void configure() {
bind(File.class).toInstance(LOG_PATH.get());
bind(Log.class).to(FileLog.class);
bind(FileLog.class).in(Singleton.class);
expose(Log.class);
}
}
|
Revert "Use HTTPS to retrieve ranking from DBB"
Not using HTTPS avoids certificate errors.
This ranking data is not sensitive, so it should be fine to continue as
before the original change. | """
dbbrankingparser.httpclient
~~~~~~~~~~~~~~~~~~~~~~~~~~~
HTTP client utilities
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: MIT, see LICENSE for details.
"""
from urllib.request import Request, urlopen
USER_AGENT = (
'Mozilla/5.0 (X11; Linux x86_64; rv:38.0) '
'Gecko/20100101 Firefox/38.0 Iceweasel/38.6.0'
) # type: str
def assemble_url(league_id: int) -> str:
"""Assemble the ranking HTML's URL for the league with that ID."""
template = (
'http://www.basketball-bund.net/public/tabelle.jsp'
'?print=1'
'&viewDescKey=sport.dbb.views.TabellePublicView/index.jsp_'
'&liga_id={:d}'
)
return template.format(league_id)
def fetch_content(url: str) -> str:
"""Retrieve and return the content of that URL."""
request = _create_request(url)
return urlopen(request).read().decode('utf-8')
def _create_request(url: str) -> Request:
"""Create an HTTP GET request."""
headers = {'User-Agent': USER_AGENT}
return Request(url, headers=headers)
| """
dbbrankingparser.httpclient
~~~~~~~~~~~~~~~~~~~~~~~~~~~
HTTP client utilities
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: MIT, see LICENSE for details.
"""
from urllib.request import Request, urlopen
USER_AGENT = (
'Mozilla/5.0 (X11; Linux x86_64; rv:38.0) '
'Gecko/20100101 Firefox/38.0 Iceweasel/38.6.0'
) # type: str
def assemble_url(league_id: int) -> str:
"""Assemble the ranking HTML's URL for the league with that ID."""
template = (
'https://www.basketball-bund.net/public/tabelle.jsp'
'?print=1'
'&viewDescKey=sport.dbb.views.TabellePublicView/index.jsp_'
'&liga_id={:d}'
)
return template.format(league_id)
def fetch_content(url: str) -> str:
"""Retrieve and return the content of that URL."""
request = _create_request(url)
return urlopen(request).read().decode('utf-8')
def _create_request(url: str) -> Request:
"""Create an HTTP GET request."""
headers = {'User-Agent': USER_AGENT}
return Request(url, headers=headers)
|
Fix test suite on <7 | <?php
namespace Installer;
use Composer\Plugin\Capability\CommandProvider as CommandProviderCapability;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Composer\Command\BaseCommand;
class CommandProvider implements CommandProviderCapability
{
public function __construct(array $args)
{
if (!$args['composer'] instanceof \Composer\Composer) {
throw new \RuntimeException('Expected a "composer" key');
}
if (!$args['io'] instanceof \Composer\IO\IOInterface) {
throw new \RuntimeException('Expected an "io" key');
}
if (!$args['plugin'] instanceof Plugin8) {
throw new \RuntimeException('Expected a "plugin" key with my own plugin');
}
}
public function getCommands()
{
return array(new Command);
}
}
class Command extends BaseCommand
{
protected function configure()
{
$this->setName('custom-plugin-command');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('Executing');
return 5;
}
}
| <?php
namespace Installer;
use Composer\Plugin\Capability\CommandProvider;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Composer\Command\BaseCommand;
class CommandProvider implements CommandProvider
{
public function __construct(array $args)
{
if (!$args['composer'] instanceof \Composer\Composer) {
throw new \RuntimeException('Expected a "composer" key');
}
if (!$args['io'] instanceof \Composer\IO\IOInterface) {
throw new \RuntimeException('Expected an "io" key');
}
if (!$args['plugin'] instanceof Plugin8) {
throw new \RuntimeException('Expected a "plugin" key with my own plugin');
}
}
public function getCommands()
{
return array(new Command);
}
}
class Command extends BaseCommand
{
protected function configure()
{
$this->setName('custom-plugin-command');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('Executing');
return 5;
}
}
|
Implement the current ``GET /ooni`` api. | """
This simulates the mlab-ns lookup request, whose code lives here:
https://code.google.com/p/m-lab/source/browse/server/mlabns/handlers/lookup.py?repo=ns
The difference in this module is that we don't support features which
ooni-support does not use and we augment features which ooni-support
would rely on if mlab-ns were to add those features.
Also, this is a twisted web server rather than appengine.
"""
import json
from twisted.web import resource
from twisted.web.server import NOT_DONE_YET
class LookupSimulatorResource (resource.Resource):
def __init__(self, db):
"""db is a dict mapping { fqdn -> other_stuff }; inserts come from mlabsim.update."""
resource.Resource.__init__(self)
self._db = db
def render_GET(self, request):
if request.args['match'] == ['all'] and request.args.get('format', ['json']) == ['json']:
request.setResponseCode(200, 'ok')
request.write(json.dumps(self._db.values(), indent=2, sort_keys=True))
request.finish()
else:
request.setResponseCode(400, 'invalid')
request.finish()
return NOT_DONE_YET
| """
This simulates the mlab-ns lookup request, whose code lives here:
https://code.google.com/p/m-lab/source/browse/server/mlabns/handlers/lookup.py?repo=ns
The difference in this module is that we don't support features which
ooni-support does not use and we augment features which ooni-support
would rely on if mlab-ns were to add those features.
Also, this is a twisted web server rather than appengine.
"""
from twisted.web import resource
from twisted.web.server import NOT_DONE_YET
class LookupSimulatorResource (resource.Resource):
def __init__(self, db):
# FIXME - db is some simple memory structure holding info;
# the details will solidfy soon. This resource reads from
# this structure.
resource.Resource.__init__(self)
self._db = db
def render_GET(self, request):
# FIXME: This is not implemented yet.
request.setResponseCode(500, 'NOT IMPLEMENTED')
request.finish()
return NOT_DONE_YET
|
Fix .remove() error and make copying work better | import Ember from 'ember';
export default Ember.Component.extend({
charClass: 'hidden-emoji-char',
copyText(text) {
let copied;
let input = $('<input>');
this.$().append(input);
try {
input.val(text);
input.select();
copied = document.execCommand('copy');
console.error('Copy failed');
} catch (err) {
console.error('Copying error', err);
copied = false;
} finally {
input.remove();
}
return copied;
},
click() {
const flashMessages = Ember.get(this, 'flashMessages');
const char = this.get('emoji.char');
let copied = this.copyText(char);
flashMessages.clearMessages();
if (copied) {
flashMessages.success(`Copied ${char}`);
} else {
flashMessages.danger(`Could not copy ${char}`);
}
},
});
| import Ember from 'ember';
function copyText(text) {
let copied;
let input = document.createElement('input');
document.body.appendChild(input);
try {
input.value = text;
input.select();
copied = document.execCommand('copy');
} catch (err) {
copied = false;
} finally {
input.remove();
}
return copied;
}
export default Ember.Component.extend({
charClass: 'hidden-emoji-char',
click() {
const flashMessages = Ember.get(this, 'flashMessages');
const char = this.get('emoji.char');
let copied = copyText(char);
flashMessages.clearMessages();
if (copied) {
flashMessages.success(`Copied ${char}`);
} else {
flashMessages.danger(`Could not copy ${char}`);
}
},
});
|
Add for-loop to arrayToList to allow for array arguments of dynamic length | // Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list, or undefined when there is no such element.
function arrayToList(array) {
const arrayLength = array.length;
let list = null;
for (let i = array.length - 1; i >= 0; i-- ) {
list = {
value: array[i],
rest: list
};
}
return list;
}
const theArray = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(arrayToList(theArray));
function listToArray(list) {
console.log(list);
const array = [
list.value,
list.rest.value,
list.rest.rest.value
];
return array;
}
// const theList = arrayToList([1, 2, 3]);
// console.log(listToArray(theList));
// write helper function 'prepend', which takes an element and a list and creates a new list that adds the element to the front of the input list
function prepend(element, list) {
let newList;
// do some stuff here
return newList;
} | // Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list, or undefined when there is no such element.
function arrayToList(array) {
const list = {
value: array[0],
rest: {
value: array[1],
rest: {
value: array[2],
rest: null
}
}
};
return list;
}
const theArray = [1, 2, 3];
console.log(arrayToList(theArray));
function listToArray(list) {
console.log(list);
const array = [
list.value,
list.rest.value,
list.rest.rest.value
];
return array;
}
const theList = arrayToList([1, 2, 3]);
console.log(listToArray(theList)); |
Change admin_room scope to view_room | var ack = require('ac-koa').require('hipchat'),
pkg = require('./package.json'),
app = ack(pkg),
_ = require('lodash');
var addon = app.addon()
.hipchat()
.allowRoom(true)
.scopes(['send_notification','view_room']),
msgOps = require('./lib/msg_operations.js');
addon.webhook('room_message', /^--.+/, function *() {
var msg = this.content,
cmdMatch = _.find(msgOps.commands, function(cmd) {
return cmd.regex.test(msg);
});
if (cmdMatch) {
var matches = msg.match(cmdMatch.regex);
yield cmdMatch.handler.apply(this, matches.slice(1));
}
});
app.listen();
| var ack = require('ac-koa').require('hipchat'),
pkg = require('./package.json'),
app = ack(pkg),
_ = require('lodash');
var addon = app.addon()
.hipchat()
.allowRoom(true)
.scopes(['send_notification','admin_room']),
msgOps = require('./lib/msg_operations.js');
addon.webhook('room_message', /^--.+/, function *() {
var msg = this.content,
cmdMatch = _.find(msgOps.commands, function(cmd) {
return cmd.regex.test(msg);
});
if (cmdMatch) {
var matches = msg.match(cmdMatch.regex);
yield cmdMatch.handler.apply(this, matches.slice(1));
}
});
app.listen();
|
Remove flash injection. Doesn't seem to work right | let path = require('path');
let fs = require('fs');
let _ = require('lodash');
let PouchDB = require('pouchdb');
module.exports = (dirpath, options) => {
options = require('./lib/config')(dirpath, options);
//Setup handlebars
let handlebars = require('./lib/handlebars')(options);
//Setup db connection
let db = new PouchDB(options.db);
//Setup express
let app = require('./lib/express')(options);
//Setup passport
let passport = require('./lib/passport')(app, db);
app.passport = passport;
//Setup injection
let di = require('./lib/di')(app);
di.value('_', _);
di.value('db', db);
di.value('handlebars', handlebars);
di.value('passport', passport);
di('user', function (req, res, next) {
res.locals.user = req.user;
next(null, req.user);
});
//Setup controllers
require('./lib/controllers')(app, options);
//Setup docs
return require('./lib/docs')(app, db, options).then(() => {
return app;
});
}
| let path = require('path');
let fs = require('fs');
let _ = require('lodash');
let PouchDB = require('pouchdb');
module.exports = (dirpath, options) => {
options = require('./lib/config')(dirpath, options);
//Setup handlebars
let handlebars = require('./lib/handlebars')(options);
//Setup db connection
let db = new PouchDB(options.db);
//Setup express
let app = require('./lib/express')(options);
//Setup passport
let passport = require('./lib/passport')(app, db);
app.passport = passport;
//Setup injection
let di = require('./lib/di')(app);
di.value('_', _);
di.value('db', db);
di.value('handlebars', handlebars);
di.value('passport', passport);
di('user', function (req, res, next) {
res.locals.user = req.user;
next(null, req.user);
});
di('flash', function (req, res, next) {
next(null, req.flash);
});
//Setup controllers
require('./lib/controllers')(app, options);
//Setup docs
return require('./lib/docs')(app, db, options).then(() => {
return app;
});
}
|
Modify and add tests for the revised connection.close | from unittest import mock
import pytest
import aiozk.connection
@pytest.fixture
def connection(event_loop):
connection = aiozk.connection.Connection(
host='zookeeper.test',
port=2181,
watch_handler=mock.MagicMock(),
read_timeout=30,
loop=event_loop)
connection.writer = mock.MagicMock()
return connection
@pytest.mark.asyncio
async def test_close_connection_in_state_closing_do_not_performs_abort(connection):
connection.abort = mock.AsyncMock()
connection.closing = True
await connection.close(0.1)
connection.abort.assert_not_awaited()
@pytest.mark.asyncio
async def test_close_cancels_read_loop_task(connection):
connection.read_loop_task = connection.loop.create_future()
connection.read_loop_task.done = mock.MagicMock(return_value=False)
connection.read_loop_task.cancel = mock.MagicMock(
wraps=connection.read_loop_task.cancel)
await connection.close(0.1)
connection.read_loop_task.cancel.assert_called_once()
@pytest.mark.asyncio
async def test_connection_abort(connection):
connection.pending_count = mock.MagicMock(return_value=1)
connection.abort = mock.MagicMock()
await connection.close(0.1)
connection.abort.assert_called_once()
| from unittest import mock
import pytest
import aiozk.connection
@pytest.fixture
def connection(event_loop):
connection = aiozk.connection.Connection(
host='zookeeper.test',
port=2181,
watch_handler=mock.MagicMock(),
read_timeout=30,
loop=mock.MagicMock(wraps=event_loop))
connection.writer = mock.MagicMock()
return connection
@pytest.mark.asyncio
async def test_close_connection_in_state_closing_do_not_performs_abort(connection):
connection.abort = mock.AsyncMock()
connection.closing = True
await connection.close(mock.ANY)
connection.abort.assert_not_awaited()
@pytest.mark.asyncio
async def test_close_cancels_read_loop_task(connection):
connection.start_read_loop()
connection.read_response = mock.AsyncMock(return_value=(0, mock.ANY, mock.ANY))
task_cancelled_future = connection.loop.create_future()
def set_result(task):
task_cancelled_future.set_result(task.cancelled())
connection.read_loop_task.add_done_callback(set_result)
await connection.close(mock.ANY)
assert await task_cancelled_future
|
Remove scope attribute from Constant | # -*- coding: utf-8 -*-
# Copyright 2013 Universidad Politécnica de Madrid
# This file is part of Wirecloud.
# Wirecloud is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Wirecloud 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 General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Wirecloud. If not, see <http://www.gnu.org/licenses/>.
from django.db import models
from django.utils.translation import gettext_lazy as _
class Constant(models.Model):
concept = models.CharField(_('Concept'), max_length=255, unique=True, null=False, blank=False)
value = models.CharField(_('Value'), max_length=256)
class Meta:
app_label = 'platform'
db_table = 'wirecloud_constant'
def __unicode__(self):
return self.concept.concept
| # -*- coding: utf-8 -*-
# Copyright 2013 Universidad Politécnica de Madrid
# This file is part of Wirecloud.
# Wirecloud is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Wirecloud 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 General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Wirecloud. If not, see <http://www.gnu.org/licenses/>.
from django.db import models
from django.utils.translation import gettext_lazy as _
class Constant(models.Model):
scope = models.CharField(_('Scope'), max_length=20, null=False, blank=False)
concept = models.CharField(_('Concept'), max_length=255, null=False, blank=False)
value = models.CharField(_('Value'), max_length=256)
class Meta:
unique_together = (('scope', 'concept'),)
app_label = 'platform'
db_table = 'wirecloud_constant'
def __unicode__(self):
return self.concept.concept
|
Define hooks on model options | const Sequelize = require('sequelize')
const bcrypt = require('bcrypt')
const sequelize = require('./../db')
const passwordHash = (user, options) => {
return bcrypt.hash(user.password, 10)
.then((hash) => { user.password = hash })
}
const userAttributes = {
'email': {
'type': Sequelize.TEXT,
'allowNull': false,
'unique': { 'msg': 'já está em uso' },
'validate': {
'notEmpty': { 'msg': 'não pode ficar em branco' },
'isEmail': { 'msg': 'formato inválido' }
}
},
'name': {
'type': Sequelize.TEXT,
'allowNull': false,
'validate': {
'notEmpty': { 'msg': 'não pode ficar em branco' }
}
},
'password': {
'type': Sequelize.TEXT,
'allowNull': false,
'validate': {
'notEmpty': { 'msg': 'não pode ficar em branco' },
'len': {
'args': [6, 18],
'msg': 'deve ter entre 6 e 18 caracteres'
}
}
}
}
const modelAttributes = {
'timestamps': true,
'underscored': true,
'hooks': {
'beforeCreate': passwordHash,
'beforeUpdate': passwordHash
}
}
const User = sequelize.define('user', userAttributes, modelAttributes)
module.exports = User
| const Sequelize = require('sequelize')
const bcrypt = require('bcrypt')
const sequelize = require('./../db')
const userAttributes = {
'email': {
'type': Sequelize.TEXT,
'allowNull': false,
'unique': { 'msg': 'já está em uso' },
'validate': {
'notEmpty': { 'msg': 'não pode ficar em branco' },
'isEmail': { 'msg': 'formato inválido' }
}
},
'name': {
'type': Sequelize.TEXT,
'allowNull': false,
'validate': {
'notEmpty': { 'msg': 'não pode ficar em branco' }
}
},
'password': {
'type': Sequelize.TEXT,
'allowNull': false,
'validate': {
'notEmpty': { 'msg': 'não pode ficar em branco' },
'len': {
'args': [6, 18],
'msg': 'deve ter entre 6 e 18 caracteres'
}
}
}
}
const modelAttributes = {
'timestamps': true,
'underscored': true
}
const passwordHash = (user, options) => {
return bcrypt.hash(user.password, 10)
.then((hash) => { user.password = hash })
}
const User = sequelize.define('user', userAttributes, modelAttributes)
User.beforeCreate(passwordHash)
User.beforeUpdate(passwordHash)
User.sync()
module.exports = User
|
Change: Include electron module to build of webpack
Pull request: #83
Approved by: MaxMEllon | 'use strict';
const webpack = require('webpack');
const path = require('path');
const JsonpTemplatePlugin = webpack.JsonpTemplatePlugin;
const FunctionModulePlugin = require('webpack/lib/FunctionModulePlugin');
const NodeTargetPlugin = require('webpack/lib/node/NodeTargetPlugin');
const opt = {
path: path.resolve('./bundle/js'),
filename: 'main.js',
libraryTarget: 'commonjs2'
};
let webpackConfig = {
resolve: {
extensions: ['', '.js', '.jsx', '.json'],
packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main']
},
entry: ['./scripts/main.js'],
output: opt,
externals: ['nicolive'],
plugins: [
new webpack.NoErrorsPlugin(),
new NodeTargetPlugin(),
new webpack.ExternalsPlugin('commonjs', ['electron'])
],
module: {
loaders: [ {
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
}, {
test: /\.json$/,
loader: 'json-loader'
}, ]
}
};
webpackConfig.target = function renderer (compiler) {
compiler.apply(
new JsonpTemplatePlugin(opt),
new FunctionModulePlugin(opt)
);
};
module.exports = webpackConfig;
| 'use strict';
const webpack = require('webpack');
const path = require('path');
const JsonpTemplatePlugin = webpack.JsonpTemplatePlugin;
const FunctionModulePlugin = require('webpack/lib/FunctionModulePlugin');
const NodeTargetPlugin = require('webpack/lib/node/NodeTargetPlugin');
const opt = {
path: path.resolve('./bundle/js'),
filename: 'main.js',
libraryTarget: 'commonjs2'
};
let webpackConfig = {
resolve: {
extensions: ['', '.js', '.jsx', '.json'],
packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main']
},
entry: ['./scripts/main.js'],
output: opt,
externals: ['electron', 'nicolive'],
plugins: [
new webpack.NoErrorsPlugin(),
new NodeTargetPlugin()
],
module: {
loaders: [ {
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
}, {
test: /\.json$/,
loader: 'json-loader'
}, ]
}
};
webpackConfig.target = function renderer (compiler) {
compiler.apply(
new JsonpTemplatePlugin(opt),
new FunctionModulePlugin(opt)
);
};
module.exports = webpackConfig;
|
Set webpack hot middleware to false
- because of annoying eslint errors | import webpack from 'webpack'
import merge from 'webpack-merge'
import common from './webpack.common'
const DEV_PORT = 3000
export default merge(common, {
entry: [
'webpack-hot-middleware/client?reload=true&overlay=false',
'./src/index.js',
],
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
},
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
devServer: {
hot: true,
historyApiFallback: true,
contentBase: './public',
port: DEV_PORT,
},
})
| import webpack from 'webpack'
import merge from 'webpack-merge'
import common from './webpack.common'
const DEV_PORT = 3000
export default merge(common, {
entry: [
'webpack-hot-middleware/client?reload=true',
'./src/index.js',
],
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
},
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
devServer: {
hot: true,
historyApiFallback: true,
contentBase: './public',
port: DEV_PORT,
},
})
|
Reword errors when version metadata does not match or is absent | # Copyright (c) 2014 AnsibleWorks, Inc.
# All Rights Reserved.
"""
WSGI config for AWX project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
# Prepare the AWX environment.
from awx import prepare_env
prepare_env()
import os
import logging
from django.conf import settings
from awx import __version__ as tower_version
logger = logging.getLogger('awx.main.models.jobs')
try:
fd = open("/var/lib/awx/.tower_version", "r")
if fd.read().strip() != tower_version:
raise Exception()
except Exception:
logger.error("Missing or incorrect metadata for Tower version. Ensure Tower was installed using the setup playbook.")
raise Exception("Missing or incorrect metadata for Tower version. Ensure Tower was installed using the setup playbook.")
# Return the default Django WSGI application.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
| # Copyright (c) 2014 AnsibleWorks, Inc.
# All Rights Reserved.
"""
WSGI config for AWX project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
# Prepare the AWX environment.
from awx import prepare_env
prepare_env()
import os
import logging
from django.conf import settings
from awx import __version__ as tower_version
logger = logging.getLogger('awx.main.models.jobs')
try:
fd = open("/var/lib/awx/.tower_version", "r")
if fd.read().strip() != tower_version:
logger.error("Tower Versions don't match, potential invalid setup detected")
raise Exception("Tower Versions don't match, potential invalid setup detected")
except Exception:
logger.error("Missing tower version metadata at /var/lib/awx/.tower_version")
raise Exception("Missing tower version metadata at /var/lib/awx/.tower_version")
# Return the default Django WSGI application.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
Remove last vestiges of kingpin | package main
import (
"os"
"github.com/cloudfoundry-community/gcp-tools-release/src/stackdriver-nozzle/firehose"
"github.com/cloudfoundry-community/go-cfclient"
"github.com/cloudfoundry/sonde-go/events"
)
func main() {
apiEndpoint := os.Getenv("FIREHOSE_ENDPOINT")
username := os.Getenv("FIREHOSE_USERNAME")
password := os.Getenv("FIREHOSE_PASSWORD")
_, skipSSLValidation := os.LookupEnv("FIREHOSE_SKIP_SSL")
cfConfig := &cfclient.Config{
ApiAddress: apiEndpoint,
Username: username,
Password: password,
SkipSslValidation: skipSSLValidation}
cfClient := cfclient.NewClient(cfConfig)
client := firehose.NewClient(cfConfig, cfClient, nil)
err := client.StartListening(&StdOut{})
if err != nil {
panic(err)
}
}
type StdOut struct{}
func (so *StdOut) HandleEvent(envelope *events.Envelope) error {
println(envelope.String())
return nil
}
| package main
import (
"os"
"github.com/cloudfoundry-community/gcp-tools-release/src/stackdriver-nozzle/firehose"
"github.com/cloudfoundry-community/go-cfclient"
"github.com/cloudfoundry/sonde-go/events"
"gopkg.in/alecthomas/kingpin.v2"
)
func main() {
kingpin.Parse()
apiEndpoint := os.Getenv("FIREHOSE_ENDPOINT")
username := os.Getenv("FIREHOSE_USERNAME")
password := os.Getenv("FIREHOSE_PASSWORD")
_, skipSSLValidation := os.LookupEnv("FIREHOSE_SKIP_SSL")
cfConfig := &cfclient.Config{
ApiAddress: apiEndpoint,
Username: username,
Password: password,
SkipSslValidation: skipSSLValidation}
cfClient := cfclient.NewClient(cfConfig)
client := firehose.NewClient(cfConfig, cfClient, nil)
err := client.StartListening(&StdOut{})
if err != nil {
panic(err)
}
}
type StdOut struct{}
func (so *StdOut) HandleEvent(envelope *events.Envelope) error {
println(envelope.String())
return nil
}
|
Fix bug in iteritems on SCAN_MODULES.
Change-Id: Ifa58f29a9e69ad46b44c301244525d711b43faca
Reviewed-on: http://review.pozytywnie.pl:8080/2340
Reviewed-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com>
Tested-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com> | import sys
from javascript_configuration import settings
class ConfigurationBuilder:
"""
Get javascript configurations from urls.py files from all installed apps.
"""
def __init__(self):
self.configuration = None
def fetch(self):
configuration = {}
for app_name, module_name in settings.SCAN_MODULES.iteritems():
try:
__import__(module_name)
urls = sys.modules[module_name]
if hasattr(urls, 'javascript_configuration'):
configuration[app_name] = urls.javascript_configuration()
except ImportError:
pass
return configuration
def get_configuration(self):
if self.configuration is None:
self.configuration = self.fetch()
return self.configuration
DEFAULT_CONFIGURATION_BUILDER = ConfigurationBuilder()
| import sys
from javascript_configuration import settings
class ConfigurationBuilder:
"""
Get javascript configurations from urls.py files from all installed apps.
"""
def __init__(self):
self.configuration = None
def fetch(self):
configuration = {}
for app_name, module_name in settings.SCAN_MODULES.iter_items():
try:
__import__(module_name)
urls = sys.modules[module_name]
if hasattr(urls, 'javascript_configuration'):
configuration[app_name] = urls.javascript_configuration()
except ImportError:
pass
return configuration
def get_configuration(self):
if self.configuration is None:
self.configuration = self.fetch()
return self.configuration
DEFAULT_CONFIGURATION_BUILDER = ConfigurationBuilder()
|
ENYO-3171: Remove irrelevant text from sample
Enyo-DCO-1.1-Signed-off-by: Stephen Choi <stephen.choi@lge.com> | var
kind = require('enyo/kind');
var
DragAvatar = require('enyo/DragAvatar'),
EnyoImage = require('enyo/Image');
module.exports = kind({
name: 'enyo.sample.DragAvatarSample',
classes: 'drag-avatar-sample enyo-fit',
components: [
{content: 'Start dragging anywhere on the screen.'},
{kind: DragAvatar, offsetX: 0, offsetY: 64, components: [
{kind: EnyoImage, name: 'imageAvatar', src: 'http://enyojs.com/img/enyo-logo.png'}
]}
],
handlers: {
ondrag: 'drag',
ondragfinish: 'dragFinish'
},
drag: function (sender, ev) {
this.$.dragAvatar.drag(ev);
},
dragFinish: function (sender, ev) {
this.$.dragAvatar.hide();
}
});
| var
kind = require('enyo/kind');
var
DragAvatar = require('enyo/DragAvatar'),
EnyoImage = require('enyo/Image');
module.exports = kind({
name: 'enyo.sample.DragAvatarSample',
classes: 'drag-avatar-sample enyo-fit',
components: [
{content: 'Start dragging anywhere on the screen (open sample in new tab).'},
{kind: DragAvatar, offsetX: 0, offsetY: 64, components: [
{kind: EnyoImage, name: 'imageAvatar', src: 'http://enyojs.com/img/enyo-logo.png'}
]}
],
handlers: {
ondrag: 'drag',
ondragfinish: 'dragFinish'
},
drag: function (sender, ev) {
this.$.dragAvatar.drag(ev);
},
dragFinish: function (sender, ev) {
this.$.dragAvatar.hide();
}
});
|
Fix unused webpack eslint error | const HtmlWebpackPlugin = require('html-webpack-plugin')
const WebpackOnBuildPlugin = require('on-build-webpack')
const replace = require('replace')
const path = require('path')
module.exports = {
entry: [
'./app/index.js'
],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
devtool: 'eval',
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: [ 'es2015', 'react', 'stage-3' ]
}
}
]
},
devServer: {
contentBase: 'dist'
},
plugins: [
new HtmlWebpackPlugin({
inject: true,
template: 'index.html'
}),
// Workaround for https://github.com/ethereum/web3.js/issues/555:
new WebpackOnBuildPlugin(function (stats) {
replace({
regex: '\u00A0',
replacement: ' ',
paths: [ path.resolve(__dirname, 'dist', 'bundle.js') ]
})
})
]
}
| const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const WebpackOnBuildPlugin = require('on-build-webpack')
const replace = require('replace')
const path = require('path')
module.exports = {
entry: [
'./app/index.js'
],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
devtool: 'eval',
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: [ 'es2015', 'react', 'stage-3' ]
}
}
]
},
devServer: {
contentBase: 'dist'
},
plugins: [
new HtmlWebpackPlugin({
inject: true,
template: 'index.html'
}),
// Workaround for https://github.com/ethereum/web3.js/issues/555:
new WebpackOnBuildPlugin(function (stats) {
replace({
regex: '\u00A0',
replacement: ' ',
paths: [ path.resolve(__dirname, 'dist', 'bundle.js') ]
})
})
]
}
|
Upgrade instance type due to RAM issues | import boto3
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
ec2 = boto3.resource('ec2')
with open('env.sh') as e, open('cloud-init.sh') as f:
script = e.read() + f.read()
instance = ec2.create_instances(
ImageId='ami-060cde69', # Ubuntu 16.04
MinCount=1,
MaxCount=1,
KeyName='ictrp',
UserData=script,
SecurityGroups=['launch-wizard-1'],
InstanceType='t3.small',
InstanceInitiatedShutdownBehavior='terminate')
logging.info(instance[0])
return instance[0].id
| import boto3
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
ec2 = boto3.resource('ec2')
with open('env.sh') as e, open('cloud-init.sh') as f:
script = e.read() + f.read()
instance = ec2.create_instances(
ImageId='ami-060cde69', # Ubuntu 16.04
MinCount=1,
MaxCount=1,
KeyName='ictrp',
UserData=script,
SecurityGroups=['launch-wizard-1'],
InstanceType='t2.micro',
InstanceInitiatedShutdownBehavior='terminate')
logging.info(instance[0])
return instance[0].id
|
Remove commented code in examples | <?php
require_once __DIR__.'/../vendor/autoload.php';
$transmission = new Transmission\Transmission();
$queue = $transmission->all();
echo "Downloading to: {$transmission->getSession()->getDownloadDir()}\n";
foreach ($queue as $torrent) {
echo "{$torrent->getName()}";
if ($torrent->isFinished()) {
echo ": done\n";
} else {
if ($torrent->isDownloading()) {
echo ": {$torrent->getPercentDone()}% ";
echo "(eta: ". gmdate("H:i:s", $torrent->getEta()) .")\n";
} else{
echo ": paused\n";
}
}
}
| <?php
require_once __DIR__.'/../vendor/autoload.php';
$transmission = new Transmission\Transmission();
$queue = $transmission->all();
echo "Downloading to: {$transmission->getSession()->getDownloadDir()}\n";
foreach ($queue as $torrent) {
echo "{$torrent->getName()}";
if ($torrent->isFinished()) {
echo ": done\n";
} else {
if ($torrent->isDownloading()) {
echo ": {$torrent->getPercentDone()}% ";
echo "(eta: ". gmdate("H:i:s", $torrent->getEta()) .")\n";
} else{
echo ": paused\n";
}
}
}
// Change download directories
// $session = $transmission->getSession();
// $session->setDownloadDir('/var/www/downloads/complete');
// $session->setIncompleteDir('/tmp/downloads');
// $session->save();
|
Add a Line field to the Upgrade struct | package adeptus
var (
regex_xp = regexp.MustCompile(`\(?\d+xp\)?`) // Match `150xp` and `(150xp)`
)
type Upgrade interface {
Mark string
Name string
Cost string
Line int
}
// ParseUpgrade generate an upgrade from a raw line
func ParseUpgrade(raw string, line int) (Upgrade, error) {
// Initialize a new upgrade
upgrade := Upgrade{
Line: line,
}
// Get the fields of the line
fields := strings.Fields(raw)
// The minimum number of fields is 2
if len(fields) < 2 {
return Upgrade{}, fmt.Errorf("not enought")
}
// Check that the mark is a valid one
if !in(fields[0], []string{"*", "+", "-"}) {
return Upgrade{}, fmt.Errorf("%s isn't a valid mark", fields[0])
}
// Set the upgrade mark
upgrade.Mark = fields[0]
fields = fields[1:]
// Check if a field seems to be a cost field
for i, field := range fields {
if !regex_xp.MatchString(field) {
continue
}
upgrade.Cost = regex_xp.FindString(field)
fields = append(fields[:i], fields[i+1:]...)
break
}
// The remaining line is the name of the upgrade
upgrade.Name = strings.Join(fields, " ")
return upgrade, nil
}
| package adeptus
var (
regex_xp = regexp.MustCompile(`\(?\d+xp\)?`) // Match `150xp` and `(150xp)`
)
type Upgrade interface {
Mark string
Name string
Cost string
}
// ParseUpgrade generate an upgrade from a raw line
func ParseUpgrade(raw string) (Upgrade, error) {
upgrade := Upgrade{}
// Get the fields of the line
fields := strings.Fields(raw)
// The minimum number of fields is 2
if len(fields) < 2 {
return upgrade, fmt.Errorf("not enought")
}
// Check that the mark is a valid one
if !in(fields[0], []string{"*", "+", "-"}) {
return upgrade, fmt.Errorf("%s isn't a valid mark", fields[0])
}
// Set the upgrade mark
upgrade.Mark = fields[0]
fields = fields[1:]
// Check if a field seems to be a cost field
for i, field := range fields {
if !regex_xp.MatchString(field) {
continue
}
upgrade.Cost = regex_xp.FindString(field)
fields = append(fields[:i], fields[i+1:]...)
break
}
// The remaining line is the name of the upgrade
upgrade.Name = strings.Join(fields, " ")
return upgrade, nil
}
|
Make each name a link to the edit page instead of using a form | <!-- resources/views/admin/tester_index.blade.php -->
@extends('layouts.app')
@section('content')
<h2>Testers</h2>
<p>Click on a name to edit</p>
<table class="table">
<tbody>
@foreach ($testers->chunk(2) as $chunk )
<tr>
@foreach ($chunk as $tester)
<td>{{ $tester->id }}</td>
<td><a href="/admin/testers/{{ $tester->id }}/edit">{{ $tester->name }}</a></td>
@endforeach
</tr>
@endforeach
</tbody>
</table>
<h2>Add a Tester</h2>
<!-- Add a new tester -->
<form class="form-inline" action="/admin/testers" method="POST">
<div class="form-group">
{{ csrf_field() }}
<label for="name">Name:</label> <input type="TEXT" class="form-control" id="name" name="name" size="25" />
<label for="initials">Initials:</label> <input type="TEXT" class="form-control" id="initials" name="initials" size="3" />
<button type="SUBMIT" class="btn btn-default">Add tester</button> / <a href="/">Main</a>
</div>
</form>
@endsection
| <!-- resources/views/admin/tester_index.blade.php -->
@extends('layouts.app')
@section('content')
<h2>Testers</h2>
<table class="table">
<tbody>
@foreach ($testers->chunk(2) as $chunk )
<tr>
@foreach ($chunk as $tester)
<td>{{ $tester->id }}</td>
<td>{{ $tester->name }}</td>
<form action="/admin/testers/{{ $tester->id }}/edit" method="POST">
<button type="submit">Edit</button>
</form>
@endforeach
</tr>
@endforeach
</tbody>
</table>
<h2>Add a Tester</h2>
<!-- Add a new tester -->
<form action="/admin/testers" method="POST">
{{ csrf_field() }}
Name: <input type="TEXT" name="name" size="25" />
Initials: <input type="TEXT" name="initials" size="3" />
<button type="SUBMIT">Add tester</button> / <a href="/">Main</a>
</form>
@endsection
|
Use M-Lab project number for BigQuery access. | import httplib2
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client import tools
import os
PROJECT_NUMBER = '233384409938'
PARENT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRETS_FILE = os.path.join(PARENT_PATH, 'client_secrets.json')
CREDENTIALS_FILE = os.path.join(PARENT_PATH, 'bigquery_credentials.dat')
FLOW = flow_from_clientsecrets(SECRETS_FILE, scope='https://www.googleapis.com/auth/bigquery')
storage = Storage(CREDENTIALS_FILE)
credentials = storage.get()
class FlowFlags():
noauth_local_webserver = True
logging_level = 'ERROR'
if credentials is None or credentials.invalid:
# Run oauth2 flow with default arguments.
credentials = tools.run_flow(FLOW, storage, FlowFlags())
http = httplib2.Http()
http = credentials.authorize(http)
bigquery_service = build('bigquery', 'v2', http = http)
| import httplib2
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client import tools
import os
PROJECT_NUMBER = '422648324111'
PARENT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRETS_FILE = os.path.join(PARENT_PATH, 'client_secrets.json')
CREDENTIALS_FILE = os.path.join(PARENT_PATH, 'bigquery_credentials.dat')
FLOW = flow_from_clientsecrets(SECRETS_FILE, scope='https://www.googleapis.com/auth/bigquery')
storage = Storage(CREDENTIALS_FILE)
credentials = storage.get()
class FlowFlags():
noauth_local_webserver = True
logging_level = 'ERROR'
if credentials is None or credentials.invalid:
# Run oauth2 flow with default arguments.
credentials = tools.run_flow(FLOW, storage, FlowFlags())
http = httplib2.Http()
http = credentials.authorize(http)
bigquery_service = build('bigquery', 'v2', http = http)
|
Set default number of articles on page to 16, up from 12. | from django.conf import settings
ARTICLE_COPYRIGHT = getattr(settings, 'NEWSROOM_ARTICLE_COPYRIGHT', "")
ARTICLES_PER_PAGE = getattr(settings, 'NEWSROOM_ARTICLES_PER_PAGE', 16)
BEAUTIFUL_SOUP_PARSER = getattr(settings, 'NEWSROOM_BEAUTIFUL_SOUP_PARSER',
"lxml")
ARTICLE_SUMMARY_IMAGE_SIZE = getattr(settings,
'NEWSROOM_ARTICLE_TEASER_IMAGE_SIZE',
"big")
ARTICLE_PRIMARY_IMAGE_SIZE = getattr(settings,
'NEWSROOM_ARTICLE_TEASER_IMAGE_SIZE',
"large")
CACHE_PERIOD = getattr(settings, 'NEWSROOM_CACHE_PERIOD', 500)
ADVERT_CODE = getattr(settings, 'NEWSROOM_ADVERT_CODE', '')
| from django.conf import settings
ARTICLE_COPYRIGHT = getattr(settings, 'NEWSROOM_ARTICLE_COPYRIGHT', "")
ARTICLES_PER_PAGE = getattr(settings, 'NEWSROOM_ARTICLES_PER_PAGE', 12)
BEAUTIFUL_SOUP_PARSER = getattr(settings, 'NEWSROOM_BEAUTIFUL_SOUP_PARSER',
"lxml")
ARTICLE_SUMMARY_IMAGE_SIZE = getattr(settings,
'NEWSROOM_ARTICLE_TEASER_IMAGE_SIZE',
"big")
ARTICLE_PRIMARY_IMAGE_SIZE = getattr(settings,
'NEWSROOM_ARTICLE_TEASER_IMAGE_SIZE',
"large")
CACHE_PERIOD = getattr(settings, 'NEWSROOM_CACHE_PERIOD', 500)
ADVERT_CODE = getattr(settings, 'NEWSROOM_ADVERT_CODE', '')
|
Fix variable name: "result" instead of "value"
Bug introduced during previous refactoring, when after inlining
a function into scope(). | // Level 2
// Static synchronous definition in a private context shared by all modules
// Implementation of scopeornot API
// https://github.com/eric-brechemier/scopeornot
// This script must be loaded in level 2
/*global scope*/
scope(function(parentContext){
var
// private field
privateContext = {};
/*
Function: scope(code[,needs[,name]]): any
Run code immediately in a private context, and set the return value,
if any, to a property with given name in the private context
Parameters:
code - function(context), the code to run with the private context
provided as parameter
needs - optional, array of strings, the names of the properties that
this code would like to find in the private context
name - optional, string, name of the private context property to set
the value that the code may return
Returns:
any, the return value of the code
*/
function scope(code,needs,name){
var result = code(privateContext);
if (typeof name !== "string"){
return result;
}
privateContext[name] = result;
if (name === "scope"){
// replace the current implementation of scope() in parent context
parentContext.scope = result;
}
return result;
}
return scope;
},[],"scope");
| // Level 2
// Static synchronous definition in a private context shared by all modules
// Implementation of scopeornot API
// https://github.com/eric-brechemier/scopeornot
// This script must be loaded in level 2
/*global scope*/
scope(function(parentContext){
var
// private field
privateContext = {};
/*
Function: scope(code[,needs[,name]]): any
Run code immediately in a private context, and set the return value,
if any, to a property with given name in the private context
Parameters:
code - function(context), the code to run with the private context
provided as parameter
needs - optional, array of strings, the names of the properties that
this code would like to find in the private context
name - optional, string, name of the private context property to set
the value that the code may return
Returns:
any, the return value of the code
*/
function scope(code,needs,name){
var result = code(privateContext);
if (typeof name !== "string"){
return result;
}
privateContext[name] = value;
if (name === "scope"){
// replace the current implementation of scope() in parent context
parentContext.scope = value;
}
return result;
}
return scope;
},[],"scope");
|
Change mdbd text driver to ignore comment lines. | package main
import (
"bufio"
"github.com/Symantec/Dominator/lib/mdb"
"io"
"log"
"strings"
)
func loadText(reader io.Reader, logger *log.Logger) (*mdb.Mdb, error) {
scanner := bufio.NewScanner(reader)
var newMdb mdb.Mdb
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) > 0 {
if fields[0][0] == '#' {
continue
}
var machine mdb.Machine
machine.Hostname = fields[0]
if len(fields) > 1 {
machine.RequiredImage = fields[1]
if len(fields) > 2 {
machine.PlannedImage = fields[2]
}
}
newMdb.Machines = append(newMdb.Machines, machine)
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return &newMdb, nil
}
| package main
import (
"bufio"
"github.com/Symantec/Dominator/lib/mdb"
"io"
"log"
"strings"
)
func loadText(reader io.Reader, logger *log.Logger) (*mdb.Mdb, error) {
scanner := bufio.NewScanner(reader)
var newMdb mdb.Mdb
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) > 0 {
var machine mdb.Machine
machine.Hostname = fields[0]
if len(fields) > 1 {
machine.RequiredImage = fields[1]
if len(fields) > 2 {
machine.PlannedImage = fields[2]
}
}
newMdb.Machines = append(newMdb.Machines, machine)
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return &newMdb, nil
}
|
Use empty tree as default | import undoable from 'redux-undo-immutable';
import { fromJS } from 'immutable';
import { findPathByNodeId } from '../utils/vertTreeUtils';
const defaultState = fromJS([
{
value: undefined,
children: [],
_id: 1000
}
]);
const verticalTreeData = (
state = defaultState,
action
) => {
let path = findPathByNodeId(action.nodeId, state);
switch (action.type) {
case 'UPDATE_VERT_STRUCTURE':
return action.newState;
case 'HIGHLIGHT_NODE':
path.push('highlighted');
return state.setIn(path, true);
case 'UNHIGHLIGHT_NODE':
path.push('highlighted');
return state.setIn(path, false);
case 'RESET_TO_DEFAULT':
return defaultState;
default:
return state;
}
};
const undoableVerticalTreeData = undoable(
verticalTreeData,
{ limit: 20 }
);
export default {
verticalTreeData: undoableVerticalTreeData,
testableVerticalTreeData: verticalTreeData
};
| import undoable from 'redux-undo-immutable';
import { fromJS } from 'immutable';
import { findPathByNodeId } from '../utils/vertTreeUtils';
const verticalTreeData = (
state = fromJS([{ value: 1, children: [{ value: 2, children: [], _id: 2000 }], _id: 1000 }]),
action
) => {
let path = findPathByNodeId(action.nodeId, state);
switch (action.type) {
case 'UPDATE_VERT_STRUCTURE':
return action.newState;
case 'HIGHLIGHT_NODE':
path.push('highlighted');
return state.setIn(path, true);
case 'UNHIGHLIGHT_NODE':
path.push('highlighted');
return state.setIn(path, false);
default:
return state;
}
};
const undoableVerticalTreeData = undoable(verticalTreeData, {
limit: 12
});
export default {
verticalTreeData: undoableVerticalTreeData,
testableVerticalTreeData: verticalTreeData
};
|
Break gutters only on large devices | import React, { PropTypes } from 'react';
import { Link, IndexLink } from 'react-router';
// This is a class-based component because the current
// version of hot reloading won't hot reload a stateless
// component at the top-level.
class App extends React.Component {
render() {
return (
<div>
<div id="header-bar">
<span>{"2016 Presidental Debates "}</span>
<IndexLink to="/">About</IndexLink>
{' | '}
<Link to="/play">Play</Link>
{' | '}
<Link to="/stats">Stats</Link>
</div>
<div className="pure-g">
<div className="pure-u-1-24 pure-u-lg-1-5"></div>
<div className="pure-u-22-24 pure-u-lg-3-5">
{this.props.children}
</div>
<div className="pure-u-1-24 pure-u-lg-1-5"></div>
</div>
</div>
);
}
}
App.propTypes = {
children: PropTypes.element
};
export default App;
| import React, { PropTypes } from 'react';
import { Link, IndexLink } from 'react-router';
// This is a class-based component because the current
// version of hot reloading won't hot reload a stateless
// component at the top-level.
class App extends React.Component {
render() {
return (
<div>
<div id="header-bar">
<span>{"2016 Presidental Debates "}</span>
<IndexLink to="/">About</IndexLink>
{' | '}
<Link to="/play">Play</Link>
{' | '}
<Link to="/stats">Stats</Link>
</div>
<div className="pure-g">
<div className="pure-u-1-24 pure-u-sm-1-5"></div>
<div className="pure-u-22-24 pure-u-sm-3-5">
{this.props.children}
</div>
<div className="pure-u-1-24 pure-u-sm-1-5"></div>
</div>
</div>
);
}
}
App.propTypes = {
children: PropTypes.element
};
export default App;
|
Fix typo extenstions -> extensions | var webpack = require('webpack');
var path = require('path');
var loader = require('babel-loader');
var BUILD_DIR = path.resolve(__dirname, 'client/src/public');
var APP_DIR = path.resolve(__dirname, 'client/src/app');
var config = {
entry: APP_DIR + '/App.jsx',
devtool: 'source-map',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
externals: {
'cheerio':
'window',
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true,
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react', 'stage-0']
},
exclude: /node_modules/,
}
],
},
watch: true
};
module.exports = config;
| var webpack = require('webpack');
var path = require('path');
var loader = require('babel-loader');
var BUILD_DIR = path.resolve(__dirname, 'client/src/public');
var APP_DIR = path.resolve(__dirname, 'client/src/app');
var config = {
entry: APP_DIR + '/App.jsx',
devtool: 'source-map',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
resolve: {
extenstions: ['', '.js', '.jsx']
},
externals: {
'cheerio':
'window',
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true,
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react', 'stage-0']
},
exclude: /node_modules/,
}
],
},
watch: true
};
module.exports = config;
|
fix: Convert to SQL to set_value | import frappe
from frappe.utils import get_datetime
def execute():
weekdays = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
weekly_events = frappe.get_list("Event", filters={"repeat_this_event": 1, "repeat_on": "Every Week"}, fields=["name", "starts_on"])
frappe.reload_doc("desk", "doctype", "event")
# Initially Daily Events had option to choose days, but now Weekly does, so just changing from Daily -> Weekly does the job
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.repeat_on='Weekly' WHERE `tabEvent`.repeat_on='Every Day'""")
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.repeat_on='Weekly' WHERE `tabEvent`.repeat_on='Every Week'""")
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.repeat_on='Monthly' WHERE `tabEvent`.repeat_on='Every Month'""")
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.repeat_on='Yearly' WHERE `tabEvent`.repeat_on='Every Year'""")
for weekly_event in weekly_events:
# Set WeekDay based on the starts_on so that event can repeat Weekly
frappe.db.set_value('Event', weekly_event.name, weekdays[get_datetime(weekly_event.starts_on).weekday()], 1, update_modified=1)
| import frappe
from frappe.utils import get_datetime
def execute():
weekdays = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
weekly_events = frappe.get_list("Event", filters={"repeat_this_event": 1, "repeat_on": "Every Week"}, fields=["name", "starts_on"])
frappe.reload_doc("desk", "doctype", "event")
# Initially Daily Events had option to choose days, but now Weekly does, so just changing from Daily -> Weekly does the job
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.repeat_on='Weekly' WHERE `tabEvent`.repeat_on='Every Day'""")
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.repeat_on='Weekly' WHERE `tabEvent`.repeat_on='Every Week'""")
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.repeat_on='Monthly' WHERE `tabEvent`.repeat_on='Every Month'""")
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.repeat_on='Yearly' WHERE `tabEvent`.repeat_on='Every Year'""")
for weekly_event in weekly_events:
# Set WeekDay based on the starts_on so that event can repeat Weekly
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.{0}=1 WHERE `tabEvent`.name='{1}'""".format(weekdays[get_datetime(weekly_event.starts_on).weekday()], weekly_event.name))
|
Delete sample changelog at end of test - check for open file leak
JENKINS-20585 reports that changelog.xml cannot be deleted on Windows
because it is held busy by a process. This test assumes that process
is Jenkins itself, and that the GitChangeLogParser.parse() method is
the most likely culprit. | package hudson.plugins.git;
import java.io.File;
import java.io.FileWriter;
import org.jvnet.hudson.test.HudsonTestCase;
/**
* Unit tests of {@link GitChangeLogParser}
*/
public class GitChangeLogParserTest extends HudsonTestCase {
/**
* Test duplicate changes filtered from parsed change set list.
*
* @throws Exception
*/
public void testDuplicatesFiltered() throws Exception {
GitChangeLogParser parser = new GitChangeLogParser(true);
File log = File.createTempFile(getClass().getName(), ".tmp");
FileWriter writer = new FileWriter(log);
writer.write("commit 123abc456def\n");
writer.write(" first message\n");
writer.write("commit 123abc456def\n");
writer.write(" second message");
writer.close();
GitChangeSetList list = parser.parse(null, log);
assertNotNull(list);
assertNotNull(list.getLogs());
assertEquals(1, list.getLogs().size());
GitChangeSet first = list.getLogs().get(0);
assertNotNull(first);
assertEquals("123abc456def", first.getId());
assertEquals("first message", first.getMsg());
assertTrue("Temp file delete failed for " + log, log.delete());
}
}
| package hudson.plugins.git;
import java.io.File;
import java.io.FileWriter;
import org.jvnet.hudson.test.HudsonTestCase;
/**
* Unit tests of {@link GitChangeLogParser}
*/
public class GitChangeLogParserTest extends HudsonTestCase {
/**
* Test duplicate changes filtered from parsed change set list.
*
* @throws Exception
*/
public void testDuplicatesFiltered() throws Exception {
GitChangeLogParser parser = new GitChangeLogParser(true);
File log = File.createTempFile(getClass().getName(), ".tmp");
FileWriter writer = new FileWriter(log);
writer.write("commit 123abc456def\n");
writer.write(" first message\n");
writer.write("commit 123abc456def\n");
writer.write(" second message");
writer.close();
GitChangeSetList list = parser.parse(null, log);
assertNotNull(list);
assertNotNull(list.getLogs());
assertEquals(1, list.getLogs().size());
GitChangeSet first = list.getLogs().get(0);
assertNotNull(first);
assertEquals("123abc456def", first.getId());
assertEquals("first message", first.getMsg());
}
}
|
Update name of user -2
Changed from StackExchange to Stack Exchange | import chatexchange
import live_testing
if live_testing.enabled:
def test_user_info():
client = chatexchange.Client('stackexchange.com')
user = client.get_user(-2)
assert user.id == -2
assert not user.is_moderator
assert user.name == "Stack Exchange"
assert user.room_count >= 18
assert user.message_count >= 129810
assert user.reputation == -1
user = client.get_user(31768)
assert user.id == 31768
assert user.is_moderator
assert user.name == "ManishEarth"
assert user.room_count >= 222
assert user.message_count >= 89093
assert user.reputation > 115000
| import chatexchange
import live_testing
if live_testing.enabled:
def test_user_info():
client = chatexchange.Client('stackexchange.com')
user = client.get_user(-2)
assert user.id == -2
assert not user.is_moderator
assert user.name == "StackExchange"
assert user.room_count >= 18
assert user.message_count >= 129810
assert user.reputation == -1
user = client.get_user(31768)
assert user.id == 31768
assert user.is_moderator
assert user.name == "ManishEarth"
assert user.room_count >= 222
assert user.message_count >= 89093
assert user.reputation > 115000
|
Change topic + add exception handling | from kafka import KafkaConsumer
import os
import nexmo
import json
client = nexmo.Client( key=os.environ["API_KEY"],
secret=os.environ["API_SECRET"])
consumer = KafkaConsumer(bootstrap_servers=os.environ["KAFKA"],
value_deserializer=lambda m: json.loads(m.decode('ascii')))
consumer.subscribe(['sms_response'])
while True:
for message in consumer:
try:
client.send_message({ 'from' : message.value['from'],
'to' : message.value['to'],
'text' : message.value['text']})
except:
print 'Unexpected error'
| from kafka import KafkaConsumer
import os
import nexmo
import json
client = nexmo.Client( key=os.environ["API_KEY"],
secret=os.environ["API_SECRET"])
consumer = KafkaConsumer(bootstrap_servers=os.environ["KAFKA"],
value_deserializer=lambda m: json.loads(m.decode('ascii')))
consumer.subscribe(['kafka_test1'])
while True:
for message in consumer:
client.send_message({ 'from' : message.value['from'],
'to' : message.value['to'],
'text' : message.value['text']})
|
:art: Make commander workaround shine a bit more | #!/usr/bin/env node
'use strict'
const command = process.argv[2] || ''
const validCommands = ['new', 'build', 'update', 'init']
// TODO: Check for updates
// Note: This is a trick to make multiple commander commands work with single executables
// In: [nodePath, 'motion', 'run', '--help']
// Out: [nodePath, 'motion run', '--help']
process.argv = [process.argv[0], [process.argv[1], process.argv[2]].join(' ').trim()].concat(process.argv.slice(3))
let showHelp = command === '--help'
if (!showHelp && (!command || command === 'run')) {
require('./motion-run')
} else if (!showHelp && validCommands.indexOf(command) !== -1) {
require(`./motion-${command}`)
} else {
console.error(`
Usage:
motion alias for 'motion run'
motion run run your motion app
motion new [name] [template] start a new app
motion build build for production
motion update update motion
motion init add a motion config to an existing app (temporary, awaiting https://github.com/motion/motion/issues/339)
`.trim())
process.exit(1)
}
| #!/usr/bin/env node
'use strict'
const command = process.argv[2] || ''
const validCommands = ['new', 'build', 'update', 'init']
// TODO: Check for updates
// Note: This is a trick to make multiple commander commands work with single executables
process.argv = process.argv.slice(0, 2).concat(process.argv.slice(3))
let showHelp = command === '--help'
if (!showHelp && (!command || command === 'run')) {
require('./motion-run')
} else if (!showHelp && validCommands.indexOf(command) !== -1) {
require(`./motion-${command}`)
} else {
console.error(`
Usage:
motion alias for 'motion run'
motion run run your motion app
motion new [name] [template] start a new app
motion build build for production
motion update update motion
motion init add a motion config to an existing app (temporary, awaiting https://github.com/motion/motion/issues/339)
`.trim())
process.exit(1)
}
|
Exclude cafes from place list | import View from '../base/view';
import Feed from '../models/feed';
import {capfirst} from '../utils';
import FeedView from './feed-view';
import itemTemplate from '../../templates/feed-place.ejs';
export default class PlacesView extends View {
constructor({app, model}) {
super({app, model});
this.feed = new Feed(
'/places/', {
fields: 'images,title,id,address',
categories: 'theatre,-cafe',
expand: 'images',
order_by: '-favorites_count',
page_size: 24,
});
this.feedView = new FeedView({app, itemTemplate, model: this.feed});
}
render() {
this.element.innerHTML = '';
this.feedView.render();
this.element.appendChild(this.feedView.element);
this.update();
}
unbind() {
this.feedView.unbind();
super.unbind();
}
onModelChange() {
this.update();
}
update() {
this.updateFeedQuery();
this.updateAppState();
}
updateFeedQuery() {
this.feed.query.set('location', this.model.get('location'));
}
updateAppState() {
const location = this.app.locations.get(this.model.get('location'));
this.app.setTitle(`Театры – ${location.name}`);
this.app.settings.set('location', location.slug);
}
}
| import View from '../base/view';
import Feed from '../models/feed';
import {capfirst} from '../utils';
import FeedView from './feed-view';
import itemTemplate from '../../templates/feed-place.ejs';
export default class PlacesView extends View {
constructor({app, model}) {
super({app, model});
this.feed = new Feed(
'/places/', {
categories: 'theatre',
fields: 'images,title,id,address',
expand: 'images',
order_by: '-favorites_count',
page_size: 24,
});
this.feedView = new FeedView({app, itemTemplate, model: this.feed});
}
render() {
this.element.innerHTML = '';
this.feedView.render();
this.element.appendChild(this.feedView.element);
this.update();
}
unbind() {
this.feedView.unbind();
super.unbind();
}
onModelChange() {
this.update();
}
update() {
this.updateFeedQuery();
this.updateAppState();
}
updateFeedQuery() {
this.feed.query.set('location', this.model.get('location'));
}
updateAppState() {
const location = this.app.locations.get(this.model.get('location'));
this.app.setTitle(`Театры – ${location.name}`);
this.app.settings.set('location', location.slug);
}
}
|
Upgrade ver a little more | #!/usr/bin/env python
from setuptools import setup, find_packages
def readme():
with open('README.rst') as f:
return f.read()
setup(
name='django-mailer-server-backend',
version='0.1.4',
description="A django mail backend for mailer server (https://github.com/spapas/mailer_server)",
long_description=readme(),
author='Serafeim Papastefanos',
author_email='spapas@gmail.com',
license='MIT',
url='https://github.com/spapas/django-mailer-server-backend',
zip_safe=False,
include_package_data=True,
packages=find_packages(exclude=['tests.*', 'tests',]),
install_requires=['Django >= 1.11', 'six'],
classifiers=[
'Environment :: Web Environment',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Framework :: Django',
'Framework :: Django :: 2.0',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries',
],
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
def readme():
with open('README.rst') as f:
return f.read()
setup(
name='django-mailer-server-backend',
version='0.1.3',
description="A django mail backend for mailer server (https://github.com/spapas/mailer_server)",
long_description=readme(),
author='Serafeim Papastefanos',
author_email='spapas@gmail.com',
license='MIT',
url='https://github.com/spapas/django-mailer-server-backend',
zip_safe=False,
include_package_data=True,
packages=find_packages(exclude=['tests.*', 'tests',]),
install_requires=['Django >= 1.11', 'six'],
classifiers=[
'Environment :: Web Environment',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Framework :: Django',
'Framework :: Django :: 2.0',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries',
],
)
|
Fix possible omission of posts when filtering feed | var createXMLTransformer = require('./xml-transformer');
var log = require('./util').log;
var patterns = require('./util').patterns;
var track = require('./util').track;
function createFilters(configs) {
return configs.map(function(config) {
var filter = { name: config.name };
if (config.type === 'blacklist') {
filter.pattern = patterns.createFromTokens(config.tokens);
}
return filter;
});
}
module.exports = function filterFeed(delegate) {
var filters = createFilters(delegate.config.filters);
var root = createXMLTransformer({ string: delegate.data, verbose: delegate.verbose });
delegate.transformMeta(root);
var skipped = [];
var entry;
while ((entry = root.find('entry'))) {
if (delegate.shouldSkipEntry(filters, entry)) {
root.skip();
skipped.push(entry.find('link'));
} else {
delegate.transformEntry(entry);
root.next();
}
}
track('Skipped '+ skipped.length +' for '+ delegate.config.name +'\n'+
skipped.join('\n'));
return root.string;
};
| var createXMLTransformer = require('./xml-transformer');
var log = require('./util').log;
var patterns = require('./util').patterns;
var track = require('./util').track;
function createFilters(configs) {
return configs.map(function(config) {
var filter = { name: config.name };
if (config.type === 'blacklist') {
filter.pattern = patterns.createFromTokens(config.tokens);
}
return filter;
});
}
module.exports = function filterFeed(delegate) {
var filters = createFilters(delegate.config.filters);
var root = createXMLTransformer({ string: delegate.data, verbose: delegate.verbose });
delegate.transformMeta(root);
var skipped = [];
var entry;
while ((entry = root.find('entry'))) {
if (delegate.shouldSkipEntry(filters, entry)) {
root.skip();
skipped.push(entry.find('link'));
} else {
delegate.transformEntry(entry);
}
root.next();
}
track('Skipped '+ skipped.length +' for '+ delegate.config.name +'\n'+
skipped.join('\n'));
return root.string;
};
|
Add @Override annotation for toString() | package uk.ac.ebi.quickgo.geneproduct.common;
/**
* An enumeration of the possible states of proteome membership a gene product can have.
* @author Tony Wardell
* Date: 06/03/2018
* Time: 10:33
* Created with IntelliJ IDEA.
*/
public enum ProteomeMembership {
REFERENCE("Reference"),
COMPLETE("Complete"),
NONE("None"),
NOT_APPLICABLE("Not-applicable");
private String value;
ProteomeMembership(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
/**
* Define the predicates required and order of importance to work out which Proteome membership category is
* applicable.
* @param isProtein is the gene product a protein
* @param isReferenceProteome is the gene product a reference proteome
* @param isComplete is the gene product a member of a complete proteome.
* @return the String representation of the ProteomeMembership matching the applied constraints
*/
public static String membership(boolean isProtein, boolean isReferenceProteome, boolean isComplete) {
if (!isProtein) {
return NOT_APPLICABLE.toString();
} else if (isReferenceProteome) {
return REFERENCE.toString();
} else if (isComplete) {
return COMPLETE.toString();
}
return NONE.toString();
}
}
| package uk.ac.ebi.quickgo.geneproduct.common;
/**
* An enumeration of the possible states of proteome membership a gene product can have.
* @author Tony Wardell
* Date: 06/03/2018
* Time: 10:33
* Created with IntelliJ IDEA.
*/
public enum ProteomeMembership {
REFERENCE("Reference"),
COMPLETE("Complete"),
NONE("None"),
NOT_APPLICABLE("Not-applicable");
private String value;
ProteomeMembership(String value) {
this.value = value;
}
public String toString() {
return value;
}
/**
* Define the predicates required and order of importance to work out which Proteome membership category is
* applicable.
* @param isProtein is the gene product a protein
* @param isReferenceProteome is the gene product a reference proteome
* @param isComplete is the gene product a member of a complete proteome.
* @return the String representation of the ProteomeMembership matching the applied constraints
*/
public static String membership(boolean isProtein, boolean isReferenceProteome, boolean isComplete) {
if (!isProtein) {
return NOT_APPLICABLE.toString();
} else if (isReferenceProteome) {
return REFERENCE.toString();
} else if (isComplete) {
return COMPLETE.toString();
}
return NONE.toString();
}
}
|
Move weekend days to Friday and Saturday | Date.prototype.toInputFormat = function() {
return [this.getFullYear(), this.getMonth() + 1, this.getDate()]
.map(function(value) {
return value < 10 ? "0" + value : value;
})
.join('-');
};
function initializeDates(container) {
if (!container) container = document;
$(container).find('[data-date]').each(function() {
var date = new Date(this.getAttribute('data-date'));
this.value = date.toInputFormat();
});
$('[data-datepicker]').datepicker({
todayBtn: "linked",
todayHighlight: true,
daysOfWeekHighlighted: "5,6"
});
}
function jsonForm(formName) {
return JSON.stringify(buildForm(formName));
}
function buildForm(formName) {
var $form = $("#" + formName);
var output = {};
$form.serializeArray().forEach(function(input) {
if (input.name.toLowerCase().indexOf('date') !== -1 && input.value) {
input.value = new Date(input.value).toISOString();
}
output[input.name] = input.value;
});
return output;
}
| Date.prototype.toInputFormat = function() {
return [this.getFullYear(), this.getMonth() + 1, this.getDate()]
.map(function(value) {
return value < 10 ? "0" + value : value;
})
.join('-');
};
function initializeDates(container) {
if (!container) container = document;
$(container).find('[data-date]').each(function() {
var date = new Date(this.getAttribute('data-date'));
this.value = date.toInputFormat();
});
$('[data-datepicker]').datepicker({
todayBtn: "linked",
todayHighlight: true,
daysOfWeekHighlighted: "0,6"
});
}
function jsonForm(formName) {
return JSON.stringify(buildForm(formName));
}
function buildForm(formName) {
var $form = $("#" + formName);
var output = {};
$form.serializeArray().forEach(function(input) {
if (input.name.toLowerCase().indexOf('date') !== -1 && input.value) {
input.value = new Date(input.value).toISOString();
}
output[input.name] = input.value;
});
return output;
}
|
Change in database configuration file | from bdo_platform.settings_management.development import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'bdo_local_database',
'USER': 'postgres',
'PASSWORD': 'sssshmmy',
'HOST': 'localhost',
'PORT': '5432',
},
'UBITECH_POSTGRES': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'bigdataocean',
'USER': 'bdo',
'PASSWORD': 'df195715HBdhahfP',
'HOST': '212.101.173.21',
'PORT': '5432',
}
}
SPARK_SUBMIT_PATH = ''
#
# # dev server URL
# SERVER_URL = 'http://127.0.0.1:8000'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True | from bdo_platform.settings_management.development import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'bdo_platform',
'USER': 'postgres',
'PASSWORD': 'sssshmmy',
'HOST': 'localhost',
'PORT': '5432',
},
'UBITECH_POSTGRES': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'bigdataocean',
'USER': 'bdo',
'PASSWORD': 'df195715HBdhahfP',
'HOST': '212.101.173.21',
'PORT': '5432',
}
}
SPARK_SUBMIT_PATH = ''
#
# # dev server URL
# SERVER_URL = 'http://127.0.0.1:8000'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True |
Fix that awful inventory migration issue | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2017-11-21 20:43
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inventory', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='item',
name='column',
field=models.IntegerField(null=True),
),
migrations.AddField(
model_name='item',
name='row',
field=models.IntegerField(null=True),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2017-11-21 20:43
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inventory', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='item',
name='place',
),
migrations.AddField(
model_name='item',
name='column',
field=models.IntegerField(null=True),
),
migrations.AddField(
model_name='item',
name='row',
field=models.IntegerField(null=True),
),
]
|
Use global to pull in the window | /**
* Treasure Client Loader
*/
// Modules
var _ = require('./utils/lodash')
var window = require('global/window')
// Helpers
function applyToClient (client, method) {
var _method = '_' + method
if (client[_method]) {
var arr = client[_method] || []
while (arr.length) {
client[method].apply(client, arr.shift())
}
delete client[_method]
}
}
// Constants
var TREASURE_KEYS = ['init', 'set', 'addRecord', 'trackPageview', 'trackEvent', 'ready']
/**
* Load clients
*/
module.exports = function loadClients (Treasure, name) {
if (_.isObject(window[name])) {
var snippet = window[name]
var clients = snippet.clients
// Copy over Treasure.prototype functions over to snippet's prototype
// This allows already-instanciated clients to work
_.mixin(snippet.prototype, Treasure.prototype)
// Iterate over each client instance
_.forEach(clients, function (client) {
// Call each key and with any stored values
_.forEach(TREASURE_KEYS, function (value) {
applyToClient(client, value)
})
})
}
}
| /**
* Treasure Client Loader
*/
// Modules
var _ = require('./utils/lodash')
// Helpers
function applyToClient (client, method) {
var _method = '_' + method
if (client[_method]) {
var arr = client[_method] || []
while (arr.length) {
client[method].apply(client, arr.shift())
}
delete client[_method]
}
}
// Constants
var TREASURE_KEYS = ['init', 'set', 'addRecord', 'trackPageview', 'trackEvent', 'ready']
/**
* Load clients
*/
module.exports = function loadClients (Treasure, name) {
if (_.isObject(global[name])) {
var snippet = global[name]
var clients = snippet.clients
// Copy over Treasure.prototype functions over to snippet's prototype
// This allows already-instanciated clients to work
_.mixin(snippet.prototype, Treasure.prototype)
// Iterate over each client instance
_.forEach(clients, function (client) {
// Call each key and with any stored values
_.forEach(TREASURE_KEYS, function (value) {
applyToClient(client, value)
})
})
}
}
|
Use LooseVersion to compare version numbers | import pytest
from distutils.version import LooseVersion
import matplotlib as mpl
from ..gui import PVSlicer
from .test_slicer import make_test_hdu
try:
import PyQt5
PYQT5OK = True
except ImportError:
PYQT5OK = False
if LooseVersion(mpl.__version__) < LooseVersion('2'):
MPLOK = True
else:
MPLOK = False
@pytest.mark.skipif('not PYQT5OK or not MPLOK')
def test_gui():
hdu = make_test_hdu()
pv = PVSlicer(hdu, clim=(-0.02, 2))
pv.show(block=False)
x = [100, 200, 220, 330, 340]
y = [100, 200, 300, 420, 430]
for i in range(len(x)):
pv.fig.canvas.motion_notify_event(x[i], y[i])
pv.fig.canvas.button_press_event(x[i], y[i], 1)
pv.fig.canvas.key_press_event('enter')
pv.fig.canvas.motion_notify_event(310, 420)
pv.fig.canvas.button_press_event(410, 420, 1)
pv.fig.canvas.draw()
assert pv.pv_slice.data.shape == (5, 2)
| import numpy as np
from numpy.testing import assert_allclose
import pytest
from astropy.io import fits
from ..pvextractor import extract_pv_slice
from ..geometry.path import Path
from ..gui import PVSlicer
from .test_slicer import make_test_hdu
try:
import PyQt5
PYQT5OK = True
except ImportError:
PYQT5OK = False
import matplotlib as mpl
if mpl.__version__[0] == '2':
MPLOK = False
else:
MPLOK = True
@pytest.mark.skipif('not PYQT5OK or not MPLOK')
def test_gui():
hdu = make_test_hdu()
pv = PVSlicer(hdu, clim=(-0.02, 2))
pv.show(block=False)
x = [100,200,220,330,340]
y = [100,200,300,420,430]
for i in range(len(x)):
pv.fig.canvas.motion_notify_event(x[i],y[i])
pv.fig.canvas.button_press_event(x[i],y[i],1)
pv.fig.canvas.key_press_event('enter')
pv.fig.canvas.motion_notify_event(310,420)
pv.fig.canvas.button_press_event(410,420,1)
pv.fig.canvas.draw()
assert pv.pv_slice.data.shape == (5,2)
|
Remove py3 for the moment | from setuptools import setup
setup(
name='icapservice',
version='0.1.0',
description='ICAP service library for Python',
author='Giles Brown',
author_email='giles_brown@hotmail.com',
url='https://github.com/gilesbrown/icapservice',
license='MIT',
packages=['icapservice'],
zip_safe=False,
install_requires=['six'],
include_package_data=True,
package_data={'': ['LICENSE']},
classifiers=(
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
#'Programming Language :: Python :: 3',
#'Programming Language :: Python :: 3.4',
#'Programming Language :: Python :: 3.5',
),
)
| from setuptools import setup
setup(
name='icapservice',
version='0.1.0',
description='ICAP service library for Python',
author='Giles Brown',
author_email='giles_brown@hotmail.com',
url='https://github.com/gilesbrown/icapservice',
license='MIT',
packages=['icapservice'],
zip_safe=False,
install_requires=['six'],
include_package_data=True,
package_data={'': ['LICENSE']},
classifiers=(
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
),
)
|
Fix fuel recipe transfer helper | package mezz.jei.plugins.vanilla.furnace;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import mezz.jei.plugins.vanilla.VanillaRecipeWrapper;
import mezz.jei.util.Translator;
public class FuelRecipe extends VanillaRecipeWrapper {
@Nonnull
private final List<List<ItemStack>> inputs;
@Nonnull
private final String burnTimeString;
public FuelRecipe(@Nonnull Collection<ItemStack> input, int burnTime) {
this.inputs = Collections.singletonList(new ArrayList<>(input));
this.burnTimeString = Translator.translateToLocalFormatted("gui.jei.furnaceBurnTime", burnTime);
}
@Nonnull
@Override
public List<List<ItemStack>> getInputs() {
return inputs;
}
@Nonnull
@Override
public List<ItemStack> getOutputs() {
return Collections.emptyList();
}
@Override
public void drawInfo(@Nonnull Minecraft minecraft, int recipeWidth, int recipeHeight) {
minecraft.fontRendererObj.drawString(burnTimeString, 24, 12, Color.gray.getRGB());
}
}
| package mezz.jei.plugins.vanilla.furnace;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import mezz.jei.plugins.vanilla.VanillaRecipeWrapper;
import mezz.jei.util.Translator;
public class FuelRecipe extends VanillaRecipeWrapper {
@Nonnull
private final List<ItemStack> input;
@Nullable
private final String burnTimeString;
public FuelRecipe(@Nonnull Collection<ItemStack> input, int burnTime) {
this.input = new ArrayList<>(input);
this.burnTimeString = Translator.translateToLocalFormatted("gui.jei.furnaceBurnTime", burnTime);
}
@Nonnull
@Override
public List<ItemStack> getInputs() {
return input;
}
@Nonnull
@Override
public List<ItemStack> getOutputs() {
return Collections.emptyList();
}
@Override
public void drawInfo(@Nonnull Minecraft minecraft, int recipeWidth, int recipeHeight) {
minecraft.fontRendererObj.drawString(burnTimeString, 24, 12, Color.gray.getRGB());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.