text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Switch revoking and adding trophies to make level trophies possible | <?php
namespace wcf\system\cronjob;
use wcf\data\cronjob\Cronjob;
use wcf\system\trophy\condition\TrophyConditionHandler;
/**
* Assigns automatically trophies.
*
* @author Joshua Ruesweg
* @copyright 2001-2018 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Cronjob
* @since 3.1
*/
class AssignTrophiesCronjob extends AbstractCronjob {
/**
* @inheritDoc
*/
public function execute(Cronjob $cronjob) {
parent::execute($cronjob);
if (MODULE_TROPHY) {
TrophyConditionHandler::getInstance()->revokeTrophies(100);
TrophyConditionHandler::getInstance()->assignTrophies(100);
}
}
}
| <?php
namespace wcf\system\cronjob;
use wcf\data\cronjob\Cronjob;
use wcf\system\trophy\condition\TrophyConditionHandler;
/**
* Assigns automatically trophies.
*
* @author Joshua Ruesweg
* @copyright 2001-2018 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Cronjob
* @since 3.1
*/
class AssignTrophiesCronjob extends AbstractCronjob {
/**
* @inheritDoc
*/
public function execute(Cronjob $cronjob) {
parent::execute($cronjob);
if (MODULE_TROPHY) {
TrophyConditionHandler::getInstance()->assignTrophies(100);
TrophyConditionHandler::getInstance()->revokeTrophies(100);
}
}
}
|
Switch doc to closure compiler templating | var polygon = require('turf-polygon');
/**
* Takes a bbox and returns the equivalent {@link Polygon} feature.
*
* @module turf/bbox-polygon
* @category measurement
* @param {Array<number>} bbox an Array of bounding box coordinates in the form: ```[xLow, yLow, xHigh, yHigh]```
* @return {Feature<Polygon>} a Polygon representation of the bounding box
* @example
* var bbox = [0, 0, 10, 10];
*
* var poly = turf.bboxPolygon(bbox);
*
* //=poly
*/
module.exports = function(bbox){
var lowLeft = [bbox[0], bbox[1]];
var topLeft = [bbox[0], bbox[3]];
var topRight = [bbox[2], bbox[3]];
var lowRight = [bbox[2], bbox[1]];
var poly = polygon([[
lowLeft,
lowRight,
topRight,
topLeft,
lowLeft
]]);
return poly;
}
| var polygon = require('turf-polygon');
/**
* Takes a bbox and returns the equivalent {@link Polygon} feature.
*
* @module turf/bbox-polygon
* @category measurement
* @param {Array<number>} bbox an Array of bounding box coordinates in the form: ```[xLow, yLow, xHigh, yHigh]```
* @return {Polygon} a Polygon representation of the bounding box
* @example
* var bbox = [0, 0, 10, 10];
*
* var poly = turf.bboxPolygon(bbox);
*
* //=poly
*/
module.exports = function(bbox){
var lowLeft = [bbox[0], bbox[1]];
var topLeft = [bbox[0], bbox[3]];
var topRight = [bbox[2], bbox[3]];
var lowRight = [bbox[2], bbox[1]];
var poly = polygon([[
lowLeft,
lowRight,
topRight,
topLeft,
lowLeft
]]);
return poly;
}
|
Send Cloudtrail logging disabled alert to MOC | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Copyright (c) 2017 Mozilla Corporation
#
# Contributors:
# Brandon Myers bmyers@mozilla.com
from lib.alerttask import AlertTask
from query_models import SearchQuery, TermMatch
class AlertCloudtrailLoggingDisabled(AlertTask):
def main(self):
search_query = SearchQuery(minutes=30)
search_query.add_must([
TermMatch('_type', 'cloudtrail'),
TermMatch('eventName', 'StopLogging'),
])
search_query.add_must_not(TermMatch('errorCode', 'AccessDenied'))
self.filtersManual(search_query)
self.searchEventsSimple()
self.walkEvents()
def onEvent(self, event):
category = 'AWSCloudtrail'
tags = ['cloudtrail', 'aws', 'cloudtrailpagerduty']
severity = 'CRITICAL'
summary = 'Cloudtrail Logging Disabled: ' + event['_source']['requestParameters']['name']
return self.createAlertDict(summary, category, tags, [event], severity)
| #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Copyright (c) 2017 Mozilla Corporation
#
# Contributors:
# Brandon Myers bmyers@mozilla.com
from lib.alerttask import AlertTask
from query_models import SearchQuery, TermMatch
class AlertCloudtrailLoggingDisabled(AlertTask):
def main(self):
search_query = SearchQuery(minutes=30)
search_query.add_must([
TermMatch('_type', 'cloudtrail'),
TermMatch('eventName', 'StopLogging'),
])
search_query.add_must_not(TermMatch('errorCode', 'AccessDenied'))
self.filtersManual(search_query)
self.searchEventsSimple()
self.walkEvents()
def onEvent(self, event):
category = 'AWSCloudtrail'
tags = ['cloudtrail', 'aws']
severity = 'CRITICAL'
summary = 'Cloudtrail Logging Disabled: ' + event['_source']['requestParameters']['name']
return self.createAlertDict(summary, category, tags, [event], severity)
|
Replace quotes around env var value | var util = require('util');
var DECLARATION = 'window.__env__ = window.__env__ || {};\n',
TEMPLATE = function(name) {
if (typeof process.env[name] !== 'undefined') {
var tmpl = 'window.__env__[\'%s\'] = \'%s\';\n';
return util.format(tmpl, name, process.env[name]);
} else {
return '';
}
};
var createEnvPreprocessor = function(args, config, logger, helper) {
var log = logger.create('preprocessor.env'),
names = config.envPreprocessor || [];
log.info('Publishing variables: ', names);
return function(content, file, done) {
var envContent = DECLARATION;
for (var i in names) {
envContent += TEMPLATE(names[i]);
}
done(envContent + '\n' + content);
};
};
module.exports = {
'preprocessor:env': ['factory', createEnvPreprocessor]
};
| var util = require('util');
var DECLARATION = 'window.__env__ = window.__env__ || {};\n',
TEMPLATE = function(name) {
if (typeof process.env[name] !== 'undefined') {
var tmpl = 'window.__env__[\'%s\'] = %s;\n';
return util.format(tmpl, name, process.env[name]);
} else {
return '';
}
};
var createEnvPreprocessor = function(args, config, logger, helper) {
var log = logger.create('preprocessor.env'),
names = config.envPreprocessor || [];
log.info('Publishing variables: ', names);
return function(content, file, done) {
var envContent = DECLARATION;
for (var i in names) {
envContent += TEMPLATE(names[i]);
}
done(envContent + '\n' + content);
};
};
module.exports = {
'preprocessor:env': ['factory', createEnvPreprocessor]
};
|
Stop propagation of keydown events on modal level. | import { Component } from 'substance'
/**
ModalDialog component
@class
@component
@prop {String} width 'small', 'medium', 'large' and 'full'
@example
```js
var form = $$(ModalDialog, {
width: 'medium',
textAlign: 'center'
});
```
*/
export default class ModalDialog extends Component {
render($$) {
let el = $$('div').addClass('sc-modal-dialog')
// TODO: don't think that this is good enough. Right the modal is closed by any unhandled click.
// Need to be discussed.
el.on('click', this._closeModal)
el.on('keydown', this._onKeydown)
if (this.props.width) {
el.addClass('sm-width-'+this.props.width)
}
if (this.props.transparent) {
el.addClass('sm-transparent-bg')
}
el.append(
$$('div').addClass('se-body').append(
this.props.children
)
)
return el
}
_onKeydown(e) {
e.stopPropagation()
}
_closeModal(e) {
e.preventDefault()
e.stopPropagation()
let closeSurfaceClick = e.target.classList.contains('sc-modal-dialog')
if (closeSurfaceClick) {
this.send('closeModal')
}
}
}
| import { Component } from 'substance'
/**
ModalDialog component
@class
@component
@prop {String} width 'small', 'medium', 'large' and 'full'
@example
```js
var form = $$(ModalDialog, {
width: 'medium',
textAlign: 'center'
});
```
*/
export default class ModalDialog extends Component {
render($$) {
let el = $$('div').addClass('sc-modal-dialog')
// TODO: don't think that this is good enough. Right the modal is closed by any unhandled click.
// Need to be discussed.
el.on('click', this._closeModal)
if (this.props.width) {
el.addClass('sm-width-'+this.props.width)
}
if (this.props.transparent) {
el.addClass('sm-transparent-bg')
}
el.append(
$$('div').addClass('se-body').append(
this.props.children
)
)
return el
}
_closeModal(e) {
e.preventDefault()
e.stopPropagation()
let closeSurfaceClick = e.target.classList.contains('sc-modal-dialog')
if (closeSurfaceClick) {
this.send('closeModal')
}
}
}
|
Use logger instead of system out | /**
* Copyright (c) Anton Johansson <antoon.johansson@gmail.com>
*
* 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 com.antonjohansson.lprs.controller.token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.antonjohansson.lprs.model.User;
/**
* {@link ITokenSender} implementation that prints the token to the console.
*/
class ConsoleTokenSender implements ITokenSender
{
private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleTokenSender.class);
@Override
public void send(User user, String token)
{
LOGGER.info("Generated token '{}'", token);
}
}
| /**
* Copyright (c) Anton Johansson <antoon.johansson@gmail.com>
*
* 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 com.antonjohansson.lprs.controller.token;
import com.antonjohansson.lprs.model.User;
/**
* {@link ITokenSender} implementation that prints the token to the console.
*/
class ConsoleTokenSender implements ITokenSender
{
@Override
public void send(User user, String token)
{
System.out.println("Generated token '" + token + "'.");
}
}
|
Remove stray variable breaking defaultUrl calculation. | var _ = require('lodash');
module.exports = function(grunt) {
var module = {};
module.domain = function() {
return process.env.GRUNT_DRUPAL_DOMAIN || grunt.config('config.domain') || require('os').hostname();
};
// Ensure a default URL for the project.
module.siteUrls = function() {
return grunt.config('config.siteUrls.default') || "http://<%= config.domain %>";
}
module.buildPaths = function() {
// Set implicit global configuration.
var buildPaths = grunt.config('config.buildPaths');
buildPaths = _.extend({
build: 'build',
html: 'build/html',
package: 'build/packages',
reports: 'build/reports',
temp: 'build/temp'
}, buildPaths);
return buildPaths;
}
module.init = function() {
if (grunt.config('config.siteUrls') === undefined)
grunt.config('config.siteUrls', {});
grunt.config('config.domain', module.domain());
grunt.config('config.siteUrls.default', module.siteUrls());
grunt.config('config.buildPaths', module.buildPaths());
};
return module;
};
| var _ = require('lodash');
module.exports = function(grunt) {
var module = {};
module.domain = function() {
return process.env.GRUNT_DRUPAL_DOMAIN || grunt.config('config.domain') || require('os').hostname();
};
// Ensure a default URL for the project.
module.siteUrls = function() {
return grunt.config('config.siteUrls.default') || "http://<%= config.domain %>";
}
module.buildPaths = function() {
// Set implicit global configuration.
var buildPaths = grunt.config('config.buildPaths');
buildPaths = _.extend({
build: 'build',
html: 'build/html',
package: 'build/packages',
reports: 'build/reports',
temp: 'build/temp'
}, buildPaths);
return buildPaths;
}
module.init = function() {
if (grunt.config('config.siteUrls') === undefined)
grunt.config('config.siteUrls', {});
grunt.config('config.domain', module.domain());
grunt.config('config.siteUrls.default', module.siteUrls(defaultUrl));
grunt.config('config.buildPaths', module.buildPaths());
};
return module;
};
|
Fix CCADB URLs in truststore retriever | package main
import (
"encoding/csv"
"fmt"
"log"
"net/http"
"os"
"strings"
)
func main() {
var (
truststore, csvURL string
csvPEMPos int
)
if len(os.Args) != 2 {
log.Fatalf("usage: %s <mozilla|microsoft>", os.Args[0])
}
truststore = os.Args[1]
switch truststore {
case "mozilla":
csvURL = "https://ccadb-public.secure.force.com/mozilla/IncludedCACertificateReportPEMCSV"
csvPEMPos = 28
case "microsoft":
csvURL = "https://ccadb-public.secure.force.com/microsoft/IncludedCACertificateReportForMSFTCSVPEM"
csvPEMPos = 6
}
resp, err := http.Get(csvURL)
if err != nil {
log.Fatal(err)
}
r := csv.NewReader(resp.Body)
defer resp.Body.Close()
records, err := r.ReadAll()
if err != nil {
log.Fatal(err)
}
for _, record := range records {
if len(record) < csvPEMPos+1 {
continue
}
fmt.Println(strings.Trim(record[csvPEMPos], `'`))
}
}
| package main
import (
"encoding/csv"
"fmt"
"log"
"net/http"
"os"
"strings"
)
func main() {
var (
truststore, csvURL string
csvPEMPos int
)
if len(os.Args) != 2 {
log.Fatalf("usage: %s <mozilla|microsoft>", os.Args[0])
}
truststore = os.Args[1]
switch truststore {
case "mozilla":
csvURL = "https://mozillacaprogram.secure.force.com/CA/IncludedCACertificateReportPEMCSV"
csvPEMPos = 28
case "microsoft":
csvURL = "https://mozillacaprogram.secure.force.com/CA/apex/IncludedCACertificateReportForMSFTCSVPEM"
csvPEMPos = 6
}
resp, err := http.Get(csvURL)
if err != nil {
log.Fatal(err)
}
r := csv.NewReader(resp.Body)
defer resp.Body.Close()
records, err := r.ReadAll()
if err != nil {
log.Fatal(err)
}
for _, record := range records {
if len(record) < csvPEMPos+1 {
continue
}
fmt.Println(strings.Trim(record[csvPEMPos], `'`))
}
}
|
Set local threads to true for peewee | import ConfigParser
from peewee import *
config = ConfigParser.RawConfigParser()
config.read('server.conf')
database = SqliteDatabase('gallery.db', threadlocals=True)
from collection import CollectionModel
from album import AlbumModel
from user import UserModel, UsersResource
from photo import PhotoModel
database.create_tables([PhotoModel, AlbumModel, UserModel, CollectionModel], True)
if UserModel.select().count() == 0:
UserModel.create(
admin = True,
name = 'Admin',
username = 'Admin',
password = '$2a$12$pMtKl1b7h1sFKbMdBvPqbuza1tJN2ZNNAFMEs1RQmwqYTbBwrrKpy'
)
from boto.s3.connection import S3Connection
s3 = S3Connection(config.get('S3', 'AccessKey'), config.get('S3', 'SecretKey'))
if s3.lookup(config.get('S3', 'Bucket')) is None:
s3.create_bucket(config.get('S3', 'Bucket'))
from flask import Flask
from flask.ext.restful import Api
app = Flask(__name__)
api = Api(app)
api.add_resource(UsersResource, '/users/')
| import ConfigParser
from peewee import *
config = ConfigParser.RawConfigParser()
config.read('server.conf')
database = SqliteDatabase('gallery.db')
from collection import CollectionModel
from album import AlbumModel
from user import UserModel, UserResource
from photo import PhotoModel
database.create_tables([PhotoModel, AlbumModel, UserModel, CollectionModel], True)
if UserModel.select().count() == 0:
UserModel.create(
admin = True,
name = 'Admin',
username = 'Admin',
password = '$2a$12$pMtKl1b7h1sFKbMdBvPqbuza1tJN2ZNNAFMEs1RQmwqYTbBwrrKpy'
)
from boto.s3.connection import S3Connection
s3 = S3Connection(config.get('S3', 'AccessKey'), config.get('S3', 'SecretKey'))
if s3.lookup(config.get('S3', 'Bucket')) is None:
s3.create_bucket(config.get('S3', 'Bucket'))
from flask import Flask
from flask.ext.restful import Api
app = Flask(__name__)
api = Api(app)
|
Migrate old passwords without "set_unusable_password" | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.hashers import make_password
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
'sha1$',
# RTD's production database doesn't have any of these
# but they are included for completeness
'md5$',
'crypt$',
)
for pattern in old_password_patterns:
users = User.objects.filter(password__startswith=pattern)
for user in users:
user.password = make_password(None)
user.save()
class Migration(migrations.Migration):
dependencies = [
('core', '0004_ad-opt-out'),
('auth', '0008_alter_user_username_max_length'),
]
operations = [
migrations.RunPython(forwards_func),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
'sha1$',
# RTD's production database doesn't have any of these
# but they are included for completeness
'md5$',
'crypt$',
)
for pattern in old_password_patterns:
users = User.objects.filter(password__startswith=pattern)
for user in users:
user.set_unusable_password()
user.save()
class Migration(migrations.Migration):
dependencies = [
('core', '0004_ad-opt-out'),
('auth', '0008_alter_user_username_max_length'),
]
operations = [
migrations.RunPython(forwards_func),
]
|
Make console windows not appear in the taskbar. | package org.mcupdater.gui;
import org.mcupdater.util.MCUpdater;
import javax.swing.*;
import java.awt.*;
import java.util.logging.Level;
public class ConsoleForm {
private final CALogHandler consoleHandler;
private final ConsoleArea console;
private final JDialog window;
public ConsoleForm(String title) {
window = new JDialog();
window.setIconImage(new ImageIcon(this.getClass().getResource("mcu-icon.png")).getImage());
window.setTitle(title);
window.setBounds(25, 25, 500, 500);
window.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
console = new ConsoleArea();
window.getContentPane().setLayout(new BorderLayout());
JScrollPane scroller = new JScrollPane(console, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
window.getContentPane().add(scroller, BorderLayout.CENTER);
consoleHandler = new CALogHandler(console);
consoleHandler.setLevel(Level.INFO);
window.setVisible(true);
MCUpdater.apiLogger.addHandler(consoleHandler);
}
public ConsoleArea getConsole() {
return console;
}
public CALogHandler getHandler() {
return consoleHandler;
}
public void allowClose() {
window.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
}
| package org.mcupdater.gui;
import org.mcupdater.util.MCUpdater;
import javax.swing.*;
import java.awt.*;
import java.util.logging.Level;
public class ConsoleForm {
private final CALogHandler consoleHandler;
private final ConsoleArea console;
private final JFrame window;
public ConsoleForm(String title) {
window = new JFrame();
window.setIconImage(new ImageIcon(this.getClass().getResource("mcu-icon.png")).getImage());
window.setTitle(title);
window.setBounds(25, 25, 500, 500);
window.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
console = new ConsoleArea();
window.getContentPane().setLayout(new BorderLayout());
JScrollPane scroller = new JScrollPane(console, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
window.getContentPane().add(scroller, BorderLayout.CENTER);
consoleHandler = new CALogHandler(console);
consoleHandler.setLevel(Level.INFO);
window.setVisible(true);
MCUpdater.apiLogger.addHandler(consoleHandler);
}
public ConsoleArea getConsole() {
return console;
}
public CALogHandler getHandler() {
return consoleHandler;
}
public void allowClose() {
window.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
}
|
Fix not found autoload on local install | <?php
foreach (array(__DIR__.'/../../autoload.php', __DIR__.'/../vendor/autoload.php', __DIR__.'/vendor/autoload.php') as $autoload) {
if (file_exists($autoload)) {
require_once $autoload;
break;
}
}
define('MANALIZE_DIR', __DIR__);
define('MANALIZE_TMP_ROOT_DIR', sys_get_temp_dir().'/Manala');
define('UPDATE_FIXTURES', filter_var(getenv('UPDATE_FIXTURES'), FILTER_VALIDATE_BOOLEAN));
/**
* Creates a unique tmp dir.
*
* @param string $prefix
*
* @return string The path to the tmp dir created
*/
function manala_get_tmp_dir($prefix = '')
{
if (!is_dir(MANALIZE_TMP_ROOT_DIR)) {
@mkdir(MANALIZE_TMP_ROOT_DIR);
}
$tmp = @tempnam(MANALIZE_TMP_ROOT_DIR, $prefix);
unlink($tmp);
mkdir($tmp, 0777, true);
return $tmp;
}
| <?php
require_once __DIR__.'/vendor/autoload.php';
define('MANALIZE_DIR', __DIR__);
define('MANALIZE_TMP_ROOT_DIR', sys_get_temp_dir().'/Manala');
define('UPDATE_FIXTURES', filter_var(getenv('UPDATE_FIXTURES'), FILTER_VALIDATE_BOOLEAN));
/**
* Creates a unique tmp dir.
*
* @param string $prefix
*
* @return string The path to the tmp dir created
*/
function manala_get_tmp_dir($prefix = '')
{
if (!is_dir(MANALIZE_TMP_ROOT_DIR)) {
@mkdir(MANALIZE_TMP_ROOT_DIR);
}
$tmp = @tempnam(MANALIZE_TMP_ROOT_DIR, $prefix);
unlink($tmp);
mkdir($tmp, 0777, true);
return $tmp;
}
|
Add getter in annotable class | package gr.iti.mklab.simmo.core;
import org.mongodb.morphia.annotations.Embedded;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* An Annotatable abstract class implemented by objects that can be annotated
*
* @author kandreadou
* @version 1.0.0
* @since July 3, 2014
*/
public abstract class Annotatable implements Associated {
@Embedded
private List<Annotation> annotations = new ArrayList<Annotation>();
public void addAnnotation(Annotation a) {
annotations.add(a);
}
public void removeAnnotation(Annotation a) {
annotations.remove(a);
}
public void setAnnotations(List<Annotation> annotations) {
this.annotations = annotations;
}
public Annotation getAnnotation(int position) {
return annotations.get(position);
}
public List<Annotation> getAnnotations() {
return annotations;
}
public List<? extends Annotation> getAnnotationsByClass(Class clazz) {
return annotations.stream().filter(t -> t.getClass() == clazz)
.collect(Collectors.toList());
}
}
| package gr.iti.mklab.simmo.core;
import org.mongodb.morphia.annotations.Embedded;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* An Annotatable abstract class implemented by objects that can be annotated
*
* @author kandreadou
* @version 1.0.0
* @since July 3, 2014
*/
public abstract class Annotatable implements Associated {
@Embedded
private List<Annotation> annotations = new ArrayList<Annotation>();
public void addAnnotation(Annotation a) {
annotations.add(a);
}
public void removeAnnotation(Annotation a) {
annotations.remove(a);
}
public void setAnnotations(List<Annotation> annotations) {
this.annotations = annotations;
}
public Annotation getAnnotation(int position) {
return annotations.get(position);
}
public List<? extends Annotation> getAnnotationsByClass(Class clazz) {
return annotations.stream().filter(t -> t.getClass() == clazz)
.collect(Collectors.toList());
}
}
|
Comment out console to merge. | // execute dependencies immediately on file parse
nrj("/js/mapbox/mapbox-1.5.2.js",1);
nrc("/js/mapbox/mapbox-1.5.2.css",1);
// the plugin callback by another name
var ddg_spice_maps_places = function (places) {
// sub function where 'places' is always defined
var f2 = function() {
// console.log("f2");
// check for the mapbox object
if (!window["L"]) {
// console.log("no L");
// wait for it
window.setTimeout(f2, 50);
// could check for a max value here
return;
}
// console.log("L found, here we go with places: %o", places);
DDG.maps.renderLocal(places);
};
f2();
};
| // execute dependencies immediately on file parse
nrj("/js/mapbox/mapbox-1.5.2.js",1);
nrc("/js/mapbox/mapbox-1.5.2.css",1);
// the plugin callback by another name
var ddg_spice_maps_places = function (places) {
// sub function where 'places' is always defined
var f2 = function() {
console.log("f2");
// check for the mapbox object
if (!window["L"]) {
console.log("no L");
// wait for it
window.setTimeout(f2, 50);
// could check for a max value here
return;
}
console.log("L found, here we go with places: %o", places);
DDG.maps.renderLocal(places);
};
f2();
};
|
Disable sitemap plugin for website as it does not work anymore | /*
* Yet Another UserAgent Analyzer
* Copyright (C) 2013-2021 Niels Basjes
*
* 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.
*/
var pkg = require('./package.json');
module.exports = {
// Documentation for Yauaa is stored under "src/main/docs"
root: './main/docs',
title: 'Yauaa: Yet Another UserAgent Analyzer',
// Enforce use of GitBook v3
gitbook: '3.2.3',
// Use the "official" theme
// plugins: ['theme-official@2.1.1', '-sharing', '-fontsettings', 'sitemap'],
// plugins: ['sitemap'],
variables: {
version: pkg.version,
YauaaVersion: "5.23"
},
// pluginsConfig: {
// sitemap: {
// hostname: 'https://yauaa.basjes.nl'
// }
// }
};
| /*
* Yet Another UserAgent Analyzer
* Copyright (C) 2013-2021 Niels Basjes
*
* 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.
*/
var pkg = require('./package.json');
module.exports = {
// Documentation for Yauaa is stored under "src/main/docs"
root: './main/docs',
title: 'Yauaa: Yet Another UserAgent Analyzer',
// Enforce use of GitBook v3
gitbook: '3.2.3',
// Use the "official" theme
// plugins: ['theme-official@2.1.1', '-sharing', '-fontsettings', 'sitemap'],
plugins: ['sitemap'],
variables: {
version: pkg.version,
YauaaVersion: "5.23"
},
pluginsConfig: {
sitemap: {
hostname: 'https://yauaa.basjes.nl'
}
}
};
|
Mark syweb as not being zip safe so that bundled files are accessible from the filesystem | #!/usr/bin/env python
# Copyright 2014 OpenMarket 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.
import os
from setuptools import setup, find_packages
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="syweb",
version="0.0.1",
packages=find_packages(exclude=["tests", "tests.*"]),
description="Matrix Angular Sdk",
include_package_data=True,
zip_safe=False,
long_description=read("README.rst"),
entry_points=""""""
)
| #!/usr/bin/env python
# Copyright 2014 OpenMarket 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.
import os
from setuptools import setup, find_packages
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="syweb",
version="0.0.1",
packages=find_packages(exclude=["tests", "tests.*"]),
description="Matrix Angular Sdk",
include_package_data=True,
long_description=read("README.rst"),
entry_points=""""""
)
|
Set HideWindow: true for the cmd exe. | package util
import (
"fmt"
"os"
"os/exec"
"strings"
"syscall"
)
func CallBrowser(url string) error {
fmt.Fprintf(os.Stderr, "Running a browser to open %s...\r\n", url)
var attr os.ProcAttr
attr.Sys = &syscall.SysProcAttr{HideWindow: true}
attr.Files = []*os.File{os.Stdin, os.Stdout, os.Stderr}
path, err := exec.LookPath("cmd")
if err != nil {
return err
}
// so on windows when you're using cmd you have to escape ampersands with the ^ character.
// ¯\(º_o)/¯
url = strings.Replace(url, "&", "^&", -1)
proc, err := os.StartProcess(path, []string{path, "/C", "start", url}, &attr)
if err != nil {
return err
}
_, err = proc.Wait()
return err
}
| package util
import (
"fmt"
"os"
"os/exec"
"strings"
"syscall"
)
func CallBrowser(url string) error {
fmt.Fprintf(os.Stderr, "Running a browser to open %s...\r\n", url)
var attr os.ProcAttr
attr.Sys = &syscall.SysProcAttr{HideWindow: false}
attr.Files = []*os.File{os.Stdin, os.Stdout, os.Stderr}
path, err := exec.LookPath("cmd")
if err != nil {
return err
}
// so on windows when you're using cmd you have to escape ampersands with the ^ character.
// ¯\(º_o)/¯
url = strings.Replace(url, "&", "^&", -1)
proc, err := os.StartProcess(path, []string{path, "/C", "start", url }, &attr)
if err != nil {
return err
}
_, err = proc.Wait()
return err
}
|
Fix crud controller for notifacation
It was not possible to get, update or retrieve a notification | from zou.app.models.notifications import Notification
from zou.app.utils import permissions
from .base import BaseModelResource, BaseModelsResource
class NotificationsResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, Notification)
def check_create_permissions(self, data):
return permissions.check_admin_permissions()
class NotificationResource(BaseModelResource):
def __init__(self):
BaseModelResource.__init__(self, Notification)
def check_read_permissions(self, instance):
return permissions.check_admin_permissions()
def check_update_permissions(self, instance, data):
return permissions.check_admin_permissions()
def check_delete_permissions(self, instance):
return permissions.check_admin_permissions()
| from zou.app.models.notifications import Notification
from zou.app.utils import permissions
from .base import BaseModelResource, BaseModelsResource
class NotificationsResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, Notification)
def check_create_permissions(self, data):
return permissions.check_admin_permissions()
class NotificationResource(BaseModelResource):
def __init__(self):
BaseModelResource.__init__(self, NotificationResource)
def check_read_permissions(self, instance):
return permissions.check_admin_permissions()
def check_update_permissions(self, instance, data):
return permissions.check_admin_permissions()
def check_delete_permissions(self, instance):
return permissions.check_admin_permissions()
|
Revert version number on release branch. | """Spherical harmonic vector wind analysis."""
# Copyright (c) 2012-2014 Andrew Dawson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import
from . import standard
from . import tools
# List to define the behaviour of imports of the form:
# from windspharm import *
__all__ = []
# Package version number.
__version__ = '1.3.x'
try:
from . import cdms
__all__.append('cdms')
metadata = cdms
except ImportError:
pass
try:
from . import iris
__all__.append('iris')
except ImportError:
pass
| """Spherical harmonic vector wind analysis."""
# Copyright (c) 2012-2014 Andrew Dawson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import
from . import standard
from . import tools
# List to define the behaviour of imports of the form:
# from windspharm import *
__all__ = []
# Package version number.
__version__ = '1.3.2'
try:
from . import cdms
__all__.append('cdms')
metadata = cdms
except ImportError:
pass
try:
from . import iris
__all__.append('iris')
except ImportError:
pass
|
Create new alert class and display an alert when user attempts to clear tasks | package guitests.guihandles;
import guitests.GuiRobot;
import javafx.stage.Stage;
/**
* A handle to the Command Box in the GUI.
*/
public class CommandBoxHandle extends GuiHandle{
private static final String COMMAND_INPUT_FIELD_ID = "#commandTextField";
public CommandBoxHandle(GuiRobot guiRobot, Stage primaryStage, String stageTitle) {
super(guiRobot, primaryStage, stageTitle);
}
public void enterCommand(String command) {
setTextField(COMMAND_INPUT_FIELD_ID, command);
}
public String getCommandInput() {
return getTextFieldText(COMMAND_INPUT_FIELD_ID);
}
/**
* Enters the given command in the Command Box and presses enter.
*/
public void runCommand(String command) {
enterCommand(command);
pressEnter();
guiRobot.sleep(10);
if (command.equals("clear")) // any commands that has an alert dialog that pops out
pressEnter();
guiRobot.sleep(700); //Give time for the command to take effect
}
public HelpWindowHandle runHelpCommand() {
enterCommand("help");
pressEnter();
return new HelpWindowHandle(guiRobot, primaryStage);
}
}
| package guitests.guihandles;
import guitests.GuiRobot;
import javafx.stage.Stage;
/**
* A handle to the Command Box in the GUI.
*/
public class CommandBoxHandle extends GuiHandle{
private static final String COMMAND_INPUT_FIELD_ID = "#commandTextField";
public CommandBoxHandle(GuiRobot guiRobot, Stage primaryStage, String stageTitle) {
super(guiRobot, primaryStage, stageTitle);
}
public void enterCommand(String command) {
setTextField(COMMAND_INPUT_FIELD_ID, command);
}
public String getCommandInput() {
return getTextFieldText(COMMAND_INPUT_FIELD_ID);
}
/**
* Enters the given command in the Command Box and presses enter.
*/
public void runCommand(String command) {
enterCommand(command);
pressEnter();
guiRobot.sleep(200);
if (command.equals("clear")) // any commands that has an alert dialog that pops out
pressEnter();
guiRobot.sleep(500); //Give time for the command to take effect
}
public HelpWindowHandle runHelpCommand() {
enterCommand("help");
pressEnter();
return new HelpWindowHandle(guiRobot, primaryStage);
}
}
|
Drop Python 2.5 support, add support for Python 3.2 | import os
from setuptools import setup, find_packages
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setup(
name='gears-less',
version='0.1',
url='https://github.com/gears/gears-less',
license='ISC',
author='Mike Yumatov',
author_email='mike@yumatov.org',
description='LESS compiler for Gears',
long_description=read('README.rst'),
packages=find_packages(),
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
],
)
| import os
from setuptools import setup, find_packages
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setup(
name='gears-less',
version='0.1',
url='https://github.com/gears/gears-less',
license='ISC',
author='Mike Yumatov',
author_email='mike@yumatov.org',
description='LESS compiler for Gears',
long_description=read('README.rst'),
packages=find_packages(),
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
|
Increase version to beta 1. | from setuptools import setup
setup(
name='jobcli',
version='0.1b1',
py_modules=['jobcli'],
install_requires=['click', 'requests',],
entry_points={'console_scripts':['jobcli=jobcli:cli',]},
url='https://www.jobcli.com',
author='Stephan Goergen',
author_email='stephan.goergen@gmail.com',
description='Job Search from the Command Line',
license='MIT',
zip_safe=False,
include_package_data=False,
keywords='board job search command line career developer engineer',
classifiers=[
'License :: OSI Approved :: MIT License'
,'Development Status :: 4 - Beta'
,'Environment :: Console'
,'Operating System :: OS Independent'
,'Natural Language :: English'
,'Intended Audience :: Developers'
,'Intended Audience :: Information Technology'
,'Intended Audience :: System Administrators'
,'Intended Audience :: Science/Research'
,'Topic :: Office/Business'
,'Programming Language :: Python :: 2'
,'Programming Language :: Python :: 2.7'
,'Programming Language :: Python :: 3'
,'Programming Language :: Python :: 3.3'
,'Programming Language :: Python :: 3.4'
,'Programming Language :: Python :: 3.5'
]
)
| from setuptools import setup
setup(
name='jobcli',
version='0.1.a2',
py_modules=['jobcli'],
install_requires=['click', 'requests',],
entry_points={'console_scripts':['jobcli=jobcli:cli',]},
url='https://www.jobcli.com',
author='Stephan Goergen',
author_email='stephan.goergen@gmail.com',
description='Job Search from the Command Line',
license='MIT',
zip_safe=False,
include_package_data=False,
keywords='board job search command line career developer engineer',
classifiers=[
'License :: OSI Approved :: MIT License'
,'Development Status :: 3 - Alpha'
,'Environment :: Console'
,'Operating System :: OS Independent'
,'Natural Language :: English'
,'Intended Audience :: Developers'
,'Intended Audience :: Information Technology'
,'Intended Audience :: System Administrators'
,'Intended Audience :: Science/Research'
,'Topic :: Office/Business'
,'Programming Language :: Python :: 2'
,'Programming Language :: Python :: 2.7'
,'Programming Language :: Python :: 3'
,'Programming Language :: Python :: 3.3'
,'Programming Language :: Python :: 3.4'
,'Programming Language :: Python :: 3.5'
]
)
|
Disable not-safe PostCSS value conversions | module.exports = {
options: {
map: true, // inline sourcemaps
processors: [
require('pixrem')(), // add fallbacks for rem units
require('autoprefixer-core')({
// add vendor prefixes
browsers: [
'last 3 version',
'ie 8',
'ff 3.6',
'opera 11.1',
'ios 4',
'android 2.3'
]
}),
require('cssnano')({
convertValues: false
}) // minify the result
]
},
dist: {
src: '<%= destCSSDir %>' + '/*.css'
}
};
| module.exports = {
options: {
map: true, // inline sourcemaps
processors: [
require('pixrem')(), // add fallbacks for rem units
require('autoprefixer-core')({
// add vendor prefixes
browsers: [
'last 3 version',
'ie 8',
'ff 3.6',
'opera 11.1',
'ios 4',
'android 2.3'
]
}),
require('cssnano')() // minify the result
]
},
dist: {
src: '<%= destCSSDir %>' + '/*.css'
}
};
|
Revert "fix: prevent [ref] from turning into shortcodes"
This reverts commit 324c5d483f354de76fdf0800bb30966a400a77ba.
Breaks pages with existing shortcodes. | import Summary from "./Summary/Summary";
import ProminentLink from "./ProminentLink/ProminentLink";
const { registerBlockType, registerBlockStyle } = wp.blocks;
const { createHigherOrderComponent } = wp.compose;
const { addFilter } = wp.hooks;
registerBlockType("owid/summary", Summary);
registerBlockType("owid/prominent-link", ProminentLink);
registerBlockStyle("core/columns", {
name: "sticky-right",
label: "Sticky right"
});
registerBlockStyle("core/columns", {
name: "side-by-side",
label: "Side by side"
});
// Temporary fix https://github.com/WordPress/gutenberg/issues/9897#issuecomment-478362380
const allowColumnStyle = createHigherOrderComponent(BlockEdit => {
return props => {
const { name, insertBlocksAfter = null } = props;
return name === "core/columns" && insertBlocksAfter === null ? (
<div />
) : (
<BlockEdit {...props} />
);
};
}, "allowColumnStyle");
addFilter("editor.BlockEdit", "owid/blocks/columns", allowColumnStyle);
| import Summary from "./Summary/Summary";
import ProminentLink from "./ProminentLink/ProminentLink";
const {
registerBlockType,
registerBlockStyle,
unregisterBlockType
} = wp.blocks;
const { createHigherOrderComponent } = wp.compose;
const { addFilter } = wp.hooks;
// Temporary hack to facilitate conversion of classic posts to Gutenberg
// https://github.com/WordPress/gutenberg/issues/11723#issuecomment-439628591
// Recommended way (https://developer.wordpress.org/block-editor/developers/filters/block-filters/#using-a-blacklist) not working
window.onload = function() {
unregisterBlockType("core/shortcode");
};
registerBlockType("owid/summary", Summary);
registerBlockType("owid/prominent-link", ProminentLink);
registerBlockStyle("core/columns", {
name: "sticky-right",
label: "Sticky right"
});
registerBlockStyle("core/columns", {
name: "side-by-side",
label: "Side by side"
});
// Temporary fix https://github.com/WordPress/gutenberg/issues/9897#issuecomment-478362380
const allowColumnStyle = createHigherOrderComponent(BlockEdit => {
return props => {
const { name, insertBlocksAfter = null } = props;
return name === "core/columns" && insertBlocksAfter === null ? (
<div />
) : (
<BlockEdit {...props} />
);
};
}, "allowColumnStyle");
addFilter("editor.BlockEdit", "owid/blocks/columns", allowColumnStyle);
|
Use log.warn instead of debug and claim it's a warn | const express = require('express');
const logger = require('../logger').policy;
const schemas = require('../schemas');
const predefined = require('./predefined');
const conditions = {};
function register ({ name, handler, schema }) {
const validate = schemas.register('condition', name, schema);
conditions[name] = (req, config) => {
const validationResult = validate(config);
if (validationResult.isValid) {
return handler(req, config);
}
logger.error(`Condition ${name} config validation failed`, validationResult.error);
throw new Error(`Condition ${name} config validation failed`);
};
}
function init () {
predefined.forEach(register);
// extending express.request
express.request.matchEGCondition = function (conditionConfig) {
logger.debug('matchEGCondition for %o', conditionConfig);
const func = conditions[conditionConfig.name];
if (!func) {
logger.warn(`Condition not found for ${conditionConfig.name}`);
return null;
}
return func(this, conditionConfig);
};
return {
register
};
}
module.exports = {
init
};
| const express = require('express');
const logger = require('../logger').policy;
const schemas = require('../schemas');
const predefined = require('./predefined');
const conditions = {};
function register ({ name, handler, schema }) {
const validate = schemas.register('condition', name, schema);
conditions[name] = (req, config) => {
const validationResult = validate(config);
if (validationResult.isValid) {
return handler(req, config);
}
logger.error(`Condition ${name} config validation failed`, validationResult.error);
throw new Error(`Condition ${name} config validation failed`);
};
}
function init () {
predefined.forEach(register);
// extending express.request
express.request.matchEGCondition = function (conditionConfig) {
logger.debug('matchEGCondition for %o', conditionConfig);
const func = conditions[conditionConfig.name];
if (!func) {
logger.debug(`warning: condition not found for ${conditionConfig.name}`);
return null;
}
return func(this, conditionConfig);
};
return {
register
};
}
module.exports = {
init
};
|
Fix for Custom Table Name
Error was:"name":"PHP Strict Warning","message":"Accessing static property nhkey\\arh\\managers\\DBManager::$tableName as non static","code":2048,"type":"yii\\base\\ErrorException","file":"/var/www/public/vendor/nhkey/yii2-activerecord-history/src/managers/BaseManager.php" if customTable was declared at behavior | <?php
/**
* @link http://mikhailmikhalev.ru
* @author Mikhail Mikhalev
*/
namespace nhkey\arh\managers;
use Yii;
use yii\db\Connection;
use yii\di\Instance;
/**
* Class DBManager for save history in DB
* @package nhkey\arh
*/
class DBManager extends BaseManager
{
public $tableName = '{{%modelhistory}}';
/**
* @var string
*/
public static $db = 'db';
/**
* @param array $data
*/
public function saveField($data)
{
self::getDB()->createCommand()
->insert($this->tableName, $data)->execute();
}
/**
* @return object Return database connection
* @throws \yii\base\InvalidConfigException
*/
private static function getDB()
{
return Instance::ensure(self::$db, Connection::className());
}
}
| <?php
/**
* @link http://mikhailmikhalev.ru
* @author Mikhail Mikhalev
*/
namespace nhkey\arh\managers;
use Yii;
use yii\db\Connection;
use yii\di\Instance;
/**
* Class DBManager for save history in DB
* @package nhkey\arh
*/
class DBManager extends BaseManager
{
public static $tableName = '{{%modelhistory}}';
/**
* @var string
*/
public static $db = 'db';
/**
* @param array $data
*/
public function saveField($data)
{
$table = isset($this->tableName) ? $this->tableName : $this::$tableName;
self::getDB()->createCommand()
->insert($table, $data)->execute();
}
/**
* @return object Return database connection
* @throws \yii\base\InvalidConfigException
*/
private static function getDB()
{
return Instance::ensure(self::$db, Connection::className());
}
}
|
Add function to add images by draggin from desktop | function setStyle(style, param) {
var range, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
document.execCommand(style, false, param);
document.designMode = "off";
}
}
Mousetrap.bind('mod+b', function(e) {
e.preventDefault();
setStyle("bold");
});
Mousetrap.bind('mod+i', function(e) {
e.preventDefault();
setStyle("italic");
});
Mousetrap.bind('mod+u', function(e) {
e.preventDefault();
setStyle("underline");
});
function addImage(e) {
e.stopPropagation();
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
setStyle("insertImage", event.target.result);
};
reader.readAsDataURL(file);
}
var pad = document.getElementById('pad');
pad.addEventListener('drop', addImage, false);
| function setStyle(style) {
var range, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
document.execCommand(style, false, null);
document.designMode = "off";
}
}
Mousetrap.bind('mod+b', function(e) {
e.preventDefault();
setStyle("bold");
});
Mousetrap.bind('mod+i', function(e) {
e.preventDefault();
setStyle("italic");
});
Mousetrap.bind('mod+u', function(e) {
e.preventDefault();
setStyle("underline");
});
|
Allow files app nav entries to have a different icon class | <div id="app-navigation">
<ul class="with-icon">
<?php foreach ($_['navigationItems'] as $item) { ?>
<li data-id="<?php p($item['id']) ?>" class="nav-<?php p($item['id']) ?>">
<a href="<?php p(isset($item['href']) ? $item['href'] : '#') ?>"
class="nav-icon-<?php p($item['icon'] !== '' ? $item['icon'] : $item['id']) ?> svg">
<?php p($item['name']);?>
</a>
</li>
<?php } ?>
</ul>
<div id="app-settings">
<div id="app-settings-header">
<button class="settings-button" data-apps-slide-toggle="#app-settings-content">
<span><?php p($l->t('Settings'));?></span>
</button>
</div>
<div id="app-settings-content">
<h2>
<label for="webdavurl"><?php p($l->t('WebDAV'));?></label>
</h2>
<input id="webdavurl" type="text" readonly="readonly" value="<?php p(\OCP\Util::linkToRemote('webdav')); ?>" />
<em><?php print_unescaped($l->t('Use this address to <a href="%s" target="_blank">access your Files via WebDAV</a>', array(link_to_docs('user-webdav'))));?></em>
</div>
</div>
</div>
| <div id="app-navigation">
<ul class="with-icon">
<?php foreach ($_['navigationItems'] as $item) { ?>
<li data-id="<?php p($item['id']) ?>" class="nav-<?php p($item['id']) ?>">
<a href="<?php p(isset($item['href']) ? $item['href'] : '#') ?>"
class="nav-icon-<?php p($item['id']) ?> svg">
<?php p($item['name']);?>
</a>
</li>
<?php } ?>
</ul>
<div id="app-settings">
<div id="app-settings-header">
<button class="settings-button" data-apps-slide-toggle="#app-settings-content">
<span><?php p($l->t('Settings'));?></span>
</button>
</div>
<div id="app-settings-content">
<h2>
<label for="webdavurl"><?php p($l->t('WebDAV'));?></label>
</h2>
<input id="webdavurl" type="text" readonly="readonly" value="<?php p(\OCP\Util::linkToRemote('webdav')); ?>" />
<em><?php print_unescaped($l->t('Use this address to <a href="%s" target="_blank">access your Files via WebDAV</a>', array(link_to_docs('user-webdav'))));?></em>
</div>
</div>
</div>
|
Test with non-spacing mark filter | <?php
namespace USlugify;
/**
* USlugify
*
* @author Florent Denis <dflorent.pokap@gmail.com>
*/
class USlugify implements USlugifyInterface
{
/**
* {@inheritdoc}
*/
public function slugify($text)
{
$reservedChars = $this->getReservedChars();
$text = str_replace($reservedChars, '-', $text);
$text = preg_replace('/\p{Mn}+/u', '-', $text);
$text = trim(preg_replace('/[-\s]+/u', '-', $text), '-');
return mb_strtolower($text, mb_detect_encoding($text));
}
/**
* Returns list of char reserved.
* http://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters
*
* @return array
*/
protected function getReservedChars()
{
return array('!', '#', '$', '&', '\'', '"', '(', ')', '*', '+', ',', '/', ':', ';', '=', '?', '@', '[', ']');
}
}
| <?php
namespace USlugify;
/**
* USlugify
*
* @author Florent Denis <dflorent.pokap@gmail.com>
*/
class USlugify implements USlugifyInterface
{
/**
* {@inheritdoc}
*/
public function slugify($text)
{
$reservedChars = $this->getReservedChars();
$text = str_replace($reservedChars, '-', $text);
$text = trim(preg_replace('/[-\s]+/u', '-', $text), '-');
return mb_strtolower($text, mb_detect_encoding($text));
}
/**
* Returns list of char reserved.
* http://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters
*
* @return array
*/
protected function getReservedChars()
{
return array('!', '#', '$', '&', '\'', '"', '(', ')', '*', '+', ',', '/', ':', ';', '=', '?', '@', '[', ']');
}
}
|
Make sure all log messages are non blocking, v1.3.0 | package connection
import (
"fmt"
"sync"
)
import "github.com/octoblu/vulcand-job-logger/pool"
var redisPool *pool.Pool
var redisPoolOnce sync.Once
// Connection connects to redis and
type Connection struct {
redisURI, redisQueueName string
}
// New constructs a new Connection
func New(redisURI, redisQueueName string) *Connection {
redisPoolOnce.Do(func() {
redisPool = pool.New()
})
return &Connection{redisURI, redisQueueName}
}
// Publish puts the thing in the redis queue
func (connection *Connection) Publish(data []byte) {
go redisPool.Publish(connection.redisURI, connection.redisQueueName, data)
}
// String will be called by loggers inside Vulcand and command line tool.
func (connection *Connection) String() string {
return fmt.Sprintf("redis-uri=%v, redis-queue-name=%v", connection.redisURI, connection.redisQueueName)
}
| package connection
import (
"fmt"
"sync"
)
import "github.com/octoblu/vulcand-job-logger/pool"
var redisPool *pool.Pool
var redisPoolOnce sync.Once
// Connection connects to redis and
type Connection struct {
redisURI, redisQueueName string
}
// New constructs a new Connection
func New(redisURI, redisQueueName string) *Connection {
redisPoolOnce.Do(func() {
redisPool = pool.New()
})
return &Connection{redisURI, redisQueueName}
}
// Publish puts the thing in the redis queue
func (connection *Connection) Publish(data []byte) {
redisPool.Publish(connection.redisURI, connection.redisQueueName, data)
}
// String will be called by loggers inside Vulcand and command line tool.
func (connection *Connection) String() string {
return fmt.Sprintf("redis-uri=%v, redis-queue-name=%v", connection.redisURI, connection.redisQueueName)
}
|
Add missing super in test
Closes gh-814 | /*
* Copyright 2002-2015 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.springframework.http.client;
import org.junit.Test;
import org.springframework.http.HttpMethod;
/**
* @author Luciano Leggieri
*/
public class OkHttpClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase {
@Override
protected ClientHttpRequestFactory createRequestFactory() {
return new OkHttpClientHttpRequestFactory();
}
@Override
@Test
public void httpMethods() throws Exception {
super.httpMethods();
assertHttpMethod("patch", HttpMethod.PATCH);
}
}
| /*
* Copyright 2002-2015 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.springframework.http.client;
import org.junit.Test;
import org.springframework.http.HttpMethod;
/**
* @author Luciano Leggieri
*/
public class OkHttpClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase {
@Override
protected ClientHttpRequestFactory createRequestFactory() {
return new OkHttpClientHttpRequestFactory();
}
@Override
@Test
public void httpMethods() throws Exception {
assertHttpMethod("patch", HttpMethod.PATCH);
}
}
|
Use new environment variables in firebase configuration | import Firebase from 'firebase';
import Fastclick from 'react-fastclick';
import { getSectors } from 'store/api/local';
import { fetchUser } from 'store/actions/user.actions';
import { setSavedSectors } from 'store/actions/sector.actions';
export default store => {
getSectors().then(saved => {
store.dispatch(setSavedSectors(saved));
});
console.log(process.env);
Firebase.initializeApp({
apiKey: process.env.REACT_APP_API_KEY,
authDomain: process.env.REACT_APP_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_DATABASE_URL,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_SENDER_ID,
});
store.dispatch(fetchUser());
Fastclick();
};
| import Firebase from 'firebase';
import Fastclick from 'react-fastclick';
import { getSectors } from 'store/api/local';
import { fetchUser } from 'store/actions/user.actions';
import { setSavedSectors } from 'store/actions/sector.actions';
export default store => {
getSectors().then(saved => {
store.dispatch(setSavedSectors(saved));
});
Firebase.initializeApp({
apiKey: 'AIzaSyDd9dgs7P1HA8EqW5yE8C2B7TLeYLTP6f4',
authDomain: 'sector-io-23cec.firebaseapp.com',
databaseURL: 'https://sector-io-23cec.firebaseio.com',
projectId: 'sector-io-23cec',
storageBucket: 'sector-io-23cec.appspot.com',
messagingSenderId: '189524790637',
});
store.dispatch(fetchUser());
Fastclick();
};
|
Add customization for conseil departemental BDR | 'use strict';
angular.module('ddsCommon').factory('CustomizationService', function(lyonMetropoleInseeCodes) {
function determineCustomizationId(testCase, currentPeriod) {
if (testCase.menages &&
testCase.menages._) {
if (testCase.menages._.depcom[currentPeriod].match(/^93/))
return 'D93-SSD';
if (testCase.menages._.depcom[currentPeriod].match(/^75/))
return 'D75-PARIS';
if (testCase.menages._.depcom[currentPeriod].match(/^14/))
return 'D14-CALVADOS';
if (testCase.menages._.depcom[currentPeriod].match(/^59/))
return 'D59-NORD';
if (testCase.menages._.depcom[currentPeriod].match(/^13/))
return 'D13-BDR';
if (_.includes(lyonMetropoleInseeCodes, testCase.menages._.depcom[currentPeriod]))
return 'M69-LYON';
}
return undefined;
}
return {
determineCustomizationId: determineCustomizationId,
};
});
| 'use strict';
angular.module('ddsCommon').factory('CustomizationService', function(lyonMetropoleInseeCodes) {
function determineCustomizationId(testCase, currentPeriod) {
if (testCase.menages &&
testCase.menages._) {
if (testCase.menages._.depcom[currentPeriod].match(/^93/))
return 'D93-SSD';
if (testCase.menages._.depcom[currentPeriod].match(/^75/))
return 'D75-PARIS';
if (testCase.menages._.depcom[currentPeriod].match(/^14/))
return 'D14-CALVADOS';
if (testCase.menages._.depcom[currentPeriod].match(/^59/))
return 'D59-NORD';
if (_.includes(lyonMetropoleInseeCodes, testCase.menages._.depcom[currentPeriod]))
return 'M69-LYON';
}
return undefined;
}
return {
determineCustomizationId: determineCustomizationId,
};
});
|
Convert byte to string before using it with ord() | from math import fmod
def byte_pad(input_bytes, length=8):
if length > 256:
raise ValueError("Maximum padding length is 256")
# Modulo input bytes length with padding length to see how many bytes to pad with
bytes_to_pad = int(fmod(len(input_bytes), length))
# Pad input bytes with a sequence of bytes containing the number of padded bytes
input_bytes += bytes([bytes_to_pad] * bytes_to_pad)
return input_bytes
def strip_byte_padding(input_bytes, length=8):
if fmod(len(input_bytes), length) != 0:
raise ValueError("Input byte length is not divisible by %s " % length)
# Get the last {length} bytes of the input bytes, reversed
byte_block = bytes(input_bytes[:length:-1])
# If input bytes is padded, the padding is equal to byte value of the number
# of bytes padded. So we can read the padding value from the last byte..
padding_byte = byte_block[0:1]
for i in range(1, ord(padding_byte.decode())):
if byte_block[i:i+1] != padding_byte:
return input_bytes
return input_bytes[0:-ord(padding_byte.decode())]
| from math import fmod
def byte_pad(input_bytes, length=8):
if length > 256:
raise ValueError("Maximum padding length is 256")
# Modulo input bytes length with padding length to see how many bytes to pad with
bytes_to_pad = int(fmod(len(input_bytes), length))
# Pad input bytes with a sequence of bytes containing the number of padded bytes
input_bytes += bytes([bytes_to_pad] * bytes_to_pad)
return input_bytes
def strip_byte_padding(input_bytes, length=8):
if fmod(len(input_bytes), length) != 0:
raise ValueError("Input byte length is not divisible by %s " % length)
# Get the last {length} bytes of the input bytes, reversed
byte_block = bytes(input_bytes[:length:-1])
# If input bytes is padded, the padding is equal to byte value of the number
# of bytes padded. So we can read the padding value from the last byte..
padding_byte = byte_block[0:1]
for i in range(1, ord(padding_byte)):
if byte_block[i:i+1] != padding_byte:
return input_bytes
return input_bytes[0:-ord(padding_byte)]
|
Remove defunct NEX aliasing from OEX shim (see: DNA-2416) | !(function( global ) {
var Opera = function() {};
Opera.prototype.REVISION = '1';
Opera.prototype.version = function() {
return this.REVISION;
};
Opera.prototype.buildNumber = function() {
return this.REVISION;
};
Opera.prototype.postError = function( str ) {
console.log( str );
};
var opera = global.opera || new Opera();
var manifest = chrome.app.getDetails(); // null in injected scripts / popups
navigator.browserLanguage=navigator.language; //Opera defines both, some extensions use the former
var isReady = false;
var _delayedExecuteEvents = [
// Example:
// { 'target': opera.extension, 'methodName': 'message', 'args': event }
];
function addDelayedEvent(target, methodName, args) {
if(isReady) {
target[methodName].apply(target, args);
} else {
_delayedExecuteEvents.push({
"target": target,
"methodName": methodName,
"args": args
});
}
};
| !(function( global ) {
// NEX<->CRX support set up
var nexAPIStubs = ['app', 'extension', 'windows', 'tabs', 'browserAction', 'contextMenus', 'i18n', 'webRequest'];
if(!global.chrome) {
global.chrome = {};
}
for(var i = 0, l = nexAPIStubs.length; i < l; i++) {
global.chrome[ nexAPIStubs[ i ] ] = global.chrome[ nexAPIStubs[ i ] ] || global.navigator[ nexAPIStubs[ i ] ] || {};
}
var Opera = function() {};
Opera.prototype.REVISION = '1';
Opera.prototype.version = function() {
return this.REVISION;
};
Opera.prototype.buildNumber = function() {
return this.REVISION;
};
Opera.prototype.postError = function( str ) {
console.log( str );
};
var opera = global.opera || new Opera();
var manifest = chrome.app.getDetails(); // null in injected scripts / popups
navigator.browserLanguage=navigator.language; //Opera defines both, some extensions use the former
var isReady = false;
var _delayedExecuteEvents = [
// Example:
// { 'target': opera.extension, 'methodName': 'message', 'args': event }
];
function addDelayedEvent(target, methodName, args) {
if(isReady) {
target[methodName].apply(target, args);
} else {
_delayedExecuteEvents.push({
"target": target,
"methodName": methodName,
"args": args
});
}
};
|
Fix python data provider test | # -*- coding: utf-8 -*-
import stromx.runtime as sr
stream = sr.Stream()
stream.setName("My stream")
data = "dfdsfdsds\nkljkljkfldsjf"
factory = sr.Factory()
with sr.ZipFileOutput("provider_test.zip") as out:
out.initialize("filename")
out.openFile(".txt", sr.OutputProvider.OpenMode.TEXT)
out.file().write(data)
sr.XmlWriter().writeStream(out, "stream", stream)
with sr.ZipFileInput("provider_test.zip") as inp:
inp.initialize("", "filename.txt")
inp.openFile(sr.InputProvider.OpenMode.TEXT)
data = inp.file().read()
stream = sr.XmlReader().readStream(inp, "stream.xml", factory)
print(stream.name())
print(data)
| # -*- coding: utf-8 -*-
import stromx.runtime as sr
stream = sr.Stream()
stream.setName("My stream")
data = "dfdsfdsds\nkljöklöjkfldsjf"
factory = sr.Factory()
with sr.ZipFileOutput("provider_test.zip") as out:
out.initialize("filename")
out.openFile(".txt", sr.OutputProvider.OpenMode.TEXT)
out.file().write(data)
sr.XmlWriter().writeStream(out, "stream", stream)
with sr.ZipFileInput("provider_test.zip") as inp:
inp.initialize("", "filename.txt")
inp.openFile(sr.InputProvider.OpenMode.TEXT)
data = inp.file().read()
stream = sr.XmlReader().readStream(inp, "stream.xml", factory)
print(stream.name())
print(data)
|
Allow to use $router in routes file | <?php namespace App\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider {
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
parent::boot($router);
//
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
$router->group(['namespace' => $this->namespace], function($router)
{
require app_path('Http/routes.php');
});
}
}
| <?php namespace App\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider {
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
parent::boot($router);
//
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
$router->group(['namespace' => $this->namespace], function()
{
require app_path('Http/routes.php');
});
}
}
|
feat(logger): Add date/time stamp to log output
The `"%d{DATE}"` in the log pattern adds a date and time stamp to log
lines.
So you get output like this from karma's logging:
```
30 06 2015 15:19:56.562:DEBUG [temp-dir]: Creating temp dir at /tmp/karma-43808925
```
The date and time are handy for figuring out if karma is running slowly. | var fs = require('fs')
var pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString())
exports.VERSION = pkg.version
exports.DEFAULT_PORT = process.env.PORT || 9876
exports.DEFAULT_HOSTNAME = process.env.IP || 'localhost'
// log levels
exports.LOG_DISABLE = 'OFF'
exports.LOG_ERROR = 'ERROR'
exports.LOG_WARN = 'WARN'
exports.LOG_INFO = 'INFO'
exports.LOG_DEBUG = 'DEBUG'
// Default patterns for the pattern layout.
exports.COLOR_PATTERN = '%[%d{DATE}:%p [%c]: %]%m'
exports.NO_COLOR_PATTERN = '%d{DATE}:%p [%c]: %m'
// Default console appender
exports.CONSOLE_APPENDER = {
type: 'console',
layout: {
type: 'pattern',
pattern: exports.COLOR_PATTERN
}
}
exports.EXIT_CODE = '\x1FEXIT'
| var fs = require('fs')
var pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString())
exports.VERSION = pkg.version
exports.DEFAULT_PORT = process.env.PORT || 9876
exports.DEFAULT_HOSTNAME = process.env.IP || 'localhost'
// log levels
exports.LOG_DISABLE = 'OFF'
exports.LOG_ERROR = 'ERROR'
exports.LOG_WARN = 'WARN'
exports.LOG_INFO = 'INFO'
exports.LOG_DEBUG = 'DEBUG'
// Default patterns for the pattern layout.
exports.COLOR_PATTERN = '%[%p [%c]: %]%m'
exports.NO_COLOR_PATTERN = '%p [%c]: %m'
// Default console appender
exports.CONSOLE_APPENDER = {
type: 'console',
layout: {
type: 'pattern',
pattern: exports.COLOR_PATTERN
}
}
exports.EXIT_CODE = '\x1FEXIT'
|
Add boolean return value to addProject | package com.example.beer.dao;
import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import com.example.beer.model.Project;
@Singleton
public class ProjectDAO {
@PersistenceContext
private EntityManager em;
public boolean addProject(Project project) {
Project foundProject = findProjectByName(project.getName());
if (foundProject != null) {
em.persist(project);
return true;
} else {
// TODO: Maybe update project title or users, or tasks?
return false;
}
}
public Project findProjectByName(String name) {
String idQueryText = "SELECT p FROM Project p WHERE p.name= :projectName";
TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
idQuery.setParameter("projectName", name);
try {
return idQuery.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
public Project findProjectById(int projectId) {
String idQueryText = "SELECT p FROM Project p WHERE p.id= :projectId";
TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
idQuery.setParameter("projectId", projectId);
try {
return idQuery.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
}
| package com.example.beer.dao;
import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import com.example.beer.model.Project;
@Singleton
public class ProjectDAO {
@PersistenceContext
private EntityManager em;
public void addProject(Project project) {
Project foundProject = findProjectByName(project.getName());
if (foundProject != null) {
em.persist(project);
} else {
// TODO: Maybe update project title or users, or tasks?
}
}
public Project findProjectByName(String name) {
String idQueryText = "SELECT p FROM Project p WHERE p.name= :projectName";
TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
idQuery.setParameter("projectName", name);
try {
return idQuery.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
public Project findProjectById(int projectId) {
String idQueryText = "SELECT p FROM Project p WHERE p.id= :projectId";
TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
idQuery.setParameter("projectId", projectId);
try {
return idQuery.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
}
|
Add an dummy import statement so that freeze programs pick up _internal.p
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@3807 94b884b6-d6fd-0310-90d3-974f1d3f35e1 |
from info import __doc__
from numpy.version import version as __version__
import multiarray
import umath
import _internal # for freeze programs
import numerictypes as nt
multiarray.set_typeDict(nt.sctypeDict)
import _sort
from numeric import *
from fromnumeric import *
from defmatrix import *
import ma
import defchararray as char
import records as rec
from records import *
from memmap import *
from defchararray import *
import scalarmath
del nt
from fromnumeric import amax as max, amin as min, \
round_ as round
from numeric import absolute as abs
__all__ = ['char','rec','memmap','ma']
__all__ += numeric.__all__
__all__ += fromnumeric.__all__
__all__ += defmatrix.__all__
__all__ += rec.__all__
__all__ += char.__all__
def test(level=1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
|
from info import __doc__
from numpy.version import version as __version__
import multiarray
import umath
import numerictypes as nt
multiarray.set_typeDict(nt.sctypeDict)
import _sort
from numeric import *
from fromnumeric import *
from defmatrix import *
import ma
import defchararray as char
import records as rec
from records import *
from memmap import *
from defchararray import *
import scalarmath
del nt
from fromnumeric import amax as max, amin as min, \
round_ as round
from numeric import absolute as abs
__all__ = ['char','rec','memmap','ma']
__all__ += numeric.__all__
__all__ += fromnumeric.__all__
__all__ += defmatrix.__all__
__all__ += rec.__all__
__all__ += char.__all__
def test(level=1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
|
Allow new version of requires | from setuptools import setup, find_packages
long_description = open('./README.rst').read()
setup(
name='ebi',
version='0.6.2',
install_requires=[
'awsebcli>=3.7.3,<4',
'boto3>==1.2.6,<2',
],
description='Simple CLI tool for ElasticBeanstalk with Docker',
long_description=long_description,
url='https://github.com/hirokiky/ebi',
author='Hiroki KIYOHARA',
author_email='hirokiky@gmail.com',
license='MIT',
packages=find_packages(),
entry_points={
'console_scripts': [
'ebi = ebi.core:main',
]
}
)
| from setuptools import setup, find_packages
long_description = open('./README.rst').read()
setup(
name='ebi',
version='0.6.2',
install_requires=[
'awsebcli==3.7.3',
'boto3==1.2.6',
],
description='Simple CLI tool for ElasticBeanstalk with Docker',
long_description=long_description,
url='https://github.com/hirokiky/ebi',
author='Hiroki KIYOHARA',
author_email='hirokiky@gmail.com',
license='MIT',
packages=find_packages(),
entry_points={
'console_scripts': [
'ebi = ebi.core:main',
]
}
)
|
Drop TODO for getVmVersion method
Review URL: https://codereview.chromium.org/12324002
git-svn-id: 1dc80909446f7a7ee3e21dd4d1b8517df524e9ee@1139 fc8a088e-31da-11de-8fef-1f5ae417a2df | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.sdk;
import java.io.IOException;
import org.chromium.sdk.util.MethodIsBlockingException;
/**
* Abstraction of a remote JavaScript virtual machine which is embedded into
* some application and accessed via TCP/IP connection to a port opened by
* DebuggerAgent. Clients can use it to conduct debugging process.
*/
public interface StandaloneVm extends JavascriptVm {
/**
* Connects to the target VM.
*
* @param listener to report the debug events to
* @throws IOException if there was a transport layer error
* @throws UnsupportedVersionException if the SDK protocol version is not
* compatible with that supported by the browser
* @throws MethodIsBlockingException because initialization implies couple of remote calls
* (to request version etc)
*/
void attach(DebugEventListener listener)
throws IOException, UnsupportedVersionException, MethodIsBlockingException;
/**
* @return name of embedding application as it wished to name itself; might be null
*/
String getEmbedderName();
/**
* This version should correspond to {@link JavascriptVm#getVersion()}. However it gets available
* earlier, at the transport handshake stage.
* @return version of V8 implementation, format is unspecified; must not be null if
* {@link StandaloneVm} has been attached
*/
String getVmVersion();
/**
* @return message explaining why VM is detached; may be null
*/
String getDisconnectReason();
}
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.sdk;
import java.io.IOException;
import org.chromium.sdk.util.MethodIsBlockingException;
/**
* Abstraction of a remote JavaScript virtual machine which is embedded into
* some application and accessed via TCP/IP connection to a port opened by
* DebuggerAgent. Clients can use it to conduct debugging process.
*/
public interface StandaloneVm extends JavascriptVm {
/**
* Connects to the target VM.
*
* @param listener to report the debug events to
* @throws IOException if there was a transport layer error
* @throws UnsupportedVersionException if the SDK protocol version is not
* compatible with that supported by the browser
* @throws MethodIsBlockingException because initialization implies couple of remote calls
* (to request version etc)
*/
void attach(DebugEventListener listener)
throws IOException, UnsupportedVersionException, MethodIsBlockingException;
/**
* @return name of embedding application as it wished to name itself; might be null
*/
String getEmbedderName();
/**
* @return version of V8 implementation, format is unspecified; must not be null if
* {@link StandaloneVm} has been attached
*/
// TODO: align this with {@link JavascriptVm#getVersion()} method.
String getVmVersion();
/**
* @return message explaining why VM is detached; may be null
*/
String getDisconnectReason();
}
|
Fix build errors with Python <3.6
The `ModuleNotFoundError` was introduced in Python 3.6. | # -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright © 2014-2016 Tim Bielawa <timbielawa@gmail.com>
# See GitHub Contributors Graph for more information
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sub-license, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Kept for backward compatibilty
from .argparse import BitmathType
try:
from .progressbar import BitmathFileTransferSpeed
except ImportError:
# Ignore missing dependency as argparse integration will fail if
# progressbar is not installed (#86).
pass
| # -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright © 2014-2016 Tim Bielawa <timbielawa@gmail.com>
# See GitHub Contributors Graph for more information
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sub-license, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Kept for backward compatibilty
from .argparse import BitmathType
try:
from .progressbar import BitmathFileTransferSpeed
except ModuleNotFoundError:
# Ignore missing dependency as argparse integration will fail if
# progressbar is not installed (#86).
pass
|
Replace calculation codes to use ScrollUtils in FillGap2 examples. | /*
* Copyright 2014 Soichiro Kashima
*
* 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 com.github.ksoichiro.android.observablescrollview.samples;
import com.github.ksoichiro.android.observablescrollview.ScrollUtils;
import com.github.ksoichiro.android.observablescrollview.Scrollable;
/**
* Almost same as FillGapBaseActivity,
* but in this activity, when swiping up, the filled space shrinks
* and the header bar moves to the top.
*/
public abstract class FillGap2BaseActivity<S extends Scrollable> extends FillGapBaseActivity<S> {
protected float getHeaderTranslationY(int scrollY) {
return ScrollUtils.getFloat(-scrollY + mFlexibleSpaceImageHeight - mHeaderBar.getHeight(), 0, Float.MAX_VALUE);
}
}
| /*
* Copyright 2014 Soichiro Kashima
*
* 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 com.github.ksoichiro.android.observablescrollview.samples;
import com.github.ksoichiro.android.observablescrollview.Scrollable;
/**
* Almost same as FillGapBaseActivity,
* but in this activity, when swiping up, the filled space shrinks
* and the header bar moves to the top.
*/
public abstract class FillGap2BaseActivity<S extends Scrollable> extends FillGapBaseActivity<S> {
protected float getHeaderTranslationY(int scrollY) {
final int headerHeight = mHeaderBar.getHeight();
int headerTranslationY = 0;
if (0 <= -scrollY + mFlexibleSpaceImageHeight - headerHeight) {
headerTranslationY = -scrollY + mFlexibleSpaceImageHeight - headerHeight;
}
return headerTranslationY;
}
}
|
Add todo about minor duplication. | package com.adaptionsoft.games.uglytrivia;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.mock;
public class PlayersTest {
public static final String PLAYER_ONE = "Thomas";
public static final String PLAYER_TWO = "Peter";
public static final String ANY_PLAYER = "Erik";
// TODO minor duplication in all Player tests for creating the Players instance.
private PlayerUI ui = mock(PlayerUI.class);
private Players players = new Players(ui);
@Before
public void addPlayers() {
players.add(PLAYER_ONE);
players.add(PLAYER_TWO);
}
@Test
public void shouldAddOnePlayer() {
assertThat(players.size(), is(2));
players.add(TestPlayer.named(ANY_PLAYER));
assertThat(players.size(), is(3));
}
@Test(expected = IllegalAccessException.class)
@Ignore("not implemented")
public void shouldFailForMoreThanSixPlayers() {
players.add(ANY_PLAYER);
players.add(ANY_PLAYER);
players.add(ANY_PLAYER);
players.add(ANY_PLAYER);
players.add("one too many");
}
}
| package com.adaptionsoft.games.uglytrivia;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.mock;
public class PlayersTest {
public static final String PLAYER_ONE = "Thomas";
public static final String PLAYER_TWO = "Peter";
public static final String ANY_PLAYER = "Erik";
private PlayerUI ui = mock(PlayerUI.class);
private Players players = new Players(ui);
@Before
public void addPlayers() {
players.add(PLAYER_ONE);
players.add(PLAYER_TWO);
}
@Test
public void shouldAddOnePlayer() {
assertThat(players.size(), is(2));
players.add(TestPlayer.named(ANY_PLAYER));
assertThat(players.size(), is(3));
}
@Test(expected = IllegalAccessException.class)
@Ignore("not implemented")
public void shouldFailForMoreThanSixPlayers() {
players.add(ANY_PLAYER);
players.add(ANY_PLAYER);
players.add(ANY_PLAYER);
players.add(ANY_PLAYER);
players.add("one too many");
}
}
|
Use reverse function for urls in carusele app | from django.core.urlresolvers import reverse
from django.db import models
class News (models.Model):
"""
News model represent detail description and
content of each carusele element.
"""
title = models.CharField(max_length=400)
description = models.TextField(default="")
content = models.TextField()
pubdate = models.DateTimeField()
image = models.ImageField(upload_to="media")
def __unicode__(self):
return unicode(self.title)
def get_absolute_url(self):
return reverse("article", args=(self.id,))
class Element (models.Model):
"""
This model presents picture and short description
of news in carusele javascript element on main page.
"""
description = models.CharField(max_length=400)
image = models.ImageField(upload_to="media")
news = models.OneToOneField("News")
def __unicode__(self):
return unicode(self.description)
| from django.db import models
class News (models.Model):
"""
News model represent detail description and
content of each carusele element.
"""
title = models.CharField(max_length=400)
description = models.TextField(default="")
content = models.TextField()
pubdate = models.DateTimeField()
image = models.ImageField(upload_to="media")
def __unicode__(self):
return unicode(self.title)
def get_absolute_url(self):
return "/carusele/art/%i/" % self.id
class Element (models.Model):
"""
This model presents picture and short description
of news in carusele javascript element on main page.
"""
description = models.CharField(max_length=400)
image = models.ImageField(upload_to="media")
news = models.OneToOneField("News")
def __unicode__(self):
return unicode(self.description)
|
Add a NotAuthorized error object | // Create a not found error object. This should at some point inherit
// from a HTTPError object with a nice .toJSON() method that can be
// used directly by handlers.
function HTTPError(status, message) {
Error.call(this, message);
// Remove the Error itself from the stack trace.
// http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.status = status;
this.message = message || '';
}
HTTPError.prototype = Object.create(Error.prototype);
HTTPError.prototype = Object.create(HTTPError.prototype);
function NotFound(message) {
Error.call(this, 404, message);
}
NotFound.prototype = Object.create(HTTPError.prototype);
module.exports.NotFound = NotFound;
function NotAuthorized(message) {
Error.call(this, 401, message);
}
NotAuthorized.prototype = Object.create(HTTPError.prototype);
module.exports.NotFound = NotFound;
function BadRequest(message) {
HTTPError.call(this, 400, message);
}
BadRequest.prototype = Object.create(HTTPError.prototype);
module.exports.BadRequest = BadRequest;
| // Create a not found error object. This should at some point inherit
// from a HTTPError object with a nice .toJSON() method that can be
// used directly by handlers.
function HTTPError(status, message) {
Error.call(this, message);
// Remove the Error itself from the stack trace.
// http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.status = status;
this.message = message || '';
}
HTTPError.prototype = Object.create(Error.prototype);
HTTPError.prototype = Object.create(HTTPError.prototype);
function NotFound(message) {
Error.call(this, 404, message);
}
NotFound.prototype = Object.create(HTTPError.prototype);
module.exports.NotFound = NotFound;
function BadRequest(message) {
HTTPError.call(this, 400, message);
}
BadRequest.prototype = Object.create(HTTPError.prototype);
module.exports.BadRequest = BadRequest;
|
Set name field on save | from django.db import models
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailcore.models import Page
from wagtail.wagtailimages.edit_handlers import ImageChooserPanel
class Category(Page):
"""
The Oscars Category as a Wagtail Page
This works because they both use Treebeard
"""
name = models.CharField(_('Name'), max_length=255, db_index=True)
description = models.TextField(_('Description'), blank=True)
image = models.ForeignKey(
'wagtailimages.Image',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
content_panels = Page.content_panels + [
FieldPanel('description', classname='full'),
ImageChooserPanel('image')
]
def save(self, *args, **kwargs):
self.name = self.title
super(Category, self).save(*args, **kwargs)
from oscar.apps.catalogue.models import * # noqa
| from django.db import models
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailcore.models import Page
from wagtail.wagtailimages.edit_handlers import ImageChooserPanel
class Category(Page):
"""
The Oscars Category as a Wagtail Page
This works because they both use Treebeard
"""
name = models.CharField(_('Name'), max_length=255, db_index=True)
description = models.TextField(_('Description'), blank=True)
image = models.ForeignKey(
'wagtailimages.Image',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
content_panels = Page.content_panels + [
FieldPanel('name', classname='full'),
FieldPanel('description', classname='full'),
ImageChooserPanel('image')
]
from oscar.apps.catalogue.models import * # noqa
|
Make utility constructor truly uninstantiable | /*
* Copyright 2012 - 2014 Maginatics, 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.
*/
package com.maginatics.jdbclint;
import java.sql.SQLException;
/** Utility methods. */
final class Utils {
private Utils() {
throw new AssertionError("intentionally unimplemented");
}
static void fail(final Configuration config, final Exception exception,
final String message) throws SQLException {
for (Configuration.Action action : config.getActions()) {
action.apply(message, exception);
}
}
static <T> T checkNotNull(final T obj) {
if (obj == null) {
throw new NullPointerException();
}
return obj;
}
}
| /*
* Copyright 2012 - 2014 Maginatics, 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.
*/
package com.maginatics.jdbclint;
import java.sql.SQLException;
/** Utility methods. */
final class Utils {
private Utils() {
// intentionally unimplemented
}
static void fail(final Configuration config, final Exception exception,
final String message) throws SQLException {
for (Configuration.Action action : config.getActions()) {
action.apply(message, exception);
}
}
static <T> T checkNotNull(final T obj) {
if (obj == null) {
throw new NullPointerException();
}
return obj;
}
}
|
Load the ffi extensions *after* setting module.exports | // The main exports is the casting function
module.exports = $
$._ = $ // legacy. TODO: remove by 0.1.0
// Load the node-ffi extensions
require('./ffi-extend')
// export the exports from the 'import' module
var Import = require('./import')
$.import = Import.import
$.resolve = Import.resolve
// This function accepts native JS types (String, Number, Date) and converts them
// to the proper Objective-C type (NSString, NSNumber, NSDate).
// Syntax Sugar...
function $ (o) {
var t = typeof o
if (t == 'string') {
return $.NSString('stringWithUTF8String', String(o))
} else if (t == 'number') {
return $.NSNumber('numberWithDouble', Number(o))
} else if (isDate(o)) {
return $.NSDate('dateWithTimeIntervalSince1970', o / 1000)
}
throw new Error('Unsupported object passed in to convert: ' + o)
}
function isDate (d) {
return d instanceof Date
|| Object.prototype.toString.call(d) == '[object Date]'
}
| // Load the node-ffi extensions
require('./ffi-extend')
// The main exports is the casting function
module.exports = $
$._ = $ // legacy. TODO: remove by 0.1.0
// export the exports from the 'import' module
var Import = require('./import')
$.import = Import.import
$.resolve = Import.resolve
// This function accepts native JS types (String, Number, Date) and converts them
// to the proper Objective-C type (NSString, NSNumber, NSDate).
// Syntax Sugar...
function $ (o) {
var t = typeof o
if (t == 'string') {
return $.NSString('stringWithUTF8String', String(o))
} else if (t == 'number') {
return $.NSNumber('numberWithDouble', Number(o))
} else if (isDate(o)) {
return $.NSDate('dateWithTimeIntervalSince1970', o / 1000)
}
throw new Error('Unsupported object passed in to convert: ' + o)
}
function isDate (d) {
return d instanceof Date
|| Object.prototype.toString.call(d) == '[object Date]'
}
|
Make main dashboard slightly better | <?php
require_once('config.php');
global $config;
require_once('page_template_dash_head.php');
require_once('page_template_dash_sidebar.php');
?>
<div class="content-wrapper">
<section class="content-header">
<h1>
Dashboard
</h1>
<ol class="breadcrumb">
<li class="active"><a href="#"><i class="fa fa-dashboard"></i> Dashboard</a></li>
</ol>
</section>
<section class="content">
<!-- Your Page Content Here -->
</section>
</div>
<?php
require_once('page_template_dash_foot.php');
?> | <?php
require_once('config.php');
global $config;
require_once('page_template_dash_head.php');
require_once('page_template_dash_sidebar.php');
?>
<div class="content-wrapper">
<section class="content-header">
<h1>
Page Header
<small>Optional description</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Level</a></li>
<li class="active">Here</li>
</ol>
</section>
<section class="content">
<!-- Your Page Content Here -->
</section>
</div>
<?php
require_once('page_template_dash_foot.php');
?> |
Use Synchronizer to serialise access to the cache | /*
* Copyright 2011 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.cache;
import org.gradle.api.internal.Factory;
import org.gradle.api.internal.Synchronizer;
public class CacheAccessSerializer<K, V> implements Cache<K, V> {
final private Synchronizer synchronizer = new Synchronizer();
final private Cache<K, V> cache;
public CacheAccessSerializer(Cache<K, V> cache) {
this.cache = cache;
}
public <T extends K> V get(final T key, final Factory<? extends V> factory) {
return synchronizer.synchronize(new Factory<V>() {
public V create() {
return cache.get(key, factory);
}
});
}
} | /*
* Copyright 2011 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.cache;
import org.gradle.api.internal.Factory;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class CacheAccessSerializer<K, V> implements Cache<K, V> {
final private Lock lock = new ReentrantLock();
final private Cache<K, V> cache;
public CacheAccessSerializer(Cache<K, V> cache) {
this.cache = cache;
}
public <T extends K> V get(T key, Factory<? extends V> factory) {
lock.lock();
try {
return cache.get(key, factory);
} finally {
lock.unlock();
}
}
} |
Remove intersphinx extension from documentation. | import os
import maec
project = u'python-maec'
copyright = u'2014, The MITRE Corporation'
version = maec.__version__
release = version
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.ifconfig',
'sphinx.ext.viewcode',
'sphinx.ext.napoleon',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
rst_prolog = """
**Version**: {0}
""".format(release)
exclude_patterns = [
'_build',
'api_vs_bindings/*_snippet.rst',
]
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd:
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
else:
html_theme = 'default'
latex_elements = {}
latex_documents = [
('index', 'python-maec.tex', u'python-maec Documentation',
u'The MITRE Corporation', 'manual'),
]
| import os
import maec
project = u'python-maec'
copyright = u'2014, The MITRE Corporation'
version = maec.__version__
release = version
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.ifconfig',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
'sphinx.ext.napoleon',
]
intersphinx_mapping = {
'python': ('http://docs.python.org/', None),
}
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
rst_prolog = """
**Version**: {0}
""".format(release)
exclude_patterns = [
'_build',
'api_vs_bindings/*_snippet.rst',
]
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd:
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
else:
html_theme = 'default'
latex_elements = {}
latex_documents = [
('index', 'python-maec.tex', u'python-maec Documentation',
u'The MITRE Corporation', 'manual'),
]
|
Fix stoptimes in range function to actually take a full blown address | from django.conf.urls.defaults import *
from django.conf import settings
import os
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'routez.travel.views.main_page'),
(r'^iphone$', 'routez.travel.views.iphone'),
(r'^about$', 'routez.travel.views.about'),
(r'^help$', 'routez.travel.views.help'),
(r'^privacy$', 'routez.travel.views.privacy'),
(r'^json/routeplan$', 'routez.travel.views.routeplan'),
(r'^stoptimes_for_stop/(\d{4})/(\d+)$',
'routez.stop.views.stoptimes_for_stop'),
(r'^stoptimes_in_range/([^/]+)/(\d+)$',
'routez.stop.views.stoptimes_in_range')
# Uncomment this for admin:
#(r'^admin/(.*)', admin.site.root),
)
# Only serve media from Django in debug mode. In non-debug mode, the regular
# web server should do this.
if settings.DEBUG:
urlpatterns += patterns('',
(r'^site_media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': os.path.join(settings.PROJECT_PATH, 'site_media'),
'show_indexes': True}),
)
| from django.conf.urls.defaults import *
from django.conf import settings
import os
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'routez.travel.views.main_page'),
(r'^iphone$', 'routez.travel.views.iphone'),
(r'^about$', 'routez.travel.views.about'),
(r'^help$', 'routez.travel.views.help'),
(r'^privacy$', 'routez.travel.views.privacy'),
(r'^json/routeplan$', 'routez.travel.views.routeplan'),
(r'^stoptimes_for_stop/(\d{4})/(\d+)$',
'routez.stop.views.stoptimes_for_stop'),
(r'^stoptimes_in_range/(\w+)/(\d+)$',
'routez.stop.views.stoptimes_in_range')
# Uncomment this for admin:
#(r'^admin/(.*)', admin.site.root),
)
# Only serve media from Django in debug mode. In non-debug mode, the regular
# web server should do this.
if settings.DEBUG:
urlpatterns += patterns('',
(r'^site_media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': os.path.join(settings.PROJECT_PATH, 'site_media'),
'show_indexes': True}),
)
|
Add token type to test id | from tests.test import Test
def pytest_addoption(parser):
parser.addoption('--transport-urls', action='store', help='Transport urls')
parser.addoption('--admin-refresh-token', action='store',
help='Admin refresh tokens')
parser.addoption('--user-refresh-token', action='store',
help='User refresh tokens')
def pytest_generate_tests(metafunc):
if metafunc.module.__name__.find('.test_api') == -1:
return
transport_urls = metafunc.config.option.transport_urls.split(',')
refresh_tokens = {'admin': metafunc.config.option.admin_refresh_token,
'user': metafunc.config.option.user_refresh_token}
tests = []
ids = []
for transport_url in transport_urls:
for token_type, refresh_token in refresh_tokens.items():
if not refresh_token:
continue
tests.append(Test(transport_url, refresh_token, token_type))
ids.append('%s:%s' % (token_type, transport_url))
metafunc.parametrize('test', tests, ids=ids)
| from tests.test import Test
def pytest_addoption(parser):
parser.addoption('--transport-urls', action='store', help='Transport urls')
parser.addoption('--admin-refresh-token', action='store',
help='Admin refresh tokens')
parser.addoption('--user-refresh-token', action='store',
help='User refresh tokens')
def pytest_generate_tests(metafunc):
if metafunc.module.__name__.find('.test_api') == -1:
return
transport_urls = metafunc.config.option.transport_urls.split(',')
refresh_tokens = {'admin': metafunc.config.option.admin_refresh_token,
'user': metafunc.config.option.user_refresh_token}
tests = []
ids = []
for transport_url in transport_urls:
for token_type, refresh_token in refresh_tokens.items():
if not refresh_token:
continue
tests.append(Test(transport_url, refresh_token, token_type))
ids.append(transport_url)
metafunc.parametrize('test', tests, ids=ids)
|
Add failing test to check if workflow is working | package com.github.paweladamski.httpclientmock;
import static com.github.paweladamski.httpclientmock.matchers.HttpResponseMatchers.hasStatus;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.hamcrest.Matchers;
import org.junit.Test;
public class HttpClientMockTest {
@Test
public void should_run_requestInterceptors() throws IOException {
HttpClientMock httpClientMock = new HttpClientMock();
httpClientMock.addRequestInterceptor((request,context)->request.addHeader("foo","bar"));
httpClientMock.onGet().withHeader("foo","bar").doReturn("ok");
HttpResponse ok = httpClientMock.execute(new HttpGet("http://localhost"));
assertThat(ok, hasStatus(200));
}
@Test
public void should_run_responseInterceptors() throws IOException {
HttpClientMock httpClientMock = new HttpClientMock();
httpClientMock.addResponseInterceptor((request,context)->request.addHeader("foo","bar"));
httpClientMock.onGet().doReturn("ok");
HttpResponse ok = httpClientMock.execute(new HttpGet("http://localhost"));
assertThat(ok.getFirstHeader("foo").getValue(), equalTo("bar2"));
}
}
| package com.github.paweladamski.httpclientmock;
import static com.github.paweladamski.httpclientmock.matchers.HttpResponseMatchers.hasStatus;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.hamcrest.Matchers;
import org.junit.Test;
public class HttpClientMockTest {
@Test
public void should_run_requestInterceptors() throws IOException {
HttpClientMock httpClientMock = new HttpClientMock();
httpClientMock.addRequestInterceptor((request,context)->request.addHeader("foo","bar"));
httpClientMock.onGet().withHeader("foo","bar").doReturn("ok");
HttpResponse ok = httpClientMock.execute(new HttpGet("http://localhost"));
assertThat(ok, hasStatus(200));
}
@Test
public void should_run_responseInterceptors() throws IOException {
HttpClientMock httpClientMock = new HttpClientMock();
httpClientMock.addResponseInterceptor((request,context)->request.addHeader("foo","bar"));
httpClientMock.onGet().doReturn("ok");
HttpResponse ok = httpClientMock.execute(new HttpGet("http://localhost"));
assertThat(ok.getFirstHeader("foo").getValue(), equalTo("bar"));
}
}
|
Fix adjective and number count to match the updated lists. | var fs = require("fs");
var path = require("path");
var _ = require("lodash");
var animals;
var adjectives;
module.exports = function () {
if (animals && adjectives) {
return { animals : animals, adjectives : adjectives };
}
adjectives = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "lists", "adjectives.json")));
animals = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "lists", "animals.json")));
_.each(adjectives, function (word, idx) { adjectives[idx] = word.toLowerCase(); });
_.each(animals, function (word, idx) { animals[idx] = word.toLowerCase(); });
return { adjectives : adjectives, animals : animals };
};NUM_
module.exports.NUM_ADJECTIVES = 1500;
module.exports.NUM_ANIMALS = 1750; | var fs = require("fs");
var path = require("path");
var _ = require("lodash");
var animals;
var adjectives;
module.exports = function () {
if (animals && adjectives) {
return { animals : animals, adjectives : adjectives };
}
adjectives = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "lists", "adjectives.json")));
animals = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "lists", "animals.json")));
_.each(adjectives, function (word, idx) { adjectives[idx] = word.toLowerCase(); });
_.each(animals, function (word, idx) { animals[idx] = word.toLowerCase(); });
return { adjectives : adjectives, animals : animals };
};
module.exports.NUM_ADJECTIVES = 8981;
module.exports.NUM_ANIMALS = 590; |
Fix conf parsing on linux | package com.github.alexvictoor.proxy;
import java.io.File;
public class FileSystemRoute {
private final String uriPrefix;
private final File directory;
private FileSystemRoute(String uriPrefix, File directory) {
this.uriPrefix = uriPrefix;
this.directory = directory;
}
public static FileSystemRoute create(String uriPrefix, String path) {
File directory = new File(path);
if (!directory.exists() || !directory.canRead() || !directory.isDirectory()) {
throw new RuntimeException(path + " is not a path to a readable directory");
}
return new FileSystemRoute(uriPrefix, directory);
}
public static FileSystemRoute parse(String input) {
String[] tokens = input.split("\\|");
String prefix = tokens[0].trim();
String path = tokens[1].trim();
return create(prefix, path);
}
public File findFile(String uri) {
if (uri ==null || !uri.startsWith(uriPrefix)) {
return null;
}
String relativePath = uri.substring(uriPrefix.length() + 1).replace('/', File.separatorChar);
File file = new File(directory, relativePath);
return file;
}
}
| package com.github.alexvictoor.proxy;
import java.io.File;
public class FileSystemRoute {
private final String uriPrefix;
private final File directory;
private FileSystemRoute(String uriPrefix, File directory) {
this.uriPrefix = uriPrefix;
this.directory = directory;
}
public static FileSystemRoute create(String uriPrefix, String path) {
File directory = new File(path);
if (!directory.exists() || !directory.canRead() || !directory.isDirectory()) {
throw new RuntimeException(path + " is not a path to a readable directory");
}
return new FileSystemRoute(uriPrefix, directory);
}
public static FileSystemRoute parse(String input) {
String[] tokens = input.split("\\|");
return create(tokens[0], tokens[1]);
}
public File findFile(String uri) {
if (uri ==null || !uri.startsWith(uriPrefix)) {
return null;
}
String relativePath = uri.substring(uriPrefix.length() + 1).replace('/', File.separatorChar);
File file = new File(directory, relativePath);
return file;
}
}
|
Change the version number to 3.0
The most notable change from 2.0 is the new initializer. | #!/usr/bin/env python
from setuptools import setup
setup(name='programmabletuple',
version='0.3.0',
description='Python metaclass for making named tuples with programmability',
long_description=open('README.rst').read(),
author='Tschijnmo TSCHAU',
author_email='tschijnmotschau@gmail.com',
url='https://github.com/tschijnmo/programmabletuple',
license='MIT',
packages=['programmabletuple', ],
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| #!/usr/bin/env python
from setuptools import setup
setup(name='programmabletuple',
version='0.2.0',
description='Python metaclass for making named tuples with programmability',
long_description=open('README.rst').read(),
author='Tschijnmo TSCHAU',
author_email='tschijnmotschau@gmail.com',
url='https://github.com/tschijnmo/programmabletuple',
license='MIT',
packages=['programmabletuple', ],
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Clean up Quote model code | from django.db import models
from django.contrib.auth.models import User
from django.utils.text import truncate_words
from automatic_timestamps.models import TimestampModel
class Chat(TimestampModel):
"""
A collection of chat items (quotes), ordered by their created_at values,
grouped together like a chat history. All quotes that belong to a Chat are
not displayable on an individual basis.
"""
title = models.CharField(max_length=200)
class Quote(TimestampModel):
"""
A quote is a single-line text excerpt from a chat (usually purposefully
out of context) belonging to a certain user. It is often view-restricted to
specific groups.
"""
# Most Quotes likely don't have a related Chat object.
chat = models.ForeignKey(Chat, blank=True, null=True)
# A quote without any associated Friend Groups is considered public and will
# be viewable to the entire world!
friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True)
text = models.CharField(max_length=1000)
user = models.ForeignKey(User)
def __unicode__(self):
"""
Return the name of the quote's authoor and text found inside
this quote.
"""
return u"{author}: {text_excerpt}".format(
author=self.user.username,
text_excerpt=self.text# truncate_words(self.text, 5)
)
| from django.db import models
from django.contrib.auth.models import User
from django.utils.text import truncate_words
from automatic_timestamps.models import TimestampModel
class Chat(TimestampModel):
"""
A collection of chat items (quotes), ordered by their created_at values,
grouped together like a chat history. All quotes that belong to a Chat are
not displayable on an individual basis.
"""
title = models.CharField(max_length=200)
class Quote(TimestampModel):
"""
A quote is a single-line text excerpt from a chat (usually purposefully
out of context) belonging to a certain user. It is often view-restricted to
specific groups.
"""
# Chat relationships are nullable; most Quotes likely don't have a related
# Chat object.
chat = models.ForeignKey(Chat, blank=True, null=True)
# A quote without any associated Friend Groups is considered public and will
# be viewable to the entire world!
friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True)
text = models.CharField(max_length=1000)
user = models.ForeignKey(User)
def __unicode__(self):
"""
Return the text found inside this quote.
"""
return u"{name}: {text_excerpt}".format(
name=self.user.username,
text_excerpt=self.text# truncate_words(self.text, 5)
)
|
Mark if a question has been answered | import DS from 'ember-data';
let Prompt = DS.Model.extend({
step: DS.belongsTo('step'),
question: DS.attr('string'), //our prompt
answer: DS.attr('string'), // their answer
clause: DS.attr('string'),
isAnswered: DS.attr('boolean'),
});
let data = [
{step: 1, prompts: ['My business is called %businessName'] },
{step: 2, prompts: ['How will the weather be tomorrow? %weather'] },
{step: 3, prompts: ['Do you use google adsense? %goodle-adsense', 'Do you use Amazon Web Services? %amazon'] },
{step: 4, prompts: ['Where do you store the data collected? %data-collected']}
];
//Turn the data above into the format that ember fixtures wants
var fixtures = [];
var id_number = 0;
for (let step of data) {
id_number +=1;
let step_number = step.step;
let prompts = step.prompts;
for (let question of prompts) {
fixtures.push({id: id_number, question: question, step: step_number});
}
}
Prompt.reopenClass({
FIXTURES: fixtures
});
export default Prompt;
| import DS from 'ember-data';
let Prompt = DS.Model.extend({
step: DS.belongsTo('step'),
question: DS.attr('string'), //our prompt
answer: DS.attr('string'), // their answer
clause: DS.attr('string')
});
let data = [
{step: 1, prompts: ['My business is called %businessName'] },
{step: 2, prompts: ['How will the weather be tomorrow? %weather'] },
{step: 3, prompts: ['Do you use google adsense? %goodle-adsense', 'Do you use Amazon Web Services? %amazon'] },
{step: 4, prompts: ['Where do you store the data collected? %data-collected']}
];
//Turn the data above into the format that ember fixtures wants
var fixtures = [];
var id_number = 0;
for (let step of data) {
id_number +=1;
let step_number = step.step;
let prompts = step.prompts;
for (let question of prompts) {
fixtures.push({id: id_number, question: question, step: step_number});
}
}
console.log(fixtures);
Prompt.reopenClass({
FIXTURES: fixtures
});
export default Prompt;
|
Modify add_occupant method to raise exception in case of a duplicate | class Room(object):
def __init__(self, room_name, room_type, max_persons):
self.room_name = room_name
self.room_type = room_type
self.max_persons = max_persons
self.persons = []
def add_occupant(self, person):
if person not in self.persons:
if len(self.persons) < self.max_persons:
self.persons.append(person)
print (person.person_type.title() + " " + person.person_name.title() + " " + person.person_surname.title() + " has been allocated " + self.room_type + " " + self.room_name.title())
else:
raise Exception(self.room_type.title() + " " + self.room_name.title() + " is at full capacity")
else:
raise Exception(person.person_type.title() + " " + person.person_name.title() + " " + person.person_surname.title() + " is already among the occupants in " + self.room_type + " " + self.room_name.title())
| class Room(object):
def __init__(self, room_name, room_type, max_persons):
self.room_name = room_name
self.room_type = room_type
self.max_persons = max_persons
self.persons = []
def add_occupant(self, person):
if len(self.persons) < self.max_persons:
self.persons.append(person)
print (person.person_type.title() + " " + person.person_name.title() + " " + person.person_surname.title() + " has been allocated " + self.room_type + " " + self.room_name.title())
else:
raise Exception(self.room_type.title() + " " + self.room_name.title() + " is at full capacity")
|
Remove iPhone scrollbar onload script
Sometimes jilts the page back to top if you've already scrolled down. Not a necessary feature. | // DOM Ready
$(function() {
// www.conditionizr.com
// Legacy content and retina scripts and styles
$('head').conditionizr({
ieLessThan : {
active: true,
version: '9',
scripts: false,
styles: false,
classes: true,
customScript: 'WORDPRESS_THEME_DIRECTORY_HERE/js/mediaqueries.min.js'
}
});
// SVG custom feature detection and svg to png fallback
// toddmotto.com/mastering-svg-use-for-a-retina-web-fallbacks-with-png-script#update
function supportsSVG() {
return !! document.createElementNS && !! document.createElementNS('http://www.w3.org/2000/svg','svg').createSVGRect;
}
if (supportsSVG()) {
document.documentElement.className += ' svg';
} else {
document.documentElement.className += ' no-svg';
var imgs = document.getElementsByTagName('img'),
dotSVG = /.*\.svg$/;
for (var i = 0; i != imgs.length; ++i) {
if(imgs[i].src.match(dotSVG)) {
imgs[i].src = imgs[i].src.slice(0, -3) + "png";
}
}
}
});
| // DOM Ready
$(function() {
// www.conditionizr.com
// Legacy content and retina scripts and styles
$('head').conditionizr({
ieLessThan : {
active: true,
version: '9',
scripts: false,
styles: false,
classes: true,
customScript: 'WORDPRESS_THEME_DIRECTORY_HERE/js/mediaqueries.min.js'
}
});
// SVG custom feature detection and svg to png fallback
// toddmotto.com/mastering-svg-use-for-a-retina-web-fallbacks-with-png-script#update
function supportsSVG() {
return !! document.createElementNS && !! document.createElementNS('http://www.w3.org/2000/svg','svg').createSVGRect;
}
if (supportsSVG()) {
document.documentElement.className += ' svg';
} else {
document.documentElement.className += ' no-svg';
var imgs = document.getElementsByTagName('img'),
dotSVG = /.*\.svg$/;
for (var i = 0; i != imgs.length; ++i) {
if(imgs[i].src.match(dotSVG)) {
imgs[i].src = imgs[i].src.slice(0, -3) + "png";
}
}
}
// iPhone Safari URL bar hides itself on pageload
if (navigator.userAgent.indexOf('iPhone') != -1) {
addEventListener("load", function () {
setTimeout(hideURLbar, 0);
}, false);
}
function hideURLbar() {
window.scrollTo(0, 0);
}
});
|
Clean play code for GStreamer | import logging
import gst
from mopidy import config
from mopidy.backends import BaseBackend
from mopidy.models import Artist, Album, Track, Playlist
logger = logging.getLogger(u'backends.gstreamer')
class GStreamerBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(GStreamerBackend, self).__init__(*args, **kwargs)
playlist = []
player = gst.element_factory_make("playbin2", "player")
fakesink = gst.element_factory_make("fakesink", "fakesink")
player.set_property("video-sink", fakesink)
self.player = player
def _play(self):
if self._current_track is None:
return False
self.player.set_property("uri", self._current_track.uri)
self.player.set_state(gst.STATE_PLAYING)
return True
def _stop(self):
self.player.set_state(gst.STATE_NULL)
return True
| import logging
import gst
from mopidy import config
from mopidy.backends import BaseBackend
from mopidy.models import Artist, Album, Track, Playlist
logger = logging.getLogger(u'backends.gstreamer')
class GStreamerBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(GStreamerBackend, self).__init__(*args, **kwargs)
playlist = []
player = gst.element_factory_make("playbin2", "player")
fakesink = gst.element_factory_make("fakesink", "fakesink")
player.set_property("video-sink", fakesink)
self.player = player
def _play_current_track(self):
self.player.set_property("uri", self._current_track.uri)
self.player.set_state(gst.STATE_PLAYING)
def _play(self):
if self._current_track is not None:
self._play_current_track()
return True
else:
return False
def _stop(self):
self.player.set_state(gst.STATE_NULL)
return True
|
Correct typo in bashbrew push --namespace message | package main
import (
"fmt"
"github.com/codegangsta/cli"
)
func cmdPush(c *cli.Context) error {
repos, err := repos(c.Bool("all"), c.Args()...)
if err != nil {
return cli.NewMultiError(fmt.Errorf(`failed gathering repo list`), err)
}
uniq := c.Bool("uniq")
namespace := c.String("namespace")
if namespace == "" {
return fmt.Errorf(`"--namespace" is a required flag for "push"`)
}
for _, repo := range repos {
r, err := fetch(repo)
if err != nil {
return cli.NewMultiError(fmt.Errorf(`failed fetching repo %q`, repo), err)
}
for _, entry := range r.Entries() {
if r.SkipConstraints(entry) {
continue
}
for _, tag := range r.Tags(namespace, uniq, entry) {
fmt.Printf("Pushing %s\n", tag)
err = dockerPush(tag)
if err != nil {
return cli.NewMultiError(fmt.Errorf(`failed pushing %q`, tag), err)
}
}
}
}
return nil
}
| package main
import (
"fmt"
"github.com/codegangsta/cli"
)
func cmdPush(c *cli.Context) error {
repos, err := repos(c.Bool("all"), c.Args()...)
if err != nil {
return cli.NewMultiError(fmt.Errorf(`failed gathering repo list`), err)
}
uniq := c.Bool("uniq")
namespace := c.String("namespace")
if namespace == "" {
return fmt.Errorf(`"--namespace" is a required flag for "tag"`)
}
for _, repo := range repos {
r, err := fetch(repo)
if err != nil {
return cli.NewMultiError(fmt.Errorf(`failed fetching repo %q`, repo), err)
}
for _, entry := range r.Entries() {
if r.SkipConstraints(entry) {
continue
}
for _, tag := range r.Tags(namespace, uniq, entry) {
fmt.Printf("Pushing %s\n", tag)
err = dockerPush(tag)
if err != nil {
return cli.NewMultiError(fmt.Errorf(`failed pushing %q`, tag), err)
}
}
}
}
return nil
}
|
Change initial version to 0.9 | #!/usr/bin/env python
# coding=utf-8
from setuptools import setup
setup(
name='alfred-workflow-packager',
version='0.9',
description='A CLI utility for packaging and exporting Alfred workflows',
url='https://github.com/caleb531/alfred-workflow-packager',
author='Caleb Evans',
author_email='caleb@calebevans.me',
license='MIT',
keywords='alfred workflow package export',
packages=['awp'],
install_requires=[
'biplist >= 1, < 2',
'jsonschema >= 2, < 3'
],
entry_points={
'console_scripts': [
'alfred-workflow-packager=awp.packager:main',
'workflow-packager=awp.packager:main'
]
}
)
| #!/usr/bin/env python
# coding=utf-8
from setuptools import setup
setup(
name='alfred-workflow-packager',
version='0.8b',
description='A CLI utility for packaging and exporting Alfred workflows',
url='https://github.com/caleb531/alfred-workflow-packager',
author='Caleb Evans',
author_email='caleb@calebevans.me',
license='MIT',
keywords='alfred workflow package export',
packages=['awp'],
install_requires=[
'biplist >= 1, < 2',
'jsonschema >= 2, < 3'
],
entry_points={
'console_scripts': [
'alfred-workflow-packager=awp.packager:main',
'workflow-packager=awp.packager:main'
]
}
)
|
Change granularity of the time picker to minutes | function initDatePicker(container, elem, pickerOptions) {
$(container + ' ' + elem).fdatepicker(pickerOptions);
$(container + ' ' + elem + '-wrapper .prefix i').on('click', function() {
$(this).closest(elem + '-wrapper')
.find(elem)
.fdatepicker('show');
});
}
function initDatepickersIn(container) {
initDatePicker(container, '.datepicker', {format: "dd-mm-yyyy"});
}
function initDateTimepickersIn(container) {
initDatePicker(container, '.datetimepicker', {
format: "dd-mm-yyyy hh:ii", pickTime: true, minuteStep: 1
});
}
$(function() {
if ($('small.error').length > 0) {
$('html, body').animate({
scrollTop: ($('small.error').first().offset().top-100)
},500);
}
initDatepickersIn("body");
initDateTimepickersIn("body");
});
| function initDatePicker(container, elem, pickerOptions) {
$(container + ' ' + elem).fdatepicker(pickerOptions);
$(container + ' ' + elem + '-wrapper .prefix i').on('click', function() {
$(this).closest(elem + '-wrapper')
.find(elem)
.fdatepicker('show');
});
}
function initDatepickersIn(container) {
initDatePicker(container, '.datepicker', {format: "dd-mm-yyyy"});
}
function initDateTimepickersIn(container) {
initDatePicker(container, '.datetimepicker', {format: "dd-mm-yyyy hh:ii", pickTime: true});
}
$(function() {
if ($('small.error').length > 0) {
$('html, body').animate({
scrollTop: ($('small.error').first().offset().top-100)
},500);
}
initDatepickersIn("body");
initDateTimepickersIn("body");
});
|
Format submission timestamp as string in CSV download | PT = PT || {};
PT.downloadCsv = function(serverResponse){
var survey = serverResponse.survey;
var responses = serverResponse.responses;
var a = document.createElement('a');
var csvString = "";
//Write title & prompts
csvString += survey.title + "\n";
csvString += 'Date of submission,"Location of submission (lat, lon)",';
survey.inputs.forEach(function(input){
csvString += '"' + input.label + '",';
})
//Write responses
responses.forEach(function(response){
csvString += "\n" + new Date(response.timestamp) + ","
+ '"' + response.locationstamp.lat + ", " + response.locationstamp.lon + '",';
response.answers.forEach(function(answer){
if(answer.value){
if (typeof(answer.value) == "string"){
csvString += '"' + answer.value + '"';
} else if(answer.value.constructor == Array) {
csvString += '"' + answer.value.join(",") + '"';
} else {
csvString += '"' + answer.value.lat + ", " + answer.value.lon + '"';
}
}
csvString += ",";
})
})
a.href = "data:application/csv;charset=utf-8," + "\uFEFF" + encodeURIComponent(csvString);
a.target = "_blank";
a.download = "PT_Data_" + survey.code + ".csv";
document.body.appendChild(a);
a.click();
}; | PT = PT || {};
PT.downloadCsv = function(serverResponse){
var survey = serverResponse.survey;
var responses = serverResponse.responses;
var a = document.createElement('a');
var csvString = "";
//Write title & prompts
csvString += survey.title + "\n";
csvString += 'Date of submission,"Location of submission (lat, lon)",';
survey.inputs.forEach(function(input){
csvString += '"' + input.label + '",';
})
//Write responses
responses.forEach(function(response){
csvString += "\n" + response.timestamp + ","
+ '"' + response.locationstamp.lat + ", " + response.locationstamp.lon + '",';
response.answers.forEach(function(answer){
if(answer.value){
if (typeof(answer.value) == "string"){
csvString += '"' + answer.value + '"';
} else if(answer.value.constructor == Array) {
csvString += '"' + answer.value.join(",") + '"';
} else {
csvString += '"' + answer.value.lat + ", " + answer.value.lon + '"';
}
}
csvString += ",";
})
})
a.href = "data:application/csv;charset=utf-8," + "\uFEFF" + encodeURIComponent(csvString);
a.target = "_blank";
a.download = "PT_Data_" + survey.code + ".csv";
document.body.appendChild(a);
a.click();
}; |
Add main() for draw_net unittest, fix import errors | import os
import unittest
from google.protobuf import text_format
import caffe.draw
from caffe.proto import caffe_pb2
def getFilenames():
"""Yields files in the source tree which are Net prototxts."""
result = []
root_dir = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..', '..', '..'))
assert os.path.exists(root_dir)
for dirname in ('models', 'examples'):
dirname = os.path.join(root_dir, dirname)
assert os.path.exists(dirname)
for cwd, _, filenames in os.walk(dirname):
for filename in filenames:
filename = os.path.join(cwd, filename)
if filename.endswith('.prototxt') and 'solver' not in filename:
yield os.path.join(dirname, filename)
class TestDraw(unittest.TestCase):
def test_draw_net(self):
for filename in getFilenames():
net = caffe_pb2.NetParameter()
with open(filename) as infile:
text_format.Merge(infile.read(), net)
caffe.draw.draw_net(net, 'LR')
if __name__ == "__main__":
unittest.main()
| import os
import unittest
from google import protobuf
import caffe.draw
from caffe.proto import caffe_pb2
def getFilenames():
"""Yields files in the source tree which are Net prototxts."""
result = []
root_dir = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..', '..', '..'))
assert os.path.exists(root_dir)
for dirname in ('models', 'examples'):
dirname = os.path.join(root_dir, dirname)
assert os.path.exists(dirname)
for cwd, _, filenames in os.walk(dirname):
for filename in filenames:
filename = os.path.join(cwd, filename)
if filename.endswith('.prototxt') and 'solver' not in filename:
yield os.path.join(dirname, filename)
class TestDraw(unittest.TestCase):
def test_draw_net(self):
for filename in getFilenames():
net = caffe_pb2.NetParameter()
with open(filename) as infile:
protobuf.text_format.Merge(infile.read(), net)
caffe.draw.draw_net(net, 'LR')
|
Add TODO comment to message listener interface | package pl.sepulkarz.socketchatroom.client.net;
import pl.sepulkarz.socketchatroom.net.data.Message;
import java.util.Date;
/**
* Listener interface for messages in general and private chat rooms.
* TODO: Split this interface to client presence/attendance listener, private and chatroom message listeners.
*/
public interface IMessageListener {
/**
* {@code Message.Type.NORMAL} message arrived.
*
* @param message {@code Message.Type.NORMAL} message.
*/
void messageArrived(Message message);
/**
* Client joined.
*
* @param when Date of the event.
* @param who The name of the client.
*/
void joined(Date when, String who);
/**
* Client left.
*
* @param when Date of the event.
* @param who The name of the client.
*/
void left(Date when, String who);
}
| package pl.sepulkarz.socketchatroom.client.net;
import pl.sepulkarz.socketchatroom.net.data.Message;
import java.util.Date;
/**
* Listener interface for messages in general and private chat rooms.
*/
public interface IMessageListener {
/**
* {@code Message.Type.NORMAL} message arrived.
*
* @param message {@code Message.Type.NORMAL} message.
*/
void messageArrived(Message message);
/**
* Client joined.
*
* @param when Date of the event.
* @param who The name of the client.
*/
void joined(Date when, String who);
/**
* Client left.
*
* @param when Date of the event.
* @param who The name of the client.
*/
void left(Date when, String who);
}
|
Validate incoming url against config | 'use strict';
var config = require('../config');
var oembed = module.exports = {
name: 'oembed'
};
// oEmbed endpoint with JSONP support.
oembed.embed = function(req, res) {
var url = req.query.url;
if (!url || !url.match(config.url.host)) { return res.send(400); }
var embedUrl = url.replace(/\/edit\?/, '/embed?');
var callback = req.query.callback;
var width = req.query.maxwidth || 640;
var height = req.query.maxheight || 480;
var oembed = {
type: 'rich',
version: '1.0',
title: 'JS Bin',
url: url,
width: width,
height: height,
html: '<iframe src="' + embedUrl + '" width="' + width + '" height="' + height + '" frameborder="0"></iframe>',
};
var output = callback ? callback + '(' + JSON.stringify(oembed) + ')' : oembed;
res.set('Content-Type', 'application/javascript');
res.send(output);
};
| 'use strict';
var oembed = module.exports = {
name: 'oembed'
};
// oEmbed endpoint with JSONP support.
oembed.embed = function(req, res) {
var url = req.query.url;
if (!url || !url.match(/https?:\/\/jsbin.com/)) return res.send(400);
var embedUrl = url.replace(/\/edit\?/, '/embed?');
var callback = req.query.callback;
var width = req.query.maxwidth || 640;
var height = req.query.maxheight || 480;
var oembed = {
type: 'rich',
version: '1.0',
title: 'JS Bin',
url: url,
width: width,
height: height,
html: '<iframe src="' + embedUrl + '" width="' + width + '" height="' + height + '" frameborder="0"></iframe>',
};
var output = callback ? callback + '(' + JSON.stringify(oembed) + ')' : oembed;
res.set('Content-Type', 'application/javascript');
res.send(output);
};
|
Add rename use of Stepper | /* eslint-disable import/no-named-as-default */
/* eslint-disable react/forbid-prop-types */
import React from 'react';
import PropTypes from 'prop-types';
import { Stepper } from './Stepper';
import { TabNavigator } from './TabNavigator';
import DataTablePageView from './DataTablePageView';
/**
* Layout component for a Tracker and TabNavigator, displaying steps
* to completion for completion. See TabNavigator and StepsTracker
* for individual component implementation.
*/
export const Wizard = ({ tabs, titles, onPress, currentTabIndex }) => (
<DataTablePageView>
<Stepper
numberOfSteps={tabs.length}
currentStep={currentTabIndex}
onPress={onPress}
titles={titles}
/>
<TabNavigator tabs={tabs} currentTabIndex={currentTabIndex} />
</DataTablePageView>
);
Wizard.propTypes = {
tabs: PropTypes.array.isRequired,
titles: PropTypes.array.isRequired,
onPress: PropTypes.func.isRequired,
currentTabIndex: PropTypes.number.isRequired,
};
| /* eslint-disable import/no-named-as-default */
/* eslint-disable react/forbid-prop-types */
import React from 'react';
import PropTypes from 'prop-types';
import { StepsTracker } from './StepsTracker';
import { TabNavigator } from './TabNavigator';
import DataTablePageView from './DataTablePageView';
/**
* Layout component for a Tracker and TabNavigator, displaying steps
* to completion for completion. See TabNavigator and StepsTracker
* for individual component implementation.
*/
export const Wizard = ({ tabs, titles, onPress, currentTabIndex }) => (
<DataTablePageView>
<StepsTracker
numberOfSteps={tabs.length}
currentStep={currentTabIndex}
onPress={onPress}
titles={titles}
/>
<TabNavigator tabs={tabs} currentTabIndex={currentTabIndex} />
</DataTablePageView>
);
Wizard.propTypes = {
tabs: PropTypes.array.isRequired,
titles: PropTypes.array.isRequired,
onPress: PropTypes.func.isRequired,
currentTabIndex: PropTypes.number.isRequired,
};
|
Disable separators for a cleaner UI. | import { Component } from 'substance'
export default class ManuscriptComponent extends Component {
render($$) {
const article = this.props.node
let el = $$('div')
.addClass('sc-article')
.attr('data-id', article.id)
// front is mandatory
const front = article.findChild('front')
const FrontComponent = this.getComponent('front')
el.append($$(FrontComponent, {
node: front
}).ref('front'))
// body is optional
// TODO: do we really want this? Otherwise we need to change TextureJATS
// and create an empty body on import
const body = article.findChild('body')
if (body) {
// el.append($$(this.getComponent('separator'), {
// label: 'manuscript-start'
// }))
const BodyComponent = this.getComponent('body')
el.append($$(BodyComponent, {
node: body
}).ref('body'))
// el.append($$(this.getComponent('separator'), {
// label: 'manuscript-end'
// }))
}
const back = article.findChild('back')
if (back) {
const BackComponent = this.getComponent('back')
el.append($$(BackComponent, {
node: back
}).ref('back'))
}
return el
}
}
| import { Component } from 'substance'
export default class ManuscriptComponent extends Component {
render($$) {
const article = this.props.node
let el = $$('div')
.addClass('sc-article')
.attr('data-id', article.id)
// front is mandatory
const front = article.findChild('front')
const FrontComponent = this.getComponent('front')
el.append($$(FrontComponent, {
node: front
}).ref('front'))
// body is optional
// TODO: do we really want this? Otherwise we need to change TextureJATS
// and create an empty body on import
const body = article.findChild('body')
if (body) {
el.append($$(this.getComponent('separator'), {
label: 'manuscript-start'
}))
const BodyComponent = this.getComponent('body')
el.append($$(BodyComponent, {
node: body
}).ref('body'))
el.append($$(this.getComponent('separator'), {
label: 'manuscript-end'
}))
}
const back = article.findChild('back')
if (back) {
const BackComponent = this.getComponent('back')
el.append($$(BackComponent, {
node: back
}).ref('back'))
}
return el
}
}
|
Change copy and test link placement on homepage | import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import Logo from './Logo.js';
class Home extends Component {
render(){
return (
<div>
<div className="logo"> <Logo /> </div>
<Link to="/instructions"><button>Take the Test</button></Link>
<p>Approximately 8.0% of males and 0.5% of females are color blind- that's about 4.5% of the human population. One common misconception is that color blindness can only be inherited; color blindness can also be acquired later in life as a result of disease, aging, or certain medications.</p>
<p>The most widely used method for detecting and measuring color vision deficiencies is the Ishihara color test. Find out now if you are colorblind, and learn what you can do to avoid colorblindness later in life.</p>
</div>
);
}
}
export default Home;
| import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import Logo from './Logo.js';
class Home extends Component {
render(){
return (
<div>
<div className="logo">
<Logo />
</div>
<p>Approximately 8.0% of males and 0.5% of females are colorblind: that's about 4.5% of the human population. One common misconception is that colorblindness can only be inherited; color vision deficiencies can also be acquired later in life as a result of disease, aging, or certain medications.</p>
<p>The most widely used method for detecting and measuring color vision deficiencies is though the Ishihara color test. Find out now if you are colorblind, and learn what you can do to avoid colorblindness later in life.</p>
<Link to="/instructions"><button>Take the Test</button></Link>
</div>
);
}
}
export default Home;
|
Check that population_size is even, and set half_population_size.
This will be used by genetic algorithms. | #
# Copyright (c) 2016, Gabriel Linder <linder.gabriel@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
#
from abc import ABC, abstractmethod
from Color import RandomColor
class Algo(ABC):
def __init__(self, population_size):
assert population_size % 2 == 0
self.half_population_size = population_size // 2
self.population_size = population_size
self.set_random_population()
def set_random_population(self):
self.population = []
for i in range(self.population_size):
self.population.append(RandomColor())
def dump(self):
for color in self.population:
print('{} '.format(color), end='')
print(flush=True)
@abstractmethod
def tick(self, deltas):
pass
| #
# Copyright (c) 2016, Gabriel Linder <linder.gabriel@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
#
from abc import ABC, abstractmethod
from Color import RandomColor
class Algo(ABC):
def __init__(self, population_size):
self.population_size = population_size
self.set_random_population()
def set_random_population(self):
self.population = []
for i in range(self.population_size):
self.population.append(RandomColor())
def dump(self):
for color in self.population:
print('{} '.format(color), end='')
print(flush=True)
@abstractmethod
def tick(self, deltas):
pass
|
Enable integration-test to start investigating why it fails | package org.apache.poi.benchmark.suite;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Setup;
import java.io.IOException;
public class TestBenchmarks extends BaseBenchmark {
@Setup
public void setUp() throws IOException {
compileAll();
}
@Benchmark
public void benchmarkTestMain() throws IOException {
testMain();
}
@Benchmark
public void benchmarkTestScratchpad() throws IOException {
testScratchpad();
}
@Benchmark
public void benchmarkTestOOXML() throws IOException {
testOOXML();
}
@Benchmark
public void benchmarkTestOOXMLLite() throws IOException {
testOOXMLLite();
}
@Benchmark
public void benchmarkTestExcelant() throws IOException {
testExcelant();
}
@Benchmark
public void benchmarkTestIntegration() throws IOException {
testIntegration();
}
}
| package org.apache.poi.benchmark.suite;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Setup;
import java.io.IOException;
public class TestBenchmarks extends BaseBenchmark {
@Setup
public void setUp() throws IOException {
compileAll();
}
@Benchmark
public void benchmarkTestMain() throws IOException {
testMain();
}
@Benchmark
public void benchmarkTestScratchpad() throws IOException {
testScratchpad();
}
@Benchmark
public void benchmarkTestOOXML() throws IOException {
testOOXML();
}
@Benchmark
public void benchmarkTestOOXMLLite() throws IOException {
testOOXMLLite();
}
@Benchmark
public void benchmarkTestExcelant() throws IOException {
testExcelant();
}
// exclude for now as it always fails and I could not find out why
// @Benchmark
public void benchmarkTestIntegration() throws IOException {
testIntegration();
}
}
|
Fix non-conventional aliases that cause problems sometimes. | <?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @since 3.0.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace TestApp\Model\Table;
use Cake\ORM\Table;
/**
* Tag table class
*/
class TagsTable extends Table
{
public function initialize(array $config)
{
$this->belongsTo('Authors');
$this->belongsToMany('Articles');
$this->hasMany('ArticlesTags', ['propertyName' => 'extraInfo']);
}
}
| <?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @since 3.0.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace TestApp\Model\Table;
use Cake\ORM\Table;
/**
* Tag table class
*/
class TagsTable extends Table
{
public function initialize(array $config)
{
$this->belongsTo('authors');
$this->belongsToMany('articles');
$this->hasMany('ArticlesTags', ['propertyName' => 'extraInfo']);
}
}
|
Make redirect test independent of db | import { test } from 'qunit';
import moduleForAcceptance from 'ember-api-docs/tests/helpers/module-for-acceptance';
moduleForAcceptance('Acceptance | redirects');
test('visiting /', function(assert) {
visit('/');
return andThen(() => {
const store = this.application.__container__.lookup('service:store');
const versions = store.peekAll('project-version').toArray();
const last = versions[versions.length - 1].get('id').split('-')[1];
assert.equal(
currentURL(),
`/ember/${last}/classes/Backburner`,
'routes to the last class of the project-version'
);
});
});
test('visiting /:project/:project_version/classes', function(assert) {
visit('/ember/1.0.0/classes');
return andThen(function() {
assert.equal(
currentURL(),
'/ember/1.0.0/classes/Container',
'routes to the first class of the project-version'
);
});
});
| import { test } from 'qunit';
import moduleForAcceptance from 'ember-api-docs/tests/helpers/module-for-acceptance';
moduleForAcceptance('Acceptance | redirects');
test('visiting /', function(assert) {
visit('/');
const last = "2.6.0"; // need help for how to get this
return andThen(function() {
assert.equal(
currentURL(),
`/ember/${last}/classes/Backburner`,
'routes to the last class of the project-version'
);
});
});
test('visiting /:project/:project_version/classes', function(assert) {
visit('/ember/1.0.0/classes');
return andThen(function() {
assert.equal(
currentURL(),
'/ember/1.0.0/classes/Container',
'routes to the first class of the project-version'
);
});
});
|
Use daemon threads for follow_file()
Signed-off-by: Jason Bernardino Alonso <f71c42a1353bbcdbe07e24c2a1c893f8ea1d05ee@hackorp.com> | """
Utility functions for dhcp2nest
"""
from queue import Queue
from subprocess import Popen, PIPE
from threading import Thread
def follow_file(fn, max_lines=100):
"""
Return a Queue that is fed lines (up to max_lines) from the given file (fn)
continuously
The implementation given here was inspired by
http://stackoverflow.com/questions/12523044/how-can-i-tail-a-log-file-in-python
"""
fq = Queue(maxsize=max_lines)
def _follow_file_thread(fn, fq):
"""
Queue lines from the given file (fn) continuously, even as the file
grows or is replaced
WARNING: This generator will block forever on the tail subprocess--no
timeouts are enforced.
"""
# Use system tail with name-based following and retry
p = Popen(["tail", "-n0", "-F", fn], stdout=PIPE)
# Loop forever on pulling data from tail
line = True
while line:
line = p.stdout.readline().decode('utf-8')
fq.put(line)
# Spawn a thread to read data from tail
Thread(target=_follow_file_thread, args=(fn, fq), daemon=True).start()
# Return the queue
return fq
| """
Utility functions for dhcp2nest
"""
from queue import Queue
from subprocess import Popen, PIPE
from threading import Thread
def follow_file(fn, max_lines=100):
"""
Return a Queue that is fed lines (up to max_lines) from the given file (fn)
continuously
The implementation given here was inspired by
http://stackoverflow.com/questions/12523044/how-can-i-tail-a-log-file-in-python
"""
fq = Queue(maxsize=max_lines)
def _follow_file_thread(fn, fq):
"""
Queue lines from the given file (fn) continuously, even as the file
grows or is replaced
WARNING: This generator will block forever on the tail subprocess--no
timeouts are enforced.
"""
# Use system tail with name-based following and retry
p = Popen(["tail", "-n0", "-F", fn], stdout=PIPE)
# Loop forever on pulling data from tail
line = True
while line:
line = p.stdout.readline().decode('utf-8')
fq.put(line)
# Spawn a thread to read data from tail
Thread(target=_follow_file_thread, args=(fn, fq)).start()
# Return the queue
return fq
|
Add message with link to seqclusterViz | import os
import shutil
import logging
from bcbio import install
install._set_matplotlib_default_backend()
import matplotlib
matplotlib.use('Agg', force=True)
from libs.read import load_data
from libs.report import make_profile
from libs.utils import safe_dirs
from db import make_database
import templates
logger = logging.getLogger('report')
def report(args):
"""
Create report in html format
"""
logger.info("reading sequeces")
data = load_data(args.json)
out_dir = os.path.join(args.out, "html")
safe_dirs(out_dir)
logger.info("create profile")
data = make_profile(data, out_dir, args)
logger.info("create database")
make_database(data, "seqcluster.db", args.out)
path_template = os.path.normpath(os.path.dirname(os.path.realpath(templates.__file__)))
css_template = os.path.join(path_template, "info.css")
js_template = os.path.join(path_template, "jquery.tablesorter.min.js")
css = os.path.join(out_dir, "info.css")
js = os.path.join(out_dir, "jquery.tablesorter.min.js")
if not os.path.exists(css):
shutil.copy(css_template, css)
shutil.copy(js_template, js)
logger.info("Done. Download https://github.com/lpantano/seqclusterViz/archive/master.zip to browse the output.")
| import os
import shutil
import logging
from bcbio import install
install._set_matplotlib_default_backend()
import matplotlib
matplotlib.use('Agg', force=True)
from libs.read import load_data
from libs.report import make_profile
from libs.utils import safe_dirs
from db import make_database
import templates
logger = logging.getLogger('report')
def report(args):
"""
Create report in html format
"""
logger.info("reading sequeces")
data = load_data(args.json)
out_dir = os.path.join(args.out, "html")
safe_dirs(out_dir)
logger.info("create profile")
data = make_profile(data, out_dir, args)
logger.info("create database")
make_database(data, "seqcluster.db", args.out)
path_template = os.path.normpath(os.path.dirname(os.path.realpath(templates.__file__)))
css_template = os.path.join(path_template, "info.css")
js_template = os.path.join(path_template, "jquery.tablesorter.min.js")
css = os.path.join(out_dir, "info.css")
js = os.path.join(out_dir, "jquery.tablesorter.min.js")
if not os.path.exists(css):
shutil.copy(css_template, css)
shutil.copy(js_template, js)
logger.info("Done")
|
Add override annotations to subclassed methods | package com.veyndan.hermes.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.veyndan.hermes.home.model.Comic;
public final class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "Hermes.db";
String CREATE_TABLE = ""
+ "CREATE TABLE " + Comic.TABLE
+ "("
+ Comic.NUM + " INTEGER PRIMARY KEY,"
+ Comic.ALT + " TEXT,"
+ Comic.IMG + " TEXT,"
+ Comic.TITLE + " TEXT"
+ ")";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Comic.TABLE);
onCreate(db);
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
} | package com.veyndan.hermes.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.veyndan.hermes.home.model.Comic;
public final class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "Hermes.db";
String CREATE_TABLE = ""
+ "CREATE TABLE " + Comic.TABLE
+ "("
+ Comic.NUM + " INTEGER PRIMARY KEY,"
+ Comic.ALT + " TEXT,"
+ Comic.IMG + " TEXT,"
+ Comic.TITLE + " TEXT"
+ ")";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Comic.TABLE);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
} |
[ADD] Upgrade para columnas en tabla courseresult | package com.liferay.lms.upgrade;
import java.io.IOException;
import java.sql.SQLException;
import com.liferay.portal.kernel.dao.db.DB;
import com.liferay.portal.kernel.dao.db.DBFactoryUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.upgrade.UpgradeProcess;
public class UpgradeVersion_4_2_0 extends UpgradeProcess {
private static Log log = LogFactoryUtil.getLog(UpgradeVersion_4_2_0.class);
public int getThreshold() {
return 420;
}
protected void doUpgrade() throws Exception {
log.info("Actualizando version a 4.2.0");
DB db = DBFactoryUtil.getDB();
String updateCourseResult = "ALTER TABLE `lms_courseresult` ADD COLUMN `registrationDate` DATETIME NULL AFTER `passed`, "
+ "ADD COLUMN `companyId` BIGINT(20) NULL AFTER `extraData`, "
+ "ADD COLUMN `userModifiedId` BIGINT(20) NULL AFTER `companyId`;";
log.info("Alter table lms_courseresult -->> Add companyId, userModifiedId");
try {
db.runSQL(updateCourseResult);
} catch (IOException | SQLException e) {
e.printStackTrace();
}
}
} | package com.liferay.lms.upgrade;
import java.io.IOException;
import java.sql.SQLException;
import com.liferay.portal.kernel.dao.db.DB;
import com.liferay.portal.kernel.dao.db.DBFactoryUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.upgrade.UpgradeProcess;
public class UpgradeVersion_4_2_0 extends UpgradeProcess {
private static Log log = LogFactoryUtil.getLog(UpgradeVersion_4_2_0.class);
public int getThreshold() {
return 420;
}
protected void doUpgrade() throws Exception {
log.info("Actualizando version a 4.1.0");
String updateCourseResult = "ALTER TABLE `lms_courseresult` ADD COLUMN `registrationDate` DATETIME NULL AFTER `passed`;";
DB db = DBFactoryUtil.getDB();
log.info("Alter table lms_courseresult -->> Add registrationDate");
try {
db.runSQL(updateCourseResult);
} catch (IOException | SQLException e) {
e.printStackTrace();
}
}
} |
Update style on cookie warning | Ensembl.LayoutManager.showCookieMessage = function() {
var cookiesAccepted = Ensembl.cookie.get('cookies_ok');
if (!cookiesAccepted) {
$(['<div class="cookie-message hidden">',
'<p class="msg">We use cookies to enhance the usability of our website. If you continue, we\'ll assume that you are happy to receive all cookies. ',
'<span class="more-info">Read more about EMBL-EBI policies: <a href="http://www.ebi.ac.uk/about/cookie-control">Cookies</a> | <a href="http://www.ebi.ac.uk/about/privacy">Privacy</a>.</span>',
'</p>',
'<span class="close">x</span>',
'</div>'
].join(''))
.appendTo(document.body).show().find('span.close').on('click', function (e) {
Ensembl.cookie.set('cookies_ok', 'yes');
$(this).parents('div').first().fadeOut(200);
});
return true;
}
return false;
};
| Ensembl.LayoutManager.showCookieMessage = function() {
var cookiesAccepted = Ensembl.cookie.get('cookies_ok');
if (!cookiesAccepted) {
$(['<div class="cookie-message hidden">',
'<div></div>',
'<p>We use cookies to enhance the usability of our website. If you continue, we\'ll assume that you are happy to receive all cookies.</p>',
'<p><button>Don\'t show this again</button></p>',
'<p>Read more about EMBL-EBI policies: <a href="http://www.ebi.ac.uk/about/cookie-control">Cookies</a> | <a href="http://www.ebi.ac.uk/about/privacy">Privacy</a>.</p>',
'</div>'
].join(''))
.appendTo(document.body).show().find('button,div').on('click', function (e) {
Ensembl.cookie.set('cookies_ok', 'yes');
$(this).parents('div').first().fadeOut(200);
}).filter('div').helptip({content:"Don't show this again"});
return true;
}
return false;
};
|
Add default page and perPage values to user likes | /* @flow */
export default function users(): Object {
return {
profile: (username: string) => {
const url = `/users/${username}`;
return this.request({
url,
method: "GET"
});
},
photos: (username: string) => {
const url = `/users/${username}/photos`;
return this.request({
url,
method: "GET"
});
},
likes: (username: string, page: number = 1, perPage: number = 10) => {
const url = `/users/${username}/likes`;
let query = {
page,
per_page: perPage
};
return this.request({
url,
method: "GET",
query
});
}
};
}
| /* @flow */
export default function users(): Object {
return {
profile: (username: string) => {
const url = `/users/${username}`;
return this.request({
url,
method: "GET"
});
},
photos: (username: string) => {
const url = `/users/${username}/photos`;
return this.request({
url,
method: "GET"
});
},
likes: (username: string, page: number, perPage: number) => {
const url = `/users/${username}/likes`;
let query = {
page,
per_page: perPage
};
return this.request({
url,
method: "GET",
query
});
}
};
}
|
Add minor note about future changes | // @flow
import { expect } from "chai";
import {
Game,
GameDescriptor,
DefaultDeck
} from "stormtide-core";
import type {
PlayerDescriptor
} from "stormtide-core";
describe("Scenario: Game Start", () => {
const settings = new GameDescriptor();
const player1: PlayerDescriptor = {
deck: DefaultDeck
};
const player2: PlayerDescriptor = {
deck: DefaultDeck
};
settings.players = [player1, player2];
const game = new Game(settings);
game.start();
const playerState1 = game.state.playerTurnOrder
.map(v => game.state.players[v])
.filter(v => v != null)
.find(player => player && player.descriptor === player1);
it("should have the right players", () => {
expect(Object.keys(game.state.players)).to.have.lengthOf(2);
});
// This will change with the addition of pre-game actions
it("should give turn and priority to player 1", () => {
expect(playerState1).to.be.ok;
if (!playerState1) {
return;
}
expect(game.state.turn).to.equal(playerState1.id);
expect(game.state.priority).to.equal(playerState1.id);
});
}); | // @flow
import { expect } from "chai";
import {
Game,
GameDescriptor,
DefaultDeck
} from "stormtide-core";
import type {
PlayerDescriptor
} from "stormtide-core";
describe("Scenario: Game Start", () => {
const settings = new GameDescriptor();
const player1: PlayerDescriptor = {
deck: DefaultDeck
};
const player2: PlayerDescriptor = {
deck: DefaultDeck
};
settings.players = [player1, player2];
const game = new Game(settings);
game.start();
const playerState1 = game.state.playerTurnOrder
.map(v => game.state.players[v])
.filter(v => v != null)
.find(player => player && player.descriptor === player1);
it("should have the right players", () => {
expect(Object.keys(game.state.players)).to.have.lengthOf(2);
});
it("should give turn and priority to player 1", () => {
expect(playerState1).to.be.ok;
if (!playerState1) {
return;
}
expect(game.state.turn).to.equal(playerState1.id);
expect(game.state.priority).to.equal(playerState1.id);
});
}); |
Fix encoding test: compare with unicode string. | # -*- encoding: utf-8 -*-
import pytest
from owslib.fes import PropertyIsEqualTo
from pydov.search.boring import BoringSearch
from tests.abstract import (
AbstractTestSearch,
service_ok,
)
class TestEncoding(AbstractTestSearch):
"""Class grouping tests related to encoding issues."""
@pytest.mark.online
@pytest.mark.skipif(not service_ok(), reason="DOV service is unreachable")
def test_search(self):
"""Test the search method with strange character in the output.
Test whether the output has the correct encoding.
"""
boringsearch = BoringSearch()
query = PropertyIsEqualTo(
propertyname='pkey_boring',
literal='https://www.dov.vlaanderen.be/data/boring/1928-031159')
df = boringsearch.search(query=query,
return_fields=('pkey_boring', 'uitvoerder'))
assert df.uitvoerder[0] == u'Societé Belge des Bétons'
| # -*- encoding: utf-8 -*-
import pytest
from owslib.fes import PropertyIsEqualTo
from pydov.search.boring import BoringSearch
from tests.abstract import (
AbstractTestSearch,
service_ok,
)
class TestEncoding(AbstractTestSearch):
"""Class grouping tests related to encoding issues."""
@pytest.mark.online
@pytest.mark.skipif(not service_ok(), reason="DOV service is unreachable")
def test_search(self):
"""Test the search method with strange character in the output.
Test whether the output has the correct encoding.
"""
boringsearch = BoringSearch()
query = PropertyIsEqualTo(
propertyname='pkey_boring',
literal='https://www.dov.vlaanderen.be/data/boring/1928-031159')
df = boringsearch.search(query=query,
return_fields=('pkey_boring', 'uitvoerder'))
assert df.uitvoerder[0] == 'Societé Belge des Bétons'
|
Enable terminals in the lab example | """
Copyright (c) Jupyter Development Team.
Distributed under the terms of the Modified BSD License.
"""
import os
from jinja2 import FileSystemLoader
from notebook.base.handlers import IPythonHandler, FileFindHandler
from notebook.notebookapp import NotebookApp
from traitlets import Unicode
class ExampleHandler(IPythonHandler):
"""Handle requests between the main app page and notebook server."""
def get(self):
"""Get the main page for the application's interface."""
return self.write(self.render_template("index.html",
static=self.static_url, base_url=self.base_url,
terminals_available=True))
def get_template(self, name):
loader = FileSystemLoader(os.getcwd())
return loader.load(self.settings['jinja2_env'], name)
class ExampleApp(NotebookApp):
default_url = Unicode('/example')
def init_webapp(self):
"""initialize tornado webapp and httpserver.
"""
super(ExampleApp, self).init_webapp()
default_handlers = [
(r'/example/?', ExampleHandler),
(r"/example/(.*)", FileFindHandler,
{'path': 'build'}),
]
self.web_app.add_handlers(".*$", default_handlers)
if __name__ == '__main__':
ExampleApp.launch_instance()
| """
Copyright (c) Jupyter Development Team.
Distributed under the terms of the Modified BSD License.
"""
import os
from jinja2 import FileSystemLoader
from notebook.base.handlers import IPythonHandler, FileFindHandler
from notebook.notebookapp import NotebookApp
from traitlets import Unicode
class ExampleHandler(IPythonHandler):
"""Handle requests between the main app page and notebook server."""
def get(self):
"""Get the main page for the application's interface."""
return self.write(self.render_template("index.html",
static=self.static_url, base_url=self.base_url))
def get_template(self, name):
loader = FileSystemLoader(os.getcwd())
return loader.load(self.settings['jinja2_env'], name)
class ExampleApp(NotebookApp):
default_url = Unicode('/example')
def init_webapp(self):
"""initialize tornado webapp and httpserver.
"""
super(ExampleApp, self).init_webapp()
default_handlers = [
(r'/example/?', ExampleHandler),
(r"/example/(.*)", FileFindHandler,
{'path': 'build'}),
]
self.web_app.add_handlers(".*$", default_handlers)
if __name__ == '__main__':
ExampleApp.launch_instance()
|
Add containers to workgroup detail view | import json
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, Http404
from cyder.base.utils import make_megafilter
from cyder.base.views import cy_detail
from cyder.cydhcp.workgroup.models import Workgroup
def workgroup_detail(request, pk):
workgroup = get_object_or_404(Workgroup, pk=pk)
return cy_detail(request, Workgroup, 'workgroup/workgroup_detail.html', {
'Attributes': 'workgroupav_set',
'Dynamic Interfaces': workgroup.dynamicinterface_set.all(),
'Static Interfaces': workgroup.staticinterface_set.all(),
'Containers': 'ctnr_set',
}, obj=workgroup)
def search(request):
"""Returns a list of workgroups matching 'term'."""
term = request.GET.get('term', '')
if not term:
raise Http404
workgroups = Workgroup.objects.filter(
make_megafilter(Workgroup, term))[:15]
workgroups = [{
'label': str(workgroup),
'pk': workgroup.id} for workgroup in workgroups]
return HttpResponse(json.dumps(workgroups))
| import json
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, Http404
from cyder.base.utils import make_megafilter
from cyder.base.views import cy_detail
from cyder.cydhcp.workgroup.models import Workgroup
def workgroup_detail(request, pk):
workgroup = get_object_or_404(Workgroup, pk=pk)
return cy_detail(request, Workgroup, 'workgroup/workgroup_detail.html', {
'Attributes': 'workgroupav_set',
'Dynamic Interfaces': workgroup.dynamicinterface_set.all(),
'Static Interfaces': workgroup.staticinterface_set.all(),
}, obj=workgroup)
def search(request):
"""Returns a list of workgroups matching 'term'."""
term = request.GET.get('term', '')
if not term:
raise Http404
workgroups = Workgroup.objects.filter(
make_megafilter(Workgroup, term))[:15]
workgroups = [{
'label': str(workgroup),
'pk': workgroup.id} for workgroup in workgroups]
return HttpResponse(json.dumps(workgroups))
|
Increase to public visibility (better for use) | package net.aeten.core.spi.factory;
import java.util.concurrent.atomic.AtomicInteger;
import net.aeten.core.spi.SpiFactory;
public class ThreadFactory implements
SpiFactory <java.util.concurrent.ThreadFactory, String> {
private static final AtomicInteger threadCount = new AtomicInteger (0);
@Override
public java.util.concurrent.ThreadFactory create (String prefix) {
final String name = prefix + "-" + threadCount.incrementAndGet ();
return new java.util.concurrent.ThreadFactory () {
@Override
public Thread newThread (Runnable runnable) {
return new Thread (runnable, name);
}
};
}
@Override
public Class <?>[] getTypes () {
return new Class[] {
java.util.concurrent.ThreadFactory.class
};
}
@Override
public Class <String> getParameterType () {
return String.class;
}
} | package net.aeten.core.spi.factory;
import java.util.concurrent.atomic.AtomicInteger;
import net.aeten.core.spi.SpiFactory;
class ThreadFactory implements
SpiFactory <java.util.concurrent.ThreadFactory, String> {
private static final AtomicInteger threadCount = new AtomicInteger (0);
@Override
public java.util.concurrent.ThreadFactory create (String prefix) {
final String name = prefix + "-" + threadCount.incrementAndGet ();
return new java.util.concurrent.ThreadFactory () {
@Override
public Thread newThread (Runnable runnable) {
return new Thread (runnable, name);
}
};
}
@Override
public Class <?>[] getTypes () {
return new Class[] {
java.util.concurrent.ThreadFactory.class
};
}
@Override
public Class <String> getParameterType () {
return String.class;
}
} |
Fix markdown image and link rendering | import Marked from 'marked'
export const orderedNotes = state => {
return state.notes.slice(0).sort((a, b) => {
const aOrder = state.notesOrder[a['.key']]
const bOrder = state.notesOrder[b['.key']]
if (aOrder === undefined || aOrder === null) return -1
if (aOrder === bOrder) return 0
if (aOrder < bOrder) return -1
return 1
})
}
export const markdown = state => text => {
return Marked(text)
}
let mdRenderer = new Marked.Renderer()
mdRenderer.image = function (href, title, altText) {
return `<img src="${href}" alt="${altText}" title="${title}" class="ui image">`
}
mdRenderer.link = function (href, title, text) {
return `<a href="${href}" title="${title}" target="_blank">${text}</a>`
}
Marked.setOptions({
renderer: mdRenderer
})
| import Marked from 'marked'
export const orderedNotes = state => {
return state.notes.slice(0).sort((a, b) => {
const aOrder = state.notesOrder[a['.key']]
const bOrder = state.notesOrder[b['.key']]
if (aOrder === undefined || aOrder === null) return -1
if (aOrder === bOrder) return 0
if (aOrder < bOrder) return -1
return 1
})
}
export const markdown = state => text => {
return Marked(text)
}
let mdRenderer = new Marked.Renderer()
mdRenderer.image = function (href, title, text) {
return '<p><img src="' + href + '" alt="' + text + '" class="ui image"></p>'
}
mdRenderer.link = function (href, title, text) {
return '<a href="' + href + '" target="_blank">' + text + '</a>'
}
Marked.setOptions({
renderer: mdRenderer
})
|
Load configuration from current directory | var fs = require('fs');
var MongoClient = require('mongodb').MongoClient;
var config = require('./config.json');
MongoClient.connect(config.mongodb, function(err, db) {
if (err) {
throw new Error(err);
}
var talks = db.collection('talks');
talks.find({}).toArray(function(err, docs) {
if (err) {
throw new Error(err);
}
docs.forEach(function(el) {
var outputFilename = "./data/talks/" + el.id + ".json";
fs.writeFile(outputFilename, JSON.stringify(el, null, 4), function(err) {
if (err) {
throw new Error(err);
}
});
});
db.close();
});
});
| var fs = require('fs');
var MongoClient = require('mongodb').MongoClient;
var config = require('../front/config.json');
MongoClient.connect(config.mongodb, function(err, db) {
if (err) {
throw new Error(err);
}
var talks = db.collection('talks');
talks.find({}).toArray(function(err, docs) {
if (err) {
throw new Error(err);
}
docs.forEach(function(el) {
var outputFilename = "./data/talks/" + el.id + ".json";
fs.writeFile(outputFilename, JSON.stringify(el, null, 4), function(err) {
if (err) {
throw new Error(err);
}
});
});
db.close();
});
});
|
Convert gameState to JS object and pass to template | var express = require('express');
var http = require('http');
var socketIO = require('socket.io');
var path = require('path');
var m = require('mori');
var game = require('./game.js');
var app = express();
var server = http.Server(app);
var io = socketIO(server);
app.set('views', path.join(__dirname, 'templates'));
app.set('view engine', 'jade');
app.use(express.static('public'));
var gameState = game.getInitialState();
app.get('/', function(req, res) {
var stateObject = m.toJs(gameState);
res.render('index', stateObject);
});
io.on('connection', function(socket){
console.log('CONNECT', socket.id);
socket.on('log on', function(name){
console.log('LOG ON', name);
socket.broadcast.emit('log on', name);
})
socket.on('log off', function(name) {
console.log('LOG OFF', name);
socket.broadcast.emit('log off', name);
})
socket.on('disconnect', function(){
console.log('DISCONNECT', socket.id);
});
socket.on('card click', function(click){
console.log('CARD CLICK', click.user, click.card);
io.emit('card click', click);
});
});
server.listen(3000, function() {
console.log("listening on port 3000");
});
| var express = require('express');
var http = require('http');
var socketIO = require('socket.io');
var path = require('path');
var m = require('mori');
var game = require('./game.js');
var app = express();
var server = http.Server(app);
var io = socketIO(server);
app.set('views', path.join(__dirname, 'templates'));
app.set('view engine', 'jade');
app.use(express.static('public'));
var gameState = game.getInitialState();
app.get('/', function(req, res) {
var dealt = m.toJs(m.get(gameState, 'dealt'));
res.render('index', {'dealt': dealt});
});
io.on('connection', function(socket){
console.log('CONNECT', socket.id);
socket.on('log on', function(name){
console.log('LOG ON', name);
socket.broadcast.emit('log on', name);
})
socket.on('log off', function(name) {
console.log('LOG OFF', name);
socket.broadcast.emit('log off', name);
})
socket.on('disconnect', function(){
console.log('DISCONNECT', socket.id);
});
socket.on('card click', function(click){
console.log('CARD CLICK', click.user, click.card);
io.emit('card click', click);
});
});
server.listen(3000, function() {
console.log("listening on port 3000");
});
|
Improve message in @Disabled test | /*
* (C) Copyright 2020 Boni Garcia (http://bonigarcia.github.io/)
*
* 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.github.bonigarcia;
import static java.lang.invoke.MethodHandles.lookup;
import static org.slf4j.LoggerFactory.getLogger;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
@Disabled("All tests in this class are skipped")
class DisabledAllTest {
static final Logger log = getLogger(lookup().lookupClass());
@Test
void skippedTestOne() {
log.debug("This test is NOT executed");
}
@Test
void skippedTestTwo() {
log.debug("This test is NOT executed");
}
}
| /*
* (C) Copyright 2020 Boni Garcia (http://bonigarcia.github.io/)
*
* 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.github.bonigarcia;
import static java.lang.invoke.MethodHandles.lookup;
import static org.slf4j.LoggerFactory.getLogger;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
@Disabled("All test in this class will be skipped")
class DisabledAllTest {
static final Logger log = getLogger(lookup().lookupClass());
@Test
void skippedTestOne() {
log.debug("This test is NOT executed");
}
@Test
void skippedTestTwo() {
log.debug("This test is NOT executed");
}
}
|
Replace deprecated methods in tests | <?php
declare(strict_types = 1);
namespace DASPRiD\FormidableTest\Mapping;
use DASPRiD\Formidable\Mapping\Constraint\ConstraintInterface;
use DASPRiD\Formidable\Mapping\MappingInterface;
trait MappingTraitTestTrait
{
public function testVerifyingReturnsNewInstanceWithNewConstraints()
{
$mappingA = $this->getInstanceForTraitTests();
$mappingB = $mappingA->verifying($this->prophesize(ConstraintInterface::class)->reveal());
$mappingC = $mappingB->verifying($this->prophesize(ConstraintInterface::class)->reveal());
$this->assertNotSame($mappingA, $mappingB);
$this->assertNotSame($mappingB, $mappingC);
$this->assertAttributeCount(0, 'constraints', $mappingA);
$this->assertAttributeCount(1, 'constraints', $mappingB);
$this->assertAttributeCount(2, 'constraints', $mappingC);
}
abstract protected function getInstanceForTraitTests() : MappingInterface;
}
| <?php
declare(strict_types = 1);
namespace DASPRiD\FormidableTest\Mapping;
use DASPRiD\Formidable\Mapping\Constraint\ConstraintInterface;
use DASPRiD\Formidable\Mapping\MappingInterface;
trait MappingTraitTestTrait
{
public function testVerifyingReturnsNewInstanceWithNewConstraints()
{
$mappingA = $this->getInstanceForTraitTests();
$mappingB = $mappingA->verifying($this->getMock(ConstraintInterface::class));
$mappingC = $mappingB->verifying($this->getMock(ConstraintInterface::class));
$this->assertNotSame($mappingA, $mappingB);
$this->assertNotSame($mappingB, $mappingC);
$this->assertAttributeCount(0, 'constraints', $mappingA);
$this->assertAttributeCount(1, 'constraints', $mappingB);
$this->assertAttributeCount(2, 'constraints', $mappingC);
}
abstract protected function getInstanceForTraitTests() : MappingInterface;
}
|
Tweak the archives migration to respect the InnoDB key size constraint | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArchivesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('archives', function (Blueprint $table) {
$table->increments('id');
$table->string('url', 250)->unique();
$table->string('filename', 250)->unique();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('archives');
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArchivesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('archives', function (Blueprint $table) {
$table->increments('id');
$table->string('url')->unique();
$table->string('filename')->unique();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('archives');
}
}
|
Rename model to todoService in RemoveTodohandler | package com.example.e4.rcp.todo.handlers;
import javax.inject.Named;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import com.example.e4.rcp.todo.model.ITodoService;
import com.example.e4.rcp.todo.model.Todo;
public class RemoveTodoHandler {
@Execute
public void execute(ITodoService todoService,
@Optional @Named(IServiceConstants.ACTIVE_SELECTION) Todo todo,
@Named (IServiceConstants.ACTIVE_SHELL) Shell shell
) {
if (todo != null) {
todoService.deleteTodo(todo.getId());
} else {
MessageDialog.openInformation(shell, "Deletion not possible",
"No todo selected");
}
}
}
| package com.example.e4.rcp.todo.handlers;
import javax.inject.Named;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import com.example.e4.rcp.todo.model.ITodoService;
import com.example.e4.rcp.todo.model.Todo;
public class RemoveTodoHandler {
@Execute
public void execute(ITodoService model,
@Optional @Named(IServiceConstants.ACTIVE_SELECTION) Todo todo,
@Named (IServiceConstants.ACTIVE_SHELL) Shell shell
) {
if (todo != null) {
model.deleteTodo(todo.getId());
} else {
MessageDialog.openInformation(shell, "Deletion not possible",
"No todo selected");
}
}
}
|
Use html directory for webpack server | var info = require('../package.json');
var path = require('path');
var clientAppPath = path.join(__dirname, '../');
var devRelativeOutput = '/';
var prodRelativeOutput = '/assets/';
var devOutput = path.join(__dirname, '../html', devRelativeOutput);
var prodOutput = path.join(__dirname, '../../public', prodRelativeOutput);
// There is a warning if the .env file is missing
// This is fine in a production setting, where settings
// are loaded from the env and not from a file
require('dotenv').load({path: path.join(__dirname, '../../.env')});
var hotPort = process.env.ASSETS_PORT || 8080;
module.exports = {
title: info.title,
author: info.author,
version: info.versions,
build: Date.now(),
devRelativeOutput: devRelativeOutput,
prodRelativeOutput: prodRelativeOutput,
devOutput: devOutput,
prodOutput: prodOutput,
// Dev urls
devAssetsUrl: process.env.ASSETS_URL || 'http://localhost:' + hotPort,
hotPort: hotPort,
buildSuffix: '_web_pack_bundle.js',
entries: {
app: clientAppPath + 'js/app.jsx'
},
cssEntries: {
styles: clientAppPath + 'styles/styles.js'
}
};
| var info = require('../package.json');
var path = require('path');
var clientAppPath = path.join(__dirname, '../');
var devRelativeOutput = '/assets/';
var prodRelativeOutput = '/assets/';
var devOutput = path.join(__dirname, '../../app', devRelativeOutput);
var prodOutput = path.join(__dirname, '../../public', prodRelativeOutput);
// There is a warning if the .env file is missing
// This is fine in a production setting, where settings
// are loaded from the env and not from a file
require('dotenv').load({path: path.join(__dirname, '../../.env')});
var hotPort = process.env.ASSETS_PORT || 8080;
module.exports = {
title: info.title,
author: info.author,
version: info.versions,
build: Date.now(),
devRelativeOutput: devRelativeOutput,
prodRelativeOutput: prodRelativeOutput,
devOutput: devOutput,
prodOutput: prodOutput,
// Dev urls
devAssetsUrl: process.env.ASSETS_URL || 'http://localhost:' + hotPort,
hotPort: hotPort,
buildSuffix: '_web_pack_bundle.js',
entries: {
app: clientAppPath + 'js/app.jsx'
},
cssEntries: {
styles: clientAppPath + 'styles/styles.js'
}
};
|
Throw an exception if passed an empty value | <?php
namespace Bolt\Storage\Mapping;
use Bolt\Exception\StorageException;
/**
* Taxonomy mapping.
*
* @author Gawain Lynch <gawain.lynch@gmail.com>
*/
class TaxonomyValue implements \ArrayAccess
{
/** @var string */
protected $name;
/** @var string */
protected $value;
/** @var array */
protected $data;
/**
* Constructor.
*
* @throws StorageException
*
* @param array $data
*/
public function __construct($name, $value, array $data)
{
if (empty($value)) {
throw new StorageException('Taxonomy value can not be empty!');
}
$this->name = $name;
$this->value = $value;
$this->data = $data;
}
public function __toString()
{
return $this->value;
}
public function offsetSet($offset, $value)
{
$this->data[$offset] = $value;
}
public function offsetExists($offset)
{
return isset($this->data[$offset]);
}
public function offsetUnset($offset)
{
unset($this->data[$offset]);
}
public function offsetGet($offset)
{
return isset($this->data[$offset]) ? $this->data[$offset] : null;
}
}
| <?php
namespace Bolt\Storage\Mapping;
/**
* Taxonomy mapping.
*
* @author Gawain Lynch <gawain.lynch@gmail.com>
*/
class TaxonomyValue implements \ArrayAccess
{
/** @var string */
protected $name;
/** @var string */
protected $value;
/** @var array */
protected $data;
/**
* Constructor.
*
* @param array $data
*/
public function __construct($name, $value, array $data)
{
$this->name = $name;
$this->value = $value;
$this->data = $data;
}
public function __toString()
{
return $this->value;
}
public function offsetSet($offset, $value)
{
$this->data[$offset] = $value;
}
public function offsetExists($offset)
{
return isset($this->data[$offset]);
}
public function offsetUnset($offset)
{
unset($this->data[$offset]);
}
public function offsetGet($offset)
{
return isset($this->data[$offset]) ? $this->data[$offset] : null;
}
}
|
Make integration longer bc now ends before interrupt? | import sys
import numpy
from galpy.orbit import Orbit
from galpy.potential import MiyamotoNagaiPotential
if __name__ == '__main__':
# python orbitint4sigint.py symplec4_c full
mp= MiyamotoNagaiPotential(normalize=1.,a=0.5,b=0.05)
ts= numpy.linspace(0.,10000000.,1000001)
if sys.argv[2] == 'full' or sys.argv[2] == 'planar':
if sys.argv[2] == 'full':
o= Orbit([1.,0.1,1.1,0.1,0.1,0.])
elif sys.argv[2] == 'planar':
o= Orbit([1.,0.1,1.1,0.1])
o.integrate(ts,mp,method=sys.argv[1])
elif sys.argv[2] == 'planardxdv':
o= Orbit([1.,0.1,1.1,0.1])
o.integrate_dxdv([0.1,0.1,0.1,0.1],ts,mp,method=sys.argv[1])
sys.exit(0)
| import sys
import numpy
from galpy.orbit import Orbit
from galpy.potential import MiyamotoNagaiPotential
if __name__ == '__main__':
# python orbitint4sigint.py symplec4_c full
mp= MiyamotoNagaiPotential(normalize=1.,a=0.5,b=0.05)
ts= numpy.linspace(0.,100000.,10001)
if sys.argv[2] == 'full' or sys.argv[2] == 'planar':
if sys.argv[2] == 'full':
o= Orbit([1.,0.1,1.1,0.1,0.1,0.])
elif sys.argv[2] == 'planar':
o= Orbit([1.,0.1,1.1,0.1])
o.integrate(ts,mp,method=sys.argv[1])
elif sys.argv[2] == 'planardxdv':
o= Orbit([1.,0.1,1.1,0.1])
o.integrate_dxdv([0.1,0.1,0.1,0.1],ts,mp,method=sys.argv[1])
sys.exit(0)
|
Add ytid to the ChannelAdmin. | from django.contrib import admin
from .models import Channel, Thumbnail, Video
class VideoInline(admin.StackedInline):
extra = 1
model = Video
class ThumbnailInline(admin.TabularInline):
extra = 1
model = Thumbnail
class ChannelAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields': ('username', 'ytid')}),
('Relations', {'fields': ('idol', 'group')}),
)
inlines = [VideoInline]
list_display = ['username', 'idol', 'group']
list_select_related = True
raw_id_fields = ('idol', 'group',)
autocomplete_lookup_fields = {'fk': ['idol', 'group']}
admin.site.register(Channel, ChannelAdmin)
class VideoAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields': ('channel', 'ytid')}),
(None, {'fields': ('title', 'description', 'published', 'duration')}),
)
inlines = [ThumbnailInline]
list_display = ['title', 'channel', 'published', 'duration', 'ytid']
list_select_related = True
raw_id_fields = ('channel',)
autocomplete_lookup_fields = {'fk': ['channel']}
admin.site.register(Video, VideoAdmin)
| from django.contrib import admin
from .models import Channel, Thumbnail, Video
class VideoInline(admin.StackedInline):
extra = 1
model = Video
class ThumbnailInline(admin.TabularInline):
extra = 1
model = Thumbnail
class ChannelAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields': ('username',)}),
('Relations', {'fields': ('idol', 'group')}),
)
inlines = [VideoInline]
list_display = ['username', 'idol', 'group']
list_select_related = True
raw_id_fields = ('idol', 'group',)
autocomplete_lookup_fields = {'fk': ['idol', 'group']}
admin.site.register(Channel, ChannelAdmin)
class VideoAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields': ('channel', 'ytid')}),
(None, {'fields': ('title', 'description', 'published', 'duration')}),
)
inlines = [ThumbnailInline]
list_display = ['title', 'channel', 'published', 'duration', 'ytid']
list_select_related = True
raw_id_fields = ('channel',)
autocomplete_lookup_fields = {'fk': ['channel']}
admin.site.register(Video, VideoAdmin)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.