text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Make platform ID a Number
|
'use babel';
import { SelectView } from 'particle-dev-views';
let $$ = null;
export default class SelectTargetPlatformView extends SelectView {
constructor(...args) {
super(...args);
this.show = this.show.bind(this);
}
initialize(profileManager) {
this.profileManager = profileManager;
super.initialize(...arguments);
({$$} = require('atom-space-pen-views'));
return this.prop('id', 'particle-dev-select-target-platform-view');
}
show() {
let items = [];
for (let k in this.profileManager.knownTargetPlatforms) {
let v = this.profileManager.knownTargetPlatforms[k];
v.id = parseInt(k);
items.push(v);
}
this.setItems(items);
return super.show(...arguments);
}
viewForItem(item) {
return $$(function view() {
return this.li(item.name);
});
}
confirmed(item) {
this.hide();
return this.profileManager.currentTargetPlatform = item.id;
}
getFilterKey() {
return 'name';
}
};
|
'use babel';
import { SelectView } from 'particle-dev-views';
let $$ = null;
export default class SelectTargetPlatformView extends SelectView {
constructor(...args) {
super(...args);
this.show = this.show.bind(this);
}
initialize(profileManager) {
this.profileManager = profileManager;
super.initialize(...arguments);
({$$} = require('atom-space-pen-views'));
return this.prop('id', 'particle-dev-select-target-platform-view');
}
show() {
let items = [];
for (let k in this.profileManager.knownTargetPlatforms) {
let v = this.profileManager.knownTargetPlatforms[k];
v.id = k;
items.push(v);
}
this.setItems(items);
return super.show(...arguments);
}
viewForItem(item) {
return $$(function view() {
return this.li(item.name);
});
}
confirmed(item) {
this.hide();
return this.profileManager.currentTargetPlatform = item.id;
}
getFilterKey() {
return 'name';
}
};
|
Allow compatibility with RN 0.47
|
package com.futurice.rctaudiotoolkit;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class AudioPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new AudioRecorderModule(reactContext));
modules.add(new AudioPlayerModule(reactContext));
return modules;
}
// Deprecated in RN 0.47
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
|
package com.futurice.rctaudiotoolkit;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class AudioPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new AudioRecorderModule(reactContext));
modules.add(new AudioPlayerModule(reactContext));
return modules;
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
|
Add pboothe temporarily for testing
|
# NOTE: User roles are not managed here. Visit PlanetLab to change user roles.
user_list = [('Stephen', 'Stuart', 'sstuart@google.com'),
('Will', 'Hawkins', 'hawkinsw@opentechinstitute.org'),
('Jordan', 'McCarthy', 'mccarthy@opentechinstitute.org'),
('Chris', 'Ritzo', 'critzo@opentechinstitute.org'),
('Josh', 'Bailey', 'joshb@google.com'),
('Steph', 'Alarcon', 'salarcon@measurementlab.net'),
('Nathan', 'Kinkade', 'kinkade@opentechinstitute.org'),
('Matt', 'Mathis', 'mattmathis@google.com')
('Peter', 'Boothe', 'pboothe@google.com')]
|
# NOTE: User roles are not managed here. Visit PlanetLab to change user roles.
user_list = [('Stephen', 'Stuart', 'sstuart@google.com'),
('Will', 'Hawkins', 'hawkinsw@opentechinstitute.org'),
('Jordan', 'McCarthy', 'mccarthy@opentechinstitute.org'),
('Chris', 'Ritzo', 'critzo@opentechinstitute.org'),
('Josh', 'Bailey', 'joshb@google.com'),
('Steph', 'Alarcon', 'salarcon@measurementlab.net'),
('Nathan', 'Kinkade', 'kinkade@opentechinstitute.org'),
('Matt', 'Mathis', 'mattmathis@google.com')]
|
Fix typo in delivery server.
|
// Continuous delivery server
const { spawn } = require('child_process')
const { resolve } = require('path')
const { createServer } = require('http')
const { urlencoded } = require('body-parser')
const hostname = '127.0.0.1'
const port = 80
const server = createServer((req, res) => {
const { headers, method, url } = request
// When a successful build has happened, kill the process, triggering a restart
if (req.method === 'POST' && req.url === '/webhook') {
// Send response
res.statusCode = 200
res.end()
let body = []
request
.on('error', err => {
console.error(err)
})
.on('data', chunk => {
body.push(chunk)
})
.on('end', () => {
body = Buffer.concat(body).toString()
const data = urlencoded(body)
console.log(data)
})
}
res.statusCode = 404
res.end()
})
|
// Continuous delivery server
const { spawn } = require('child_process')
const { resolve } = require('path')
const { createServer } = require('http')
const { urlencoded } = require('body-parser')
const hostname = '127.0.0.1'
const port = 80
const server = http.createServer((req, res) => {
const { headers, method, url } = request
// When a successful build has happened, kill the process, triggering a restart
if (req.method === 'POST' && req.url === '/webhook') {
// Send response
res.statusCode = 200
res.end()
let body = []
request
.on('error', err => {
console.error(err)
})
.on('data', chunk => {
body.push(chunk)
})
.on('end', () => {
body = Buffer.concat(body).toString()
const data = urlencoded(body)
console.log(data)
})
}
res.statusCode = 404
res.end()
})
|
Trim the input on user form
|
<?php
namespace UBC\Exam\MainBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', 'text', array('trim' => true))
->add('firstname', 'text', array('trim' => true))
->add('lastname', 'text', array('trim' => true))
->add('roleString', 'text', array('trim' => true))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'UBC\Exam\MainBundle\Entity\User'
));
}
public function getName()
{
return 'ubc_exam_mainbundle_user';
}
}
|
<?php
namespace UBC\Exam\MainBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username')
->add('firstname')
->add('lastname')
->add('roleString')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'UBC\Exam\MainBundle\Entity\User'
));
}
public function getName()
{
return 'ubc_exam_mainbundle_user';
}
}
|
Raise exception if sdb does not exist
|
#!/usr/bin/env python3
# Copyright 2015-2016 Samsung Electronics Co., Ltd.
#
# 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.
from configparser import RawConfigParser
from litmus.core.util import call
def load_project_list(projects):
"""docstring for load_project_list"""
configparser = RawConfigParser()
configparser.read(projects)
project_list = []
for section in configparser.sections():
item = dict(configparser.items(section))
item['name'] = section
project_list.append(item)
return project_list
def sdb_does_exist():
help_url = 'https://github.com/dhs-shine/litmus#prerequisite'
try:
call(['sdb', 'version'], timeout=10)
except FileNotFoundError:
raise Exception('Please install sdb. Refer to {}'.format(help_url))
return
|
#!/usr/bin/env python3
# Copyright 2015-2016 Samsung Electronics Co., Ltd.
#
# 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.
from configparser import RawConfigParser
from litmus.core.util import call
def load_project_list(projects):
"""docstring for load_project_list"""
configparser = RawConfigParser()
configparser.read(projects)
project_list = []
for section in configparser.sections():
item = dict(configparser.items(section))
item['name'] = section
project_list.append(item)
return project_list
def sdb_does_exist():
help_url = 'https://github.com/dhs-shine/litmus#prerequisite'
try:
call('sdb version', shell=True, timeout=10)
except FileNotFoundError:
raise Exception('Please install sdb. Refer to {}'.format(help_url))
return
|
Fix prefix problem that made a 404 error
|
package kwiscale
import (
"crypto/md5"
"fmt"
"net/http"
"os"
"path/filepath"
)
// StaticHandler handle static files handlers. Use App.SetStatic(path) that create the static handler
type staticHandler struct {
RequestHandler
}
// Use http.FileServer to serve file after adding ETag.
func (s *staticHandler) Get() {
file := s.Vars["file"]
abs, _ := filepath.Abs(s.app.Config.StaticDir)
file = filepath.Join(abs, file)
// control or add etag
if etag, err := eTag(file); err == nil {
s.response.Header().Add("ETag", etag)
}
// create a fileserver for the static dir
fs := http.FileServer(http.Dir(s.app.Config.StaticDir))
// stip directory name and serve the file
http.StripPrefix("/"+filepath.Base(s.app.Config.StaticDir), fs).
ServeHTTP(s.Response(), s.Request())
}
// Get a etag for the file. It's constuct with a md5 sum of
// <filename> + "." + <modification-time>
func eTag(file string) (string, error) {
stat, err := os.Stat(file)
if err != nil {
return "", err
}
s := md5.Sum([]byte(stat.Name() + "." + stat.ModTime().String()))
return fmt.Sprintf("%x", s), nil
}
|
package kwiscale
import (
"crypto/md5"
"fmt"
"net/http"
"os"
"path/filepath"
)
// StaticHandler handle static files handlers. Use App.SetStatic(path) that create the static handler
type staticHandler struct {
RequestHandler
}
// Use http.FileServer to serve file after adding ETag.
func (s *staticHandler) Get() {
file := s.Vars["file"]
file = filepath.Join(s.app.Config.StaticDir, file)
// control or add etag
if etag, err := eTag(file); err == nil {
s.response.Header().Add("ETag", etag)
}
fs := http.FileServer(http.Dir(s.app.Config.StaticDir))
fs.ServeHTTP(s.response, s.request)
}
// Get a etag for the file. It's constuct with a md5 sum of
// <filename> + "." + <modification-time>
func eTag(file string) (string, error) {
stat, err := os.Stat(file)
if err != nil {
return "", err
}
s := md5.Sum([]byte(stat.Name() + "." + stat.ModTime().String()))
return fmt.Sprintf("%x", s), nil
}
|
Remove axios and unused function
|
export const liveRootUrl = 'https://bolg-app.herokuapp.com/posts/';
export const states = {
LOADING: 0,
EDITING: 1,
SAVED: 2,
ERROR: 3,
EDITING_OFFLINE: 4,
SAVED_OFFLINE: 5,
PUBLISHED: 6,
};
export const mapsAPIKey = 'AIzaSyBADvjevyMmDkHb_xjjh3FOltkO2Oa8iAQ';
export const sizes = [
{
width: 2560,
height: 1440,
},
{
width: 1920,
height: 1080,
},
{
width: 1024,
height: 576,
},
{
width: 640,
height: 360,
},
];
export const slugger = str => str
.toLowerCase()
.replace(/ä/g, 'ae')
.replace(/ö/g, 'oe')
.replace(/ü/g, 'ue')
.replace(/[^\w ]+/g, ' ')
.replace(/ +/g, '-');
|
import axios from 'axios';
export const liveRootUrl = 'https://bolg-app.herokuapp.com/posts/';
export const states = {
LOADING: 0,
EDITING: 1,
SAVED: 2,
ERROR: 3,
EDITING_OFFLINE: 4,
SAVED_OFFLINE: 5,
PUBLISHED: 6,
};
export const mapsAPIKey = 'AIzaSyBADvjevyMmDkHb_xjjh3FOltkO2Oa8iAQ';
export function reverseGeocode(lat, lng) {
return axios.get(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${mapsAPIKey}`);
}
export const sizes = [
{
width: 2560,
height: 1440,
},
{
width: 1920,
height: 1080,
},
{
width: 1024,
height: 576,
},
{
width: 640,
height: 360,
},
];
export const slugger = str => str
.toLowerCase()
.replace(/ä/g, 'ae')
.replace(/ö/g, 'oe')
.replace(/ü/g, 'ue')
.replace(/[^\w ]+/g, ' ')
.replace(/ +/g, '-');
|
Remove CHANNEL. Why is it even there?
|
#!/usr/bin/env python2
################################################################################
# broadcast_any_song.py
#
# Uses the Exfm REST API to broadcast a song, (basically scours Tumblr for an
# audio file matching a query then sends it to PiFM.)
#
# Maintained By: Ryan Jacobs <ryan.mjacobs@gmail.com>
#
# May 18, 2014 -> Creation date.
################################################################################
# Global Variables
NC_HOST="gamma"
NC_PORT=1234
import os # to execute shell commands
import sys # arguments
import json # json parsing
import urllib2 # url parsing and downloading
if not len(sys.argv) > 1:
print('Usage: ' + sys.argv[0] + ' <search term>')
exit(1)
json_url = urllib2.urlopen("http://ex.fm/api/v3/song/search/%s"% "+".join(sys.argv[1:]))
parsed_json = json.loads(json_url.read())
song_url = parsed_json["songs"][0]["url"]
os.system("wget -O - " + song_url + " | nc " + str(NC_HOST) + " " + str(NC_PORT))
|
#!/usr/bin/env python2
################################################################################
# broadcast_any_song.py
#
# Uses the Exfm REST API to broadcast a song, (basically scours Tumblr for an
# audio file matching a query then sends it to PiFM.)
#
# Maintained By: Ryan Jacobs <ryan.mjacobs@gmail.com>
#
# May 18, 2014 -> Creation date.
################################################################################
# Global Variables
NC_HOST="gamma"
NC_PORT=1234
CHANNEL=94.3
import os # to execute shell commands
import sys # arguments
import json # json parsing
import urllib2 # url parsing and downloading
if not len(sys.argv) > 1:
print('Usage: ' + sys.argv[0] + ' <search term>')
exit(1)
json_url = urllib2.urlopen("http://ex.fm/api/v3/song/search/%s"% "+".join(sys.argv[1:]))
parsed_json = json.loads(json_url.read())
song_url = parsed_json["songs"][0]["url"]
os.system("wget -O - " + song_url + " | nc " + str(NC_HOST) + " " + str(NC_PORT))
|
Fix (*): Remove unused variable
|
<?php
namespace AppBundle\Twig\Extension;
class GpsDMSExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('gps_dms', array($this, 'dmsFilter')),
);
}
public function dmsFilter($number)
{
$vars = explode(".",$number);
$deg = $vars[0];
$tempma = "0.".$vars[1];
$tempma = $tempma * 3600;
$min = floor($tempma / 60);
// Second is $tempma - ($min*60);
$coordinate = $deg.'°'.$min.'\'';
return $coordinate;
}
}
|
<?php
namespace AppBundle\Twig\Extension;
class GpsDMSExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('gps_dms', array($this, 'dmsFilter')),
);
}
public function dmsFilter($number)
{
$vars = explode(".",$number);
$deg = $vars[0];
$tempma = "0.".$vars[1];
$tempma = $tempma * 3600;
$min = floor($tempma / 60);
$sec = $tempma - ($min*60);
$coordinate = $deg.'°'.$min.'\'';
return $coordinate;
}
}
|
Allow `id` to be passed by default
It seems rather common that you want to assign an id and since it's a generic prop it cannot hurt to allow it to always pass through.
|
/* @flow weak */
import { createElement, PropTypes } from 'react'
export default function createComponent(rule, type = 'div', passThroughProps = []) {
const FelaComponent = ({ children, className, id, style, passThrough = [], ...ruleProps }, { renderer, theme }) => {
// filter props to extract props to pass through
const componentProps = [ ...passThroughProps, ...passThrough ].reduce((output, prop) => {
output[prop] = ruleProps[prop]
return output
}, { })
componentProps.style = style
componentProps.id = id
const cls = className ? className + ' ' : ''
ruleProps.theme = theme || { }
componentProps.className = cls + renderer.renderRule(rule, ruleProps)
return createElement(type, componentProps, children)
}
FelaComponent.contextTypes = {
renderer: PropTypes.object,
theme: PropTypes.object
}
// use the rule name as display name to better debug with react inspector
FelaComponent.displayName = rule.name && rule.name || 'FelaComponent'
return FelaComponent
}
|
/* @flow weak */
import { createElement, PropTypes } from 'react'
export default function createComponent(rule, type = 'div', passThroughProps = []) {
const FelaComponent = ({ children, className, style, passThrough = [], ...ruleProps }, { renderer, theme }) => {
// filter props to extract props to pass through
const componentProps = [ ...passThroughProps, ...passThrough ].reduce((output, prop) => {
output[prop] = ruleProps[prop]
return output
}, { })
componentProps.style = style
const cls = className ? className + ' ' : ''
ruleProps.theme = theme || { }
componentProps.className = cls + renderer.renderRule(rule, ruleProps)
return createElement(type, componentProps, children)
}
FelaComponent.contextTypes = {
renderer: PropTypes.object,
theme: PropTypes.object
}
// use the rule name as display name to better debug with react inspector
FelaComponent.displayName = rule.name && rule.name || 'FelaComponent'
return FelaComponent
}
|
Allow for loading from inside a web component
Walk up to the root to find url, don't depend on document's location
|
/*
* Copyright 2012 The Toolkitchen Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
(function() {
var thisFile = 'pointerevents.js';
var libLocation = '';
/*
* if we are loaded inside a component, we need to know the relative path from
* that location, not the document
*/
var baseUrlFromNode = function(inNode) {
var n = inNode, p;
while ((p = n.parentNode)) {
n = p;
}
return (n && (n.URL || n.name)) || '';
};
var appendScriptPath = function(inBasePath, inRelPath) {
// include last slash as well
var ls = inBasePath.lastIndexOf('/') + 1;
return inBasePath.slice(0, ls) + inRelPath;
};
var require = function(inSrc) {
document.write('<script src="' + libLocation + inSrc + '"></script>');
};
var s$ = document.querySelectorAll('script[src]');
Array.prototype.forEach.call(s$, function(s) {
var src = s.getAttribute('src');
if (src.slice(-thisFile.length) == thisFile) {
var source = baseUrlFromNode(s);
var base = src.slice(0, -thisFile.length);
libLocation = appendScriptPath(source, base);
}
});
[
'initialize.js',
'pointermap.js',
'dispatcher.js',
'platform-events.js',
'flick.js',
'finalize.js'
].forEach(require);
})();
|
/*
* Copyright 2012 The Toolkitchen Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
(function() {
var thisFile = 'pointerevents.js';
var source = '', base = '';
var s$ = document.querySelectorAll('script[src]');
Array.prototype.forEach.call(s$, function(s) {
var src = s.getAttribute('src');
if (src.slice(-thisFile.length) == thisFile) {
source = s;
base = src.slice(0, -thisFile.length);
}
});
var require = function(inSrc) {
document.write('<script src="' + base + inSrc + '"></script>');
};
[
'initialize.js',
'pointermap.js',
'dispatcher.js',
'platform-events.js',
'flick.js',
'finalize.js'
].forEach(require);
})();
|
Use a custom logging handler.
|
package main
import (
"flag"
"fmt"
"io"
"net/http"
"os"
)
const VERSION = "0.1.0"
var clientDir string
func init() {
clientEnv := os.Getenv("CLIENT")
flag.StringVar(&clientDir, "client", clientEnv, "the directory where the client data is stored")
}
func main() {
flag.Parse()
fmt.Printf("resolutionizerd %s starting...\n", VERSION)
fmt.Printf("listening on port %s\n", os.Getenv("PORT"))
if clientDir == "" {
clientDir = os.Getenv("CLIENT")
}
fmt.Printf("client root: %s\n", clientDir)
if _, err := os.Stat(clientDir); err != nil {
fmt.Println(err)
os.Exit(1)
}
http.Handle("/", LoggingHandler(os.Stdout, http.FileServer(http.Dir(clientDir))))
if err := http.ListenAndServe(":"+os.Getenv("PORT"), nil); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
type loggingHandler struct {
writer io.Writer
handler http.Handler
}
func (h loggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(h.writer, "%s %s %s", r.Method, r.RequestURI, r.Header.Get("User-Agent"))
h.handler.ServeHTTP(w, r)
}
func LoggingHandler(w io.Writer, h http.Handler) http.Handler {
return loggingHandler{w, h}
}
|
package main
import (
"flag"
"fmt"
"net/http"
"os"
"github.com/gorilla/handlers"
)
const VERSION = "0.1.0"
var clientDir string
func init() {
clientEnv := os.Getenv("CLIENT")
flag.StringVar(&clientDir, "client", clientEnv, "the directory where the client data is stored")
}
func main() {
flag.Parse()
fmt.Printf("resolutionizerd %s starting...\n", VERSION)
fmt.Printf("listening on port %s\n", os.Getenv("PORT"))
if clientDir == "" {
clientDir = os.Getenv("CLIENT")
}
fmt.Printf("client root: %s\n", clientDir)
if _, err := os.Stat(clientDir); err != nil {
fmt.Println(err)
os.Exit(1)
}
http.Handle("/", handlers.CombinedLoggingHandler(os.Stdout, http.FileServer(http.Dir(clientDir))))
if err := http.ListenAndServe(":"+os.Getenv("PORT"), nil); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
|
Add support for customizing the mysql port number
|
<?php namespace Nord\Lumen\Doctrine\ORM\Configuration;
use Nord\Lumen\Doctrine\ORM\Contracts\ConfigurationAdapter as ConfigurationAdapterContract;
class SqlAdapter implements ConfigurationAdapterContract
{
/**
* @inheritdoc
*/
public function map(array $config)
{
return [
'driver' => $this->normalizeDriver($config['driver']),
'host' => $config['host'],
'port' => $config['port'],
'dbname' => $config['database'],
'user' => $config['username'],
'password' => $config['password'],
'charset' => $config['charset'],
'prefix' => array_get($config, 'prefix'),
];
}
/**
* @param $driver
*
* @return string
*/
private function normalizeDriver($driver)
{
$driverMap = [
'mysql' => 'pdo_mysql',
'pgsql' => 'pdo_pgsql',
'sqlsrv' => 'pdo_sqlsrv',
];
return $driverMap[$driver];
}
}
|
<?php namespace Nord\Lumen\Doctrine\ORM\Configuration;
use Nord\Lumen\Doctrine\ORM\Contracts\ConfigurationAdapter as ConfigurationAdapterContract;
class SqlAdapter implements ConfigurationAdapterContract
{
/**
* @inheritdoc
*/
public function map(array $config)
{
return [
'driver' => $this->normalizeDriver($config['driver']),
'host' => $config['host'],
'dbname' => $config['database'],
'user' => $config['username'],
'password' => $config['password'],
'charset' => $config['charset'],
'prefix' => array_get($config, 'prefix'),
];
}
/**
* @param $driver
*
* @return string
*/
private function normalizeDriver($driver)
{
$driverMap = [
'mysql' => 'pdo_mysql',
'pgsql' => 'pdo_pgsql',
'sqlsrv' => 'pdo_sqlsrv',
];
return $driverMap[$driver];
}
}
|
Use correct file name to require enums.js
|
var enums = require("./enums.js");
describe("Enum", function() {
it("can have symbols with custom properties", function() {
var color = new enums.Enum({
red: { de: "rot" },
green: { de: "grün" },
blue: { de: "blau" },
});
function translate(c) {
return c.de;
}
expect(translate(color.green)).toEqual("grün");
});
it("can check for symbol membership", function() {
var color = new enums.Enum("red", "green", "blue");
var fruit = new enums.Enum("apple", "banana");
expect(color.contains(color.red)).toBeTruthy();
expect(color.contains(fruit.apple)).toBeFalsy();
});
});
|
var enums = require("./enum.js");
describe("Enum", function() {
it("can have symbols with custom properties", function() {
var color = new enums.Enum({
red: { de: "rot" },
green: { de: "grün" },
blue: { de: "blau" },
});
function translate(c) {
return c.de;
}
expect(translate(color.green)).toEqual("grün");
});
it("can check for symbol membership", function() {
var color = new enums.Enum("red", "green", "blue");
var fruit = new enums.Enum("apple", "banana");
expect(color.contains(color.red)).toBeTruthy();
expect(color.contains(fruit.apple)).toBeFalsy();
});
});
|
Convert entire table to cartesian
|
"""
Add very large RV errors for stars with no known RVs.
Convert to cartesian.
"""
import numpy as np
import sys
sys.path.insert(0, '..')
from chronostar import tabletool
from astropy.table import Table
datafile = '../data/ScoCen_box_result.fits')
d = tabletool.read(datafile)
# Set missing radial velocities (nan) to 0
d['radial_velocity'] = np.nan_to_num(d['radial_velocity'])
# Set missing radial velocity errors (nan) to 1e+10
d['radial_velocity_error'][np.isnan(d['radial_velocity_error'])] = 1e+4
print('Convert to cartesian')
tabletool.convert_table_astro2cart(table=d, return_table=True)
d.write('../data/ScoCen_box_result_15M_ready_for_bg_ols.fits')
print('Cartesian written.', len(d))
|
"""
Add very large RV errors for stars with no known RVs.
Convert to cartesian.
"""
import numpy as np
import sys
sys.path.insert(0, '..')
from chronostar import tabletool
from astropy.table import Table
datafile = Table.read('../data/ScoCen_box_result.fits')
d = Table.read(datafile)
# Set missing radial velocities (nan) to 0
d['radial_velocity'] = np.nan_to_num(d['radial_velocity'])
# Set missing radial velocity errors (nan) to 1e+10
d['radial_velocity_error'][np.isnan(d['radial_velocity_error'])] = 1e+4
print('Convert to cartesian')
tabletool.convert_table_astro2cart(table=d, return_table=True)
d.write('../data/ScoCen_box_result_15M_ready_for_bg_ols.fits')
print('Cartesian written.', len(d))
|
Clean up imports in trade reporter
|
package org.jvirtanen.parity.reporter;
import static org.jvirtanen.lang.Strings.*;
import java.util.Locale;
import org.jvirtanen.parity.net.ptr.PTR;
import org.jvirtanen.parity.net.ptr.PTRListener;
class Display implements PTRListener {
private static final double PRICE_FACTOR = 10000.0;
private static final String HEADER = "" +
"Timestamp Inst Quantity Price Buyer Seller\n" +
"------------ -------- ---------- --------- -------- --------";
public Display() {
printf("\n%s\n", HEADER);
}
@Override
public void trade(PTR.Trade message) {
printf("%12s %8s %10d %9.2f %8s %8s\n", Timestamps.format(message.timestamp),
decodeLong(message.instrument), message.quantity, message.price / PRICE_FACTOR,
decodeLong(message.buyer), decodeLong(message.seller));
}
private void printf(String format, Object... args) {
System.out.printf(Locale.US, format, args);
}
}
|
package org.jvirtanen.parity.reporter;
import static org.jvirtanen.lang.Strings.*;
import org.jvirtanen.parity.net.ptr.PTR;
import org.jvirtanen.parity.net.ptr.PTRListener;
import java.util.Locale;
class Display implements PTRListener {
private static final double PRICE_FACTOR = 10000.0;
private static final String HEADER = "" +
"Timestamp Inst Quantity Price Buyer Seller\n" +
"------------ -------- ---------- --------- -------- --------";
public Display() {
printf("\n%s\n", HEADER);
}
@Override
public void trade(PTR.Trade message) {
printf("%12s %8s %10d %9.2f %8s %8s\n", Timestamps.format(message.timestamp),
decodeLong(message.instrument), message.quantity, message.price / PRICE_FACTOR,
decodeLong(message.buyer), decodeLong(message.seller));
}
private void printf(String format, Object... args) {
System.out.printf(Locale.US, format, args);
}
}
|
Add line to make code more visible
|
// PiscoBot Script
var commandDescription = {
name: 'Do It',
author: 'Daniel Gallegos [@that_taco_guy]',
trigger: 'do it',
version: 1.0,
description: 'Motivate your team using Shia Lebouf.',
module: 'Fun'
};
global.botHelp.push(commandDescription);
var _ = require('underscore');
global.piscobot.hears(['do(it| it)'], ['ambient', 'direct_mention', 'direct_message', 'mention'],
function(bot, message) {
var doIt = [
'http://i.giphy.com/10FUfTApAeoZK8.gif',
'http://i.giphy.com/qvdqF0PGFPfyg.gif',
'http://i.giphy.com/wCiFka9RsSW9W.gif',
'http://i.giphy.com/ypO01RIuQ3tHW.gif',
'http://i.giphy.com/87xihBthJ1DkA.gif'
];
var motivation = _.sample(doIt);
bot.reply(message, '<@' + message.user + '>: ' + motivation);
}
);
|
// PiscoBot Script
var commandDescription = {
name: 'Do It',
author: 'Daniel Gallegos [@that_taco_guy]',
trigger: 'do it',
version: 1.0,
description: 'Motivate your team using Shia Lebouf.',
module: 'Fun'
};
global.botHelp.push(commandDescription);
var _ = require('underscore');
global.piscobot.hears(['do(it| it)'], ['ambient', 'direct_mention', 'direct_message', 'mention'],
function(bot, message) {
var doIt = [
'http://i.giphy.com/10FUfTApAeoZK8.gif',
'http://i.giphy.com/qvdqF0PGFPfyg.gif',
'http://i.giphy.com/wCiFka9RsSW9W.gif',
'http://i.giphy.com/ypO01RIuQ3tHW.gif',
'http://i.giphy.com/87xihBthJ1DkA.gif'
];
var motivation = _.sample(doIt);
bot.reply(message, '<@' + message.user + '>: ' + motivation);
}
);
|
Add ability to change how request parser decodes json
Can choose between associative or object
|
<?php
/**
* Created by IntelliJ IDEA.
* User: mduncan
* Date: 9/29/15
* Time: 12:49 PM
*/
namespace Fulfillment\Api\Utilities;
use GuzzleHttp\Exception\RequestException;
class RequestParser
{
/**
* Returns an object or array of the FDC error parsed from the Guzzle Request exception
* @param RequestException $requestException
* @param bool $isAssoc
* @return string
*/
public static function parseError(RequestException $requestException, $isAssoc = true)
{
$error = $error = json_decode($requestException->getResponse()->getBody(), $isAssoc);
if (!is_null($error)) {
return $error;
} else {
return $requestException->getMessage();
}
}
public static function getErrorCode(RequestException $requestException)
{
$error = $error = json_decode($requestException->getResponse()->getBody());
if (!is_null($error) && isset($error->error_code)) {
return $error->error_code;
} else {
return null;
}
}
}
|
<?php
/**
* Created by IntelliJ IDEA.
* User: mduncan
* Date: 9/29/15
* Time: 12:49 PM
*/
namespace Fulfillment\Api\Utilities;
use GuzzleHttp\Exception\RequestException;
class RequestParser
{
public static function parseError(RequestException $requestException)
{
$error = $error = json_decode($requestException->getResponse()->getBody(), true);
if (!is_null($error)) {
return $error;
} else {
return $requestException->getMessage();
}
}
public static function getErrorCode(RequestException $requestException)
{
$error = $error = json_decode($requestException->getResponse()->getBody());
if (!is_null($error) && isset($error->error_code)) {
return $error->error_code;
} else {
return null;
}
}
}
|
Make new code pass all new tests
This was done by setting the moderator flag in the helper
function that creates admin users.
|
const Bluebird = require('bluebird');
const mongoose = require('mongoose');
const Alternative = require('../app/models/alternative');
const Election = require('../app/models/election');
const Vote = require('../app/models/vote');
const User = require('../app/models/user');
exports.dropDatabase = () =>
mongoose.connection.dropDatabase().then(() => mongoose.disconnect());
exports.clearCollections = () =>
Bluebird.map([Alternative, Election, Vote, User], collection =>
collection.remove()
);
const hash = '$2a$10$qxTI.cWwa2kwcjx4SI9KAuV4KxuhtlGOk33L999UQf1rux.4PBz7y'; // 'password'
const testUser = (exports.testUser = {
username: 'testuser',
cardKey: '99TESTCARDKEY',
hash
});
const adminUser = (exports.adminUser = {
username: 'admin',
admin: true,
moderator: true,
cardKey: '55TESTCARDKEY',
hash
});
exports.createUsers = () => User.create([testUser, adminUser]);
|
const Bluebird = require('bluebird');
const mongoose = require('mongoose');
const Alternative = require('../app/models/alternative');
const Election = require('../app/models/election');
const Vote = require('../app/models/vote');
const User = require('../app/models/user');
exports.dropDatabase = () =>
mongoose.connection.dropDatabase().then(() => mongoose.disconnect());
exports.clearCollections = () =>
Bluebird.map([Alternative, Election, Vote, User], collection =>
collection.remove()
);
const hash = '$2a$10$qxTI.cWwa2kwcjx4SI9KAuV4KxuhtlGOk33L999UQf1rux.4PBz7y'; // 'password'
const testUser = (exports.testUser = {
username: 'testuser',
cardKey: '99TESTCARDKEY',
hash
});
const adminUser = (exports.adminUser = {
username: 'admin',
admin: true,
cardKey: '55TESTCARDKEY',
hash
});
exports.createUsers = () => User.create([testUser, adminUser]);
|
Update up to changes in memoizee
|
'use strict';
var noop = require('es5-ext/lib/Function/noop')
, extend = require('es5-ext/lib/Object/extend')
, memoize = require('memoizee')
, ee = require('event-emitter')
, deferred = require('deferred')
, isPromise = deferred.isPromise;
module.exports = function (fn/*, options*/) {
var factory, memoized;
if (fn.memoized) {
return fn;
}
memoized = memoize(fn, extend(Object(arguments[1]), { refCounter: true }));
factory = function () {
var watcher, emitter, pipe, args, def;
args = arguments;
watcher = memoized.apply(this, arguments);
if (isPromise(watcher)) {
def = deferred();
emitter = def.promise;
def.resolve(watcher);
} else {
emitter = ee();
}
pipe = ee.pipe(watcher, emitter);
emitter.close = function () {
emitter.close = noop;
pipe.close();
if (memoized.clearRef.apply(this, args)) {
watcher.close();
}
};
return emitter;
};
factory.clear = memoized.clear;
factory.memoized = true;
return factory;
};
|
'use strict';
var noop = require('es5-ext/lib/Function/noop')
, extend = require('es5-ext/lib/Object/extend')
, memoize = require('memoizee')
, ee = require('event-emitter')
, deferred = require('deferred')
, isPromise = deferred.isPromise;
module.exports = function (fn/*, options*/) {
var factory, memoized;
if (fn.memoized) {
return fn;
}
memoized = memoize(fn, extend(Object(arguments[1]), { gc: true }));
factory = function () {
var watcher, emitter, pipe, args, def;
args = arguments;
watcher = memoized.apply(this, arguments);
if (isPromise(watcher)) {
def = deferred();
emitter = def.promise;
def.resolve(watcher);
} else {
emitter = ee();
}
pipe = ee.pipe(watcher, emitter);
emitter.close = function () {
emitter.close = noop;
pipe.close();
if (memoized.clearRef.apply(this, args)) {
watcher.close();
}
};
return emitter;
};
factory.clear = memoized.clear;
factory.memoized = true;
return factory;
};
|
Test push post repo transfer to git-phaser org
|
angular.module('gitphaser')
.controller('NearbyCtrl', NearbyCtrl);
// @controller NearbyCtrl
// @params: $scope, $reactive
// @route: /tab/nearby
//
// Exposes Meteor mongo 'connections' to DOM, filtered against current user as 'transmitter'
// Subscription to 'connections' is handled in the route resolve. Also
// exposes GeoLocate service (for the maps view) and Notify service (to trigger notification when user
// clicks on list item to see profile)
function NearbyCtrl ($scope, $reactive, Notify, GeoLocate ){
$reactive(this).attach($scope);
var self = this;
// Slide constants bound to the GeoLocate directive
// and other DOM events, trigger updates based on
// whether we are looking at List || Map view.
self.listSlide = 0
self.mapSlide = 1;
self.slide = 0;
// Services
self.geolocate = GeoLocate;
self.notify = Notify;
self.helpers({
connections: function () {
if (Meteor.userId()){
return Connections.find( {transmitter: Meteor.userId() } );
}
}
});
};
|
var nc_debug;
angular.module('gitphaser')
.controller('NearbyCtrl', NearbyCtrl);
// @controller NearbyCtrl
// @params: $scope, $reactive
// @route: /tab/nearby
//
// Exposes Meteor mongo 'connections' to DOM, filtered against current user as 'transmitter'
// Subscription to 'connections' is handled in the route resolve. Also
// exposes GeoLocate service (for the maps view) and Notify service (to trigger notification when user
// clicks on list item to see profile)
function NearbyCtrl ($scope, $reactive, Notify, GeoLocate ){
$reactive(this).attach($scope);
var self = this;
// Slide constants bound to the GeoLocate directive
// and other DOM events, trigger updates based on
// whether we are looking at List || Map view.
self.listSlide = 0
self.mapSlide = 1;
self.slide = 0;
// Services
self.geolocate = GeoLocate;
self.notify = Notify;
self.helpers({
connections: function () {
if (Meteor.userId()){
return Connections.find( {transmitter: Meteor.userId() } );
}
}
});
};
|
Change default close operation of main window to "dispose"
Add windowClosed listener which interrupts all model threads
|
package ru.nsu.ccfit.bogush.view;
import ru.nsu.ccfit.bogush.CarFactoryModel;
import ru.nsu.ccfit.bogush.factory.Supplier;
import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class FactoryView extends JPanel {
private JPanel mainPanel;
private ControlPanel controlPanel;
private InformationPanel infoPanel;
private ButtonPanel buttonPanel;
private CarFactoryModel model;
public FactoryView(CarFactoryModel model) {
this.model = model;
JFrame frame = new JFrame("Car Factory");
frame.setContentPane(mainPanel);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
model.getStore().stop();
model.getEngineSupplier().getThread().interrupt();
model.getBodySupplier().getThread().interrupt();
for (Supplier s : model.getAccessorySuppliers()) {
s.getThread().interrupt();
}
model.getCarFactory().getThreadPool().stop();
}
});
frame.setResizable(false);
frame.setLocation(0, 0);
frame.pack();
frame.setVisible(true);
}
private void createUIComponents() {
controlPanel = new ControlPanel(model);
infoPanel = new InformationPanel(model);
buttonPanel = new ButtonPanel(model);
}
}
|
package ru.nsu.ccfit.bogush.view;
import ru.nsu.ccfit.bogush.CarFactoryModel;
import javax.swing.*;
public class FactoryView extends JPanel {
private JPanel mainPanel;
private ControlPanel controlPanel;
private InformationPanel infoPanel;
private ButtonPanel buttonPanel;
private CarFactoryModel model;
public FactoryView(CarFactoryModel model) {
this.model = model;
JFrame frame = new JFrame("Car Factory");
frame.setContentPane(mainPanel);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocation(0, 0);
frame.pack();
frame.setVisible(true);
}
private void createUIComponents() {
controlPanel = new ControlPanel(model);
infoPanel = new InformationPanel(model);
buttonPanel = new ButtonPanel(model);
}
}
|
Fix botched React default require in bundled module
Turns out you shouldn't mix `import React …` and `import * as React …`!
|
import React from 'react';
import Radium from 'radium';
type SpanT = {
span: 1 | 2 | 3 | 4 | 5 | 6,
children: React.Node
};
const Span = ({span = 6, children}: SpanT) => {
const style = {
boxSizing: 'border-box',
display: 'flex',
flexBasis: '100%',
// Bug fix for Firefox; width and flexBasis don't work on horizontally scrolling code blocks
maxWidth: '100%',
flexWrap: 'wrap',
margin: '24px 0 0 0',
padding: 0,
position: 'relative',
'@media (min-width: 640px)': {
flexBasis: `calc(${span / 6 * 100}% - 10px)`,
// Bug fix for Firefox; width and flexBasis don't work on horizontally scrolling code blocks
maxWidth: `calc(${span / 6 * 100}% - 10px)`,
margin: '24px 10px 0 0'
}
};
return (
<div style={style}>
{children}
</div>
);
};
export default Radium(Span);
|
import * as React from 'react';
import Radium from 'radium';
type SpanT = {
span: 1 | 2 | 3 | 4 | 5 | 6,
children: React.Node
};
const Span = ({span = 6, children}: SpanT) => {
const style = {
boxSizing: 'border-box',
display: 'flex',
flexBasis: '100%',
// Bug fix for Firefox; width and flexBasis don't work on horizontally scrolling code blocks
maxWidth: '100%',
flexWrap: 'wrap',
margin: '24px 0 0 0',
padding: 0,
position: 'relative',
'@media (min-width: 640px)': {
flexBasis: `calc(${span / 6 * 100}% - 10px)`,
// Bug fix for Firefox; width and flexBasis don't work on horizontally scrolling code blocks
maxWidth: `calc(${span / 6 * 100}% - 10px)`,
margin: '24px 10px 0 0'
}
};
return (
<div style={style}>
{children}
</div>
);
};
export default Radium(Span);
|
Fix Parting Shot in Trademarked
|
'use strict';
exports.BattleScripts = {
init: function() {
Object.values(this.data.Movedex).forEach(move => {
let bannedMoves = {'Baton Pass':1, 'Detect':1, 'Mat Block':1, 'Protect':1, 'Roar':1, 'Skill Swap':1, 'Whirlwind':1};
if (move.category === 'Status' && !bannedMoves[move.name]) {
this.data.Abilities[move.id] = {
desc: move.desc,
shortDesc: move.shortDesc,
id: move.id,
name: move.name,
onStart: function (pokemon) {
this.add('-activate', pokemon, 'ability: ' + move.name);
this.useMove(move.id, pokemon);
},
};
}
});
},
}
|
'use strict';
exports.BattleScripts = {
init: function() {
Object.values(this.data.Movedex).forEach(move => {
let bannedMoves = {'Baton Pass':1, 'Detect':1, 'Mat Block':1, 'Parting Shot':1, 'Protect':1, 'Roar':1, 'Skill Swap':1, 'Whirlwind':1};
if (move.category === 'Status' && !bannedMoves[move.name]) {
this.data.Abilities[move.id] = {
desc: move.desc,
shortDesc: move.shortDesc,
id: move.id,
name: move.name,
onStart: function (pokemon) {
this.add('-activate', pokemon, 'ability: ' + move.name);
this.useMove(move.id, pokemon);
},
};
}
});
},
}
|
Add semicolon to allow concatenation
The anonymous function syntax causes errors when this file gets concatenated with other files that are stingy with their semicolons, as happens in ``tests/a1-package-stubs.js`` with other community stubs with different semicolon conventions.
|
// router package
//
// Stubs for the tmeasday's Router package.
// https://github.com/tmeasday/meteor-router
;
(function () {
var emptyFunction = function () {};
// The Meteor stub needs to be call before.
Meteor = Meteor || {};
Meteor.Router = {
add: function(paths){
var options;
for(var i in paths){
if(paths.hasOwnProperty(i)){
options = paths[i];
// Need to create the *Path function when a route is added.
if(options && typeof(options) == 'string'){
Meteor.router[options+'Path'] = emptyFunction;
} else if(options && options.as){
Meteor.Router[options.as+'Path'] = emptyFunction;
}
}
}
},
page: emptyFunction,
to: emptyFunction,
beforeRouting: emptyFunction,
filters: emptyFunction,
filter: emptyFunction,
configure: emptyFunction
};
})();
|
// router package
//
// Stubs for the tmeasday's Router package.
// https://github.com/tmeasday/meteor-router
(function () {
var emptyFunction = function () {};
// The Meteor stub needs to be call before.
Meteor = Meteor || {};
Meteor.Router = {
add: function(paths){
var options;
for(var i in paths){
if(paths.hasOwnProperty(i)){
options = paths[i];
// Need to create the *Path function when a route is added.
if(options && typeof(options) == 'string'){
Meteor.router[options+'Path'] = emptyFunction;
} else if(options && options.as){
Meteor.Router[options.as+'Path'] = emptyFunction;
}
}
}
},
page: emptyFunction,
to: emptyFunction,
beforeRouting: emptyFunction,
filters: emptyFunction,
filter: emptyFunction,
configure: emptyFunction
};
})();
|
Fix a bug on a query example for python
Methods used by the former example, `query.more()` and `query.next()`, do not exist any longer.
I've modified them to `query.execute()`, according to `BaseXClient.py`, to make it run as good as it should be.
|
# This example shows how queries can be executed in an iterative manner.
# Iterative evaluation will be slower, as more server requests are performed.
#
# Documentation: http://docs.basex.org/wiki/Clients
#
# (C) BaseX Team 2005-12, BSD License
import BaseXClient, time
try:
# create session
session = BaseXClient.Session('localhost', 1984, 'admin', 'admin')
try:
# create query instance
input = "for $i in 1 to 10 return <xml>Text { $i }</xml>"
query = session.query(input)
print query.execute()
# close query object
query.close()
except IOError as e:
# print exception
print e
# close session
session.close()
except IOError as e:
# print exception
print e
|
# This example shows how queries can be executed in an iterative manner.
# Iterative evaluation will be slower, as more server requests are performed.
#
# Documentation: http://docs.basex.org/wiki/Clients
#
# (C) BaseX Team 2005-12, BSD License
import BaseXClient, time
try:
# create session
session = BaseXClient.Session('localhost', 1984, 'admin', 'admin')
try:
# create query instance
input = "for $i in 1 to 10 return <xml>Text { $i }</xml>"
query = session.query(input)
# loop through all results
while query.more():
print query.next()
# close query object
query.close()
except IOError as e:
# print exception
print e
# close session
session.close()
except IOError as e:
# print exception
print e
|
Print the Format class used
|
def print_header():
import sys
from dxtbx.format.Registry import Registry
# this will do the lookup for every frame - this is strictly not needed
# if all frames are from the same instrument
for arg in sys.argv[1:]:
format = Registry.find(arg)
print 'Using header reader: %s' % format.__name__
i = format(arg)
print 'Beam:'
print i.get_beam()
print 'Goniometer:'
print i.get_goniometer()
print 'Detector:'
print i.get_detector()
print 'Scan:'
print i.get_scan()
print 'Total Counts:'
print sum(i.get_raw_data())
if __name__ == '__main__':
print_header()
|
def print_header():
import sys
from dxtbx.format.Registry import Registry
# this will do the lookup for every frame - this is strictly not needed
# if all frames are from the same instrument
for arg in sys.argv[1:]:
format = Registry.find(arg)
i = format(arg)
print 'Beam:'
print i.get_beam()
print 'Goniometer:'
print i.get_goniometer()
print 'Detector:'
print i.get_detector()
print 'Scan:'
print i.get_scan()
print 'Total Counts:'
print sum(i.get_raw_data())
if __name__ == '__main__':
print_header()
|
Add homepage to plugin details
|
<?php namespace PopcornPHP\RedirectToHTTPS;
use System\Classes\PluginBase;
class Plugin extends PluginBase
{
public function pluginDetails()
{
return [
'name' => 'RedirectToHTTPS',
'description' => 'Simple plugin for redirect all request to HTTPS',
'author' => 'Alexander Shapoval',
'icon' => 'icon-exchange',
'homepage' => 'https://github.com/PopcornPHP/oc-redirect-to-https'
];
}
public function boot()
{
$this->app['Illuminate\Contracts\Http\Kernel']
->prependMiddleware('PopcornPHP\RedirectToHTTPS\Classes\HTTPSMiddleware');
}
}
|
<?php namespace PopcornPHP\RedirectToHTTPS;
use System\Classes\PluginBase;
class Plugin extends PluginBase
{
public function pluginDetails()
{
return [
'name' => 'RedirectToHTTPS',
'description' => 'Simple plugin for redirect all request to HTTPS',
'author' => 'Alexander Shapoval',
'icon' => 'icon-exchange',
];
}
public function boot()
{
$this->app['Illuminate\Contracts\Http\Kernel']
->prependMiddleware('PopcornPHP\RedirectToHTTPS\Classes\HTTPSMiddleware');
}
}
|
Update our Froala Editor license key
|
/* eslint ember/order-in-components: 0 */
import $ from 'jquery';
import { inject as service } from '@ember/service';
import Component from '@ember/component';
import { computed } from '@ember/object';
const defaultButtons = [
'bold',
'italic',
'subscript',
'superscript',
'formatOL',
'formatUL',
'insertLink',
'html'
];
export default Component.extend({
i18n: service(),
content: '',
/**
* Disable Froala's built in beacon tracking
* Has to be done on the global jQuery plugin object
*/
init() {
this._super(...arguments);
$.FE.DT = true;
},
options: computed('i18n.locale', function(){
const i18n = this.get('i18n');
const language = i18n.get('locale');
return {
key : '3A9A5C4A3gC3E3C3E3B7A4A2F4B2D2zHMDUGENKACTMXQL==',
theme : 'gray',
language,
toolbarInline: false,
placeholderText: '',
allowHTML: true,
saveInterval: false,
pastePlain: true,
spellcheck: true,
toolbarButtons: defaultButtons,
toolbarButtonsMD: defaultButtons,
toolbarButtonsSM: defaultButtons,
toolbarButtonsXS: defaultButtons,
quickInsertButtons: false,
pluginsEnabled: ['lists', 'code_view', 'link'],
};
})
});
|
/* eslint ember/order-in-components: 0 */
import $ from 'jquery';
import { inject as service } from '@ember/service';
import Component from '@ember/component';
import { computed } from '@ember/object';
const defaultButtons = [
'bold',
'italic',
'subscript',
'superscript',
'formatOL',
'formatUL',
'insertLink',
'html'
];
export default Component.extend({
i18n: service(),
content: '',
/**
* Disable Froala's built in beacon tracking
* Has to be done on the global jQuery plugin object
*/
init() {
this._super(...arguments);
$.FE.DT = true;
},
options: computed('i18n.locale', function(){
const i18n = this.get('i18n');
const language = i18n.get('locale');
return {
key : 'vD1Ua1Mf1e1VSYKa1EPYD==',
theme : 'gray',
language,
toolbarInline: false,
placeholderText: '',
allowHTML: true,
saveInterval: false,
pastePlain: true,
spellcheck: true,
toolbarButtons: defaultButtons,
toolbarButtonsMD: defaultButtons,
toolbarButtonsSM: defaultButtons,
toolbarButtonsXS: defaultButtons,
quickInsertButtons: false,
pluginsEnabled: ['lists', 'code_view', 'link'],
};
})
});
|
Remove prefix to save some characters.
|
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law 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 fuse
import (
"flag"
"io"
"io/ioutil"
"log"
"os"
"sync"
)
var fEnableDebug = flag.Bool(
"fuse.debug",
false,
"Write FUSE debugging messages to stderr.")
var gLogger *log.Logger
var gLoggerOnce sync.Once
func initLogger() {
if !flag.Parsed() {
panic("initLogger called before flags available.")
}
var writer io.Writer = ioutil.Discard
if *fEnableDebug {
writer = os.Stderr
}
const flags = log.Ldate | log.Ltime | log.Lmicroseconds
gLogger = log.New(writer, "", flags)
}
func getLogger() *log.Logger {
gLoggerOnce.Do(initLogger)
return gLogger
}
|
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law 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 fuse
import (
"flag"
"io"
"io/ioutil"
"log"
"os"
"sync"
)
var fEnableDebug = flag.Bool(
"fuse.debug",
false,
"Write FUSE debugging messages to stderr.")
var gLogger *log.Logger
var gLoggerOnce sync.Once
func initLogger() {
if !flag.Parsed() {
panic("initLogger called before flags available.")
}
var writer io.Writer = ioutil.Discard
if *fEnableDebug {
writer = os.Stderr
}
const flags = log.Ldate | log.Ltime | log.Lmicroseconds
gLogger = log.New(writer, "fuse: ", flags)
}
func getLogger() *log.Logger {
gLoggerOnce.Do(initLogger)
return gLogger
}
|
Fix for dynamic value of FacilityDataset.preset.choices causing migration inconsistencies
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-12-26 19:25
from __future__ import unicode_literals
from django.db import migrations, models
# This is necessary because:
# 1. The list generator has an unpredictable order, and when items swap places
# then this would be picked up as a change in Django if we had used
# 2. These choices can be changed in facility_configuration_presets.json
# and such change should not warrant warnings that models are inconsistent
# as it has no impact.
# Notice: The 'choices' property of a field does NOT have any impact on DB
# See: https://github.com/learningequality/kolibri/pull/3180
from ..constants.facility_presets import choices as facility_choices
class Migration(migrations.Migration):
dependencies = [
('kolibriauth', '0006_auto_20171206_1207'),
]
operations = [
migrations.AlterField(
model_name='facilitydataset',
name='preset',
field=models.CharField(choices=facility_choices, default='nonformal', max_length=50),
),
migrations.AlterUniqueTogether(
name='facilityuser',
unique_together=set([]),
),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-12-26 19:25
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kolibriauth', '0006_auto_20171206_1207'),
]
operations = [
migrations.AlterField(
model_name='facilitydataset',
name='preset',
field=models.CharField(choices=[('informal', 'Informal and personal use'), ('nonformal', 'Self-managed'), ('formal', 'Admin-managed')], default='nonformal', max_length=50),
),
migrations.AlterUniqueTogether(
name='facilityuser',
unique_together=set([]),
),
]
|
Add footnotes extension to showdown
refs 1318
- based on Markdown Extra https://michelf.ca/projects/php-markdown/extra/
- allows [^n] for automatic numbering based on sequence
|
/* global Showdown, Handlebars, html_sanitize*/
import cajaSanitizers from 'ghost/utils/caja-sanitizers';
var showdown,
formatMarkdown;
showdown = new Showdown.converter({extensions: ['ghostimagepreview', 'ghostgfm', 'footnotes']});
formatMarkdown = Ember.Handlebars.makeBoundHelper(function (markdown) {
var escapedhtml = '';
// convert markdown to HTML
escapedhtml = showdown.makeHtml(markdown || '');
// replace script and iFrame
// jscs:disable
escapedhtml = escapedhtml.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
'<pre class="js-embed-placeholder">Embedded JavaScript</pre>');
escapedhtml = escapedhtml.replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,
'<pre class="iframe-embed-placeholder">Embedded iFrame</pre>');
// jscs:enable
// sanitize html
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
escapedhtml = html_sanitize(escapedhtml, cajaSanitizers.url, cajaSanitizers.id);
// jscs:enable requireCamelCaseOrUpperCaseIdentifiers
return new Handlebars.SafeString(escapedhtml);
});
export default formatMarkdown;
|
/* global Showdown, Handlebars, html_sanitize*/
import cajaSanitizers from 'ghost/utils/caja-sanitizers';
var showdown,
formatMarkdown;
showdown = new Showdown.converter({extensions: ['ghostimagepreview', 'ghostgfm']});
formatMarkdown = Ember.Handlebars.makeBoundHelper(function (markdown) {
var escapedhtml = '';
// convert markdown to HTML
escapedhtml = showdown.makeHtml(markdown || '');
// replace script and iFrame
// jscs:disable
escapedhtml = escapedhtml.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
'<pre class="js-embed-placeholder">Embedded JavaScript</pre>');
escapedhtml = escapedhtml.replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,
'<pre class="iframe-embed-placeholder">Embedded iFrame</pre>');
// jscs:enable
// sanitize html
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
escapedhtml = html_sanitize(escapedhtml, cajaSanitizers.url, cajaSanitizers.id);
// jscs:enable requireCamelCaseOrUpperCaseIdentifiers
return new Handlebars.SafeString(escapedhtml);
});
export default formatMarkdown;
|
Mask the API key shown in settings
|
package tr.xip.wanikani.settings;
import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import tr.xip.wanikani.R;
import tr.xip.wanikani.managers.PrefManager;
/**
* Created by xihsa_000 on 4/4/14.
*/
public class SettingsActivity extends PreferenceActivity {
PrefManager prefMan;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
prefMan = new PrefManager(this);
Preference mApiKey = findPreference(PrefManager.PREF_API_KEY);
String apiKey = prefMan.getApiKey();
String maskedApiKey = "************************";
for (int i = 25; i < apiKey.length(); i++) {
maskedApiKey += apiKey.charAt(i);
}
mApiKey.setSummary(maskedApiKey);
}
@Override
public void onBackPressed() {
if (Build.VERSION.SDK_INT >= 16) {
super.onNavigateUp();
} else {
super.onBackPressed();
}
}
}
|
package tr.xip.wanikani.settings;
import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import tr.xip.wanikani.R;
import tr.xip.wanikani.managers.PrefManager;
/**
* Created by xihsa_000 on 4/4/14.
*/
public class SettingsActivity extends PreferenceActivity {
PrefManager prefMan;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
prefMan = new PrefManager(this);
Preference mApiKey = findPreference(PrefManager.PREF_API_KEY);
mApiKey.setSummary(prefMan.getApiKey());
}
@Override
public void onBackPressed() {
if (Build.VERSION.SDK_INT >= 16) {
super.onNavigateUp();
} else {
super.onBackPressed();
}
}
}
|
Allow setup function to update dynamic mapping
|
import json
import os
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Index
from model import APIDoc
def exists():
return Index(APIDoc.Index.name).exists()
def setup():
"""
Setup Elasticsearch Index with dynamic template.
Run it on an open index to update dynamic mapping.
"""
_dirname = os.path.dirname(__file__)
with open(os.path.join(_dirname, 'mapping.json'), 'r') as file:
mapping = json.load(file)
if not exists():
APIDoc.init()
elastic = Elasticsearch()
elastic.indices.put_mapping(
index=APIDoc.Index.name,
body=mapping
)
def delete():
Index(APIDoc.Index.name).delete()
def reset():
if exists():
delete()
setup()
def refresh():
index = Index(APIDoc.Index.name)
index.refresh()
|
import json
import os
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Index
from model import APIDoc
def exists():
return Index(APIDoc.Index.name).exists()
def setup():
"""
Setup Elasticsearch Index.
Primary index with dynamic template.
Secondary index with static mappings.
"""
_dirname = os.path.dirname(__file__)
with open(os.path.join(_dirname, 'mapping.json'), 'r') as file:
mapping = json.load(file)
if not exists():
APIDoc.init()
elastic = Elasticsearch()
elastic.indices.put_mapping(
index=APIDoc.Index.name,
body=mapping
)
def delete():
Index(APIDoc.Index.name).delete()
def reset():
if exists():
delete()
setup()
def refresh():
index = Index(APIDoc.Index.name)
index.refresh()
|
Add subdirs of nativeconfig package to build.
|
import os
from setuptools import setup
from sys import platform
REQUIREMENTS = []
if platform.startswith('darwin'):
REQUIREMENTS.append('pyobjc-core >= 2.5')
with open(os.path.join(os.path.dirname(__file__), 'nativeconfig', 'version.py')) as f:
version = None
code = compile(f.read(), 'version.py', 'exec')
exec(code)
assert version
setup(
name='nativeconfig',
version=version,
packages=['nativeconfig', 'nativeconfig.options', 'nativeconfig.config'],
url='https://github.com/GreatFruitOmsk/nativeconfig',
license='MIT License',
author='Ilya Kulakov',
author_email='kulakov.ilya@gmail.com',
description="Cross-platform python module to store application config via native subsystems such as Windows Registry or NSUserDefaults.",
platforms=["Mac OS X 10.6+", "Windows XP+", "Linux 2.6+"],
keywords='config',
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
],
install_requires=REQUIREMENTS,
test_suite='test'
)
|
import os
from setuptools import setup
from sys import platform
REQUIREMENTS = []
if platform.startswith('darwin'):
REQUIREMENTS.append('pyobjc-core >= 2.5')
with open(os.path.join(os.path.dirname(__file__), 'nativeconfig', 'version.py')) as f:
version = None
code = compile(f.read(), 'version.py', 'exec')
exec(code)
assert version
setup(
name='nativeconfig',
version=version,
packages=['nativeconfig'],
url='https://github.com/GreatFruitOmsk/nativeconfig',
license='MIT License',
author='Ilya Kulakov',
author_email='kulakov.ilya@gmail.com',
description="Cross-platform python module to store application config via native subsystems such as Windows Registry or NSUserDefaults.",
platforms=["Mac OS X 10.6+", "Windows XP+", "Linux 2.6+"],
keywords='config',
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
],
install_requires=REQUIREMENTS,
test_suite='test'
)
|
Exclude emulated attachment on OpenJ9.
|
package net.bytebuddy.test.utility;
import com.sun.jna.Platform;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.logging.Logger;
public class UnixRule implements MethodRule {
private final boolean enabled;
public UnixRule() {
this.enabled = !Platform.isWindows() && !Platform.isWindowsCE() && System.getProperty("java.vm.vendor").contains("OpenJ9");
}
public Statement apply(Statement base, FrameworkMethod method, Object target) {
return enabled || method.getAnnotation(Enforce.class) == null
? base
: new NoOpStatement();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Enforce {
}
private static class NoOpStatement extends Statement {
public void evaluate() {
Logger.getLogger("net.bytebuddy").warning("Ignoring Unix sockets on this machine");
}
}
}
|
package net.bytebuddy.test.utility;
import com.sun.jna.Platform;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.logging.Logger;
public class UnixRule implements MethodRule {
private final boolean enabled;
public UnixRule() {
this.enabled = !Platform.isWindows() && !Platform.isWindowsCE();
}
public Statement apply(Statement base, FrameworkMethod method, Object target) {
return enabled || method.getAnnotation(Enforce.class) == null
? base
: new NoOpStatement();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Enforce {
}
private static class NoOpStatement extends Statement {
public void evaluate() {
Logger.getLogger("net.bytebuddy").warning("Ignoring Unix sockets on this machine");
}
}
}
|
Swap out global function for static Str::camel() method
|
<?php
namespace Konsulting\Laravel\RuleRepository;
use Illuminate\Support\Str;
use Konsulting\Laravel\RuleRepository\Contracts\RuleRepository;
use Konsulting\Laravel\RuleRepository\Exceptions\NonExistentStateException;
class RepositoryManager
{
/**
* The repository instance.
*
* @var RuleRepository
*/
protected $repository;
/**
* Set the repository instance.
*
* @param RuleRepository $repository
*/
public function __construct(RuleRepository $repository)
{
$this->repository = $repository;
}
/**
* Return the rules for the given state. Get the default state if not specified.
*
* @param string $state
* @return array
* @throws NonExistentStateException
*/
public function getRules($state = null)
{
$method = Str::camel($state ?: 'default');
if ( ! method_exists($this->repository, $method)) {
throw new NonExistentStateException($method);
}
return array_merge(
$this->repository->default(),
is_array($this->repository->$method()) ? $this->repository->$method() : []
);
}
}
|
<?php
namespace Konsulting\Laravel\RuleRepository;
use Konsulting\Laravel\RuleRepository\Contracts\RuleRepository;
use Konsulting\Laravel\RuleRepository\Exceptions\NonExistentStateException;
class RepositoryManager
{
/**
* The repository instance.
*
* @var RuleRepository
*/
protected $repository;
/**
* Set the repository instance.
*
* @param RuleRepository $repository
*/
public function __construct(RuleRepository $repository)
{
$this->repository = $repository;
}
/**
* Return the rules for the given state. Get the default state if not specified.
*
* @param string $state
* @return array
* @throws NonExistentStateException
*/
public function getRules($state = null)
{
$method = camel_case($state ?: 'default');
if ( ! method_exists($this->repository, $method)) {
throw new NonExistentStateException($method);
}
return array_merge(
$this->repository->default(),
is_array($this->repository->$method()) ? $this->repository->$method() : []
);
}
}
|
FIX Change the completed-error state
|
/*
* Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of iotagent-thinking-things
*
* iotagent-thinking-things is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* iotagent-thinking-things is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with iotagent-thinking-things.
* If not, seehttp://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with::[iot_support@tid.es]
*/
var constants = {
states: {
PENDING: 'P',
SUCCESS: 'C.S',
FAILED: 'C.F',
CLOSED: 'X'
}
};
module.exports = constants;
|
/*
* Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of iotagent-thinking-things
*
* iotagent-thinking-things is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* iotagent-thinking-things is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with iotagent-thinking-things.
* If not, seehttp://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with::[iot_support@tid.es]
*/
var constants = {
states: {
PENDING: 'P',
SUCCESS: 'C.S',
FAILED: 'C.E',
CLOSED: 'X'
}
};
module.exports = constants;
|
Add marker for log-lines that are printed to stdout
|
package org.apache.poi.benchmark.util;
import com.google.common.collect.EvictingQueue;
import org.apache.commons.lang3.StringUtils;
import org.dstadler.commons.exec.BufferingLogOutputStream;
import java.util.Collection;
import java.util.Queue;
/**
* An extension to {@link BufferingLogOutputStream} which additionally
* keeps the last few lines of output in a buffer so they can be retrieved
* even when all the lines were sent to the logging system already and thus
* cannot be retrieved any more.
*/
public class TailLogOutputStream extends BufferingLogOutputStream {
private final Queue<String> lastLines;
public TailLogOutputStream(int capacity) {
//noinspection UnstableApiUsage
lastLines = EvictingQueue.create(capacity);
}
@Override
protected void processLine(String line, int level) {
synchronized (lastLines) {
// silently ignore null and empty lines here as the queue does not accept this value
if (StringUtils.isNotEmpty(line)) {
lastLines.add("Log: " + line);
}
}
super.processLine(line, level);
}
/**
* Return the last lines that were sent to the logging system
*
* @return A collection of log-lines up to the limit
* that is specified in the constructor.
*/
public Collection<String> getLines() {
return lastLines;
}
}
|
package org.apache.poi.benchmark.util;
import com.google.common.collect.EvictingQueue;
import org.apache.commons.lang3.StringUtils;
import org.dstadler.commons.exec.BufferingLogOutputStream;
import java.util.Collection;
import java.util.Queue;
/**
* An extension to {@link BufferingLogOutputStream} which additionally
* keeps the last few lines of output in a buffer so they can be retrieved
* even when all the lines were sent to the logging system already and thus
* cannot be retrieved any more.
*/
public class TailLogOutputStream extends BufferingLogOutputStream {
private final Queue<String> lastLines;
public TailLogOutputStream(int capacity) {
//noinspection UnstableApiUsage
lastLines = EvictingQueue.create(capacity);
}
@Override
protected void processLine(String line, int level) {
synchronized (lastLines) {
// silently ignore null and empty lines here as the queue does not accept this value
if (StringUtils.isNotEmpty(line)) {
lastLines.add(line);
}
}
super.processLine(line, level);
}
/**
* Return the last lines that were sent to the logging system
*
* @return A collection of log-lines up to the limit
* that is specified in the constructor.
*/
public Collection<String> getLines() {
return lastLines;
}
}
|
Mark the close map dialog button with role button
Bug: T308320
Change-Id: I429ec8a081614d90e2b82e5e31918b9e61ca602d
|
/**
* # Control to close the full screen dialog.
*
* See [L.Control](https://www.mapbox.com/mapbox.js/api/v2.3.0/l-control/)
* documentation for more details.
*
* @class Kartographer.Dialog.CloseFullScreenControl
* @extends L.Control
*/
var CloseFullScreenControl = L.Control.extend( {
options: {
position: 'topright'
},
/**
* Creates the control element.
*
* @override
* @protected
*/
onAdd: function () {
var container = L.DomUtil.create( 'div', 'leaflet-bar' ),
link = L.DomUtil.create( 'a', 'oo-ui-icon-close', container );
link.title = mw.msg( 'kartographer-fullscreen-close' );
link.role = 'button';
link.tabIndex = '0';
L.DomEvent.addListener( link, 'click', this.closeFullScreen, this );
L.DomEvent.disableClickPropagation( container );
return container;
},
/**
* Closes the full screen dialog on `click`.
*
* @param {Event} e
* @protected
*/
closeFullScreen: function ( e ) {
L.DomEvent.stop( e );
// eslint-disable-next-line no-underscore-dangle
this._map.closeFullScreen();
}
} );
module.exports = CloseFullScreenControl;
|
/**
* # Control to close the full screen dialog.
*
* See [L.Control](https://www.mapbox.com/mapbox.js/api/v2.3.0/l-control/)
* documentation for more details.
*
* @class Kartographer.Dialog.CloseFullScreenControl
* @extends L.Control
*/
var CloseFullScreenControl = L.Control.extend( {
options: {
position: 'topright'
},
/**
* Creates the control element.
*
* @override
* @protected
*/
onAdd: function () {
var container = L.DomUtil.create( 'div', 'leaflet-bar' ),
link = L.DomUtil.create( 'a', 'oo-ui-icon-close', container );
link.href = '';
link.title = mw.msg( 'kartographer-fullscreen-close' );
L.DomEvent.addListener( link, 'click', this.closeFullScreen, this );
L.DomEvent.disableClickPropagation( container );
return container;
},
/**
* Closes the full screen dialog on `click`.
*
* @param {Event} e
* @protected
*/
closeFullScreen: function ( e ) {
L.DomEvent.stop( e );
// eslint-disable-next-line no-underscore-dangle
this._map.closeFullScreen();
}
} );
module.exports = CloseFullScreenControl;
|
Fix for redirect after signing up
|
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UniversityRegisterRequest;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\University;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
class RegisterController extends Controller
{
use CreateUserTrait;
public function showRegister()
{
return view('auth.register');
}
/**
* Create the university and a user instance.
*
* @param UniversityRegisterRequest $request
* @return \Illuminate\Http\RedirectResponse
*/
public function register(UniversityRegisterRequest $request)
{
$university = University::create($request->all());
$user = $this->createAuthenticableUserAndLogin($request, 'university', $university->contact_first_name . ' ' . $university->contact_last_name);
Auth::login($user);
return redirect('dashboard');
}
}
|
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UniversityRegisterRequest;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\University;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
class RegisterController extends Controller
{
use CreateUserTrait;
public function showRegister()
{
return view('auth.register');
}
/**
* Create the university and a user instance.
*
* @param UniversityRegisterRequest $request
* @return \Illuminate\Http\RedirectResponse
*/
public function register(UniversityRegisterRequest $request)
{
$university = University::create($request->all());
$user = $this->createAuthenticableUserAndLogin($request, 'university', $university->contact_first_name . ' ' . $university->contact_last_name);
if (Auth::attempt($user)) {
return redirect('dashboard');
}
}
}
|
Define a MD->RST conversion function
|
from setuptools import setup
try:
from pypandoc import convert
def read_md():
return lambda f: convert(f, 'rst')
except ImportError:
print(
"warning: pypandoc module not found, could not convert Markdown to RST"
)
def read_md():
return lambda f: open(f, 'r').read()
setup(name='centerline',
version='0.1',
description='Calculate the centerline of a polygon',
long_description=read_md('README.md'),
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: GIS'
],
url='https://github.com/fitodic/centerline.git',
author='Filip Todic',
author_email='todic.filip@gmail.com',
license='MIT',
packages=['centerline'],
install_requires=['numpy', 'scipy', 'Shapely', 'GDAL', 'click', 'cligj', 'six', 'Fiona'],
scripts=['bin/shp2centerline'],
include_package_data=True,
zip_safe=False)
|
from setuptools import setup
try:
from pypandoc import convert
read_md = lambda f: convert(f, 'rst')
except ImportError:
print("warning: pypandoc module not found, could not convert Markdown to RST")
read_md = lambda f: open(f, 'r').read()
setup(name='centerline',
version='0.1',
description='Calculate the centerline of a polygon',
long_description=read_md('README.md'),
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: GIS'
],
url='https://github.com/fitodic/centerline.git',
author='Filip Todic',
author_email='todic.filip@gmail.com',
license='MIT',
packages=['centerline'],
install_requires=['numpy', 'scipy', 'Shapely', 'GDAL', 'click', 'cligj', 'six', 'Fiona'],
scripts=['bin/shp2centerline'],
include_package_data=True,
zip_safe=False)
|
Determine API_URL based on hostname
|
import fetch from 'isomorphic-fetch'
const hostname = window && window.location && window.location.hostname
const API_URL =
hostname === 'localhost' ? process.env.REACT_APP_RAILS_API_DEV_URL : process.env.REACT_APP_RAILS_API_PROD_URL
const headers = () => {
const token = JSON.parse(localStorage.getItem('token'))
return {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
'Access-Control-Allow-Origin': '*',
}
}
export default {
get(url) {
return fetch(`${API_URL}${url}`, {
method: 'GET',
headers: headers(),
})
.then(res => res.json())
.then(data => data)
},
post(url, data = {}) {
const body = JSON.stringify(data)
return fetch(`${API_URL}${url}`, {
method: 'POST',
headers: headers(),
body,
})
.then(res => {
if (!res.ok) {
throw new Error(res.statusText)
}
return res.json()
})
.then(data => data)
},
}
|
import fetch from 'isomorphic-fetch'
const API_URL = process.env.REACT_APP_RAILS_API_URL
const headers = () => {
const token = JSON.parse(localStorage.getItem('token'))
return {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
'Access-Control-Allow-Origin': '*',
}
}
export default {
get(url) {
return fetch(`${API_URL}${url}`, {
method: 'GET',
headers: headers(),
})
.then(res => res.json())
.then(data => data)
},
post(url, data = {}) {
const body = JSON.stringify(data)
return fetch(`${API_URL}${url}`, {
method: 'POST',
headers: headers(),
body,
})
.then(res => {
if (!res.ok) {
throw new Error(res.statusText)
}
return res.json()
})
.then(data => data)
},
}
|
Exclude notes and private_notes from api for now
|
from rest_framework import serializers
from reversion import revisions
from wafer.talks.models import Talk
class TalkSerializer(serializers.ModelSerializer):
class Meta:
model = Talk
# private_notes should possibly be accessible to
# talk reviewers by the API, but certainly
# not to the other users.
# Similar considerations apply to notes, which should
# not be generally accessible
exclude = ('_abstract_rendered', 'private_notes', 'notes')
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(TalkSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, talk, validated_data):
revisions.set_comment("Changed via REST api")
talk.abstract = validated_data['abstract']
talk.title = validated_data['title']
talk.status = validated_data['status']
talk.talk_type = validated_data['talk_type']
talk.notes = validated_data['notes']
talk.private_notes = validated_data['private_notes']
talk.save()
return talk
|
from rest_framework import serializers
from reversion import revisions
from wafer.talks.models import Talk
class TalkSerializer(serializers.ModelSerializer):
class Meta:
model = Talk
exclude = ('_abstract_rendered', )
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(TalkSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, talk, validated_data):
revisions.set_comment("Changed via REST api")
talk.abstract = validated_data['abstract']
talk.title = validated_data['title']
talk.status = validated_data['status']
talk.talk_type = validated_data['talk_type']
talk.notes = validated_data['notes']
talk.private_notes = validated_data['private_notes']
talk.save()
return talk
|
Remove query from method name and specify comment
|
package com.novoda.notils.string;
import java.util.Arrays;
public class QueryUtils {
/**
* Creates a string to be used as a placeholder in {@link android.content.ContentResolver} operations selection.
* This will allow to use more selection arguments and have them replaced when using the IN operator.
*
* @param size The number of selection arguments
* @return Example: for size == 3 : "?, ?, ?"
*/
public static String createSelectionPlaceholdersOfSize(int size) {
String[] questionMarks = new String[size];
for (int i = 0; i < size; i++) {
questionMarks[i] = "?";
}
return StringUtils.join(Arrays.asList(questionMarks), ", ");
}
}
|
package com.novoda.notils.string;
import java.util.Arrays;
public class QueryUtils {
/**
* Creates a string to be used as a placeholder in {@link android.content.ContentResolver} operations selection.
* This will allow to use more selection arguments and have them replaced.
*
* @param size The number of selection arguments
* @return Example: for size == 3 : "?, ?, ?"
*/
public static String createQuerySelectionPlaceholdersOfSize(int size) {
String[] questionMarks = new String[size];
for (int i = 0; i < size; i++) {
questionMarks[i] = "?";
}
return StringUtils.join(Arrays.asList(questionMarks), ", ");
}
}
|
Set environment settings to suit localhost
|
import os
# *****************************
# Environment specific settings
# *****************************
# The settings below can (and should) be over-ruled by OS environment variable settings
# Flask settings # Generated with: import os; os.urandom(24)
SECRET_KEY = '\x9d|*\xbb\x82T\x83\xeb\xf52\xd1\xdfl\x87\xb4\x9e\x10f\xdf\x9e\xea\xf8_\x99'
# PLEASE USE A DIFFERENT KEY FOR PRODUCTION ENVIRONMENTS!
# SQLAlchemy settings
SQLALCHEMY_DATABASE_URI = 'sqlite:///../app.sqlite'
# Flask-Mail settings
MAIL_USERNAME = ''
MAIL_PASSWORD = ''
MAIL_DEFAULT_SENDER = ''
MAIL_SERVER = 'localhost'
MAIL_PORT = 25
MAIL_USE_SSL = False
MAIL_USE_TLS = False
ADMINS = [
'"Admin One" <admin1@gmail.com>',
]
|
import os
# *****************************
# Environment specific settings
# *****************************
# The settings below can (and should) be over-ruled by OS environment variable settings
# Flask settings # Generated with: import os; os.urandom(24)
SECRET_KEY = '\xb9\x8d\xb5\xc2\xc4Q\xe7\x8ej\xe0\x05\xf3\xa3kp\x99l\xe7\xf2i\x00\xb1-\xcd'
# PLEASE USE A DIFFERENT KEY FOR PRODUCTION ENVIRONMENTS!
# SQLAlchemy settings
SQLALCHEMY_DATABASE_URI = 'sqlite:///../app.sqlite'
# Flask-Mail settings
MAIL_USERNAME = 'email@example.com'
MAIL_PASSWORD = 'password'
MAIL_DEFAULT_SENDER = '"AppName" <noreply@example.com>'
MAIL_SERVER = 'MAIL_SERVER', 'smtp.gmail.com'
MAIL_PORT = 465
MAIL_USE_SSL = True
MAIL_USE_TLS = False
ADMINS = [
'"Admin One" <admin1@gmail.com>',
]
|
test(store): Reset jest modules and NODE_ENV after store tests
|
// @flow
describe('store', () => {
beforeEach(() => jest.resetModules())
afterEach(() => jest.resetModules())
it('should create a development redux store with the reducers passed', () => {
process.env.NODE_ENV = 'development'
const createStore = require('../../../src/store')
const store = createStore({})
expect(store.dispatch).toBeDefined()
expect(store.getState).toBeDefined()
expect(store.subscribe).toBeDefined()
})
it('should create a production redux store with the reducers passed', () => {
process.env.NODE_ENV = 'production'
const createStore = require('../../../src/store')
const store = createStore({})
expect(store.dispatch).toBeDefined()
expect(store.getState).toBeDefined()
expect(store.subscribe).toBeDefined()
})
it('should create a test redux store with', () => {
process.env.NODE_ENV = 'test'
const createStore = require('../../../src/store')
const store = createStore({})
expect(store.dispatch).toBeDefined()
expect(store.getState).toBeDefined()
expect(store.subscribe).toBeDefined()
expect(store.getActions).toBeDefined()
})
})
|
/* globals describe, expect, it, jest */
describe('store', () => {
it('should create a development redux store with the reducers passed', () => {
jest.resetModules()
process.env.NODE_ENV = 'development'
const createStore = require('../../../src/store')
const store = createStore({})
expect(store.dispatch).toBeDefined()
expect(store.getState).toBeDefined()
expect(store.subscribe).toBeDefined()
})
it('should create a production redux store with the reducers passed', () => {
jest.resetModules()
process.env.NODE_ENV = 'production'
const createStore = require('../../../src/store')
const store = createStore({})
expect(store.dispatch).toBeDefined()
expect(store.getState).toBeDefined()
expect(store.subscribe).toBeDefined()
})
})
|
Update requests to its latest version
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
execfile('panoply/constants.py')
setup(
name=__package_name__,
version=__version__,
packages=["panoply"],
install_requires=[
"requests==2.21.0",
"oauth2client==4.1.1"
],
extras_require={
"test": [
"pep8==1.7.0",
"coverage==4.3.4"
]
},
url="https://github.com/panoplyio/panoply-python-sdk",
author="Panoply.io",
author_email="support@panoply.io"
)
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
execfile('panoply/constants.py')
setup(
name=__package_name__,
version=__version__,
packages=["panoply"],
install_requires=[
"requests==2.3.0",
"oauth2client==4.1.1"
],
extras_require={
"test": [
"pep8==1.7.0",
"coverage==4.3.4"
]
},
url="https://github.com/panoplyio/panoply-python-sdk",
author="Panoply.io",
author_email="support@panoply.io"
)
|
Fix and refactor where() mutator
|
<?php
namespace Underscore\Mutator;
use Underscore\Collection;
use Underscore\Mutator;
class WhereMutator extends Mutator
{
/**
* Remove all values that do not match the given key-value pairs.
*
* By default strict comparison is used.
*
* @param Collection $collection
* @param array $properties
* @param boolean $strict
* @return Collection
*/
public function __invoke($collection, array $properties, $strict = true)
{
return $this->wrap(array_filter((array)$collection, function ($item) use ($properties, $strict) {
foreach ($properties as $key => $value) {
if (empty($item[$key])
|| ($strict && $item[$key] !== $value)
|| (!$strict && $item[$key] != $value)
) {
return false;
}
}
return true;
}));
}
}
|
<?php
namespace Underscore\Mutator;
use Underscore\Collection;
use Underscore\Mutator;
/**
* Class WhereMutator
* @package Underscore\Mutator
*/
class WhereMutator extends Mutator
{
/**
* Remove all values that do not match the given key-value pairs.
*
* By default strict comparison is used.
*
* @param Collection $collection
* @param array $properties
* @param boolean $strict
* @return Collection
*/
public function __invoke($collection, array $properties, $strict = true)
{
$collection = clone $collection;
// This can be refactored to use array_filter once #54 is merged.
foreach ($collection as $index => $item) {
$item = new Collection($item);
foreach ($properties as $key => $value) {
if (empty($item[$key])
|| ($strict && $item[$key] !== $value)
|| (!$strict && $item[$key] != $value)
) {
unset($collection[$index]);
}
}
}
return $collection;
}
}
|
[Bundle] Make getPath() less error prone by allowing both backward and forward slashes
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\WebProfilerBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* Bundle.
*
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
*/
class WebProfilerBundle extends Bundle
{
/**
* {@inheritdoc}
*/
public function getNamespace()
{
return __NAMESPACE__;
}
/**
* {@inheritdoc}
*/
protected function getPath()
{
return __DIR__;
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\WebProfilerBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* Bundle.
*
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
*/
class WebProfilerBundle extends Bundle
{
/**
* {@inheritdoc}
*/
public function getNamespace()
{
return __NAMESPACE__;
}
/**
* {@inheritdoc}
*/
public function getPath()
{
return strtr(__DIR__, '\\', '/');
}
}
|
Fix wrong console command namespace
|
<?php
declare(strict_types=1);
namespace Cortex\Foundation\Console\Commands;
use Illuminate\Database\Console\Migrations\MigrateMakeCommand as BaseMigrateMakeCommand;
class MigrateMakeCommand extends BaseMigrateMakeCommand
{
/**
* The console command signature.
*
* @var string
*/
protected $signature = 'make:migration {name : The name of the migration.}
{--module= : The name of the module.}
{--create= : The table to be created.}
{--table= : The table to migrate.}
{--path= : The location where the migration file should be created.}';
/**
* Get migration path (either specified by '--path' option or module location).
*
* @return string
*/
protected function getMigrationPath()
{
if (! is_null($targetPath = $this->input->getOption('path'))) {
return $this->laravel->basePath().'/'.$targetPath;
}
if (! is_null($module = $this->input->getOption('module')) && $this->laravel->files->exists($modulePath = $this->laravel->path().DIRECTORY_SEPARATOR.$module)) {
return $modulePath.DIRECTORY_SEPARATOR.'database'.DIRECTORY_SEPARATOR.'migrations';
}
return $this->laravel->databasePath().DIRECTORY_SEPARATOR.'migrations';
}
}
|
<?php
declare(strict_types=1);
namespace Cortex\Foundation\Console;
use Illuminate\Database\Console\Migrations\MigrateMakeCommand as BaseMigrateMakeCommand;
class MigrateMakeCommand extends BaseMigrateMakeCommand
{
/**
* The console command signature.
*
* @var string
*/
protected $signature = 'make:migration {name : The name of the migration.}
{--module= : The name of the module.}
{--create= : The table to be created.}
{--table= : The table to migrate.}
{--path= : The location where the migration file should be created.}';
/**
* Get migration path (either specified by '--path' option or module location).
*
* @return string
*/
protected function getMigrationPath()
{
if (! is_null($targetPath = $this->input->getOption('path'))) {
return $this->laravel->basePath().'/'.$targetPath;
}
if (! is_null($module = $this->input->getOption('module')) && $this->laravel->files->exists($modulePath = $this->laravel->path().DIRECTORY_SEPARATOR.$module)) {
return $modulePath.DIRECTORY_SEPARATOR.'database'.DIRECTORY_SEPARATOR.'migrations';
}
return $this->laravel->databasePath().DIRECTORY_SEPARATOR.'migrations';
}
}
|
Add externalUrl to all resources
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-respond',
contentFor: function(type, config) {
if (type === 'head-footer') {
var output = '<script src="' + config.respond.externalUrl + 'ember-cli-respond/respond.min.js"></script>';
if (typeof config.respond !== 'undefined' && config.respond.proxy === true) {
output += '<link href="' + config.respond.externalUrl + 'respond-proxy.html" id="respond-proxy" rel="respond-proxy" />' +
'<link href="' + config.respond.externalUrl + '"ember-cli-respond/respond.proxy.gif" id="respond-redirect" rel="respond-redirect" />' +
'<script src="' + config.respond.externalUrl + '"ember-cli-respond/respond.proxy.js"></script>';
}
return output;
}
}
};
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-respond',
contentFor: function(type, config) {
if (type === 'head-footer') {
var output = '<script src="/ember-cli-respond/respond.min.js"></script>';
if (typeof config.respond !== 'undefined' && config.respond.proxy === true) {
output += '<link href="' + config.respond.externalUrl + 'respond-proxy.html" id="respond-proxy" rel="respond-proxy" />' +
'<link href="/ember-cli-respond/respond.proxy.gif" id="respond-redirect" rel="respond-redirect" />' +
'<script src="/ember-cli-respond/respond.proxy.js"></script>';
}
return output;
}
}
};
|
Fix the bugs in the main code
ref #58
|
'use babel';
let InteractiveConfigurationPanel = null;
let RandomTipPanel = null;
function initializeInteractiveConfiguration() {
if (InteractiveConfigurationPanel !== null) return ;
InteractiveConfigurationPanel = require('./interactive-configuration-panel');
}
function initializeRandomTips() {
if (RandomTipPanel !== null) return;
RandomTipPanel = require('./random-tip-panel');
}
export default class UserSupportHelper {
constructor() {
this.tips = []
}
destroy() {
if (this.configurationPanel !== null) {
this.configurationPanel.destroy();
}
for (const tip of tips) tip.destory()
}
getInteractiveConfigurationPanel() {
initializeInteractiveConfiguration();
if (!this.configurationPanel) {
this.configurationPanel = new InteractiveConfigurationPanel()
}
return this.configurationPanel;
}
createRandomTipPanel(configurationPrefix, words) {
initializeRandomTips();
const panel = new RandomTipPanel(configurationPrefix, words);
this.tips.push(panel)
return panel;
}
};
|
'use babel';
let InteractiveConfigurationPanel = null;
let RandomTipPanel = null;
initializeInteractiveConfiguration() {
if (InteractiveConfigurationPanel !== null) return ;
InteractiveConfigurationPanel = require('./interactive-configuration-panel');
}
initializeRandomTips() {
if (RandomTipPanel !== null) return;
RandomTipPanel = require('./random-tip-panel');
}
export default class UserSupportHelper {
constructor() {
this.tips = []
}
destroy() {
if (this.configurationPanel !== null) {
this.configurationPanel.destroy();
}
for (const tip of tips) tip.destory()
}
getInteractiveConfigurationPanel() {
this.initializeInteractiveConfiguration();
if (!this.configurationPanel) {
this.configurationPanel = new InteractiveConfigurationPanel()
}
return this.configurationPanel;
},
createRandomTipPanel(configurationPrefix, words) {
this.initializeRandomTips();
const panel = new RandomTipPanel(configurationPrefix, words);
this.tips.push(panel)
return panel;
}
};
|
Add readable text for debugging.
|
package com.github.kubode.wiggle;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class MockView extends TextView {
private final WiggleHelper helper = new WiggleHelper();
public MockView(Context context) {
super(context);
}
public MockView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MockView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
helper.onViewAttachedToWindow(this);
}
@Override
protected void onDetachedFromWindow() {
helper.onViewDetachedFromWindow(this);
super.onDetachedFromWindow();
}
@SuppressLint("SetTextI18n")
@Override
public void setTranslationY(float translationY) {
super.setTranslationY(translationY);
setText("translationY=" + translationY);
}
}
|
package com.github.kubode.wiggle;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
public class MockView extends View {
private final WiggleHelper helper = new WiggleHelper();
public MockView(Context context) {
super(context);
}
public MockView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MockView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
helper.onViewAttachedToWindow(this);
}
@Override
protected void onDetachedFromWindow() {
helper.onViewDetachedFromWindow(this);
super.onDetachedFromWindow();
}
}
|
Remove caching of normalized paths again
Caching them avoided some short term allocations, but
significantly increased long-term heap consumption.
|
/*
* Copyright 2016 the original author or 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.
*/
package org.gradle.api.internal.changedetection.state;
public class IndexedNormalizedFileSnapshot extends AbstractNormalizedFileSnapshot {
private final String absolutePath;
private final int index;
public IndexedNormalizedFileSnapshot(String absolutePath, int index, FileContentSnapshot snapshot) {
super(snapshot);
this.absolutePath = absolutePath;
this.index = index;
}
@Override
public String getNormalizedPath() {
return absolutePath.substring(index);
}
public String getAbsolutePath() {
return absolutePath;
}
public int getIndex() {
return index;
}
}
|
/*
* Copyright 2016 the original author or 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.
*/
package org.gradle.api.internal.changedetection.state;
public class IndexedNormalizedFileSnapshot extends AbstractNormalizedFileSnapshot {
private final String absolutePath;
private final int index;
private String normalizedPath;
public IndexedNormalizedFileSnapshot(String absolutePath, int index, FileContentSnapshot snapshot) {
super(snapshot);
this.absolutePath = absolutePath;
this.index = index;
}
@Override
public String getNormalizedPath() {
if (normalizedPath == null) {
normalizedPath = absolutePath.substring(index);
}
return normalizedPath;
}
public String getAbsolutePath() {
return absolutePath;
}
public int getIndex() {
return index;
}
}
|
Update test: mock module request
|
<?php
namespace tests\SlackApi;
use SlackApi\Client;
use SlackApi\Response;
use \tests\Fixtures\TestModule;
/**
* Class AbstractModuleTest
*/
class ModuleTest extends \PHPUnit_Framework_TestCase
{
/**
* @return string
*/
protected function getRealToken()
{
return getenv('SLACK_TEST_TOKEN');
}
/**
* @return string
*/
protected function getFakeToken()
{
return 'fake-token';
}
/**
* @return Client
*/
protected function getClient()
{
return new Client($this->getRealToken());
}
/**
*
*/
public function testRequest()
{
$mock = $this->getMockBuilder(TestModule::class)
->setMethods(['request'])
->disableOriginalConstructor()
->getMock();
$mock->expects($this->once())
->method('request')
->will($this->returnValue(new Response(['ok' => true])));
/** @var TestModule $mock */
$response = $mock->request('test');
$this->assertInstanceOf('\SlackApi\Response', $response);
$this->assertTrue($response->isSuccess());
}
}
|
<?php
namespace tests\SlackApi;
use SlackApi\Client;
use \tests\Fixtures\TestModule;
/**
* Class AbstractModuleTest
*/
class ModuleTest extends \PHPUnit_Framework_TestCase
{
/**
* @return string
*/
protected function getRealToken()
{
return getenv('SLACK_TEST_TOKEN');
}
/**
* @return string
*/
protected function getFakeToken()
{
return 'fake-token';
}
/**
* @return Client
*/
protected function getClient()
{
return new Client($this->getRealToken());
}
/**
*
*/
public function testRequest()
{
$module = new TestModule('api', $this->getClient());
$response = $module->request('test', ['argument' => 'value']);
$this->assertInstanceOf('\SlackApi\Response', $response);
$this->assertTrue($response->isSuccess());
}
/**
*
*/
public function testPredefinedRequest()
{
$module = new TestModule('api', $this->getClient());
$response = $module->test();
$this->assertInstanceOf('\SlackApi\Response', $response);
$this->assertTrue($response->isSuccess());
}
}
|
Fix - was flipping display twice
Gah. Here is a speedup for pygame -- don't flip the display twice.
|
"""enchanting2.py
This is the main entry point of the system"""
import sys
import xml.etree.cElementTree as ElementTree
import actor
import media
def main(argv):
"""This is a naive, blocking, co-operatively multitasking approach"""
filename = argv[1] # xml file to open
tree = ElementTree.parse(filename)
project = actor.Project()
project.deserialize(tree.getroot())
# Now, we can run the code
all_actors = [project.stage]
all_actors.extend([sprite for sprite in project.stage.sprites
if isinstance(sprite, actor.BaseActor)])
# Create our media environment
# (now that we have dimensions for the screen)
media_environment = media.PyGameMediaEnvironment()
media_environment.setup_for_project(project)
for sprite in all_actors:
sprite.convert_art(media_environment)
while True:
media_environment.check_for_events()
for sprite in all_actors:
for script in sprite.scripts:
try:
script.step(sprite)
except StopIteration:
pass
# note: the stage is the first sprite in the list, and erases the screen
for sprite in all_actors:
sprite.draw(media_environment)
media_environment.finished_frame()
if __name__ == "__main__":
main(sys.argv)
|
"""enchanting2.py
This is the main entry point of the system"""
import sys
import xml.etree.cElementTree as ElementTree
import pygame
import actor
import media
def main(argv):
"""This is a naive, blocking, co-operatively multitasking approach"""
filename = argv[1] # xml file to open
tree = ElementTree.parse(filename)
project = actor.Project()
project.deserialize(tree.getroot())
# Now, we can run the code
all_actors = [project.stage]
all_actors.extend([sprite for sprite in project.stage.sprites
if isinstance(sprite, actor.BaseActor)])
# Create our media environment
# (now that we have dimensions for the screen)
media_environment = media.PyGameMediaEnvironment()
media_environment.setup_for_project(project)
for sprite in all_actors:
sprite.convert_art(media_environment)
while True:
media_environment.check_for_events()
for sprite in all_actors:
for script in sprite.scripts:
try:
script.step(sprite)
except StopIteration:
pass
# note: the stage is the first sprite in the list, and erases the screen
for sprite in all_actors:
sprite.draw(media_environment)
pygame.display.flip()
media_environment.finished_frame()
if __name__ == "__main__":
main(sys.argv)
|
Make icon a class component
|
import React from 'react';
import PropTypes from 'prop-types';
import constants from './constants';
import cx from 'classnames';
class Icon extends React.Component {
render() {
const classes = {
'material-icons': true
};
constants.PLACEMENTS.forEach(p => {
classes[p] = this.props[p];
});
constants.ICON_SIZES.forEach(s => {
classes[s] = this.props[s];
});
return (
<i className={cx(classes, this.props.className)}>{this.props.children}</i>
);
}
}
Icon.propTypes = {
/*
* Classname passed to i tag
*/
className: PropTypes.string,
/*
* Icon type: <a href='https://material.io/icons/'>https://material.io/icons/</a>
*/
children: PropTypes.string,
/*
* Placement for icon if used beside a text ↓
*/
left: PropTypes.bool,
center: PropTypes.bool,
right: PropTypes.bool,
/*
* Sizes for icons ↓
*/
tiny: PropTypes.bool,
small: PropTypes.bool,
medium: PropTypes.bool,
large: PropTypes.bool
};
export default Icon;
|
import React from 'react';
import PropTypes from 'prop-types';
import constants from './constants';
import cx from 'classnames';
const Icon = props => {
let classes = {
'material-icons': true
};
constants.PLACEMENTS.forEach(p => {
classes[p] = props[p];
});
constants.ICON_SIZES.forEach(s => {
classes[s] = props[s];
});
return <i className={cx(classes, props.className)}>{props.children}</i>;
};
Icon.propTypes = {
/*
* Classname passed to i tag
*/
className: PropTypes.string,
/*
* Icon type: <a href='https://material.io/icons/'>https://material.io/icons/</a>
*/
children: PropTypes.string,
/*
* Placement for icon if used beside a text ↓
*/
left: PropTypes.bool,
center: PropTypes.bool,
right: PropTypes.bool,
/*
* Sizes for icons ↓
*/
tiny: PropTypes.bool,
small: PropTypes.bool,
medium: PropTypes.bool,
large: PropTypes.bool
};
export default Icon;
|
Update ptvsd version number for 2.0 beta 2.
|
#!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft. 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.
#--------------------------------------------------------------------------
from distutils.core import setup
setup(name='ptvsd',
version='2.1.0b2',
description='Python Tools for Visual Studio remote debugging server',
license='Apache License 2.0',
author='Microsoft Corporation',
author_email='ptvshelp@microsoft.com',
url='https://pytools.codeplex.com/',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: Apache Software License'],
packages=['ptvsd']
)
|
#!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft. 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.
#--------------------------------------------------------------------------
from distutils.core import setup
setup(name='ptvsd',
version='2.1.0b1',
description='Python Tools for Visual Studio remote debugging server',
license='Apache License 2.0',
author='Microsoft Corporation',
author_email='ptvshelp@microsoft.com',
url='https://pytools.codeplex.com/',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: Apache Software License'],
packages=['ptvsd']
)
|
Use phpcs as a library.
|
#!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
require 'vendor/autoload.php';
$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php'), 'warningSeverity' => 0);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
if ($phpcsViolations > 0) {
exit(1);
}
$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
exit(1);
}
$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(1);
}
echo "Code coverage was 100%\n";
|
#!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
require 'vendor/autoload.php';
passthru('./vendor/bin/phpcs --standard=PSR1 -n src tests *.php', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
exit(1);
}
$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(1);
}
echo "Code coverage was 100%\n";
|
Update trove classifiers and django test version requirements
|
#-*- coding: utf-8 -*-
from setuptools import setup
version = "1.0.post1"
setup(
name = "django-easy-pjax",
version = version,
description = "Easy PJAX for Django.",
license = "BSD",
author = "Filip Wasilewski",
author_email = "en@ig.ma",
url = "https://github.com/nigma/django-easy-pjax",
download_url='https://github.com/nigma/django-easy-pjax/zipball/master',
long_description = open("README.rst").read(),
packages = ["easy_pjax"],
include_package_data=True,
classifiers = (
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Topic :: Software Development :: Libraries :: Python Modules"
),
tests_require=[
"django>=1.4,<1.6",
],
zip_safe = False
)
|
#-*- coding: utf-8 -*-
from setuptools import setup
version = "1.0.post1"
setup(
name = "django-easy-pjax",
version = version,
description = "Easy PJAX for Django.",
license = "BSD",
author = "Filip Wasilewski",
author_email = "en@ig.ma",
url = "https://github.com/nigma/django-easy-pjax",
download_url='https://github.com/nigma/django-easy-pjax/zipball/master',
long_description = open("README.rst").read(),
packages = ["easy_pjax"],
include_package_data=True,
classifiers = (
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Topic :: Software Development :: Libraries :: Python Modules"
),
tests_require=[
"django>=1.4,<1.5",
],
zip_safe = False
)
|
Add global vars for refreshing
|
function parseMessages(messages, users, callback) {
var allWords = {};
console.log('parseMessages.js - messages', messages);
console.log('parseMessages.js (start) - users', users);
for(var i = 0; i < messages.length; i++) {
var author = users[messages[i].from.name];
var split = messages[i].message.split(' ');
for(var j = 0; j < split.length; j++) {
var word = split[j];
if(!author.words[word]) {
author.words[word] = 1;
} else {
author.words[word]++;
}
if(!allWords[word]) {
allWords[word] = 1; // populate allWords obj
} else {
allWords[word]++;
}
}
}
console.log('parseMessages.js (end) - users', users);
console.log('parseMessages.js (end) - allWords', allWords);
window.users = users;
window.allWords = allWords;
callback(users, allWords);
}
|
function parseMessages(messages, users, callback) {
var allWords = {};
console.log('parseMessages.js - messages', messages);
console.log('parseMessages.js (start) - users', users);
for(var i = 0; i < messages.length; i++) {
var author = users[messages[i].from.name];
var split = messages[i].message.split(' ');
for(var j = 0; j < split.length; j++) {
var word = split[j];
if(!author.words[word]) {
author.words[word] = 1;
} else {
author.words[word]++;
}
if(!allWords[word]) {
allWords[word] = 1; // populate allWords obj
} else {
allWords[word]++;
}
}
}
console.log('parseMessages.js (end) - users', users);
console.log('parseMessages.js (end) - allWords', allWords);
callback(users, allWords);
}
|
Fix buildXML() call for extension w/o update_url
|
"use strict";
var path = require('path');
/**
* Initializes the crx autoupdate grunt helper
*
* @param {grunt} grunt
* @returns {{buildXML: Function, build: Function}}
*/
exports.init = function(grunt){
/**
* Generates an autoupdate XML file
*
* @todo relocate that to {@link lib/crx.js} as it's totally irrelevant now
* @param {crx} ChromeExtension
* @param {Function} callback
*/
function buildXML(ChromeExtension, callback) {
if (!ChromeExtension.manifest.update_url || !ChromeExtension.codebase){
callback();
return;
}
ChromeExtension.generateUpdateXML();
var dest = path.dirname(ChromeExtension.dest);
var filename = path.join(dest, path.basename(ChromeExtension.manifest.update_url));
grunt.file.write(filename, ChromeExtension.updateXML);
callback();
}
/*
* Blending
*/
return {
"buildXML": buildXML,
/** @deprecated (will be removed in 0.3) */
"build": buildXML
};
};
|
"use strict";
var path = require('path');
/**
* Initializes the crx autoupdate grunt helper
*
* @param {grunt} grunt
* @returns {{buildXML: Function, build: Function}}
*/
exports.init = function(grunt){
/**
* Generates an autoupdate XML file
*
* @todo relocate that to {@link lib/crx.js} as it's totally irrelevant now
* @param {crx} ChromeExtension
* @param {Function} callback
*/
function buildXML(ChromeExtension, callback) {
if (!ChromeExtension.manifest.update_url || !ChromeExtension.codebase){
callback();
}
ChromeExtension.generateUpdateXML();
var dest = path.dirname(ChromeExtension.dest);
var filename = path.join(dest, path.basename(ChromeExtension.manifest.update_url));
grunt.file.write(filename, ChromeExtension.updateXML);
callback();
}
/*
* Blending
*/
return {
"buildXML": buildXML,
/** @deprecated (will be removed in 0.3) */
"build": buildXML
};
};
|
Fix unit test for JDK 1.3.
git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@701 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e
|
package com.thoughtworks.xstream.core;
import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;
public class TreeMarshallerTest extends AbstractAcceptanceTest {
static class Thing {
Thing thing;
}
protected void setUp() throws Exception {
super.setUp();
xstream.setMode(XStream.NO_REFERENCES);
}
public void testThrowsExceptionWhenDetectingCircularReferences() {
Thing a = new Thing();
Thing b = new Thing();
a.thing = b;
b.thing = a;
try {
xstream.toXML(a);
fail("expected exception");
} catch (TreeMarshaller.CircularReferenceException expected) {
// good
}
}
}
|
package com.thoughtworks.xstream.core;
import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;
public class TreeMarshallerTest extends AbstractAcceptanceTest {
class Thing {
Thing thing;
}
protected void setUp() throws Exception {
super.setUp();
xstream.setMode(XStream.NO_REFERENCES);
}
public void testThrowsExceptionWhenDetectingCircularReferences() {
Thing a = new Thing();
Thing b = new Thing();
a.thing = b;
b.thing = a;
try {
xstream.toXML(a);
fail("expected exception");
} catch (TreeMarshaller.CircularReferenceException expected) {
// good
}
}
}
|
Update config to point at keff.dev
|
module.exports = {
siteMetadata: {
title: 'keff',
},
plugins: [
'gatsby-plugin-react-helmet',
'gatsby-plugin-sass',
{
resolve: 'gatsby-plugin-manifest',
options: {
name: 'keff.dev',
short_name: 'keff.dev',
start_url: '/',
display: 'minimal-ui',
},
},
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/posts`,
name: 'markdown-pages',
},
},
{
resolve: 'gatsby-transformer-remark',
options: {
plugins: [
'gatsby-remark-katex',
'gatsby-remark-prismjs',
'gatsby-remark-external-links',
],
},
},
'gatsby-plugin-offline',
],
};
|
module.exports = {
siteMetadata: {
title: 'keff',
},
plugins: [
'gatsby-plugin-react-helmet',
'gatsby-plugin-sass',
{
resolve: 'gatsby-plugin-manifest',
options: {
name: 'keff.me',
short_name: 'keff.me',
start_url: '/',
display: 'minimal-ui',
},
},
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/posts`,
name: 'markdown-pages',
},
},
{
resolve: 'gatsby-transformer-remark',
options: {
plugins: [
'gatsby-remark-katex',
'gatsby-remark-prismjs',
'gatsby-remark-external-links',
],
},
},
'gatsby-plugin-offline',
],
};
|
Change shebang to /usr/bin/env for better venv support
|
#!/usr/bin/env python3
"""Setup.py for dirbrowser."""
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name="dirbrowser",
version="1.0b1",
description="Command line based directory browser",
long_description=long_description,
url="https://github.com/campenr/dirbrowser",
author="Richard Campen",
author_email="richard@campen.co",
license="BSD License",
# TODO add more classifiers (e.g. platform)
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development :: User Interfaces",
"License :: OSI Approved :: BSD License",
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
keywords="directory browser interface",
packages=find_packages(),
include_package_data=True
# TODO add entry into scripts folder
)
|
#!/usr/bin/python3
"""Setup.py for dirbrowser."""
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name="dirbrowser",
version="1.0b1",
description="Command line based directory browser",
long_description=long_description,
url="https://github.com/campenr/dirbrowser",
author="Richard Campen",
author_email="richard@campen.co",
license="BSD License",
# TODO add more classifiers (e.g. platform)
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development :: User Interfaces",
"License :: OSI Approved :: BSD License",
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
keywords="directory browser interface",
packages=find_packages(),
include_package_data=True
# TODO add entry into scripts folder
)
|
Use SecurityActions to set the TCCL
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 io.undertow.servlet.core;
import io.undertow.server.HttpServerExchange;
import io.undertow.servlet.api.ThreadSetupAction;
/**
* @author Stuart Douglas
*/
public class ContextClassLoaderSetupAction implements ThreadSetupAction {
private final ClassLoader classLoader;
public ContextClassLoaderSetupAction(final ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
public Handle setup(final HttpServerExchange exchange) {
final ClassLoader old = SecurityActions.getContextClassLoader();
SecurityActions.setContextClassLoader(classLoader);
return new Handle() {
@Override
public void tearDown() {
SecurityActions.setContextClassLoader(old);
}
};
}
}
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 io.undertow.servlet.core;
import io.undertow.server.HttpServerExchange;
import io.undertow.servlet.api.ThreadSetupAction;
/**
* @author Stuart Douglas
*/
public class ContextClassLoaderSetupAction implements ThreadSetupAction {
private final ClassLoader classLoader;
public ContextClassLoaderSetupAction(final ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
public Handle setup(final HttpServerExchange exchange) {
final ClassLoader old = SecurityActions.getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
return new Handle() {
@Override
public void tearDown() {
SecurityActions.setContextClassLoader(old);
}
};
}
}
|
Fix test case for SLEEP statement
|
package com.orientechnologies.orient.core.sql.executor;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.orientechnologies.orient.core.sql.executor.ExecutionPlanPrintUtils.printExecutionPlan;
/**
* @author Luigi Dell'Aquila (l.dellaquila-(at)-orientdb.com)
*/
public class OSleepStatementExecutionTest {
static ODatabaseDocument db;
@BeforeClass public static void beforeClass() {
db = new ODatabaseDocumentTx("memory:OSleepStatementExecutionTest");
db.create();
}
@AfterClass public static void afterClass() {
db.close();
}
@Test public void testBasic() {
long begin = System.currentTimeMillis();
OTodoResultSet result = db.command("sleep 1000");
Assert.assertTrue(System.currentTimeMillis() - begin >= 1000);
printExecutionPlan(null, result);
Assert.assertNotNull(result);
Assert.assertTrue(result.hasNext());
OResult item = result.next();
Assert.assertEquals("sleep", item.getProperty("operation"));
Assert.assertFalse(result.hasNext());
}
}
|
package com.orientechnologies.orient.core.sql.executor;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.orientechnologies.orient.core.sql.executor.ExecutionPlanPrintUtils.printExecutionPlan;
/**
* @author Luigi Dell'Aquila (l.dellaquila-(at)-orientdb.com)
*/
public class OSleepStatementExecutionTest {
static ODatabaseDocument db;
@BeforeClass public static void beforeClass() {
db = new ODatabaseDocumentTx("memory:OSleepStatementExecutionTest");
db.create();
}
@AfterClass public static void afterClass() {
db.close();
}
@Test public void testBegin() {
long begin = System.currentTimeMillis();
OTodoResultSet result = db.command("sleep 1000");
Assert.assertTrue(System.currentTimeMillis() - begin > 1000);
printExecutionPlan(null, result);
Assert.assertNotNull(result);
Assert.assertTrue(result.hasNext());
OResult item = result.next();
Assert.assertEquals("sleep", item.getProperty("operation"));
Assert.assertFalse(result.hasNext());
}
}
|
Add a TDD funct to test the solution (only kings)
|
# -*- coding: utf-8 -*-
from app.chess.chess import Chess
import unittest
class TestBuildChess(unittest.TestCase):
"""
`TestBuildChess()` class is unit-testing the class
Chess().
"""
# ///////////////////////////////////////////////////
def setUp(self):
params = [4, 4]
pieces = {'King': 2, 'Queen': 1, 'Bishop': 0, 'Rook': 0, 'Knight': 0}
params.append(pieces)
self.chess = Chess(params)
# ///////////////////////////////////////////////////
def test_solve(self):
"""Tests validity of solution"""
self.assertEqual(self.chess.pieces_types == ['K', 'K', 'Q'], True)
self.assertEqual(self.chess.number_pieces == 3, True)
# self.assertEqual(self.chess.solutions == 1, True)
def test_solution_only_kings(self):
params = [5, 5]
pieces = {'King': 2, 'Queen': 0, 'Bishop': 0, 'Rook': 0, 'Knight': 0}
params.append(pieces)
self.chess = Chess(params)
self.chess.run_game()
self.assertEqual(self.chess.solutions == 228, True)
if __name__ == '__main__':
unittest.main()
|
# -*- coding: utf-8 -*-
from app.chess.chess import Chess
import unittest
class TestBuildChess(unittest.TestCase):
"""
`TestBuildChess()` class is unit-testing the class
Chess().
"""
# ///////////////////////////////////////////////////
def setUp(self):
params = [4, 4]
pieces = {'King': 2, 'Queen': 1, 'Bishop': 0, 'Rook': 0, 'Knight': 0}
params.append(pieces)
self.chess = Chess(params)
# ///////////////////////////////////////////////////
def test_solve(self):
"""Tests validity of solution"""
self.assertEqual(self.chess.pieces_types == ['K', 'K', 'Q'], True)
self.assertEqual(self.chess.number_pieces == 3, True)
# self.assertEqual(self.chess.solutions == 1, True)
if __name__ == '__main__':
unittest.main()
|
Remove text coloring in AlertFeed if it seems like scheduled text
|
import asyncio
import json
import aiohttp
import SLA_bot.config as cf
class AlertFeed:
source_url = 'http://pso2emq.flyergo.eu/api/v2/'
async def download(url):
try:
async with aiohttp.get(url) as response:
return await response.json()
except json.decoder.JSONDecodeError:
pass
def parse_data(data):
latest_alert = data[0]['text']
lines = latest_alert.splitlines()
code_color = 'fix' if len(lines) >= 10 else ''
header = '-' * len(lines[0])
lines.insert(1, header)
text = '\n'.join(lines)
return '```{}\n{}\n```'.format(code_color, text)
async def fetch():
header = cf.get('PSO2 Feed', 'header')
raw_data = await AlertFeed.download(AlertFeed.source_url)
return '** **\n' + header + '\n' + AlertFeed.parse_data(raw_data)
|
import asyncio
import json
import aiohttp
import SLA_bot.config as cf
class AlertFeed:
source_url = 'http://pso2emq.flyergo.eu/api/v2/'
async def download(url):
try:
async with aiohttp.get(url) as response:
return await response.json()
except json.decoder.JSONDecodeError:
pass
def parse_data(data):
latest_alert = data[0]['text']
lines = latest_alert.splitlines()
header = '-' * len(lines[0])
lines.insert(1, header)
text = '\n'.join(lines)
return '```fix\n{}\n```'.format(text)
async def fetch():
header = cf.get('PSO2 Feed', 'header')
raw_data = await AlertFeed.download(AlertFeed.source_url)
return '** **\n' + header + '\n' + AlertFeed.parse_data(raw_data)
|
Set default isConfidential to false for client entity
|
<?php
/**
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
*
* @link https://github.com/thephpleague/oauth2-server
*/
namespace League\OAuth2\Server\Entities\Traits;
trait ClientTrait
{
/**
* @var string
*/
protected $name;
/**
* @var string|string[]
*/
protected $redirectUri;
/**
* @var bool
*/
protected $isConfidential = false;
/**
* Get the client's name.
*
* @return string
* @codeCoverageIgnore
*/
public function getName()
{
return $this->name;
}
/**
* Returns the registered redirect URI (as a string).
*
* Alternatively return an indexed array of redirect URIs.
*
* @return string|string[]
*/
public function getRedirectUri()
{
return $this->redirectUri;
}
/**
* Returns true if the client is confidential.
*
* @return bool
*/
public function isConfidential()
{
return $this->isConfidential;
}
}
|
<?php
/**
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
*
* @link https://github.com/thephpleague/oauth2-server
*/
namespace League\OAuth2\Server\Entities\Traits;
trait ClientTrait
{
/**
* @var string
*/
protected $name;
/**
* @var string|string[]
*/
protected $redirectUri;
/**
* @var bool
*/
protected $isConfidential;
/**
* Get the client's name.
*
* @return string
* @codeCoverageIgnore
*/
public function getName()
{
return $this->name;
}
/**
* Returns the registered redirect URI (as a string).
*
* Alternatively return an indexed array of redirect URIs.
*
* @return string|string[]
*/
public function getRedirectUri()
{
return $this->redirectUri;
}
/**
* Returns true if the client is confidential.
*
* @return bool
*/
public function isConfidential()
{
return $this->isConfidential;
}
}
|
Use Requests to encode stop as query param, verify API status code.
|
#!/usr/bin/env python
import os, requests, getSchedule
from flask import Flask, request, jsonify, render_template, abort
app = Flask(__name__)
@app.route('/')
def root():
return render_template('index.html')
@app.route('/m')
def mobileView():
stop = request.args.get('stop', 1, type=int)
payload = {'stop': stop}
r = requests.get('http://nextride.alykhan.com/api', params=payload)
if r.status_code == requests.codes.ok:
path = r.json()
else:
abort(400)
return render_template('index.html', path=path)
@app.route('/api')
def api():
stop = request.args.get('stop', 1, type=int)
schedule = getSchedule.parseSchedule(getSchedule.getRides(stop))
if schedule:
response = jsonify(meta=dict(status=200, message='OK'),data=schedule)
else:
abort(400)
return response
@app.errorhandler(400)
def bad_request(error):
response = jsonify(meta=dict(status=error.code, message=error.message))
return response, error.code
if __name__ == "__main__":
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
#!/usr/bin/env python
import os, requests, getSchedule
from flask import Flask, request, jsonify, render_template, abort
app = Flask(__name__)
@app.route('/')
def root():
return render_template('index.html')
@app.route('/m')
def mobileView():
stop = request.args.get('stop', 1, type=int)
route = requests.get('http://nextride.alykhan.com/api?stop='+str(stop)).json()
if route:
path = route
else:
abort(400)
return render_template('index.html', path=path)
@app.route('/api')
def api():
stop = request.args.get('stop', 1, type=int)
schedule = getSchedule.parseSchedule(getSchedule.getRides(stop))
if schedule:
response = jsonify(meta=dict(status=200, message='OK'),data=schedule)
else:
abort(400)
return response
@app.errorhandler(400)
def bad_request(error):
response = jsonify(meta=dict(status=error.code, message=error.message))
return response, error.code
if __name__ == "__main__":
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
fix: Fix useless parameter in Hash handling test data provider
|
<?php
namespace Monolol\Lolifiers;
use Monolog\Logger;
class HashTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider testHandlingProvider
*/
public function testHandling($level)
{
$record = array('level' => $level);
$lolifier = new Hash();
$this->assertTrue($lolifier->isHandling($record));
}
public function testHandlingProvider()
{
return array(
'debug' => array(Logger::DEBUG),
'info' => array(Logger::INFO),
'notice' => array(Logger::NOTICE),
'warning' => array(Logger::WARNING),
'error' => array(Logger::ERROR),
'critical' => array(Logger::CRITICAL),
'alert' => array(Logger::ALERT),
'emergency' => array(Logger::EMERGENCY),
);
}
public function testHash()
{
$record = array('message' => 'my littlest pony', 'datetime' => new \DateTime());
$lolifier = new Hash();
$lolified = $lolifier->lolify($record);
$this->assertNotSame($record, $lolified);
}
}
|
<?php
namespace Monolol\Lolifiers;
use Monolog\Logger;
class HashTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider testHandlingProvider
*/
public function testHandling($level, $expected)
{
$record = array('level' => $level);
$lolifier = new Hash();
$this->assertSame($expected, $lolifier->isHandling($record));
}
public function testHandlingProvider()
{
return array(
'debug' => array(Logger::DEBUG, true),
'info' => array(Logger::INFO, true),
'notice' => array(Logger::NOTICE, true),
'warning' => array(Logger::WARNING, true),
'error' => array(Logger::ERROR, true),
'critical' => array(Logger::CRITICAL, true),
'alert' => array(Logger::ALERT, true),
'emergency' => array(Logger::EMERGENCY, true),
);
}
public function testHash()
{
$record = array('message' => 'my littlest pony', 'datetime' => new \DateTime());
$lolifier = new Hash();
$lolified = $lolifier->lolify($record);
$this->assertNotSame($record, $lolified);
}
}
|
Update version number to 0.1.3.
|
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, 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 setuptools
def readme():
return '`pstar` documentation and source code can be found at https://github.com/iansf/pstar.'
def version():
return '0.1.3'
setuptools.setup(
name='pstar',
description='pstar: numpy for arbitrary data',
long_description=readme(),
version=version(),
url='https://github.com/iansf/pstar',
download_url='https://github.com/iansf/pstar/archive/%s.tar.gz' % version(),
author='Ian Fischer, Google',
author_email='iansf@google.com',
packages=['pstar'],
license='Apache 2.0',
install_requires=['qj'],
test_suite='nose.collector',
tests_require=['nose'],
)
|
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, 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 setuptools
def readme():
return '`pstar` documentation and source code can be found at https://github.com/iansf/pstar.'
def version():
return '0.1.2'
setuptools.setup(
name='pstar',
description='pstar: numpy for arbitrary data',
long_description=readme(),
version=version(),
url='https://github.com/iansf/pstar',
download_url='https://github.com/iansf/pstar/archive/%s.tar.gz' % version(),
author='Ian Fischer, Google',
author_email='iansf@google.com',
packages=['pstar'],
license='Apache 2.0',
install_requires=['qj'],
test_suite='nose.collector',
tests_require=['nose'],
)
|
Fix for failing demo setup
|
/* 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.activiti.examples.bpmn.servicetask;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.impl.el.Expression;
/**
* @author Frederik Heremans
*/
public class ToUpperCaseSetterInjected implements JavaDelegate {
private Expression text;
private boolean setterInvoked = false;
public void execute(DelegateExecution execution) {
if(!setterInvoked) {
throw new RuntimeException("Setter was not invoked");
}
execution.setVariable("setterVar", ((String)text.getValue(execution)).toUpperCase());
}
public void setText(Expression text) {
setterInvoked = true;
this.text = text;
}
}
|
/* 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.activiti.examples.bpmn.servicetask;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.impl.el.Expression;
import org.junit.Assert;
/**
* @author Frederik Heremans
*/
public class ToUpperCaseSetterInjected implements JavaDelegate {
private Expression text;
private boolean setterInvoked = false;
public void execute(DelegateExecution execution) {
if(!setterInvoked) {
Assert.fail("Setter was not invoked");
}
execution.setVariable("setterVar", ((String)text.getValue(execution)).toUpperCase());
}
public void setText(Expression text) {
setterInvoked = true;
this.text = text;
}
}
|
Add cafile support to the go-nethttp stub
|
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
)
func main() {
if len(os.Args) < 3 || len(os.Args) > 4 {
fmt.Printf("usage: %v <host> <port> [cafile]\n", os.Args[0])
os.Exit(1)
}
client := http.DefaultClient
if len(os.Args) == 4 {
cadata, err := ioutil.ReadFile(os.Args[3])
if err != nil {
fmt.Println(err)
os.Exit(1)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(cadata) {
fmt.Println("Couldn't append certs")
os.Exit(1)
}
client = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: pool},
},
}
}
// Perform an HTTPS Request
_, err := client.Get("https://" + os.Args[1] + ":" + os.Args[2])
if err != nil {
fatalError := strings.Contains(err.Error(), "no such host")
fmt.Println(err.Error())
if fatalError {
os.Exit(1)
}
fmt.Println("REJECT")
} else {
fmt.Println("ACCEPT")
}
os.Exit(0)
}
|
package main
import (
"fmt"
"net/http"
"os"
"strings"
)
func main() {
if len(os.Args) == 4 {
fmt.Println("UNSUPPORTED")
os.Exit(0)
} else if len(os.Args) != 3 {
fmt.Printf("usage: %v <host> <port>\n", os.Args[0])
os.Exit(1)
}
url := "https://" + os.Args[1] + ":" + os.Args[2]
// Perform an HTTP(S) Request
_, err := http.Get(url)
if err != nil {
fatalError := strings.Contains(err.Error(), "no such host")
fmt.Println(err.Error())
if fatalError {
os.Exit(1)
}
fmt.Println("REJECT")
} else {
fmt.Println("ACCEPT")
}
os.Exit(0)
}
|
Allow Ref's in addition to basestrings
|
# Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty, Ref
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
'AlarmActions': ([basestring, Ref], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
'InsufficientDataActions': ([basestring, Ref], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
'OKActions': ([basestring, Ref], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
|
# Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
'AlarmActions': ([basestring], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
'InsufficientDataActions': ([basestring], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
'OKActions': ([basestring], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
|
Fix a build error reported by ReadTheDocs
|
import os
import pathlib
import sys
import toml
# Allow autodoc to import listparser.
sys.path.append(os.path.abspath("../src"))
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ["sphinx.ext.autodoc"]
# The suffix of source filenames.
source_suffix = ".rst"
# The master toctree document.
master_doc = "index"
# General information about the project.
project = "listparser"
copyright = "2009-2022 Kurt McKee"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
info = toml.load(pathlib.Path(__file__).parent.parent / "pyproject.toml")
version = release = info["tool"]["poetry"]["version"]
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ()
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
|
import os
import pathlib
import sys
import toml
# Allow autodoc to import listparser.
sys.path.append(os.path.abspath("../src"))
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ["sphinx.ext.autodoc"]
# The suffix of source filenames.
source_suffix = ".rst"
# The master toctree document.
master_doc = "index"
# General information about the project.
project = "listparser"
copyright = "2009-2022 Kurt McKee"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
info = toml.load(pathlib.Path(__file__) / "../../pyproject.toml")
version = release = info["tool"]["poetry"]["version"]
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ()
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
|
Add Basic Auth in generateToken()
|
<?php
/**
* ownCloud - oauth2
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Jonathan Neugebauer
* @copyright Jonathan Neugebauer 2016
*/
namespace OCA\OAuth2\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\JSONResponse;
use OCP\IRequest;
use OCP\AppFramework\ApiController;
class OAuthApiController extends ApiController {
public function __construct($appName, IRequest $request) {
parent::__construct($appName, $request);
}
/**
* Implements the OAuth 2.0 Access Token Response.
*
* Is accessible by the client via the /index.php/apps/oauth2/token
*
* @return JSONResponse The Access Token or an empty JSON Object.
*
* @NoAdminRequired
* @NoCSRFRequired
* @PublicPage
* @CORS
*/
public function generateToken($access_code) {
if ($access_code === '123456789'
&& $_SERVER['PHP_AUTH_USER'] === 'lw'
&& $_SERVER['PHP_AUTH_PW'] === 'secret') {
return new JSONResponse(
[
'access_token' => '2YotnFZFEjr1zCsicMWpAA',
'token_type' => 'Bearer'
]
);
}
return new JSONResponse(array(), Http::STATUS_BAD_REQUEST);
}
}
|
<?php
/**
* ownCloud - oauth2
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Jonathan Neugebauer
* @copyright Jonathan Neugebauer 2016
*/
namespace OCA\OAuth2\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\JSONResponse;
use OCP\IRequest;
use OCP\AppFramework\ApiController;
class OAuthApiController extends ApiController {
public function __construct($appName, IRequest $request) {
parent::__construct($appName, $request);
}
/**
* Implements the OAuth 2.0 Access Token Response.
*
* Is accessible by the client via the /index.php/apps/oauth2/token
*
* @return JSONResponse The Access Token or an empty JSON Object.
*
* @NoAdminRequired
* @NoCSRFRequired
* @PublicPage
* @CORS
*/
public function generateToken($access_code) {
if ($access_code === '123456789') {
return new JSONResponse(
[
'access_token' => '2YotnFZFEjr1zCsicMWpAA',
'token_type' => 'Bearer'
]
);
}
return new JSONResponse(array(), Http::STATUS_BAD_REQUEST);
}
}
|
Make generated QR code larger
|
<?php
namespace eien\Http\Controllers;
use Illuminate\Http\Request;
use ParagonIE\ConstantTime\Base32;
use PragmaRX\Google2FA\Vendor\Laravel\Facade as Google2FA;
class TFAController extends Controller
{
/**
* @param Request $request
* @return \Illuminate\View\View
*/
public function enable(Request $request)
{
$secret = $this->generateSecret();
$user = $request->user();
$user->twofa_secret = $secret;
$user->save();
$qrUri = Google2FA::getQRCodeInline('永遠', $user->email, $secret, 666);
return view('TFA.enable', ['image' => $qrUri, 'secret' => $secret]);
}
/**
* @param Request $request
* @return \Illuminate\View\View
*/
public function disable(Request $request)
{
$user = $request->user();
$user->twofa_secret = null;
$user->save();
return view('TFA.disable');
}
/**
* Generate a secure secret with the constant time library.
*
* @return string
*/
public function generateSecret()
{
$randomBytes = random_bytes(10);
return Base32::encode($randomBytes);
}
}
|
<?php
namespace eien\Http\Controllers;
use Illuminate\Http\Request;
use ParagonIE\ConstantTime\Base32;
use PragmaRX\Google2FA\Vendor\Laravel\Facade as Google2FA;
class TFAController extends Controller
{
/**
* @param Request $request
* @return \Illuminate\View\View
*/
public function enable(Request $request)
{
$secret = $this->generateSecret();
$user = $request->user();
$user->twofa_secret = $secret;
$user->save();
$qrUri = Google2FA::getQRCodeInline('永遠', $user->email, $secret);
return view('TFA.enable', ['image' => $qrUri, 'secret' => $secret]);
}
/**
* @param Request $request
* @return \Illuminate\View\View
*/
public function disable(Request $request)
{
$user = $request->user();
$user->twofa_secret = null;
$user->save();
return view('TFA.disable');
}
/**
* Generate a secure secret with the constant time library.
*
* @return string
*/
public function generateSecret()
{
$randomBytes = random_bytes(10);
return Base32::encode($randomBytes);
}
}
|
Replace testcontainers deprecated image constant with name
|
package org.synyx.urlaubsverwaltung;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.MariaDBContainer;
import static org.testcontainers.containers.MariaDBContainer.NAME;
@DirtiesContext
public abstract class TestContainersBase {
static MariaDBContainer<?> mariaDB = new MariaDBContainer<>(NAME + ":10.5");
@DynamicPropertySource
static void mariaDBProperties(DynamicPropertyRegistry registry) {
mariaDB.start();
registry.add("spring.datasource.url", mariaDB::getJdbcUrl);
registry.add("spring.datasource.username", mariaDB::getUsername);
registry.add("spring.datasource.password", mariaDB::getPassword);
}
}
|
package org.synyx.urlaubsverwaltung;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.MariaDBContainer;
import static org.testcontainers.containers.MariaDBContainer.IMAGE;
@DirtiesContext
public abstract class TestContainersBase {
static MariaDBContainer<?> mariaDB = new MariaDBContainer<>(IMAGE + ":10.5");
@DynamicPropertySource
static void mariaDBProperties(DynamicPropertyRegistry registry) {
mariaDB.start();
registry.add("spring.datasource.url", mariaDB::getJdbcUrl);
registry.add("spring.datasource.username", mariaDB::getUsername);
registry.add("spring.datasource.password", mariaDB::getPassword);
}
}
|
Return "unknown" for the empty string key
|
<?php
namespace Ojs\ImportBundle\Helper;
class FileHelper {
public static $mimeToExtMap = [
'' => 'unknown',
'application/pdf' => 'pdf',
'image/jpeg' => 'jpg',
'image/png' => 'png',
'application/msword' => 'doc',
'application/zip' => 'zip',
'application/xml' => 'xml',
'text/plain' => 'txt',
'application/rar ' => 'rar',
'application/x-rar' => 'rar',
'application/octet-stream' => 'bin',
'application/text-plain:formatted' => 'txt',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx'
];
}
|
<?php
namespace Ojs\ImportBundle\Helper;
class FileHelper {
public static $mimeToExtMap = [
'application/pdf' => 'pdf',
'image/jpeg' => 'jpg',
'image/png' => 'png',
'application/msword' => 'doc',
'application/zip' => 'zip',
'application/xml' => 'xml',
'text/plain' => 'txt',
'application/rar ' => 'rar',
'application/x-rar' => 'rar',
'application/octet-stream' => 'bin',
'application/text-plain:formatted' => 'txt',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx'
];
}
|
Make nodeModulesBabelLoader compatible with Babel 6
|
import { includePaths, excludePaths } from '../config/utils';
export default options => ({
test: /\.(mjs|jsx?)$/,
use: [
{
loader: 'babel-loader',
options,
},
],
include: includePaths,
exclude: excludePaths,
});
export const nodeModulesBabelLoader = {
test: /\.js$/,
include: /\/node_modules\/safe-eval\//,
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
babelrc: false,
presets: [
[
'env',
{
modules: 'commonjs',
},
],
],
},
},
],
};
|
import { includePaths, excludePaths } from '../config/utils';
export default options => ({
test: /\.(mjs|jsx?)$/,
use: [
{
loader: 'babel-loader',
options,
},
],
include: includePaths,
exclude: excludePaths,
});
export const nodeModulesBabelLoader = {
test: /\.js$/,
include: /\/node_modules\/safe-eval\//,
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
babelrc: false,
presets: [
[
require.resolve('@babel/preset-env'),
{
useBuiltIns: 'usage',
modules: 'commonjs',
},
],
],
},
},
],
};
|
Add text to selection grid
|
from wagtail.core import blocks
from wagtail.core.blocks import RichTextBlock
from wagtail.core.fields import StreamField
from wagtail.admin.edit_handlers import TabbedInterface, StreamFieldPanel, ObjectList
from falmer.content import components
from falmer.content.blocks import HeroImageBlock, FalmerImageChooserBlock
from falmer.content.models.core import Page
class GridItem(blocks.StructBlock):
title = blocks.CharBlock(required=True)
link = blocks.URLBlock()
image = FalmerImageChooserBlock()
description = RichTextBlock(required=False)
class Meta:
icon = 'item'
class SelectionGridPage(Page):
body = StreamField([
('heading_hero', HeroImageBlock()),
components.text.to_pair(),
('selection_grid', blocks.ListBlock(GridItem)),
])
content_panels = Page.content_panels + [
StreamFieldPanel('body'),
]
edit_handler = TabbedInterface([
ObjectList(content_panels, heading='Content'),
ObjectList(Page.promote_panels, heading='Promote'),
ObjectList(Page.settings_panels, heading='Settings', classname="settings"),
])
type_fields = (
'body',
)
|
from wagtail.core import blocks
from wagtail.core.blocks import RichTextBlock
from wagtail.core.fields import StreamField
from wagtail.admin.edit_handlers import TabbedInterface, StreamFieldPanel, ObjectList
from falmer.content.blocks import HeroImageBlock, FalmerImageChooserBlock
from falmer.content.models.core import Page
class GridItem(blocks.StructBlock):
title = blocks.CharBlock(required=True)
link = blocks.URLBlock()
image = FalmerImageChooserBlock()
description = RichTextBlock(required=False)
class Meta:
icon = 'item'
class SelectionGridPage(Page):
body = StreamField([
('heading_hero', HeroImageBlock()),
('selection_grid', blocks.ListBlock(GridItem)),
])
content_panels = Page.content_panels + [
StreamFieldPanel('body'),
]
edit_handler = TabbedInterface([
ObjectList(content_panels, heading='Content'),
ObjectList(Page.promote_panels, heading='Promote'),
ObjectList(Page.settings_panels, heading='Settings', classname="settings"),
])
type_fields = (
'body',
)
|
Rename type into hook_type
"type" itself if a built-in function. Using this name could be unsave.
|
#!/usr/bin/env python3
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
import sys
def exceptHook(hook_type, value, traceback):
import cura.CrashHandler
cura.CrashHandler.show(hook_type, value, traceback)
sys.excepthook = exceptHook
# Workaround for a race condition on certain systems where there
# is a race condition between Arcus and PyQt. Importing Arcus
# first seems to prevent Sip from going into a state where it
# tries to create PyQt objects on a non-main thread.
import Arcus
import cura.CuraApplication
if sys.platform == "win32" and hasattr(sys, "frozen"):
import os
dirpath = os.path.expanduser("~/AppData/Local/cura/")
os.makedirs(dirpath, exist_ok = True)
sys.stdout = open(os.path.join(dirpath, "stdout.log"), "w")
sys.stderr = open(os.path.join(dirpath, "stderr.log"), "w")
app = cura.CuraApplication.CuraApplication.getInstance()
app.run()
|
#!/usr/bin/env python3
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
import sys
def exceptHook(type, value, traceback):
import cura.CrashHandler
cura.CrashHandler.show(type, value, traceback)
sys.excepthook = exceptHook
# Workaround for a race condition on certain systems where there
# is a race condition between Arcus and PyQt. Importing Arcus
# first seems to prevent Sip from going into a state where it
# tries to create PyQt objects on a non-main thread.
import Arcus
import cura.CuraApplication
if sys.platform == "win32" and hasattr(sys, "frozen"):
import os
dirpath = os.path.expanduser("~/AppData/Local/cura/")
os.makedirs(dirpath, exist_ok = True)
sys.stdout = open(os.path.join(dirpath, "stdout.log"), "w")
sys.stderr = open(os.path.join(dirpath, "stderr.log"), "w")
app = cura.CuraApplication.CuraApplication.getInstance()
app.run()
|
Use absolute / implicit relative imports for local deps
Since Composer is Python 2.7 only for now, this sample can use implicit
relative imports. Airflow doesn't seem to support explicit relative
imports when I try to run the use_local_deps.py file in Composer.
Aside: Airflow is using the imp.load_source method to load the DAG
modules. This will be problematic for Python 3 support, see:
https://issues.apache.org/jira/browse/AIRFLOW-2243.
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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.
"""A DAG consisting of a BashOperator that prints the result of a coin flip."""
import datetime
import airflow
from airflow.operators import bash_operator
# [START composer_dag_local_deps]
from dependencies import coin_module
# [END composer_dag_local_deps]
default_args = {
'start_date':
datetime.datetime.combine(
datetime.datetime.today() - datetime.timedelta(days=1),
datetime.datetime.min.time()),
}
with airflow.DAG('dependencies_dag', default_args=default_args) as dag:
t1 = bash_operator.BashOperator(
task_id='print_coin_result',
bash_command='echo "{0}"'.format(coin_module.flip_coin()),
dag=dag)
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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.
"""A DAG consisting of a BashOperator that prints the result of a coin flip."""
import datetime
import airflow
from airflow.operators import bash_operator
# [START composer_dag_local_deps]
from .dependencies import coin_module
# [END composer_dag_local_deps]
default_args = {
'start_date':
datetime.datetime.combine(
datetime.datetime.today() - datetime.timedelta(days=1),
datetime.datetime.min.time()),
}
with airflow.DAG('dependencies_dag', default_args=default_args) as dag:
t1 = bash_operator.BashOperator(
task_id='print_coin_result',
bash_command='echo "{0}"'.format(coin_module.flip_coin()),
dag=dag)
|
Golint: Replace += 1 with ++
|
// Copyright © 2017 Makoto Ito
//
// 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 utils
import (
"github.com/ynqa/word-embedding/utils/set"
)
type FreqMap map[string]int
func NewFreqMap() FreqMap {
return make(FreqMap)
}
func (f FreqMap) Update(words []string) {
for _, w := range words {
f[w]++
}
}
func (f FreqMap) Keys() set.String {
keys := set.New()
for k := range f {
keys.Add(k)
}
return keys
}
func (f FreqMap) Terms() int {
return len(f)
}
func (f FreqMap) Words() (s int) {
for _, v := range f {
s += v
}
return
}
|
// Copyright © 2017 Makoto Ito
//
// 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 utils
import (
"github.com/ynqa/word-embedding/utils/set"
)
type FreqMap map[string]int
func NewFreqMap() FreqMap {
return make(FreqMap)
}
func (f FreqMap) Update(words []string) {
for _, w := range words {
f[w] += 1
}
}
func (f FreqMap) Keys() set.String {
keys := set.New()
for k := range f {
keys.Add(k)
}
return keys
}
func (f FreqMap) Terms() int {
return len(f)
}
func (f FreqMap) Words() (s int) {
for _, v := range f {
s += v
}
return
}
|
Add an option to show the location of where hidden links point to.
|
export const CLASSNAME = 'list-graph';
export const SCROLLBAR_WIDTH = 6;
export const COLUMNS = 5;
export const ROWS = 5;
// An empty path is equal to inline SVG.
export const ICON_PATH = '';
// -1 = desc, 1 = asc
export const DEFAULT_SORT_ORDER = -1;
export const DEFAULT_BAR_MODE = 'one';
export const HIGHLIGHT_ACTIVE_LEVEL = true;
export const ACTIVE_LEVEL = 0;
export const NO_ROOT_ACTIVE_LEVEL_DIFF = 0;
export const QUERYING = false;
export const HIDE_OUTWARDS_LINKS = false;
export const SHOW_LINK_LOCATION = false;
export const TRANSITION_LIGHTNING_FAST = 150;
export const TRANSITION_FAST = 200;
export const TRANSITION_SEMI_FAST = 250;
export const TRANSITION_NORMAL = 333;
export const TRANSITION_SLOW = 666;
export const TRANSITION_SLOWEST = 1;
// Gradient colors
export const COLOR_ORANGE = '#f23e00';
export const COLOR_NEGATIVE_RED = '#e0001c';
export const COLOR_POSITIVE_GREEN = '#60bf00';
|
export const CLASSNAME = 'list-graph';
export const SCROLLBAR_WIDTH = 6;
export const COLUMNS = 5;
export const ROWS = 5;
// An empty path is equal to inline SVG.
export const ICON_PATH = '';
// -1 = desc, 1 = asc
export const DEFAULT_SORT_ORDER = -1;
export const DEFAULT_BAR_MODE = 'one';
export const HIGHLIGHT_ACTIVE_LEVEL = true;
export const ACTIVE_LEVEL = 0;
export const NO_ROOT_ACTIVE_LEVEL_DIFF = 0;
export const QUERYING = false;
export const HIDE_OUTWARDS_LINKS = false;
export const TRANSITION_LIGHTNING_FAST = 150;
export const TRANSITION_FAST = 200;
export const TRANSITION_SEMI_FAST = 250;
export const TRANSITION_NORMAL = 333;
export const TRANSITION_SLOW = 666;
export const TRANSITION_SLOWEST = 1;
// Gradient colors
export const COLOR_ORANGE = '#f23e00';
export const COLOR_NEGATIVE_RED = '#e0001c';
export const COLOR_POSITIVE_GREEN = '#60bf00';
|
Clean up and fix warnings
|
'use strict';
var cheerio = require('cheerio');
var curl = require('../../curl');
function messageListener(db, from, channel, message, reply) {
var match = /(https?:\/\/[^ ]+)/.exec(message);
if (match) {
curl(match[1], function (html) {
var $ = cheerio.load(html);
var lines = [];
if ($('title').length === 1) {
var title = $('title').text();
reply({ to: channel, message: title.trim() });
}
if ($('meta[property="og:description"]').length === 1) {
var desc = $('meta[property="og:description"]').attr("content");
desc = desc.trim();
if (desc.length > 163) {
desc = desc.substring(0, 160) + '...';
}
reply({ to: channel, message: desc });
}
});
}
}
module.exports = messageListener;
|
'use strict';
var cheerio = require('cheerio');
var curl = require('../../curl');
function messageListener(db, from, channel, message, reply) {
var match = /(https?:\/\/[^ ]+)/.exec(message);
if (match) {
curl(match[1], function (res) {
var $ = cheerio.load(res);
var lines = [];
if ($('meta[property="og:description"]').length === 1) {
var desc = $('meta[property="og:description"]').attr("content");
lines = desc.trim().split('\n');
} else if ($('title').length === 1) {
var title = $('title').text();
lines = title.trim().split('\n');
}
var res = lines.join(' ');
if (res.length > 163) {
res = res.substring(0, 160) + '...';
}
reply({ to: channel, message: res });
});
}
}
module.exports = messageListener;
|
Fix postgres table exists command
|
package peergos.server.sql;
public class PostgresCommands implements SqlSupplier {
@Override
public String listTablesCommand() {
return "SELECT tablename FROM pg_catalog.pg_tables " +
"WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema';";
}
@Override
public String tableExistsCommand() {
return "SELECT table_name FROM information_schema.tables WHERE table_schema LIKE 'public' AND table_type LIKE 'BASE TABLE' AND table_name = ?;";
}
@Override
public String createFollowRequestsTableCommand() {
return "CREATE TABLE IF NOT EXISTS followrequests (id serial primary key, " +
"name text not null, followrequest text not null);";
}
@Override
public String insertTransactionCommand() {
return "INSERT INTO transactions (tid, owner, hash) VALUES(?, ?, ?) ON CONFLICT DO NOTHING;";
}
@Override
public String insertOrIgnoreCommand(String prefix, String suffix) {
return prefix + suffix + " ON CONFLICT DO NOTHING;";
}
@Override
public String getByteArrayType() {
return "BYTEA";
}
@Override
public String getSerialIdType() {
return "SERIAL";
}
@Override
public String sqlInteger() {
return "BIGINT";
}
}
|
package peergos.server.sql;
public class PostgresCommands implements SqlSupplier {
@Override
public String listTablesCommand() {
return "SELECT tablename FROM pg_catalog.pg_tables " +
"WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema';";
}
@Override
public String tableExistsCommand() {
return "SELECT table_name FROM information_schema.tables WHERE table_schema LIKE 'public' AND table_type LIKE 'BASE TABLE' AND table_name = '?';";
}
@Override
public String createFollowRequestsTableCommand() {
return "CREATE TABLE IF NOT EXISTS followrequests (id serial primary key, " +
"name text not null, followrequest text not null);";
}
@Override
public String insertTransactionCommand() {
return "INSERT INTO transactions (tid, owner, hash) VALUES(?, ?, ?) ON CONFLICT DO NOTHING;";
}
@Override
public String insertOrIgnoreCommand(String prefix, String suffix) {
return prefix + suffix + " ON CONFLICT DO NOTHING;";
}
@Override
public String getByteArrayType() {
return "BYTEA";
}
@Override
public String getSerialIdType() {
return "SERIAL";
}
@Override
public String sqlInteger() {
return "BIGINT";
}
}
|
Make command argument validation clear.
|
const commands = {
'join': ['channel'],
'part': ['channel', '?message'],
'ctcp': ['target', 'type', 'text'],
'action': ['target', 'message'],
'whois': ['nick'],
'list': [],
};
export const CommandParser = {
validateArgs(info, args) {
return info.length === args.length ||
info.filter(s => s.charAt(0) !== '?').length === args.length;
},
processArgs(commandName, args) {
if (commandName === 'join' || commandName === 'part') {
if (args[0].charAt(0) !== '#') {
args[0] = '#' + args[0];
}
}
return args;
},
parse(raw) {
let tokens = raw.split(' ');
let commandName = tokens[0];
let args = tokens.splice(1);
let commandInfo = this.info(commandName);
if (!commandInfo) {
return {valid: false, errMsg: 'Invalid command name'};
}
if (this.validateArgs(commandInfo, args)) {
args = this.processArgs(commandName, args);
return {valid: true, name: commandName, args: args};
} else {
return {valid: false, errMsg: `Invalid command arguments: [${commandInfo}]`};
}
},
info(commandName) {
return commands[commandName];
},
};
|
const commands = {
'join': ['channel'],
'part': ['channel', 'message?'],
'ctcp': ['target', 'type', 'text'],
'action': ['target', 'message'],
'whois': ['nick'],
'list': [],
};
export const CommandParser = {
validateArgs(info, args) {
if (info.length !== args.length &&
info.filter(s => s[s.length - 1] === '?').length !== args.length) {
return false;
}
return true;
},
processArgs(commandName, args) {
if (commandName === 'join' || commandName === 'part') {
if (args[0].charAt(0) !== '#') {
args[0] = '#' + args[0];
}
}
return args;
},
parse(raw) {
let tokens = raw.split(' ');
let commandName = tokens[0];
let args = tokens.splice(1);
let commandInfo = this.info(commandName);
if (!commandInfo) {
return {valid: false, errMsg: 'Invalid command name'};
}
if (this.validateArgs(commandInfo, args)) {
args = this.processArgs(commandName, args);
return {valid: true, name: commandName, args: args};
} else {
return {valid: false, errMsg: 'Invalid command arguments: ' + commandInfo};
}
},
info(commandName) {
return commands[commandName];
},
};
|
Fix end of line format
|
#!/usr/bin/python
# coding: utf-8
import sys
import signal
import logging
import argparse
from lib.DbConnector import DbConnector
from lib.Acquisition import Acquisition
from lib.SystemMonitor import SystemMonitor
acq = Acquisition()
sm = SystemMonitor()
def signalHandler(signal, frame):
logging.warning("Caught ^C")
acq.Stop()
sm.Stop()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description = 'Start acquisition'
)
parser.add_argument("-v", "--verbose", help="Verbositiy setting",
action="count", default=0)
args = parser.parse_args()
# configure logging
if args.verbose == 1:
wLogLevel = logging.WARNING
elif args.verbose == 2:
wLogLevel = logging.INFO
elif args.verbose >= 3:
wLogLevel = logging.DEBUG
else:
wLogLevel = logging.ERROR
logging.basicConfig(level=wLogLevel)
logging.info('Started')
# signal handling
signal.signal(signal.SIGINT, signalHandler)
# start things
with DbConnector() as wDb:
wDb.Init()
sm.start()
acq.GetData()
# exit things
sys.exit(0)
|
#!/usr/bin/python
# coding: utf-8
import sys
import signal
import logging
import argparse
from lib.DbConnector import DbConnector
from lib.Acquisition import Acquisition
from lib.SystemMonitor import SystemMonitor
acq = Acquisition()
sm = SystemMonitor()
def signalHandler(signal, frame):
logging.warning("Caught ^C")
acq.Stop()
sm.Stop()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description = 'Start acquisition'
)
parser.add_argument("-v", "--verbose", help="Verbositiy setting",
action="count", default=0)
args = parser.parse_args()
# configure logging
if args.verbose == 1:
wLogLevel = logging.WARNING
elif args.verbose == 2:
wLogLevel = logging.INFO
elif args.verbose >= 3:
wLogLevel = logging.DEBUG
else:
wLogLevel = logging.ERROR
logging.basicConfig(level=wLogLevel)
logging.info('Started')
# signal handling
signal.signal(signal.SIGINT, signalHandler)
# start things
with DbConnector() as wDb:
wDb.Init()
sm.start()
acq.GetData()
# exit things
sys.exit(0)
|
Make cards have h2s not h1s
|
import React, { PropTypes } from 'react';
import { Card } from '../UI';
import styles from './ImageCard.css';
export default class ImageCard extends React.Component {
render() {
const { onClick, onImageLoaded, image, text, description } = this.props;
return (
<Card onClick={onClick} className={styles.root}>
<img src={image} onLoad={onImageLoaded} />
<h2>{text}</h2>
{description ? <p>{description}</p> : null}
</Card>
);
}
}
ImageCard.propTypes = {
image: PropTypes.string,
onClick: PropTypes.func,
onImageLoaded: PropTypes.func,
text: PropTypes.string.isRequired,
description: PropTypes.string
};
ImageCard.defaultProps = {
onClick: function() {},
onImageLoaded: function() {}
};
|
import React, { PropTypes } from 'react';
import { Card } from '../UI';
import styles from './ImageCard.css';
export default class ImageCard extends React.Component {
render() {
const { onClick, onImageLoaded, image, text, description } = this.props;
return (
<Card onClick={onClick} className={styles.root}>
<img src={image} onLoad={onImageLoaded} />
<h1>{text}</h1>
{description ? <p>{description}</p> : null}
</Card>
);
}
}
ImageCard.propTypes = {
image: PropTypes.string,
onClick: PropTypes.func,
onImageLoaded: PropTypes.func,
text: PropTypes.string.isRequired,
description: PropTypes.string
};
ImageCard.defaultProps = {
onClick: function() {},
onImageLoaded: function() {}
};
|
Add flake8 to installation dependencies
|
import os
from setuptools import find_packages
from setuptools import setup
import sys
sys.path.insert(0, os.path.abspath('lib'))
exec(open('lib/ansiblereview/version.py').read())
setup(
name='ansible-review',
version=__version__,
description=('reviews ansible playbooks, roles and inventory and suggests improvements'),
keywords='ansible, code review',
author='Will Thames',
author_email='will@thames.id.au',
url='https://github.com/willthames/ansible-review',
package_dir={'': 'lib'},
packages=find_packages('lib'),
zip_safe=False,
install_requires=['ansible-lint>=3.0.0', 'pyyaml', 'appdirs', 'unidiff', 'flake8'],
scripts=['bin/ansible-review'],
classifiers=[
'License :: OSI Approved :: MIT License',
],
test_suite="test"
)
|
import os
from setuptools import find_packages
from setuptools import setup
import sys
sys.path.insert(0, os.path.abspath('lib'))
exec(open('lib/ansiblereview/version.py').read())
setup(
name='ansible-review',
version=__version__,
description=('reviews ansible playbooks, roles and inventory and suggests improvements'),
keywords='ansible, code review',
author='Will Thames',
author_email='will@thames.id.au',
url='https://github.com/willthames/ansible-review',
package_dir={'': 'lib'},
packages=find_packages('lib'),
zip_safe=False,
install_requires=['ansible-lint>=3.0.0', 'pyyaml', 'appdirs', 'unidiff'],
scripts=['bin/ansible-review'],
classifiers=[
'License :: OSI Approved :: MIT License',
],
test_suite="test"
)
|
Use match instead of non-existant head routing method
|
<?php
namespace Vaffel\Tuski\Silex\Provider;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Silex\ControllerProviderInterface;
use Silex\Application;
class TusControllerProvider implements ControllerProviderInterface
{
public function setBaseRoute($baseRoute)
{
$this->baseRoute = $baseRoute;
return $this;
}
public function connect(Application $app)
{
return $this->extractControllers($app);
}
private function extractControllers(Application $app)
{
$controllers = $app['controllers_factory'];
// HEAD request for checking file upload status
$controllers->match('/{resourceId}', function (Request $req, $resourceId) use ($app) {
$fileStatus = $app[TusServiceProvider::GET_FILE_STATUS]($resourceId);
if (!$fileStatus) {
return new Response('Not Found', 404);
}
return new Response('', 200, ['Offset' => 1337]);
}, 'HEAD');
return $controllers;
}
}
|
<?php
namespace Vaffel\Tuski\Silex\Provider;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Silex\ControllerProviderInterface;
use Silex\Application;
class TusControllerProvider implements ControllerProviderInterface
{
public function setBaseRoute($baseRoute)
{
$this->baseRoute = $baseRoute;
return $this;
}
public function connect(Application $app)
{
return $this->extractControllers($app);
}
private function extractControllers(Application $app)
{
$controllers = $app['controllers_factory'];
// HEAD request for checking file upload status
$controllers->head('/{resourceId}', function (Request $req, $resourceId) use ($app) {
$fileStatus = $app[TusServiceProvider::GET_FILE_STATUS]($resourceId);
if (!$fileStatus) {
return new Response('Not Found', 404);
}
return new Response('', 200, ['Offset' => 1337])
});
return $controllers;
}
}
|
Update default testing SMTP settings in project template
|
"""
Settings for local development.
These settings are not fast or efficient, but allow local servers to be run
using the django-admin.py utility.
This file should be excluded from version control to keep the settings local.
"""
import os
import os.path
from .base import *
# Run in debug mode.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
# Save media files to the user's Sites folder.
MEDIA_ROOT = os.path.expanduser(os.path.join("~/Sites", SITE_DOMAIN, "media"))
STATIC_ROOT = os.path.expanduser(os.path.join("~/Sites", SITE_DOMAIN, "static"))
# Use local server.
SITE_DOMAIN = "localhost:8000"
PREPEND_WWW = False
# Disable the template cache for development.
TEMPLATE_LOADERS = (
"django.template.loaders.filesystem.Loader",
"django.template.loaders.app_directories.Loader",
)
# Optional separate database settings
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"HOST": "localhost",
"NAME": "{{ project_name }}",
"USER": os.getlogin(),
"PASSWORD": "",
},
}
# Mailtrip SMTP
EMAIL_HOST = 'mailtrap.io'
EMAIL_HOST_USER = '178288370161874a6'
EMAIL_HOST_PASSWORD = '5033a6d5bca3f0'
EMAIL_PORT = '2525'
EMAIL_USE_TLS = True
|
"""
Settings for local development.
These settings are not fast or efficient, but allow local servers to be run
using the django-admin.py utility.
This file should be excluded from version control to keep the settings local.
"""
import os
import os.path
from .base import *
# Run in debug mode.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
# Save media files to the user's Sites folder.
MEDIA_ROOT = os.path.expanduser(os.path.join("~/Sites", SITE_DOMAIN, "media"))
STATIC_ROOT = os.path.expanduser(os.path.join("~/Sites", SITE_DOMAIN, "static"))
# Use local server.
SITE_DOMAIN = "localhost:8000"
PREPEND_WWW = False
# Disable the template cache for development.
TEMPLATE_LOADERS = (
"django.template.loaders.filesystem.Loader",
"django.template.loaders.app_directories.Loader",
)
# Optional separate database settings
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"HOST": "localhost",
"NAME": "{{ project_name }}",
"USER": os.getlogin(),
"PASSWORD": "",
},
}
# Mailtrip SMTP
EMAIL_HOST = 'mailtrap.io'
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = '2525'
EMAIL_USE_TLS = True
|
Add missing trick to appear in the classmap
This should have been part of 9a3d73acfcac1104c33cda810eedfedea2a7b7ba
|
<?php
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\CoreBundle\Model;
if (interface_exists(\Sonata\Doctrine\Model\PageableManagerInterface::class, false)) {
@trigger_error(
'The '.__NAMESPACE__.'\PageableManagerInterface class is deprecated since version 3.x and will be removed in 4.0.'
.' Use Sonata\DatagridBundle\Pager\PageableInterface instead.',
E_USER_DEPRECATED
);
}
class_alias(
\Sonata\Doctrine\Model\PageableManagerInterface::class,
__NAMESPACE__.'\PageableManagerInterface'
);
if (false) {
interface PageableManagerInterface extends \Sonata\Doctrine\Model\PageableManagerInterface
{
}
}
|
<?php
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\CoreBundle\Model;
if (interface_exists(\Sonata\Doctrine\Model\PageableManagerInterface::class, false)) {
@trigger_error(
'The '.__NAMESPACE__.'\PageableManagerInterface class is deprecated since version 3.x and will be removed in 4.0.'
.' Use Sonata\DatagridBundle\Pager\PageableInterface instead.',
E_USER_DEPRECATED
);
}
class_alias(
\Sonata\Doctrine\Model\PageableManagerInterface::class,
__NAMESPACE__.'\PageableManagerInterface'
);
|
Fix bug where progress bar can be wider than the screen
|
<?php
namespace Concise\Console\ResultPrinter\Utilities;
use Concise\Core\ArgumentChecker;
class ProportionalProgressBar extends ProgressBar
{
/**
* @param integer $size
* @param integer $total
* @param array $parts
* @return string
*/
public function renderProportional($size, $total, array $parts)
{
ArgumentChecker::check($size, 'integer');
ArgumentChecker::check($total, 'integer', 2);
$this->calculateTotal($parts);
if (0 === $total) {
$total = $this->total;
}
if (0 === $total) {
return str_repeat('_', $size);
}
$barSize = min($size * $this->total / $total, $size);
$bar = parent::render((int)$barSize, $parts);
$spaces = max(0, $size - substr_count($bar, ' '));
return $bar . str_repeat('_', $spaces);
}
}
|
<?php
namespace Concise\Console\ResultPrinter\Utilities;
use Concise\Core\ArgumentChecker;
class ProportionalProgressBar extends ProgressBar
{
/**
* @param integer $size
* @param integer $total
* @param array $parts
* @return string
*/
public function renderProportional($size, $total, array $parts)
{
ArgumentChecker::check($size, 'integer');
ArgumentChecker::check($total, 'integer', 2);
$this->calculateTotal($parts);
if (0 === $total) {
$total = $this->total;
}
if (0 === $total) {
return str_repeat('_', $size);
}
$barSize = $size * $this->total / $total;
$bar = parent::render((int)$barSize, $parts);
$spaces = $size - substr_count($bar, ' ');
return $bar . str_repeat('_', $spaces);
}
}
|
Add const and var rules to lit config
|
module.exports = {
"extends": "./index.js",
"parser": "babel-eslint",
"env": {
"browser": true
},
"plugins": [
"lit", "html"
],
"globals": {
"D2L": false,
"Promise": false
},
"rules": {
"no-var": 2,
"prefer-const": 2,
"strict": [2, "never"],
"lit/no-duplicate-template-bindings": 2,
"lit/no-legacy-template-syntax": 2,
"lit/no-template-bind": 2,
"lit/no-template-map": 0,
"lit/no-useless-template-literals": 2,
"lit/attribute-value-entities": 2,
"lit/binding-positions": 2,
"lit/no-property-change-update": 2,
"lit/no-invalid-html": 2,
"lit/no-value-attribute": 2
}
};
|
module.exports = {
"extends": "./index.js",
"parser": "babel-eslint",
"env": {
"browser": true
},
"plugins": [
"lit", "html"
],
"globals": {
"D2L": false,
"Promise": false
},
"rules": {
"strict": [2, "never"],
"lit/no-duplicate-template-bindings": 2,
"lit/no-legacy-template-syntax": 2,
"lit/no-template-bind": 2,
"lit/no-template-map": 0,
"lit/no-useless-template-literals": 2,
"lit/attribute-value-entities": 2,
"lit/binding-positions": 2,
"lit/no-property-change-update": 2,
"lit/no-invalid-html": 2,
"lit/no-value-attribute": 2
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.