text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix test run on buildserver.
Though that way we don have a coverage overview after each manual run... | module.exports = function (config) {
'use strict'
config.set({
frameworks: ['jspm', 'mocha', 'chai', 'sinon'],
jspm: {
config: 'src/jspm.conf.js',
loadFiles: [
'node_modules/core-js/client/core.js',
'test/**/*.spec.js'
],
serveFiles: [
'src/**/*.js',
'test/stubs.js'
],
meta: {
'src/*': { format: 'register' }
}
},
proxies: {
'/node_modules/': '/base/node_modules/',
'/jspm_packages/': '/base/src/jspm_packages/',
'/src/': '/base/src/',
'/test/': '/base/test/'
},
autoWatchBatchDelay: 10000,
singleRun: true,
browsers: ['PhantomJS'],
captureTimeout: 2000,
browserDisconnectTimeout: 2000,
browserDisconnectTolerance: 3,
browserNoActivityTimeout: 10000,
preprocessors: {
'src/!(jspm.conf).js': ['coverage', 'sourcemap'],
'src/app/**/*.js': ['coverage', 'sourcemap']
},
reporters: ['progress', 'coverage'],
coverageReporter: {
type: 'in-memory',
includeAllSources: true
},
remapCoverageReporter: {
'text-summary': null,
json: 'reports/coverage-ts.json'
}
})
}
| module.exports = function (config) {
'use strict'
config.set({
frameworks: ['jspm', 'mocha', 'chai', 'sinon'],
jspm: {
config: 'src/jspm.conf.js',
loadFiles: [
'node_modules/core-js/client/core.js',
'test/**/*.spec.js'
],
serveFiles: [
'src/**/*.js',
'test/stubs.js'
],
meta: {
'src/*': { format: 'register' }
}
},
proxies: {
'/node_modules/': '/base/node_modules/',
'/jspm_packages/': '/base/src/jspm_packages/',
'/src/': '/base/src/',
'/test/': '/base/test/'
},
autoWatchBatchDelay: 10000,
singleRun: true,
browsers: ['PhantomJS'],
captureTimeout: 2000,
browserDisconnectTimeout: 2000,
browserDisconnectTolerance: 3,
browserNoActivityTimeout: 10000,
preprocessors: {
'src/!(jspm.conf).js': ['coverage', 'sourcemap'],
'src/app/**/*.js': ['coverage', 'sourcemap']
},
reporters: ['progress', 'coverage', 'remap-coverage'],
coverageReporter: {
type: 'in-memory',
includeAllSources: true
},
remapCoverageReporter: {
'text-summary': null,
json: '../reports/coverage-ts.json'
}
})
}
|
Reconfigure progress report record type calculation | /*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext,Slate*/
Ext.define('SlateAdmin.model.person.ProgressReport', {
extend: 'Ext.data.Model',
fields: [
'AuthorUsername',
'Subject',
{
name: 'ID',
type: 'integer',
useNull: true,
defaultValue: null
}, {
name: 'Class',
defaultValue: 'Slate\\Progress\\Note'
}, {
name: 'Type',
depends: [
'Class'
],
calculate: function (data) {
switch (data.Class) {
case 'Slate\\Progress\\SectionInterimReport':
return 'InterimReport';
case 'Slate\\Progress\\SectionTermReport':
case 'NarrativeReport':
return 'TermReport';
case 'Slate\\Progress\\Note':
default:
return 'ProgressNote';
// case 'Standards':
// return 'Standard';
}
}
}, {
name: 'Date',
type: 'date',
dateFormat: 'Y-m-d H:i:s'
}, {
name: 'StudentID',
type: 'integer'
}, {
name: 'CourseSectionID',
type: 'integer'
}, {
name: 'TermID',
type: 'integer'
}
],
proxy: {
type: 'slaterecords',
url: '/progress'
}
});
| /*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext,Slate*/
Ext.define('SlateAdmin.model.person.ProgressReport', {
extend: 'Ext.data.Model',
fields: [
'AuthorUsername',
'Subject',
{
name: 'ID',
type: 'integer',
useNull: true,
defaultValue: null
}, {
name: 'Class',
defaultValue: 'ProgressNote'
}, {
name: 'Type',
convert: function (v, r) {
switch (r.get('Class'))
{
case 'InterimReport':
return 'Interim';
case 'NarrativeReport':
return 'Narrative';
case 'ProgressNote':
return 'Note';
case 'Standards':
return 'Standards';
}
}
}, {
name: 'Date',
type: 'date',
dateFormat: 'Y-m-d H:i:s'
}, {
name: 'StudentID',
type: 'integer'
}, {
name: 'CourseSectionID',
type: 'integer'
}, {
name: 'TermID',
type: 'integer'
}
],
proxy: {
type: 'slaterecords',
url: '/progress'
}
});
|
Add new jpf test cases | package org.joda.time.field;
import org.joda.time.DateTimeFieldType;
import org.joda.time.chrono.IslamicChronology;
public class DriveDividedDateTimeField {
static DividedDateTimeField rdtf = new DividedDateTimeField(
DateTimeFieldType.dayOfMonth().getField(IslamicChronology.getInstance()),
null,
DateTimeFieldType.dayOfMonth(),
5);
static void add(long instant, int value) {
rdtf.add(instant, value);
}
static void add2(long instant, long value) {
rdtf.add(instant, value);
}
static void set(long instant, int value) {
rdtf.set(instant, value);
}
static void addWrapField(long instant, int amount) {
rdtf.addWrapField(instant, amount);
}
static void getDifference(long minuendInstant, long subtrahendInstant) {
rdtf.getDifference(minuendInstant,subtrahendInstant);
}
static void getDifferenceAsLong(long minuendInstant, long subtrahendInstant){
rdtf.getDifferenceAsLong(minuendInstant,subtrahendInstant);
}
static void remainder(long instant){
rdtf.remainder(instant);
}
public static void main(String[] args) {
add(1L, 2);
add2(1L, 2L);
set(1L,2);
addWrapField(1L,2);
remainder(1L);
getDifferenceAsLong(1L,1L);
getDifferenceAsLong(1L,1L);
}
}
| package org.joda.time.field;
import org.joda.time.DateTimeFieldType;
import org.joda.time.chrono.IslamicChronology;
public class DriveDividedDateTimeField {
static DividedDateTimeField rdtf = new DividedDateTimeField(
DateTimeFieldType.dayOfMonth().getField(IslamicChronology.getInstance()),
null,
DateTimeFieldType.dayOfMonth(),
5);
static void add(long instant, int value) {
rdtf.add(instant, value);
}
static void add2(long instant, long value) {
rdtf.add(instant, value);
}
static void set(long instant, int value) {
rdtf.set(instant, value);
}
static void addWrapField(long instant, int amount) {
rdtf.addWrapField(instant, amount);
}
static void getDifference(long minuendInstant, long subtrahendInstant) {
rdtf.getDifference(minuendInstant,subtrahendInstant);
}
static void getDifferenceAsLong(long minuendInstant, long subtrahendInstant){
rdtf.getDifferenceAsLong(minuendInstant,subtrahendInstant);
}
static void remainder(long instant){
rdtf.remainder(instant);
}
public static void main(String[] args) {
add(1L, 2);
add2(1L, 2L);
set(1L,2);
addWrapField(1L,2);
remainder(1L);
}
}
|
Add parameter to only email output from scheduled commands if it exists | <?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('import:collections --quiet')
->everyFiveMinutes()
->withoutOverlapping()
->appendOutputTo(storage_path('logs/import-collections.log'))
->sendOutputTo(storage_path('logs/import-collections-last-run.log'))
->emailOutputTo([env('LOG_EMAIL_1'), env('LOG_EMAIL_2')], true);
$schedule->command('import:daily --quiet')
->dailyAt('23:00')
->withoutOverlapping()
->appendOutputTo(storage_path('logs/import-daily.log'))
->sendOutputTo(storage_path('logs/import-daily-last-run.log'))
->emailOutputTo([env('LOG_EMAIL_1'), env('LOG_EMAIL_2')], true);
}
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
}
}
| <?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('import:collections --quiet')
->everyFiveMinutes()
->withoutOverlapping()
->appendOutputTo(storage_path('logs/import-collections.log'))
->sendOutputTo(storage_path('logs/import-collections-last-run.log'))
->emailOutputTo([env('LOG_EMAIL_1'), env('LOG_EMAIL_2')]);
$schedule->command('import:daily --quiet')
->dailyAt('23:00')
->withoutOverlapping()
->appendOutputTo(storage_path('logs/import-daily.log'))
->sendOutputTo(storage_path('logs/import-daily-last-run.log'))
->emailOutputTo([env('LOG_EMAIL_1'), env('LOG_EMAIL_2')]);
}
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
}
}
|
Set only PhantomJS as the test browser for TravisCI. | module.exports = function(config) {
config.set({
basePath: '../',
frameworks: ['jasmine'],
autoWatch: false,
browsers: ['PhantomJS'],
files: [
// angular libs
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-aria/angular-aria.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-messages/angular-messages.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-touch/angular-touch.js',
'bower_components/angular-mocks/angular-mocks.js',
// app code
'app/scripts/app.js',
'app/scripts/controllers/*.js',
// include unit tests
'test/spec/controllers/*.js',
],
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-phantomjs-launcher',
'karma-coverage',
],
reporters: [
'coverage',
],
preprocessors: {
'**/lib/*js': 'coverage',
},
coverageReporter: {
type: 'lcov',
dir: 'coverage/'
},
});
}; | module.exports = function(config) {
config.set({
basePath: '../',
frameworks: ['jasmine'],
autoWatch: false,
browsers: ['Chrome', 'PhantomJS'],
files: [
// angular libs
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-aria/angular-aria.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-messages/angular-messages.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-touch/angular-touch.js',
'bower_components/angular-mocks/angular-mocks.js',
// app code
'app/scripts/app.js',
'app/scripts/controllers/*.js',
// include unit tests
'test/spec/controllers/*.js',
],
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-phantomjs-launcher',
'karma-coverage',
],
reporters: [
'coverage',
],
preprocessors: {
'**/lib/*js': 'coverage',
},
coverageReporter: {
type: 'lcov',
dir: 'coverage/'
},
});
}; |
Set methods that don't use any fields as static | package com.alexstyl.specialdates.contact;
import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.ContactsContract;
import com.alexstyl.specialdates.DisplayName;
class DeviceContactFactory {
private final ContentResolver resolver;
DeviceContactFactory(ContentResolver contentResolver) {
resolver = contentResolver;
}
DeviceContact createContactWithId(long contactID) throws ContactNotFoundException {
String selection = ContactsContract.Data.CONTACT_ID + " = " + contactID + " AND " + ContactsContract.Data.MIMETYPE + " = ?";
Cursor cursor = resolver.query(ContactsQuery.CONTENT_URI, ContactsQuery.PROJECTION, selection, new String[]{
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE
}, ContactsQuery.SORT_ORDER + " LIMIT 1");
if (isInvalid(cursor)) {
throw new RuntimeException("Cursor was invalid");
}
try {
if (cursor.moveToFirst()) {
DisplayName displayName = getDisplayNameFrom(cursor);
String lookupKey = getLookupKeyFrom(cursor);
return new DeviceContact(contactID, displayName, lookupKey);
}
} finally {
cursor.close();
}
throw new ContactNotFoundException(contactID);
}
private static boolean isInvalid(Cursor cursor) {
return cursor == null || cursor.isClosed();
}
private static DisplayName getDisplayNameFrom(Cursor cursor) {
return DisplayName.from(cursor.getString(ContactsQuery.DISPLAY_NAME));
}
private static String getLookupKeyFrom(Cursor cursor) {
return cursor.getString(ContactsQuery.LOOKUP_KEY);
}
}
| package com.alexstyl.specialdates.contact;
import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.ContactsContract;
import com.alexstyl.specialdates.DisplayName;
class DeviceContactFactory {
private final ContentResolver resolver;
DeviceContactFactory(ContentResolver contentResolver) {
resolver = contentResolver;
}
DeviceContact createContactWithId(long contactID) throws ContactNotFoundException {
String selection = ContactsContract.Data.CONTACT_ID + " = " + contactID + " AND " + ContactsContract.Data.MIMETYPE + " = ?";
Cursor cursor = resolver.query(ContactsQuery.CONTENT_URI, ContactsQuery.PROJECTION, selection, new String[]{
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE
}, ContactsQuery.SORT_ORDER + " LIMIT 1");
if (isInvalid(cursor)) {
throw new RuntimeException("Cursor was invalid");
}
try {
if (cursor.moveToFirst()) {
DisplayName displayName = getDisplayNameFrom(cursor);
String lookupKey = getLookupKeyFrom(cursor);
return new DeviceContact(contactID, displayName, lookupKey);
}
} finally {
cursor.close();
}
throw new ContactNotFoundException(contactID);
}
private boolean isInvalid(Cursor cursor) {
return cursor == null || cursor.isClosed();
}
private String getLookupKeyFrom(Cursor cursor) {
return cursor.getString(ContactsQuery.LOOKUP_KEY);
}
private DisplayName getDisplayNameFrom(Cursor cursor) {
return DisplayName.from(cursor.getString(ContactsQuery.DISPLAY_NAME));
}
}
|
Add a big, fat warning message that scrap will delete the entire folder.
Closes #39. | <?php
namespace Studio\Console;
use Studio\Package;
use Studio\Config\Config;
use Studio\Shell\Shell;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Filesystem\Filesystem;
class ScrapCommand extends BaseCommand
{
protected $config;
public function __construct(Config $config)
{
parent::__construct();
$this->config = $config;
}
protected function configure()
{
$this
->setName('scrap')
->setDescription('Delete a previously created package skeleton')
->addArgument(
'path',
InputArgument::REQUIRED,
'The path where the package resides'
);
}
protected function fire()
{
$path = $this->input->getArgument('path');
if ($this->abortDeletion($path)) {
$this->output->note('Aborted.');
return;
}
$package = Package::fromFolder($path);
$this->config->removePackage($package);
$this->output->note('Removing package...');
$filesystem = new Filesystem;
$filesystem->remove($path);
$this->output->success('Package successfully removed.');
$this->output->note('Dumping autoloads...');
Shell::run('composer dump-autoload');
$this->output->success('Autoloads successfully generated.');
}
protected function abortDeletion($path)
{
$this->output->caution("This will delete the entire $path folder and all files within.");
return ! $this->output->confirm(
"<question>Do you really want to scrap the package at $path?</question> ",
false
);
}
}
| <?php
namespace Studio\Console;
use Studio\Package;
use Studio\Config\Config;
use Studio\Shell\Shell;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Filesystem\Filesystem;
class ScrapCommand extends BaseCommand
{
protected $config;
public function __construct(Config $config)
{
parent::__construct();
$this->config = $config;
}
protected function configure()
{
$this
->setName('scrap')
->setDescription('Delete a previously created package skeleton')
->addArgument(
'path',
InputArgument::REQUIRED,
'The path where the package resides'
);
}
protected function fire()
{
$path = $this->input->getArgument('path');
if ($this->abortDeletion($path)) {
$this->output->note('Aborted.');
return;
}
$package = Package::fromFolder($path);
$this->config->removePackage($package);
$this->output->note('Removing package...');
$filesystem = new Filesystem;
$filesystem->remove($path);
$this->output->success('Package successfully removed.');
$this->output->note('Dumping autoloads...');
Shell::run('composer dump-autoload');
$this->output->success('Autoloads successfully generated.');
}
protected function abortDeletion($path)
{
return ! $this->output->confirm(
"<question>Do you really want to scrap the package at $path?</question> ",
false
);
}
}
|
Add BMP files to supported list | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
def is_image_file(f):
known_extensions = ('.bmp', '.jpg', '.jpeg', '.png')
return os.path.isfile(f) and f.lower().endswith(known_extensions)
def get_files_list(paths, recursive):
result = []
for path in paths:
if os.path.isdir(path):
if recursive:
for root, dir_names, file_names in os.walk(path):
for filename in file_names:
f = os.path.join(root, filename)
if is_image_file(f):
result.append(f)
else:
for filename in os.listdir(path):
f = os.path.join(path, filename)
if is_image_file(f):
result.append(f)
elif is_image_file(path):
result.append(path)
else:
raise RuntimeError('unknown image format ', path)
return result
def get_file_list(path):
return get_files_list((path,), True)
def make_dir_by_file_name(file_name):
dir_name, file_name = os.path.split(file_name)
file_name_wo_ext = os.path.splitext(file_name)[0]
out_dir = os.path.join(dir_name, file_name_wo_ext)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
return out_dir
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
def is_image_file(f):
known_extensions = ('.jpg', '.jpeg', '.png')
return os.path.isfile(f) and f.lower().endswith(known_extensions)
def get_files_list(paths, recursive):
result = []
for path in paths:
if os.path.isdir(path):
if recursive:
for root, dir_names, file_names in os.walk(path):
for filename in file_names:
f = os.path.join(root, filename)
if is_image_file(f):
result.append(f)
else:
for filename in os.listdir(path):
f = os.path.join(path, filename)
if is_image_file(f):
result.append(f)
elif is_image_file(path):
result.append(path)
else:
raise RuntimeError('unknown image format ', path)
return result
def get_file_list(path):
return get_files_list((path,), True)
def make_dir_by_file_name(file_name):
dir_name, file_name = os.path.split(file_name)
file_name_wo_ext = os.path.splitext(file_name)[0]
out_dir = os.path.join(dir_name, file_name_wo_ext)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
return out_dir
|
Fix issue with creating new document | import React from "react";
import styled from "styled-components";
import AddIcon from "@atlaskit/icon/glyph/add";
import ListIcon from "@atlaskit/icon/glyph/list";
import Button, { ButtonGroup } from "@atlaskit/button";
import {
updateSelectionAndCreateNewDoc,
updateSelectionAndSwitchToList
} from "../actions";
const TitleBarWrapper = styled.div`
height: 26px;
padding: 0 12px 12px 52px;
display: flex;
align-items: center;
-webkit-app-region: drag;
`;
const Center = styled.div`flex-grow: 1;`;
const getSelection = editorActions => {
const editorView = editorActions._privateGetEditorView();
return editorView && editorView.state && editorView.state.selection.toJSON();
};
export default function TitleBar({ onAction, editorActions }) {
return (
<TitleBarWrapper>
<Center />
<ButtonGroup>
<Button
appearance="subtle-link"
spacing="none"
iconBefore={<AddIcon size="small" label="some label" />}
onClick={() =>
onAction(
updateSelectionAndCreateNewDoc(getSelection(editorActions))
)}
/>
<Button
appearance="subtle-link"
spacing="none"
iconBefore={<ListIcon size="small" label="some label" />}
onClick={() =>
onAction(
updateSelectionAndSwitchToList(getSelection(editorActions))
)}
/>
</ButtonGroup>
</TitleBarWrapper>
);
}
| import React from "react";
import styled from "styled-components";
import AddIcon from "@atlaskit/icon/glyph/add";
import ListIcon from "@atlaskit/icon/glyph/list";
import Button, { ButtonGroup } from "@atlaskit/button";
import {
updateSelectionAndCreateNewDoc,
updateSelectionAndSwitchToList
} from "../actions";
const TitleBarWrapper = styled.div`
height: 26px;
padding: 0 12px 12px 52px;
display: flex;
align-items: center;
-webkit-app-region: drag;
`;
const Center = styled.div`flex-grow: 1;`;
export default function TitleBar({ onAction, editorActions }) {
return (
<TitleBarWrapper>
<Center />
<ButtonGroup>
<Button
appearance="subtle-link"
spacing="none"
iconBefore={<AddIcon size="small" label="some label" />}
onClick={() =>
onAction(
updateSelectionAndCreateNewDoc(
editorActions._privateGetEditorView().state.selection.toJSON()
)
)}
/>
<Button
appearance="subtle-link"
spacing="none"
iconBefore={<ListIcon size="small" label="some label" />}
onClick={() =>
onAction(
updateSelectionAndSwitchToList(
editorActions._privateGetEditorView().state.selection.toJSON()
)
)}
/>
</ButtonGroup>
</TitleBarWrapper>
);
}
|
Remove lxml requirement b/c it is not easily easy_installable | from setuptools import setup, find_packages
import sys, os
version = '0.1'
setup(name='FastPt',
version=version,
description="Really fast well-formed xml templates",
long_description="""Are you tired of the slow performance of Genshi? But
you still long for the assurance that your output is well-formed that you
miss from all those other templating engines? Do you wish you had Jinja's
blocks with Genshi's syntax? Then look no further, FastPt is for you!
FastPt uses lxml to *quickly* compile Genshi-like syntax to *real python
bytecode* that renders with blazing-fast speed! Don't delay! Pick up your
copy of FastPt today!""",
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Markup :: HTML',
'Topic :: Text Processing :: Markup :: XML'
],
keywords='template xml',
author='Rick Copeland',
author_email='[email protected]',
url='http://bitbucket.org/rick446/fastpt',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
# 'lxml',
],
entry_points="""
# -*- Entry points: -*-
""",
)
| from setuptools import setup, find_packages
import sys, os
version = '0.1'
setup(name='FastPt',
version=version,
description="Really fast well-formed xml templates",
long_description="""Are you tired of the slow performance of Genshi? But
you still long for the assurance that your output is well-formed that you
miss from all those other templating engines? Do you wish you had Jinja's
blocks with Genshi's syntax? Then look no further, FastPt is for you!
FastPt uses lxml to *quickly* compile Genshi-like syntax to *real python
bytecode* that renders with blazing-fast speed! Don't delay! Pick up your
copy of FastPt today!""",
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Markup :: HTML',
'Topic :: Text Processing :: Markup :: XML'
],
keywords='template xml',
author='Rick Copeland',
author_email='[email protected]',
url='http://bitbucket.org/rick446/fastpt',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
'lxml',
],
entry_points="""
# -*- Entry points: -*-
""",
)
|
Fix a path of manifest file | const path = require('path');
const webpack = require('webpack');
const ManifestPlugin = require('webpack-manifest-plugin');
module.exports = {
entry: './resources/assets/js/app.js',
output: {
filename: './assets/app.[hash].js',
path: path.join(__dirname, '/public'),
},
module: {
rules: [
{
test: /\.scss$/,
use: [ 'style-loader', 'css-loader', 'sass-loader' ],
},
{
test: /\.(woff2?|ttf|eot|svg|png|json)(\?v=[\d.]+|\?[\s\S]+)?$/,
use: [
{ loader: 'file-loader?name=/assets/[name].[ext]' },
],
},
],
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
comments: false,
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
}),
new ManifestPlugin({
fileName: './assets/manifest.json',
}),
],
};
| const path = require('path');
const webpack = require('webpack');
const ManifestPlugin = require('webpack-manifest-plugin');
module.exports = {
entry: './resources/assets/js/app.js',
output: {
filename: './assets/app.[hash].js',
path: path.join(__dirname, '/public'),
},
module: {
rules: [
{
test: /\.scss$/,
use: [ 'style-loader', 'css-loader', 'sass-loader' ],
},
{
test: /\.(woff2?|ttf|eot|svg|png|json)(\?v=[\d.]+|\?[\s\S]+)?$/,
use: [
{ loader: 'file-loader?name=/assets/[name].[ext]' },
],
},
],
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
comments: false,
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
}),
new ManifestPlugin({
fileName: '/assets/manifest.json',
}),
],
};
|
Change hasattr check to isinstance check because it's faster. | from discord.ext.commands import Bot, CommandInvokeError
from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument
class BeattieBot(Bot):
async def reply(self, ctx, message):
return await ctx.send(f'{ctx.message.author.mention}\n{message}')
async def handle_error(self, exception, ctx):
if isinstance(exception, MissingRequiredArgument):
await ctx.send('Missing required arguments.')
elif not isinstance(exception, CommandNotFound):
await ctx.send('Generic error handler triggered. '
'This should never happen.')
if isinstance(exception, CommandInvokeError):
exception = exception.original
raise exception
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
msg = message.content.split(None, 1)
msg[0] = msg[0].lower()
message.content = ' '.join(msg)
await self.process_commands(message)
async def on_command_error(self, exception, ctx):
if ctx.command is None or not hasattr(ctx.command, 'on_error'):
await self.handle_error(exception, ctx)
| from discord.ext.commands import Bot
from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument
class BeattieBot(Bot):
async def reply(self, ctx, message):
return await ctx.send(f'{ctx.message.author.mention}\n{message}')
async def handle_error(self, exception, ctx):
if isinstance(exception, MissingRequiredArgument):
await ctx.send('Missing required arguments.')
elif not isinstance(exception, CommandNotFound):
await ctx.send('Generic error handler triggered. '
'This should never happen.')
if hasattr(exception, 'original'):
exception = exception.original
raise exception
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
msg = message.content.split(None, 1)
msg[0] = msg[0].lower()
message.content = ' '.join(msg)
await self.process_commands(message)
async def on_command_error(self, exception, ctx):
if ctx.command is None or not hasattr(ctx.command, 'on_error'):
await self.handle_error(exception, ctx)
|
Fix __unicode__ for DataPoint model | import numpy
import ast
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
options = models.CharField(max_length=100)
homo = models.FloatField()
lumo = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
return unicode(self.name)
@classmethod
def get_all_data(cls):
data = DataPoint.objects.filter(band_gap__isnull=False,
exact_name__isnull=False,
decay_feature__isnull=False)
M = len(data)
HOMO = numpy.zeros((M, 1))
LUMO = numpy.zeros((M, 1))
GAP = numpy.zeros((M, 1))
vectors = []
for i, x in enumerate(data):
HOMO[i] = x.homo
LUMO[i] = x.lumo
GAP[i] = x.band_gap
vectors.append(ast.literal_eval(x.decay_feature))
FEATURE = numpy.matrix(vectors)
return FEATURE, HOMO, LUMO, GAP | import numpy
import ast
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
options = models.CharField(max_length=100)
homo = models.FloatField()
lumo = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
return self.exact_name
@classmethod
def get_all_data(cls):
data = DataPoint.objects.filter(band_gap__isnull=False,
exact_name__isnull=False,
decay_feature__isnull=False)
M = len(data)
HOMO = numpy.zeros((M, 1))
LUMO = numpy.zeros((M, 1))
GAP = numpy.zeros((M, 1))
vectors = []
for i, x in enumerate(data):
HOMO[i] = x.homo
LUMO[i] = x.lumo
GAP[i] = x.band_gap
vectors.append(ast.literal_eval(x.decay_feature))
FEATURE = numpy.matrix(vectors)
return FEATURE, HOMO, LUMO, GAP |
Set date when creating event, not when it's require'd | define(['backbone', 'marionette'], function(Backbone, Marionette) {
return Backbone.View.extend({
template: '#event-creation',
events: {
'click button.create-event': 'create_event'
},
initialize: function() {},
render: function() {
var rendered_template = _.template($(this.template).html())();
this.$el.empty();
this.$el.append(rendered_template);
return this;
},
create_event: function(e) {
e.preventDefault();
var title = this.$el.find('.event-title').val();
var description = this.$el.find('.event-description').val();
this.$el.html($('#loading').html());
this.collection.create({
title: title,
description: description,
date: Date.now()
}, {
wait: true,
success: function (model, response, options) {
this.render();
console.log(this.collection.models);
}.bind(this),
error: function (model, xhr, options) {
console.log('ERROR!');
this.render();
}
});
}
});
});
| define(['backbone', 'marionette'], function(Backbone, Marionette) {
return Backbone.View.extend({
template: '#event-creation',
events: {
'click button.create-event': 'create_event'
},
initialize: function() {},
render: function() {
var rendered_template = _.template($(this.template).html())();
this.$el.empty();
this.$el.append(rendered_template);
return this;
},
create_event: function(e) {
e.preventDefault();
var title = this.$el.find('.event-title').val();
var description = this.$el.find('.event-description').val();
this.$el.html($('#loading').html());
this.collection.create({
title: title,
description: description
}, {
wait: true,
success: function (model, response, options) {
this.render();
}.bind(this),
error: function (model, xhr, options) {
}
});
}
});
});
|
Check for Predis\Client existance before running tests. | <?php
namespace Doctrine\Tests\Common\Cache;
use Doctrine\Common\Cache\Cache;
use Doctrine\Common\Cache\PredisCache;
use Predis\Client;
use Predis\Connection\ConnectionException;
class PredisCacheTest extends CacheTest
{
private $client;
public function setUp()
{
if (!class_exists('Predis\Client')) {
$this->markTestSkipped('Predis\Client is missing. Make sure to "composer install" to have all dev dependencies.');
}
$this->client = new Client();
try {
$this->client->connect();
} catch (ConnectionException $e) {
$this->markTestSkipped('The ' . __CLASS__ .' requires the use of redis');
}
}
public function testHitMissesStatsAreProvided()
{
$cache = $this->_getCacheDriver();
$stats = $cache->getStats();
$this->assertNotNull($stats[Cache::STATS_HITS]);
$this->assertNotNull($stats[Cache::STATS_MISSES]);
}
/**
* @return PredisCache
*/
protected function _getCacheDriver()
{
return new PredisCache($this->client);
}
/**
* {@inheritDoc}
*
* @dataProvider falseCastedValuesProvider
*/
public function testFalseCastedValues($value)
{
if (array() === $value) {
$this->markTestIncomplete(
'Predis currently doesn\'t support saving empty array values. '
. 'See https://github.com/nrk/predis/issues/241'
);
}
parent::testFalseCastedValues($value);
}
}
| <?php
namespace Doctrine\Tests\Common\Cache;
use Doctrine\Common\Cache\Cache;
use Doctrine\Common\Cache\PredisCache;
use Predis\Client;
use Predis\Connection\ConnectionException;
class PredisCacheTest extends CacheTest
{
private $client;
public function setUp()
{
$this->client = new Client();
try {
$this->client->connect();
} catch (ConnectionException $e) {
$this->markTestSkipped('The ' . __CLASS__ .' requires the use of redis');
}
}
public function testHitMissesStatsAreProvided()
{
$cache = $this->_getCacheDriver();
$stats = $cache->getStats();
$this->assertNotNull($stats[Cache::STATS_HITS]);
$this->assertNotNull($stats[Cache::STATS_MISSES]);
}
/**
* @return PredisCache
*/
protected function _getCacheDriver()
{
return new PredisCache($this->client);
}
/**
* {@inheritDoc}
*
* @dataProvider falseCastedValuesProvider
*/
public function testFalseCastedValues($value)
{
if (array() === $value) {
$this->markTestIncomplete(
'Predis currently doesn\'t support saving empty array values. '
. 'See https://github.com/nrk/predis/issues/241'
);
}
parent::testFalseCastedValues($value);
}
}
|
Make it possible to include the ID in the name mask
For example an entry mask could be "Boat #%id%" and the result would be "Boat #5" | <?php
namespace Concrete\Core\Express\Entry\Formatter;
use Concrete\Core\Entity\Express\Entry;
use Concrete\Core\Express\Formatter\FormatterInterface;
class LabelFormatter implements EntryFormatterInterface
{
/** @var \Concrete\Core\Express\Formatter\FormatterInterface */
protected $formatter;
public function __construct(FormatterInterface $formatter)
{
$this->formatter = $formatter;
}
/**
* Format a mask given an entry
* @param string $mask
* @param \Concrete\Core\Entity\Express\Entry $entry
* @return string|null
*/
public function format($mask, Entry $entry)
{
return $this->formatter->format($mask, function($key) use ($entry) {
if ($key === 'id') {
return $entry->getID();
}
$attribute = $entry->getAttribute($key);
if ($attribute) {
return $attribute;
}
$association = $entry->getAssociation($key);
if (is_object($association)) {
return $association->getSelectedEntry()->getLabel();
}
});
}
public function getLabel(Entry $entry)
{
foreach($entry->getEntity()->getAttributes() as $ak) {
if ($ak->getAttributeType()->getAttributeTypeHandle() == 'text') {
return $entry->getAttribute($ak);
}
}
}
}
| <?php
namespace Concrete\Core\Express\Entry\Formatter;
use Concrete\Core\Entity\Express\Entry;
use Concrete\Core\Express\Formatter\FormatterInterface;
class LabelFormatter implements EntryFormatterInterface
{
/** @var \Concrete\Core\Express\Formatter\FormatterInterface */
protected $formatter;
public function __construct(FormatterInterface $formatter)
{
$this->formatter = $formatter;
}
/**
* Format a mask given an entry
* @param string $mask
* @param \Concrete\Core\Entity\Express\Entry $entry
* @return string|null
*/
public function format($mask, Entry $entry)
{
return $this->formatter->format($mask, function($key) use ($entry) {
$attribute = $entry->getAttribute($key);
if ($attribute) {
return $attribute;
}
$association = $entry->getAssociation($key);
if (is_object($association)) {
return $association->getSelectedEntry()->getLabel();
}
});
}
public function getLabel(Entry $entry)
{
foreach($entry->getEntity()->getAttributes() as $ak) {
if ($ak->getAttributeType()->getAttributeTypeHandle() == 'text') {
return $entry->getAttribute($ak);
}
}
}
}
|
Add the README as the long description. | #!/usr/bin/env python
# Copyright Least Authority Enterprises.
# See LICENSE for details.
import setuptools
_metadata = {}
with open("src/txkube/_metadata.py") as f:
exec(f.read(), _metadata)
with open("README.rst") as f:
_metadata["description"] = f.read()
setuptools.setup(
name="txkube",
version=_metadata["version_string"],
description="A Twisted-based Kubernetes client.",
long_description=_metadata["description"],
author="txkube Developers",
url="https://github.com/leastauthority.com/txkube",
license="MIT",
package_dir={"": "src"},
packages=setuptools.find_packages(where="src"),
include_package_data=True,
zip_safe=False,
install_requires=[
"zope.interface",
"attrs",
"pyrsistent",
"incremental",
# See https://github.com/twisted/treq/issues/167
# And https://twistedmatrix.com/trac/ticket/9032
"twisted[tls]!=17.1.0",
"pem",
"eliot",
"python-dateutil",
"pykube",
"treq",
"klein",
],
extras_require={
"dev": [
"testtools",
"hypothesis",
"eliot-tree>=17.0.0",
],
},
)
| #!/usr/bin/env python
# Copyright Least Authority Enterprises.
# See LICENSE for details.
import setuptools
_metadata = {}
with open("src/txkube/_metadata.py") as f:
exec(f.read(), _metadata)
setuptools.setup(
name="txkube",
version=_metadata["version_string"],
description="A Twisted-based Kubernetes client.",
author="txkube Developers",
url="https://github.com/leastauthority.com/txkube",
license="MIT",
package_dir={"": "src"},
packages=setuptools.find_packages(where="src"),
include_package_data=True,
zip_safe=False,
install_requires=[
"zope.interface",
"attrs",
"pyrsistent",
"incremental",
# See https://github.com/twisted/treq/issues/167
# And https://twistedmatrix.com/trac/ticket/9032
"twisted[tls]!=17.1.0",
"pem",
"eliot",
"python-dateutil",
"pykube",
"treq",
"klein",
],
extras_require={
"dev": [
"testtools",
"hypothesis",
"eliot-tree>=17.0.0",
],
},
)
|
Add Azure SQL Server "connection lost" message | <?php
namespace Illuminate\Database;
use Throwable;
use Illuminate\Support\Str;
trait DetectsLostConnections
{
/**
* Determine if the given exception was caused by a lost connection.
*
* @param \Throwable $e
* @return bool
*/
protected function causedByLostConnection(Throwable $e)
{
$message = $e->getMessage();
return Str::contains($message, [
'server has gone away',
'no connection to the server',
'Lost connection',
'is dead or not enabled',
'Error while sending',
'decryption failed or bad record mac',
'server closed the connection unexpectedly',
'SSL connection has been closed unexpectedly',
'Error writing data to the connection',
'Resource deadlock avoided',
'Transaction() on null',
'child connection forced to terminate due to client_idle_limit',
'query_wait_timeout',
'reset by peer',
'Physical connection is not usable',
'TCP Provider: Error code 0x68',
'php_network_getaddresses: getaddrinfo failed: Name or service not known',
'ORA-03114',
'Packets out of order. Expected',
'Adaptive Server connection failed',
'Communication link failure',
]);
}
}
| <?php
namespace Illuminate\Database;
use Throwable;
use Illuminate\Support\Str;
trait DetectsLostConnections
{
/**
* Determine if the given exception was caused by a lost connection.
*
* @param \Throwable $e
* @return bool
*/
protected function causedByLostConnection(Throwable $e)
{
$message = $e->getMessage();
return Str::contains($message, [
'server has gone away',
'no connection to the server',
'Lost connection',
'is dead or not enabled',
'Error while sending',
'decryption failed or bad record mac',
'server closed the connection unexpectedly',
'SSL connection has been closed unexpectedly',
'Error writing data to the connection',
'Resource deadlock avoided',
'Transaction() on null',
'child connection forced to terminate due to client_idle_limit',
'query_wait_timeout',
'reset by peer',
'Physical connection is not usable',
'TCP Provider: Error code 0x68',
'php_network_getaddresses: getaddrinfo failed: Name or service not known',
'ORA-03114',
'Packets out of order. Expected',
'Adaptive Server connection failed',
]);
}
}
|
Allow a user’s widget data to be null on the settings page. | import React from 'react'
import PropTypes from 'prop-types'
import WidgetSettings from './WidgetSettingsContainer'
import SettingsChildWrapper from '../SettingsChildWrapperComponent'
import FullScreenProgress from 'general/FullScreenProgress'
class WidgetsSettings extends React.Component {
constructor (props) {
super(props)
this.state = {
userWidgets: null
}
}
componentDidMount () {
const { user } = this.props
const userWidgets = {}
var node
for (var index in user.widgets.edges) {
node = user.widgets.edges[index].node
userWidgets[node.name] = node
}
this.setState({
userWidgets: userWidgets
})
}
render () {
const { user, app, showError } = this.props
// We need to wait for the
// userWidgetsMap to be created before
// mounting the WidgetSettings.
if (!this.state.userWidgets) {
return (<FullScreenProgress />)
}
const self = this
return (
<SettingsChildWrapper>
<div style={{ paddingTop: 0 }} >
{app.widgets.edges.map((edge, index) => {
return (<WidgetSettings
key={index}
user={user}
appWidget={edge.node}
widget={self.state.userWidgets[edge.node.name] || null}
showError={showError} />)
})}
</div>
</SettingsChildWrapper>
)
}
}
WidgetsSettings.propTypes = {
user: PropTypes.object.isRequired,
app: PropTypes.object.isRequired,
showError: PropTypes.func.isRequired
}
export default WidgetsSettings
| import React from 'react'
import PropTypes from 'prop-types'
import WidgetSettings from './WidgetSettingsContainer'
import SettingsChildWrapper from '../SettingsChildWrapperComponent'
import FullScreenProgress from 'general/FullScreenProgress'
class WidgetsSettings extends React.Component {
constructor (props) {
super(props)
this.state = {
userWidgets: null
}
}
componentDidMount () {
const { user } = this.props
const userWidgets = {}
var node
for (var index in user.widgets.edges) {
node = user.widgets.edges[index].node
userWidgets[node.name] = node
}
this.setState({
userWidgets: userWidgets
})
}
render () {
const { user, app, showError } = this.props
// We need to wait for the
// userWidgetsMap to be created before
// mounting the WidgetSettings.
if (!this.state.userWidgets) {
return (<FullScreenProgress />)
}
const self = this
return (
<SettingsChildWrapper>
<div style={{ paddingTop: 0 }} >
{app.widgets.edges.map((edge, index) => {
return (<WidgetSettings
key={index}
user={user}
appWidget={edge.node}
widget={self.state.userWidgets[edge.node.name]}
showError={showError} />)
})}
</div>
</SettingsChildWrapper>
)
}
}
WidgetsSettings.propTypes = {
user: PropTypes.object.isRequired,
app: PropTypes.object.isRequired,
showError: PropTypes.func.isRequired
}
export default WidgetsSettings
|
Add data change to updates string only if new value is not None in order to preserve scraped data, that user decided to hide. | from __future__ import unicode_literals
from config import settings
import os
import re
import string
import pytz
def clear_screen():
# Clear screen
os.system(['clear', 'cls'][os.name == 'nt'])
def print_obj(obj):
for attr, val in obj.__dict__.iteritems():
print "{0}: {1}".format(attr, val)
def convert_to_snake_case(name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def parse_int(text):
digits = ''.join([c for c in text if c.isdigit()])
if digits.isdigit():
return int(digits)
return None
def as_client_tz(dt):
return dt.astimezone(pytz.timezone(settings.CLIENT_TZ))
def make_data_updates_string(data_changes):
updates = ""
if data_changes:
for key in data_changes:
title = key.replace("_", " ").capitalize()
old_val = data_changes[key]['old']
new_val = data_changes[key]['new']
if new_val:
updates += "\n{0}: {1} => {2}".format(title, old_val, new_val)
return updates
def delta_minutes(now, before):
delta_datetime = now - before
minutes_ago = int(delta_datetime.total_seconds() / 60)
return minutes_ago
| from __future__ import unicode_literals
from config import settings
import os
import re
import string
import pytz
def clear_screen():
# Clear screen
os.system(['clear', 'cls'][os.name == 'nt'])
def print_obj(obj):
for attr, val in obj.__dict__.iteritems():
print "{0}: {1}".format(attr, val)
def convert_to_snake_case(name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def parse_int(text):
digits = ''.join([c for c in text if c.isdigit()])
if digits.isdigit():
return int(digits)
return None
def as_client_tz(dt):
return dt.astimezone(pytz.timezone(settings.CLIENT_TZ))
def make_data_updates_string(data_changes):
updates = ""
if data_changes:
for key in data_changes:
title = key.replace("_", " ").capitalize()
old_val = data_changes[key]['old']
new_val = data_changes[key]['new']
updates += "\n{0}: {1} => {2}".format(title, old_val, new_val)
return updates
def delta_minutes(now, before):
delta_datetime = now - before
minutes_ago = int(delta_datetime.total_seconds() / 60)
return minutes_ago
|
Switch Array.indexOf to determine if event string exists | import MCStoreBus from './mcstorebus';
export const EVTYPE = {
EVUPDATE: 'EVUPDATE',
EVREMOVE: 'EVREMOVE',
EVADD: 'EVADD'
};
const _KNOWN_EVENTS = _.values(EVTYPE);
function isKnownEvent(event) {
return _KNOWN_EVENTS.indexOf(event) !== -1;
}
export class MCStore {
constructor(initialState) {
this.store = initialState;
this.bus = new MCStoreBus();
this.EVUPDATE = 'EVUPDATE';
this.EVREMOVE = 'EVREMOVE';
this.EVADD = 'EVADD';
this.knownEvents = [this.EVUPDATE, this.EVREMOVE, this.EVADD];
}
subscribe(event, fn) {
if (!isKnownEvent(event)) {
throw new Error(`Unknown Event ${event}`);
}
return this.bus.subscribe(event, fn);
}
_knownEvent(event) {
return _.findIndex(this.knownEvents, event) !== -1;
}
update(fn) {
this._performStoreAction(this.EVUPDATE, fn);
}
remove(fn) {
this._performStoreAction(this.EVREMOVE, fn);
}
add(fn) {
this._performStoreAction(this.EVADD, fn);
}
_performStoreAction(event, fn) {
fn(this.store);
this.bus.fireEvent(event, this.store);
}
} | import MCStoreBus from './mcstorebus';
export const EVTYPE = {
EVUPDATE: 'EVUPDATE',
EVREMOVE: 'EVREMOVE',
EVADD: 'EVADD'
};
const _KNOWN_EVENTS = _.values(EVTYPE);
function isKnownEvent(event) {
return _.findIndex(_KNOWN_EVENTS, event) !== -1;
}
export class MCStore {
constructor(initialState) {
this.store = initialState;
this.bus = new MCStoreBus();
this.EVUPDATE = 'EVUPDATE';
this.EVREMOVE = 'EVREMOVE';
this.EVADD = 'EVADD';
this.knownEvents = [this.EVUPDATE, this.EVREMOVE, this.EVADD];
}
subscribe(event, fn) {
if (!isKnownEvent(event)) {
throw new Error(`Unknown Event ${event}`);
}
return this.bus.subscribe(event, fn);
}
_knownEvent(event) {
return _.findIndex(this.knownEvents, event) !== -1;
}
update(fn) {
this._performStoreAction(this.EVUPDATE, fn);
}
remove(fn) {
this._performStoreAction(this.EVREMOVE, fn);
}
add(fn) {
this._performStoreAction(this.EVADD, fn);
}
_performStoreAction(event, fn) {
fn(this.store);
this.bus.fireEvent(event, this.store);
}
} |
Make sure we always get the selection list with a default value. (Cleans up error on startup.) | adjectiveArray = [{name: "happy"},{name:"sad"},{name:"angry"},{name:"afraid"}];
if (Meteor.isClient) {
Template.adjectives.adjective = function() {
return adjectiveArray;
};
Template.adjectives.events({
'click li.adjective': function() {
var selectedAdjectives = Session.get('selectedAdjectives') || [];
var newSelection = [];
if (_.contains(selectedAdjectives, this.name)) {
newSelection = _.without(selectedAdjectives, this.name);
}
else {
newSelection = selectedAdjectives;
newSelection.push(this.name);
}
Session.set('selectedAdjectives', newSelection);
},
});
Template.adjectives.isSelected = function() {
var selectedAdjectives = Session.get('selectedAdjectives');
var curAdjective = this.name;
if (_.contains(selectedAdjectives, this.name)) {
return 'selected';
}
};
Template.adjectives.numSelected = function () {
var selectedAdjectives = Session.get('selectedAdjectives') || [];
return selectedAdjectives.length;
};
Template.adjectives.validSelection = function () {
var selectedAdjectives = Session.get('selectedAdjectives') || [];
return selectedAdjectives.length == 3;
};
}
if (Meteor.isServer) {
Meteor.startup(function() {
// code to run on server at startup
});
}
| adjectiveArray = [{name: "happy"},{name:"sad"},{name:"angry"},{name:"afraid"}];
if (Meteor.isClient) {
Template.adjectives.adjective = function() {
return adjectiveArray;
};
Template.adjectives.events({
'click li.adjective': function() {
var selectedAdjectives = Session.get('selectedAdjectives') || [];
var newSelection = [];
if (_.contains(selectedAdjectives, this.name)) {
newSelection = _.without(selectedAdjectives, this.name);
}
else {
newSelection = selectedAdjectives;
newSelection.push(this.name);
}
Session.set('selectedAdjectives', newSelection);
},
});
Template.adjectives.isSelected = function() {
var selectedAdjectives = Session.get('selectedAdjectives');
var curAdjective = this.name;
if (_.contains(selectedAdjectives, this.name)) {
return 'selected';
}
};
Template.adjectives.numSelected = function () {
var selectedAdjectives = Session.get('selectedAdjectives');
return selectedAdjectives.length;
};
Template.adjectives.validSelection = function () {
var selectedAdjectives = Session.get('selectedAdjectives');
return selectedAdjectives.length == 3;
};
}
if (Meteor.isServer) {
Meteor.startup(function() {
// code to run on server at startup
});
}
|
Make sure the tifffile.py is installed. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup, Extension
import numpy
import re
with open('README.rst') as f:
readme = f.read()
with open('tifffile.py') as f:
text = f.read()
version = re.search("__version__ = '(.*?)'", text).groups()[0]
setup(
name='tifffile',
version=version,
description='Read and write image data from and to TIFF files.',
long_description=readme,
author='Steven Silvester',
author_email='[email protected]',
url='https://github.com/blink1073/tifffile',
py_modules=['tifffile'],
include_package_data=True,
ext_modules=[Extension('_tifffile',
['tifffile.c'],
include_dirs=[numpy.get_include()])],
requires=['numpy (>=1.8.2)'],
license="BSD",
zip_safe=False,
keywords='tifffile',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
"Programming Language :: C",
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup, Extension
import numpy
import re
with open('README.rst') as f:
readme = f.read()
with open('tifffile.py') as f:
text = f.read()
version = re.search("__version__ = '(.*?)'", text).groups()[0]
setup(
name='tifffile',
version=version,
description='Read and write image data from and to TIFF files.',
long_description=readme,
author='Steven Silvester',
author_email='[email protected]',
url='https://github.com/blink1073/tifffile',
include_package_data=True,
ext_modules=[Extension('_tifffile',
['tifffile.c'],
include_dirs=[numpy.get_include()])],
requires=['numpy (>=1.8.2)'],
license="BSD",
zip_safe=False,
keywords='tifffile',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
"Programming Language :: C",
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
)
|
Validate Model function to allow permission | from collections import defaultdict
from .utils import get_value_from_accessor
class RoleBehaviour(object):
ids = []
object_accessors = {}
def __init__(self, user, request):
self.user = user
self.request = request
def has_role(self):
return False
def has_role_for(self, obj):
if self.has_role() and self.ids and obj:
if self.role in obj.role_accessors:
return get_value_from_accessor(obj, obj.role_accessors[self.role]) in self.ids
return True
def can_apply_permission(self, obj, perm):
method = 'has_{}_{}_permission'.format(self.role, perm.name)
print method, hasattr(obj, method), getattr(obj, method), callable(getattr(obj, method))
if hasattr(obj, method):
function = getattr(obj, method)
if callable(function):
return function(self.user)
return True
class UserBehaviour(RoleBehaviour):
role= 'user'
def has_role(self):
return True
def role_behaviour_factory():
return RoleBehaviour
class RoleBehaviourRegistry(object):
_registry = defaultdict(role_behaviour_factory)
def register(self, cls):
self._registry[cls.role] = cls
def get_role(self, role):
return self._registry[role]
registry = RoleBehaviourRegistry() | from collections import defaultdict
from .utils import get_value_from_accessor
class RoleBehaviour(object):
ids = []
object_accessors = {}
def __init__(self, user, request):
self.user = user
self.request = request
def has_role(self):
return False
def has_role_for(self, obj):
if self.has_role() and self.ids and obj:
if self.role in obj.role_accessors:
return get_value_from_accessor(obj, obj.role_accessors[self.role]) in self.ids
return True
def can_apply_permission(self, obj, perm):
method = 'has_{}_{}_permission'.format(self.role, perm.name)
if hasattr(obj, method):
function = getattr(obj, method)
if callable(function):
return function(self.user)
return True
class UserBehaviour(RoleBehaviour):
role= 'user'
def has_role(self):
return True
def role_behaviour_factory():
return RoleBehaviour
class RoleBehaviourRegistry(object):
_registry = defaultdict(role_behaviour_factory)
def register(self, cls):
self._registry[cls.role] = cls
def get_role(self, role):
return self._registry[role]
registry = RoleBehaviourRegistry() |
Fix a copy and paste error | /* @flow */
import ConversionContext from './ConversionContext';
export type Options = {
ignore?: boolean;
assert?: boolean;
warn?: boolean;
annotate?: boolean;
suppressComments?: string[];
suppressTypes?: string[];
// deprecated
decorate?: boolean;
};
export default function createConversionContext (options: Options): ConversionContext {
const context = new ConversionContext();
context.shouldAssert = options.assert === undefined
? process.env.NODE_ENV === 'development'
: Boolean(options.assert)
;
context.shouldWarn = options.warn ? true : false;
if ('decorate' in options) {
console.warn('Warning: "decorate" option for babel-plugin-flow-runtime is now called "annotate", support for "decorate" will be removed in a future version.');
if (!('annotate' in options)) {
options.annotate = options.decorate;
}
}
context.shouldAnnotate = options.annotate === undefined
? true
: Boolean(options.annotate)
;
if ('suppressComments' in options && Array.isArray(options.suppressComments)) {
context.suppressCommentPatterns = options.suppressComments.map(RegExp);
}
if ('suppressTypes' in options && Array.isArray(options.suppressTypes)) {
context.suppressTypeNames = options.suppressTypes;
}
return context;
}
| /* @flow */
import ConversionContext from './ConversionContext';
export type Options = {
ignore?: boolean;
assert?: boolean;
warn?: boolean;
annotate?: boolean;
suppressComments?: string[];
suppressTypes?: string[];
// deprecated
decorate?: boolean;
};
export default function createConversionContext (options: Options): ConversionContext {
const context = new ConversionContext();
context.shouldAssert = options.assert === undefined
? process.env.NODE_ENV === 'development'
: Boolean(options.assert)
;
context.shouldWarn = options.warn ? true : false;
if ('decorate' in options) {
console.warn('Warning: "decorate" option for babel-plugin-flow-runtime is now called "annotate", support for "decorate" will be removed in a future version.');
if (!('annotate' in options)) {
options.annotate = options.decorate;
}
}
context.shouldAnnotate = options.annotate === undefined
? true
: Boolean(options.annotate)
;
if ('suppressComments' in options && Array.isArray(options.suppressComments)) {
context.suppressCommentPatterns = options.suppressComments.map(RegExp);
}
if ('suppressTypes' in options && Array.isArray(options.suppressTypes)) {
context.suppressTypeNames = options.suppressTypeNames;
}
return context;
}
|
Test sync return for Twisted too | from __future__ import absolute_import, division, print_function
import pytest
pytest.importorskip("twisted")
from twisted.internet.defer import Deferred, succeed, fail
from prometheus_async import tx
class TestTime(object):
@pytest.inlineCallbacks
def test_decorator_sync(self, fo, patch_timer):
"""
time works with sync results functions.
"""
@tx.time(fo)
def func():
return 42
assert 42 == (yield func())
assert [1] == fo._observed
@pytest.inlineCallbacks
def test_decorator(self, fo, patch_timer):
"""
time works with functions returning Deferreds.
"""
@tx.time(fo)
def func():
return succeed(42)
rv = func()
# Twisted runs fires callbacks immediately.
assert [1] == fo._observed
assert 42 == (yield rv)
assert [1] == fo._observed
@pytest.inlineCallbacks
def test_decorator_exc(self, fo, patch_timer):
"""
Does not swallow exceptions.
"""
v = ValueError("foo")
@tx.time(fo)
def func():
return fail(v)
with pytest.raises(ValueError) as e:
yield func()
assert v is e.value
@pytest.inlineCallbacks
def test_deferred(self, fo, patch_timer):
"""
time works with Deferreds.
"""
d = tx.time(fo, Deferred())
assert [] == fo._observed
d.callback(42)
assert 42 == (yield d)
assert [1] == fo._observed
| from __future__ import absolute_import, division, print_function
import pytest
pytest.importorskip("twisted")
from twisted.internet.defer import Deferred, succeed, fail
from prometheus_async import tx
class TestTime(object):
@pytest.inlineCallbacks
def test_decorator(self, fo, patch_timer):
"""
time works with functions returning Deferreds.
"""
@tx.time(fo)
def func():
return succeed(42)
rv = func()
# Twisted runs fires callbacks immediately.
assert [1] == fo._observed
assert 42 == (yield rv)
assert [1] == fo._observed
@pytest.inlineCallbacks
def test_decorator_exc(self, fo, patch_timer):
"""
Does not swallow exceptions.
"""
v = ValueError("foo")
@tx.time(fo)
def func():
return fail(v)
with pytest.raises(ValueError) as e:
yield func()
assert v is e.value
@pytest.inlineCallbacks
def test_deferred(self, fo, patch_timer):
"""
time works with Deferreds.
"""
d = tx.time(fo, Deferred())
assert [] == fo._observed
d.callback(42)
assert 42 == (yield d)
assert [1] == fo._observed
|
Update joke of day: Fix for moved SpinnerThread | from plugin import plugin, require
import requests
from colorama import Fore
@require(network=True)
@plugin('joke daily')
class joke_of_day:
"""
Provides you with a joke of day to help you laugh amidst the
daily boring schedule
Enter 'joke daily' to use
"""
def __call__(self, jarvis, s):
jarvis.say("Welcome To The Plugin Joke Of Day!", Fore.CYAN)
jarvis.say("Jokes provided by jokes.one API", Fore.CYAN, False)
print()
joke_fetch = self.get_joke(jarvis)
if joke_fetch is not None:
self.joke(jarvis, joke_fetch)
def get_joke(self, jarvis):
while True:
url = "https://api.jokes.one/jod"
jarvis.spinner_start('Fetching')
r = requests.get(url)
if r is None:
spinner.stop()
jarvis.say(
"Error in fetching joke - try again! later", Fore.RED)
jarvis.spinner_stop()
return r.json()
def joke(self, jarvis, joke_fetch):
title = joke_fetch["contents"]["jokes"][0]["joke"]["title"]
joke = joke_fetch["contents"]["jokes"][0]["joke"]["text"]
print()
jarvis.say("Title: " + title, Fore.BLUE)
print()
jarvis.say(joke, Fore.YELLOW)
| from plugin import plugin, require
import requests
from colorama import Fore
from plugins.animations import SpinnerThread
@require(network=True)
@plugin('joke daily')
class joke_of_day:
"""
Provides you with a joke of day to help you laugh amidst the
daily boring schedule
Enter 'joke daily' to use
"""
def __call__(self, jarvis, s):
jarvis.say("Welcome To The Plugin Joke Of Day!", Fore.CYAN)
jarvis.say("Jokes provided by jokes.one API", Fore.CYAN, False)
print()
joke_fetch = self.get_joke(jarvis)
if joke_fetch is not None:
self.joke(jarvis, joke_fetch)
def get_joke(self, jarvis):
spinner = SpinnerThread('Fetching ', 0.15)
while True:
url = "https://api.jokes.one/jod"
spinner.start()
r = requests.get(url)
if r is None:
spinner.stop()
jarvis.say(
"Error in fetching joke - try again! later", Fore.RED)
spinner.stop()
return r.json()
def joke(self, jarvis, joke_fetch):
title = joke_fetch["contents"]["jokes"][0]["joke"]["title"]
joke = joke_fetch["contents"]["jokes"][0]["joke"]["text"]
print()
jarvis.say("Title: " + title, Fore.BLUE)
print()
jarvis.say(joke, Fore.YELLOW)
|
Fix icon class of share this page services
Use same icon class with social network icon classes | <?php
namespace Concrete\Core\Sharing\ShareThisPage;
class ServiceList
{
protected static function getServices()
{
return array(
array('facebook', 'Facebook', 'fab fa-facebook'),
array('twitter', 'Twitter', 'fab fa-twitter'),
array('linkedin', 'LinkedIn', 'fab fa-linkedin'),
array('reddit', 'Reddit', 'fab fa-reddit'),
array('pinterest', 'Pinterest', 'fab fa-pinterest'),
array('google_plus', 'Google Plus', 'fab fa-google-plus-square'),
array('print', t('Print'), 'print', '<i class="fas fa-print" aria-hidden="true" title="' . h(t("Print")) . '"></i>'),
array('email', 'Email', 'envelope', '<i class="fas fa-envelope" aria-hidden="true" title="' . h(t("Email")) . '"></i>'),
);
}
public static function get()
{
$services = [];
foreach (static::getServices() as $serviceArray) {
$ssHandle = isset($serviceArray[0]) ? $serviceArray[0] : null;
$ssName = isset($serviceArray[1]) ? $serviceArray[1] : null;
$ssIcon = isset($serviceArray[2]) ? $serviceArray[2] : null;
$customHTML = isset($serviceArray[3]) ? $serviceArray[3] : null;
$service = new Service($ssHandle, $ssName, $ssIcon, $customHTML);
$services[] = $service;
}
return $services;
}
}
| <?php
namespace Concrete\Core\Sharing\ShareThisPage;
class ServiceList
{
protected static function getServices()
{
return array(
array('facebook', 'Facebook', 'facebook'),
array('twitter', 'Twitter', 'twitter'),
array('linkedin', 'LinkedIn', 'linkedin-in'),
array('reddit', 'Reddit', 'reddit'),
array('pinterest', 'Pinterest', 'pinterest'),
array('google_plus', 'Google Plus', 'google-plus'),
array('print', t('Print'), 'print', '<i class="fas fa-print" aria-hidden="true" title="' . h(t("Print")) . '"></i>'),
array('email', 'Email', 'envelope', '<i class="fas fa-envelope" aria-hidden="true" title="' . h(t("Email")) . '"></i>'),
);
}
public static function get()
{
$services = [];
foreach (static::getServices() as $serviceArray) {
$ssHandle = isset($serviceArray[0]) ? $serviceArray[0] : null;
$ssName = isset($serviceArray[1]) ? $serviceArray[1] : null;
$ssIcon = isset($serviceArray[2]) ? $serviceArray[2] : null;
$customHTML = isset($serviceArray[3]) ? $serviceArray[3] : null;
$service = new Service($ssHandle, $ssName, $ssIcon, $customHTML);
$services[] = $service;
}
return $services;
}
}
|
Remove pylint disables (for now) | # Generated by Django 3.2.6 on 2021-08-23 18:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='SiteVisit',
fields=[
('id', models.BigAutoField(primary_key=True, serialize=False)),
('date_time', models.DateTimeField(auto_now_add=True)),
('url', models.URLField(max_length=300)),
('user_agent', models.CharField(max_length=300)),
('referer', models.CharField(max_length=300)),
],
),
migrations.CreateModel(
name='LookupData',
fields=[
('id', models.BigAutoField(primary_key=True, serialize=False)),
('language1', models.CharField(max_length=50)),
('language2', models.CharField(max_length=50)),
('structure', models.CharField(max_length=50)),
('site_visit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.sitevisit')),
],
),
]
| # Generated by Django 3.2.6 on 2021-08-23 18:33
# pylint:disable=line-too-long
# pylint:disable=missing-module-docstring
# pylint:disable=
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='SiteVisit',
fields=[
('id', models.BigAutoField(primary_key=True, serialize=False)),
('date_time', models.DateTimeField(auto_now_add=True)),
('url', models.URLField(max_length=300)),
('user_agent', models.CharField(max_length=300)),
('referer', models.CharField(max_length=300)),
],
),
migrations.CreateModel(
name='LookupData',
fields=[
('id', models.BigAutoField(primary_key=True, serialize=False)),
('language1', models.CharField(max_length=50)),
('language2', models.CharField(max_length=50)),
('structure', models.CharField(max_length=50)),
('site_visit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.sitevisit')),
],
),
]
|
Add keys iterator for ``TypeParameter`` | from hoomd.parameterdicts import AttachedTypeParameterDict
class TypeParameter:
def __init__(self, name, type_kind, param_dict):
self.name = name
self.type_kind = type_kind
self.param_dict = param_dict
def __getitem__(self, key):
return self.param_dict[key]
def __setitem__(self, key, value):
self.param_dict[key] = value
@property
def default(self):
return self.param_dict.default
@default.setter
def default(self, value):
self.param_dict.default = value
def attach(self, cpp_obj, sim):
self.param_dict = AttachedTypeParameterDict(cpp_obj,
self.name,
self.type_kind,
self.param_dict,
sim)
return self
def detach(self):
self.param_dict = self.param_dict.to_dettached()
return self
def to_dict(self):
return self.param_dict.to_dict()
def keys(self):
yield from self.param_dict.keys()
| from hoomd.parameterdicts import AttachedTypeParameterDict
class TypeParameter:
def __init__(self, name, type_kind, param_dict):
self.name = name
self.type_kind = type_kind
self.param_dict = param_dict
def __getitem__(self, key):
return self.param_dict[key]
def __setitem__(self, key, value):
self.param_dict[key] = value
@property
def default(self):
return self.param_dict.default
@default.setter
def default(self, value):
self.param_dict.default = value
def attach(self, cpp_obj, sim):
self.param_dict = AttachedTypeParameterDict(cpp_obj,
self.name,
self.type_kind,
self.param_dict,
sim)
return self
def detach(self):
self.param_dict = self.param_dict.to_dettached()
return self
def to_dict(self):
return self.param_dict.to_dict()
|
Add missing semicolons and wrapped the line to 80 columns | var config = require('yaml-config')
.readConfig(__dirname + '/../config/config.yml')
, mail = require('../config/mail')(config)
, emailTemplates = require('email-templates')
, nodemailer = require('nodemailer');
// send mail with templates
exports.sendMail = function (name, to, subject, data, callback) {
var template = 'welcome.jade';
templateOptions = {
user: {
email: '[email protected]'
}
};
jade.renderFile(path.join(__dirname, '../email_templates/account_activation',
template), templateOptions, function (err, text) {
if (err) {
console.log(err);
} else {
var mailOptions = {
from: "[email protected]", // sender address
to: "[email protected]", // list of receivers
subject: "Hello", // Subject line
text: "Hello world", // plaintext body
html: text
};
if (typeof to !== 'undefined') {
mailOptions.to = to;
}
if (typeof subject !== 'undefined') {
mailOptions.subject = subject;
}
mail.sendMail(mailOptions, function (error, response) {
if (error) {
console.log(error);
} else {
console.log("Message sent: " + response.message);
}
});
mail.close();
if (callback !== undefined) {
callback(error, response);
}
}
});
}; | var config = require('yaml-config').readConfig(__dirname + '/../config/config.yml')
, mail = require('../config/mail')(config)
, emailTemplates = require('email-templates')
, nodemailer = require('nodemailer');
// send mail with templates
exports.sendMail = function (name, to, subject, data, callback) {
var template = 'welcome.jade';
templateOptions = {
user: {
email: '[email protected]'
}
}
jade.renderFile(path.join(__dirname, '../email_templates/account_activation', template), templateOptions , function(err, text) {
if (err) {
console.log(err);
} else {
var mailOptions = {
from: "[email protected]", // sender address
to: "[email protected]", // list of receivers
subject: "Hello", // Subject line
text: "Hello world", // plaintext body
html: text
}
if (typeof to !== 'undefined') {
mailOptions.to = to;
}
if (typeof subject !== 'undefined') {
mailOptions.subject = subject;
}
mail.sendMail(mailOptions, function(error, response) {
if (error) {
console.log(error);
} else {
console.log("Message sent: " + response.message);
}
});
mail.close();
if (callback !== undefined) {
callback(error, response);
}
}
});
} |
Add simple test for token on landig with redirect on app | (() => {
'use strict';
angular
.module('app')
.controller('LoginController', LoginController);
LoginController.$inject = ['growl', '$window', '$http', '$routeSegment', 'TokenService', 'Endpoints', '$localStorage'];
function LoginController(growl, $window, $http, $routeSegment, TokenService, Endpoints, $localStorage) {
const vm = this;
vm.data = {};
vm.login = login;
////
// If we have token, we don`t need input mail and password
if ($localStorage.token) {
console.log($localStorage.token);
$window.location.pathname = '/app/';
}
function login() {
let req = {
email: vm.data.email,
password: vm.data.password
};
let config = {
'Content-Type': 'application/json',
'Accept': 'application/json'
};
let response = (res) => {
if (res.status == 200) {
if (res.data.success) {
TokenService.save(res.data.data.token);
$window.location.pathname = '/app/';
} else {
growl.info(res.data.data.message);
$routeSegment.chain[0].reload();
}
}
vm.form.$setUntouched();
vm.form.$setPristine();
vm.form.$setDirty();
};
$http.post(Endpoints.AUTH, req, config).then(response);
}
}
})();
| (() => {
'use strict';
angular
.module('app')
.controller('LoginController', LoginController);
LoginController.$inject = ['growl', '$window', '$http', '$routeSegment', 'TokenService', 'Endpoints'];
function LoginController(growl, $window, $http, $routeSegment, TokenService, Endpoints) {
const vm = this;
vm.data = {};
vm.login = login;
////
function login() {
let req = {
email: vm.data.email,
password: vm.data.password
};
let config = {
'Content-Type': 'application/json',
'Accept': 'application/json'
};
let response = (res) => {
if (res.status == 200) {
if (res.data.success) {
TokenService.save(res.data.data.token);
$window.location.pathname = '/app/';
} else {
growl.info(res.data.data.message);
$routeSegment.chain[0].reload();
}
}
vm.form.$setUntouched();
vm.form.$setPristine();
vm.form.$setDirty();
};
$http.post(Endpoints.AUTH, req, config).then(response);
}
}
})();
|
Update import path method to reflect behaviour | from __future__ import unicode_literals
from optparse import make_option
import os
from csv import reader
from codecs import BOM_UTF8
import pickle
from django.utils.six import string_types, PY3
from django.core.management.base import BaseCommand, CommandError
from ...models import Path
class Command(BaseCommand):
help = 'Encode txt files in ascii format'
def add_arguments(self, parser):
parser.add_argument('--input', '-i', help='input file as pickle')
def handle(self, *args, **options):
i = options['input']
if not os.path.isfile(i):
raise CommandError
trips = pickle.load(open(i, "rb"))
print(len(trips))
i = 0
for k, path in trips.items():
trip_id = k[0]
stop_id = k[1]
if i%1000==0: print(i)
try:
_, created = Path.objects.get_or_create(
trip_id = int(trip_id),
stop_id = int(stop_id),
path = str(path)
)
pass
except Exception as e:
self.stdout.write("Error with row {} {} : {}".format(k, path, e))
i = i+1
self.stdout.write("Done") | from __future__ import unicode_literals
from optparse import make_option
import os
from csv import reader
from codecs import BOM_UTF8
import pickle
from django.utils.six import string_types, PY3
from django.core.management.base import BaseCommand, CommandError
from ...models import Path
class Command(BaseCommand):
help = 'Encode txt files in ascii format'
def add_arguments(self, parser):
parser.add_argument('--input', '-i', help='input file as pickle')
def handle(self, *args, **options):
i = options['input']
if not os.path.isfile(i):
raise CommandError
trips = pickle.load(open(i, "rb"))
print(len(trips))
for k, path in trips.items():
trip_id = k[0]
stop_id = k[1]
try:
_, created = Path.objects.get_or_create(
trip_id = int(trip_id),
stop_id = int(stop_id),
path = str(path)
)
pass
except Exception as e:
self.stdout.write("Error with row {} {} : {}".format(k, path, e))
self.stdout.write("Done") |
Extend AbstractTestCase instead of TestBase when creating and using your own mainWindow
svn changeset:22078/svn branch:6.7 | package com.vaadin.tests.components.treetable;
import com.vaadin.terminal.ExternalResource;
import com.vaadin.tests.components.AbstractTestCase;
import com.vaadin.ui.Link;
import com.vaadin.ui.TreeTable;
import com.vaadin.ui.Window;
public class DisappearingComponents extends AbstractTestCase {
@Override
public void init() {
Window mainWindow = new Window("Application");
final TreeTable tt = new TreeTable();
tt.setSizeUndefined();
tt.setWidth("100%");
tt.setImmediate(true);
tt.setPageLength(0);
tt.addContainerProperty("i", Integer.class, null);
tt.addContainerProperty("link", Link.class, null);
Object[] items = new Object[3];
for (int i = 0; i < items.length; i++) {
items[i] = tt
.addItem(
new Object[] {
i + 1,
new Link(String.valueOf(i + 1),
new ExternalResource(
"http://www.google.fi")) },
null);
}
tt.setChildrenAllowed(items[0], false);
tt.setChildrenAllowed(items[2], false);
tt.setParent(items[2], items[1]);
mainWindow.addComponent(tt);
setMainWindow(mainWindow);
}
@Override
protected String getDescription() {
return "TreeTable column component empty after expand+collapse when pageLength is set to zero";
}
@Override
protected Integer getTicketNumber() {
return 7808;
}
}
| package com.vaadin.tests.components.treetable;
import com.vaadin.terminal.ExternalResource;
import com.vaadin.tests.components.TestBase;
import com.vaadin.ui.Link;
import com.vaadin.ui.TreeTable;
import com.vaadin.ui.Window;
public class DisappearingComponents extends TestBase {
@Override
protected void setup() {
Window mainWindow = new Window("Application");
final TreeTable tt = new TreeTable();
tt.setSizeUndefined();
tt.setWidth("100%");
tt.setImmediate(true);
tt.setPageLength(0);
tt.addContainerProperty("i", Integer.class, null);
tt.addContainerProperty("link", Link.class, null);
Object[] items = new Object[3];
for (int i = 0; i < items.length; i++) {
items[i] = tt
.addItem(
new Object[] {
i + 1,
new Link(String.valueOf(i + 1),
new ExternalResource(
"http://www.google.fi")) },
null);
}
tt.setChildrenAllowed(items[0], false);
tt.setChildrenAllowed(items[2], false);
tt.setParent(items[2], items[1]);
mainWindow.addComponent(tt);
setMainWindow(mainWindow);
}
@Override
protected String getDescription() {
return "TreeTable column component empty after expand+collapse when pageLength is set to zero";
}
@Override
protected Integer getTicketNumber() {
return 7808;
}
}
|
Update syntax on SHOUTcast authhash form. | <?php
use App\Entity\StationMount;
$form_config = require __DIR__ . '/generic.php';
$form_config['groups']['basic_info']['elements']['name'][1]['validator'] = function ($text) {
$forbidden_paths = ['listen', 'admin', 'statistics', '7.html'];
foreach ($forbidden_paths as $forbidden_path) {
if (stripos($text, $forbidden_path) !== false) {
return __('Stream path cannot include reserved keywords: %s', implode(', ', $forbidden_paths));
}
}
return true;
};
$form_config['groups']['basic_info']['elements']['authhash'] = [
'text',
[
'label' => __('YP Directory Authorization Hash'),
'description' => __('If your stream is set to advertise to YP directories above, you must specify an authorization hash. You can manage authhashes <a href="%s" target="_blank">on the SHOUTcast web site</a>.',
'https://rmo.shoutcast.com'),
'default' => '',
'form_group_class' => 'col-sm-12',
],
];
$form_config['groups']['autodj']['elements']['autodj_format'][1]['choices'] = [
StationMount::FORMAT_MP3 => 'MP3',
StationMount::FORMAT_AAC => 'AAC+ (MPEG4 HE-AAC v2)',
];
$form_config['groups']['autodj']['elements']['autodj_format'][1]['default'] = StationMount::FORMAT_MP3;
return $form_config;
| <?php
use App\Entity\StationMount;
$form_config = require __DIR__.'/generic.php';
$form_config['groups']['basic_info']['elements']['name'][1]['validator'] = function($text) {
$forbidden_paths = ['listen', 'admin', 'statistics', '7.html'];
foreach($forbidden_paths as $forbidden_path) {
if (stripos($text, $forbidden_path) !== false) {
return __('Stream path cannot include reserved keywords: %s', implode(', ', $forbidden_paths));
}
}
return true;
};
$form_config['groups']['basic_info']['elements']['authhash'] = [
'text',
[
'label' => __('YP Directory Authorization Hash'),
'description' => sprintf(__('If your stream is set to advertise to YP directories above, you must specify an authorization hash. You can manage authhashes <a href="%s" target="_blank">on the SHOUTcast web site</a>.'),
'https://rmo.shoutcast.com'),
'default' => '',
'form_group_class' => 'col-sm-12',
]
];
$form_config['groups']['autodj']['elements']['autodj_format'][1]['choices'] = [
StationMount::FORMAT_MP3 => 'MP3',
StationMount::FORMAT_AAC => 'AAC+ (MPEG4 HE-AAC v2)',
];
$form_config['groups']['autodj']['elements']['autodj_format'][1]['default'] = StationMount::FORMAT_MP3;
return $form_config;
|
Fix Customer Group Type and RuleChecker | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Core\Promotion\Checker\Rule;
use Sylius\Component\Core\Model\CustomerInterface;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Promotion\Checker\Rule\RuleCheckerInterface;
use Sylius\Component\Promotion\Exception\UnsupportedTypeException;
use Sylius\Component\Promotion\Model\PromotionSubjectInterface;
/**
* @author Antonio Perić <[email protected]>
*/
class CustomerGroupRuleChecker implements RuleCheckerInterface
{
/**
* {@inheritdoc}
*/
public function isEligible(PromotionSubjectInterface $subject, array $configuration)
{
if (!$subject instanceof OrderInterface) {
throw new UnsupportedTypeException($subject, OrderInterface::class);
}
if (null === $customer = $subject->getCustomer()) {
return false;
}
if (!$customer instanceof CustomerInterface) {
return false;
}
if (is_null($customer->getGroup())) {
return false;
}
if ($configuration['group'] === $customer->getGroup()->getId()) {
return true;
}
return false;
}
/**
* {@inheritdoc}
*/
public function getConfigurationFormType()
{
return 'sylius_promotion_rule_customer_group_configuration';
}
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Core\Promotion\Checker\Rule;
use Sylius\Component\Core\Model\CustomerInterface;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Promotion\Checker\Rule\RuleCheckerInterface;
use Sylius\Component\Promotion\Exception\UnsupportedTypeException;
use Sylius\Component\Promotion\Model\PromotionSubjectInterface;
/**
* @author Antonio Perić <[email protected]>
*/
class CustomerGroupRuleChecker implements RuleCheckerInterface
{
/**
* {@inheritdoc}
*/
public function isEligible(PromotionSubjectInterface $subject, array $configuration)
{
if (!$subject instanceof OrderInterface) {
throw new UnsupportedTypeException($subject, OrderInterface::class);
}
if (null === $customer = $subject->getCustomer()) {
return false;
}
if (!$customer instanceof CustomerInterface) {
return false;
}
if ($configuration['groups'] === $customer->getGroup()->getId()) {
return true;
}
return false;
}
/**
* {@inheritdoc}
*/
public function getConfigurationFormType()
{
return 'sylius_promotion_rule_customer_group_configuration';
}
}
|
Use a valid port from env | require('../../../support/test_helper.js');
var _ = require('underscore');
var assert = require('assert');
var cartodbServer = require('../../../../lib/cartodb/server');
var serverOptions = require('../../../../lib/cartodb/server_options');
describe('windshaft', function() {
it('should have valid global environment', function() {
assert.equal(global.environment.name, 'test');
});
it('can instantiate a Windshaft object (configured express instance)', function(){
var ws = cartodbServer(serverOptions);
assert.ok(ws);
});
it('can spawn a new server on the global listen port', function(done){
var ws = cartodbServer(serverOptions);
var server = ws.listen(global.environment.port, function() {
assert.ok(ws);
server.close(done); /* allow proper tear down */
});
});
it('throws exception if incorrect options passed in', function(){
assert.throws(
function(){
var ws = cartodbServer({unbuffered_logging:true});
ws.listen();
}, /Cannot read property 'mapnik' of undefined/
);
});
it('options are set on main windshaft object', function(){
var ws = cartodbServer(serverOptions);
assert.ok(_.isObject(ws.bind));
assert.ok(_.isObject(ws.grainstore));
assert.equal(ws.base_url, '/tiles/:table');
});
});
| require('../../../support/test_helper.js');
var _ = require('underscore');
var assert = require('assert');
var cartodbServer = require('../../../../lib/cartodb/server');
var serverOptions = require('../../../../lib/cartodb/server_options');
describe('windshaft', function() {
it('should have valid global environment', function() {
assert.equal(global.environment.name, 'test');
});
it('can instantiate a Windshaft object (configured express instance)', function(){
var ws = cartodbServer(serverOptions);
assert.ok(ws);
});
it('can spawn a new server on the global listen port', function(done){
var ws = cartodbServer(serverOptions);
var server = ws.listen(global.environment.windshaft_port, function() {
assert.ok(ws);
server.close(done); /* allow proper tear down */
});
});
it('throws exception if incorrect options passed in', function(){
assert.throws(
function(){
var ws = cartodbServer({unbuffered_logging:true});
ws.listen();
}, /Cannot read property 'mapnik' of undefined/
);
});
it('options are set on main windshaft object', function(){
var ws = cartodbServer(serverOptions);
assert.ok(_.isObject(ws.bind));
assert.ok(_.isObject(ws.grainstore));
assert.equal(ws.base_url, '/tiles/:table');
});
});
|
Add the to_dependency method to ProjectPackage | from poetry_core.semver import VersionRange
from poetry_core.semver import parse_constraint
from poetry_core.version.markers import parse_marker
from .package import Package
from .utils.utils import create_nested_marker
class ProjectPackage(Package):
def __init__(self, name, version, pretty_version=None):
super(ProjectPackage, self).__init__(name, version, pretty_version)
self.build = None
self.packages = []
self.include = []
self.exclude = []
self.custom_urls = {}
if self._python_versions == "*":
self._python_constraint = parse_constraint("~2.7 || >=3.4")
def is_root(self):
return True
def to_dependency(self):
dependency = super(ProjectPackage, self).to_dependency()
dependency.is_root = True
return dependency
@property
def python_versions(self):
return self._python_versions
@python_versions.setter
def python_versions(self, value):
self._python_versions = value
if value == "*" or value == VersionRange():
value = "~2.7 || >=3.4"
self._python_constraint = parse_constraint(value)
self._python_marker = parse_marker(
create_nested_marker("python_version", self._python_constraint)
)
@property
def urls(self):
urls = super(ProjectPackage, self).urls
urls.update(self.custom_urls)
return urls
| from poetry_core.semver import VersionRange
from poetry_core.semver import parse_constraint
from poetry_core.version.markers import parse_marker
from .package import Package
from .utils.utils import create_nested_marker
class ProjectPackage(Package):
def __init__(self, name, version, pretty_version=None):
super(ProjectPackage, self).__init__(name, version, pretty_version)
self.build = None
self.packages = []
self.include = []
self.exclude = []
self.custom_urls = {}
if self._python_versions == "*":
self._python_constraint = parse_constraint("~2.7 || >=3.4")
def is_root(self):
return True
@property
def python_versions(self):
return self._python_versions
@python_versions.setter
def python_versions(self, value):
self._python_versions = value
if value == "*" or value == VersionRange():
value = "~2.7 || >=3.4"
self._python_constraint = parse_constraint(value)
self._python_marker = parse_marker(
create_nested_marker("python_version", self._python_constraint)
)
@property
def urls(self):
urls = super(ProjectPackage, self).urls
urls.update(self.custom_urls)
return urls
|
Add unit test for daily email | package models
import (
"testing"
"socialapi/config"
. "github.com/smartystreets/goconvey/convey"
)
func TestTemplateRender(t *testing.T) {
uc := UserContact{}
Convey("Daily email", t, func() {
Convey("Should load a correct config", func() {
So(func() { config.MustRead("./test.toml") }, ShouldNotPanic)
Convey("Should load a template parser", func() {
tp := NewTemplateParser()
tp.UserContact = &uc
So(tp, ShouldNotBeNil)
err := tp.validateTemplateParser()
So(err, ShouldBeNil)
Convey("Should be able to inline css from style.css", func() {
base := "<html><head></head><body><a href='test'>test</a></body></html>"
html := tp.inlineCss(base)
So(html, ShouldNotBeNil)
So(html, ShouldNotEqual, base)
So(html, ShouldContainSubstring, "style=")
})
Convey("Should be able to inline css from style.css", func() {
var containers []*MailerContainer
html, err := tp.RenderDailyTemplate(containers)
So(err, ShouldBeNil)
So(html, ShouldNotBeNil)
So(html, ShouldContainSubstring, "style=")
})
})
})
})
}
| package models
import (
"testing"
"socialapi/config"
. "github.com/smartystreets/goconvey/convey"
)
func TestTemplateRender(t *testing.T) {
uc := UserContact{}
Convey("Daily email", t, func() {
Convey("Should load a correct config", func() {
So(func() { config.MustRead("./test.toml") }, ShouldNotPanic)
Convey("Should load a template parser", func() {
tp := NewTemplateParser()
tp.UserContact = &uc
So(tp, ShouldNotBeNil)
err := tp.validateTemplateParser()
So(err, ShouldBeNil)
Convey("Should be able to inline css from style.css", func() {
base := "<html><head></head><body><a href='test'>test</a></body></html>"
html := tp.inlineCss(base)
So(html, ShouldNotBeNil)
So(html, ShouldNotEqual, base)
So(html, ShouldContainSubstring, "style=")
})
})
})
})
}
|
Fix typo in message name constraints | package seedu.agendum.model.task;
import seedu.agendum.commons.exceptions.IllegalValueException;
/**
* Represents a Task's name in the to do list.
* Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
*/
public class Name {
public static final String MESSAGE_NAME_CONSTRAINTS = "Task names should only contain spaces or alphanumeric characters";
public static final String NAME_VALIDATION_REGEX = "[\\p{Alnum} ]+";
public final String fullName;
/**
* Validates given name.
*
* @throws IllegalValueException if given name string is invalid.
*/
public Name(String name) throws IllegalValueException {
assert name != null;
name = name.trim();
if (!isValidName(name)) {
throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
}
this.fullName = name;
}
/**
* Returns true if a given string is a valid task name.
*/
public static boolean isValidName(String test) {
return test.matches(NAME_VALIDATION_REGEX);
}
@Override
public String toString() {
return fullName;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Name // instanceof handles nulls
&& this.fullName.equals(((Name) other).fullName)); // state check
}
@Override
public int hashCode() {
return fullName.hashCode();
}
}
| package seedu.agendum.model.task;
import seedu.agendum.commons.exceptions.IllegalValueException;
/**
* Represents a Task's name in the to do list.
* Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
*/
public class Name {
public static final String MESSAGE_NAME_CONSTRAINTS = "Task names should only conyain spaces or alphanumeric characters";
public static final String NAME_VALIDATION_REGEX = "[\\p{Alnum} ]+";
public final String fullName;
/**
* Validates given name.
*
* @throws IllegalValueException if given name string is invalid.
*/
public Name(String name) throws IllegalValueException {
assert name != null;
name = name.trim();
if (!isValidName(name)) {
throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
}
this.fullName = name;
}
/**
* Returns true if a given string is a valid task name.
*/
public static boolean isValidName(String test) {
return test.matches(NAME_VALIDATION_REGEX);
}
@Override
public String toString() {
return fullName;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Name // instanceof handles nulls
&& this.fullName.equals(((Name) other).fullName)); // state check
}
@Override
public int hashCode() {
return fullName.hashCode();
}
}
|
Change BindTextureRenderNode to make fewer GL calls when the texture scale is None. | """
bind_texture
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from OpenGL import GL
from mcedit2.rendering.scenegraph import rendernode
from mcedit2.rendering.scenegraph.rendernode import RenderstateRenderNode
from mcedit2.rendering.scenegraph.scenenode import Node
from mcedit2.util import glutils
log = logging.getLogger(__name__)
class BindTextureRenderNode(RenderstateRenderNode):
def enter(self):
GL.glPushAttrib(GL.GL_ENABLE_BIT | GL.GL_TEXTURE_BIT)
scale = self.sceneNode.scale
if scale is not None:
GL.glMatrixMode(GL.GL_TEXTURE)
GL.glPushMatrix()
GL.glLoadIdentity()
GL.glScale(*scale)
glutils.glActiveTexture(GL.GL_TEXTURE0) # disable texture1?
GL.glEnable(GL.GL_TEXTURE_2D)
if self.sceneNode.texture is not None:
self.sceneNode.texture.bind()
def exit(self):
if self.sceneNode.scale is not None:
# Please do not change BindTextureNode.scale during RenderNode calls, thx
GL.glMatrixMode(GL.GL_TEXTURE)
GL.glPopMatrix()
GL.glPopAttrib()
class BindTextureNode(Node):
RenderNodeClass = BindTextureRenderNode
def __init__(self, texture, scale=None):
"""
:type texture: glutils.Texture
"""
super(BindTextureNode, self).__init__()
self.texture = texture
self.scale = scale
| """
bind_texture
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from OpenGL import GL
from mcedit2.rendering.scenegraph import rendernode
from mcedit2.rendering.scenegraph.rendernode import RenderstateRenderNode
from mcedit2.rendering.scenegraph.scenenode import Node
from mcedit2.util import glutils
log = logging.getLogger(__name__)
class BindTextureRenderNode(RenderstateRenderNode):
def enter(self):
GL.glPushAttrib(GL.GL_ENABLE_BIT | GL.GL_TEXTURE_BIT)
GL.glMatrixMode(GL.GL_TEXTURE)
GL.glPushMatrix()
GL.glLoadIdentity()
scale = self.sceneNode.scale
if scale is not None:
GL.glScale(*scale)
glutils.glActiveTexture(GL.GL_TEXTURE0)
GL.glEnable(GL.GL_TEXTURE_2D)
if self.sceneNode.texture is not None:
self.sceneNode.texture.bind()
def exit(self):
GL.glMatrixMode(GL.GL_TEXTURE)
GL.glPopMatrix()
GL.glPopAttrib()
class BindTextureNode(Node):
RenderNodeClass = BindTextureRenderNode
def __init__(self, texture, scale=None):
"""
:type texture: glutils.Texture
"""
super(BindTextureNode, self).__init__()
self.texture = texture
self.scale = scale
|
Change one more CAPTIVA to Intelligent Capture | import React from 'react';
import { version } from 'root/package.json';
import RaisedButton from 'material-ui/lib/raised-button';
import FlatButton from 'material-ui/lib/flat-button';
import Dialog from 'material-ui/lib/dialog';
export default class AboutButton extends React.Component {
state = {
dialogIsOpen: false
};
render() {
const okButton = (
<FlatButton
label="OK"
primary
onTouchTap={this.closeDialog}
/>
);
return (
<div style={style.container}>
<RaisedButton
label="About"
onTouchTap={this.openDialog}
/>
<Dialog
title="About this tool"
open={this.state.dialogIsOpen}
actions={[okButton]}
onRequestClose={this.closeDialog}
modal={false}
>
<p>Intelligent Capture License Decoder (version {version})</p>
<p>
{'Concept and specifications by Jim Smith. Designed and implemented by '}
<a href="https://www.linkedin.com/in/ksmithbaylor" target="_blank">
Kevin Smith
</a>.
</p>
</Dialog>
</div>
);
}
closeDialog = () => this.setState({ dialogIsOpen: false });
openDialog = () => this.setState({ dialogIsOpen: true });
}
const style = {
container: {
display: 'inline-block',
marginRight: '0.5em'
}
};
| import React from 'react';
import { version } from 'root/package.json';
import RaisedButton from 'material-ui/lib/raised-button';
import FlatButton from 'material-ui/lib/flat-button';
import Dialog from 'material-ui/lib/dialog';
export default class AboutButton extends React.Component {
state = {
dialogIsOpen: false
};
render() {
const okButton = (
<FlatButton
label="OK"
primary
onTouchTap={this.closeDialog}
/>
);
return (
<div style={style.container}>
<RaisedButton
label="About"
onTouchTap={this.openDialog}
/>
<Dialog
title="About this tool"
open={this.state.dialogIsOpen}
actions={[okButton]}
onRequestClose={this.closeDialog}
modal={false}
>
<p>CAPTIVA License Decoder (version {version})</p>
<p>
{'Concept and specifications by Jim Smith. Designed and implemented by '}
<a href="https://www.linkedin.com/in/ksmithbaylor" target="_blank">
Kevin Smith
</a>.
</p>
</Dialog>
</div>
);
}
closeDialog = () => this.setState({ dialogIsOpen: false });
openDialog = () => this.setState({ dialogIsOpen: true });
}
const style = {
container: {
display: 'inline-block',
marginRight: '0.5em'
}
};
|
Check whether six has been installed before running tests | #!/usr/bin/env python
from __future__ import unicode_literals
import os, sys
try:
import six
from django.conf import settings
except ImportError:
print("Django has not been installed.")
sys.exit(0)
if not settings.configured:
settings.configure(
INSTALLED_APPS=["jstemplate"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3"}})
def runtests(*test_args):
if not test_args:
test_args = ["jstemplate"]
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
import django
if six.PY3 and django.VERSION < (1, 5):
print("Django " + '.'.join([str(i) for i in django.VERSION]) +
" is not compatible with Python 3. Skipping tests.")
sys.exit(0)
runtests()
| #!/usr/bin/env python
from __future__ import unicode_literals
import os, sys
import six
try:
from django.conf import settings
except ImportError:
print("Django has not been installed.")
sys.exit(0)
if not settings.configured:
settings.configure(
INSTALLED_APPS=["jstemplate"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3"}})
def runtests(*test_args):
if not test_args:
test_args = ["jstemplate"]
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
import django
if six.PY3 and django.VERSION < (1, 5):
print("Django " + '.'.join([str(i) for i in django.VERSION]) +
" is not compatible with Python 3. Skipping tests.")
sys.exit(0)
runtests()
|
Rename isAlive method to is_alive
Python 3.9 compatibility fix | import threading
from . import pypofetch
def __timeout(func, timeout_duration, default, args, kwargs):
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = default
def run(self):
self.result = func(*args, **kwargs)
first_attempt = True
while True:
it = InterruptableThread()
it.start()
if not first_attempt:
timeout_duration = timeout_duration * 2
it.join(timeout_duration)
if it.is_alive():
"""Restart Liquidsoap and try the command one more time. If it
fails again then there is something critically wrong..."""
if first_attempt:
# restart liquidsoap
pypofetch.PypoFetch.ref.restart_liquidsoap()
else:
raise Exception("Thread did not terminate")
else:
return it.result
first_attempt = False
def ls_timeout(f, timeout=15, default=None):
def new_f(*args, **kwargs):
return __timeout(f, timeout, default, args, kwargs)
return new_f
| import threading
from . import pypofetch
def __timeout(func, timeout_duration, default, args, kwargs):
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = default
def run(self):
self.result = func(*args, **kwargs)
first_attempt = True
while True:
it = InterruptableThread()
it.start()
if not first_attempt:
timeout_duration = timeout_duration * 2
it.join(timeout_duration)
if it.isAlive():
"""Restart Liquidsoap and try the command one more time. If it
fails again then there is something critically wrong..."""
if first_attempt:
# restart liquidsoap
pypofetch.PypoFetch.ref.restart_liquidsoap()
else:
raise Exception("Thread did not terminate")
else:
return it.result
first_attempt = False
def ls_timeout(f, timeout=15, default=None):
def new_f(*args, **kwargs):
return __timeout(f, timeout, default, args, kwargs)
return new_f
|
Revert back not replacing content for general likes directive | angular.module('codebrag.commits')
.directive('generalLikes', function (authService) {
return {
restrict: 'E',
scope: {
author: '=',
likesCollection: '=',
submitLike: '&'
},
templateUrl: 'generalLikes',
link: function (scope, element) {
scope.noLikes = function () {
return _.isEmpty(scope.likesCollection)
};
scope.conjugatedLike = "likes";
var currentUserName = authService.loggedInUser.fullName;
var setUserAlreadyLikedStyle = function (isAlreadyLiked) {
if (isAlreadyLiked) $('div.like-commit', element).addClass("liked-by-user");
};
var removeAuthorWatch = scope.$watch(function () {
return scope.author
}, function (newVal) {
if (angular.isUndefined(newVal)) {
return;
}
setUserAlreadyLikedStyle(scope.author == currentUserName);
removeAuthorWatch();
});
var removeCollectionReferenceWatch = scope.$watch(function () {
return scope.likesCollection
}, function (newVal) {
if (angular.isUndefined(newVal)) {
return;
}
scope.$watch(function () {
return scope.likesCollection.length;
}, function (newVal) {
if (newVal > 1) {
scope.conjugatedLike = "like";
}
if (_.some(scope.likesCollection, function (like) {
return like.authorName == currentUserName
})) {
setUserAlreadyLikedStyle(true);
}
}
);
removeCollectionReferenceWatch();
});
}
}
}
)
;
| angular.module('codebrag.commits')
.directive('generalLikes', function (authService) {
return {
restrict: 'E',
replace: true,
scope: {
author: '=',
likesCollection: '=',
submitLike: '&'
},
templateUrl: 'generalLikes',
link: function (scope, element) {
scope.noLikes = function () {
return _.isEmpty(scope.likesCollection)
};
scope.conjugatedLike = "likes";
var currentUserName = authService.loggedInUser.fullName;
var setUserAlreadyLikedStyle = function (isAlreadyLiked) {
if (isAlreadyLiked) $('div.like-commit', element).addClass("liked-by-user");
};
var removeAuthorWatch = scope.$watch(function () {
return scope.author
}, function (newVal) {
if (angular.isUndefined(newVal)) {
return;
}
setUserAlreadyLikedStyle(scope.author == currentUserName);
removeAuthorWatch();
});
var removeCollectionReferenceWatch = scope.$watch(function () {
return scope.likesCollection
}, function (newVal) {
if (angular.isUndefined(newVal)) {
return;
}
scope.$watch(function () {
return scope.likesCollection.length;
}, function (newVal) {
if (newVal > 1) {
scope.conjugatedLike = "like";
}
if (_.some(scope.likesCollection, function (like) {
return like.authorName == currentUserName
})) {
setUserAlreadyLikedStyle(true);
}
}
);
removeCollectionReferenceWatch();
});
}
}
}
)
;
|
Use /base in the SVG path
Unfortunatly we need that. | define(["sugar-web/graphics/icon"], function (icon) {
describe("icon", function () {
var wasLoaded;
var iconUrlResult;
it("should be able to change icon more than once", function () {
var elem = document.createElement('div');
var iconUrl;
function callback(url) {
iconUrlResult = url;
wasLoaded = true;
}
runs(function () {
wasLoaded = false;
iconUrl = "/base/graphics/icons/actions/dialog-ok-active.svg";
iconInfo = {
"uri": iconUrl,
"strokeColor": '#B20008',
"fillColor": '#FF2B34'
};
icon.load(iconInfo, callback);
});
waitsFor(function () {
return wasLoaded;
}, "icon loaded");
runs(function () {
expect(iconUrlResult).not.toBe(iconUrl);
});
runs(function () {
wasLoaded = false;
iconUrl = iconUrlResult;
iconInfo = {
"uri": iconUrl,
"strokeColor": '#FF2B34',
"fillColor": '#B20008'
};
icon.load(iconInfo, callback);
});
waitsFor(function () {
return wasLoaded;
}, "icon loaded");
runs(function () {
expect(iconUrlResult).not.toBe(iconUrl);
});
});
});
});
| define(["sugar-web/graphics/icon"], function (icon) {
describe("icon", function () {
var wasLoaded;
var iconUrlResult;
it("should be able to change icon more than once", function () {
var elem = document.createElement('div');
var iconUrl;
function callback(url) {
iconUrlResult = url;
wasLoaded = true;
}
runs(function () {
wasLoaded = false;
iconUrl = "graphics/icons/actions/dialog-ok-active.svg";
iconInfo = {
"uri": iconUrl,
"strokeColor": '#B20008',
"fillColor": '#FF2B34'
};
icon.load(iconInfo, callback);
});
waitsFor(function () {
return wasLoaded;
}, "icon loaded");
runs(function () {
expect(iconUrlResult).not.toBe(iconUrl);
});
runs(function () {
wasLoaded = false;
iconUrl = iconUrlResult;
iconInfo = {
"uri": iconUrl,
"strokeColor": '#FF2B34',
"fillColor": '#B20008'
};
icon.load(iconInfo, callback);
});
waitsFor(function () {
return wasLoaded;
}, "icon loaded");
runs(function () {
expect(iconUrlResult).not.toBe(iconUrl);
});
});
});
});
|
Add another user in fixture code | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask
from flask_restful import Api
from .db import configure_database
class Application:
def __init__(self):
self.flask_app = Flask(__name__)
self.api = Api(self.flask_app)
self.import_configuration()
self.configure_database()
self.setup_api()
def import_configuration(self):
self.flask_app.config.from_object('core.settings')
def configure_database(self):
self.db = configure_database(self.flask_app)
def setup_api(self):
from .api import setup_api
setup_api(self)
def bootstrap(self):
from .models import User, Question, Category
if not Question.find_all():
User.create('peter', 'valdez')
User.create('sundar', 'raman')
Question.create(text='Is this what you want?')
Question.create(text='Really?')
Question.create(text='Are you sure?')
Category.create(name='Strength')
Category.create(name='Dexterity')
Category.create(name='Intelligence')
Category.create(name='Luck')
def run(self):
if self.flask_app.config['DEBUG']:
self.bootstrap()
self.flask_app.run(host='0.0.0.0')
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask
from flask_restful import Api
from .db import configure_database
class Application:
def __init__(self):
self.flask_app = Flask(__name__)
self.api = Api(self.flask_app)
self.import_configuration()
self.configure_database()
self.setup_api()
def import_configuration(self):
self.flask_app.config.from_object('core.settings')
def configure_database(self):
self.db = configure_database(self.flask_app)
def setup_api(self):
from .api import setup_api
setup_api(self)
def bootstrap(self):
from .models import User, Question, Category
if not Question.find_all():
User.create('peter', 'asdf')
Question.create(text='Is this what you want?')
Question.create(text='Really?')
Question.create(text='Are you sure?')
Category.create(name='Strength')
Category.create(name='Dexterity')
Category.create(name='Intelligence')
Category.create(name='Luck')
def run(self):
if self.flask_app.config['DEBUG']:
self.bootstrap()
self.flask_app.run(host='0.0.0.0')
|
Add missing title to navigation options in payment info screen | import React, { Component } from 'react';
import { View, Alert } from 'react-native';
import { Text, ListItem, Thumbnail, Body, Left, Form, Content, Button } from 'native-base';
import paymentInfoScreenStyle from './paymentInfoScreenStyle';
const alertMessage1 = 'För Kortet .... .... .... 4499\n';
const alertMessage2 = 'För Kortet .... .... .... 3232\n';
export default class PaymentInfoScreen extends Component {
static navigationOptions = {
title: 'Payment Information',
};
render() {
return (
<Content>
<Form>
<ListItem avatar onPress={() => Alert.alert('Bekräfta Betalning', alertMessage1)}>
<Left>
<Thumbnail source={require('./master.png')} />
</Left>
<Body>
<Text> .... .... .... 4499</Text>
<Text note>Master Card</Text>
</Body>
</ListItem>
<ListItem avatar onPress={() => Alert.alert('Bekräfta Betalning', alertMessage2)}>
<Left>
<Thumbnail source={require('./visa.png')} />
</Left>
<Body>
<Text> .... .... .... 3232</Text>
<Text note>Visa Card</Text>
</Body>
</ListItem>
</Form>
<View style={paymentInfoScreenStyle.addCardButton}>
<Button block light>
<Text>Lägg Till Kort</Text>
</Button>
</View>
</Content>
);
}
}
| import React, { Component } from 'react';
import { View, Alert } from 'react-native';
import { Text, ListItem, Thumbnail, Body, Left, Form, Content, Button } from 'native-base';
import paymentInfoScreenStyle from './paymentInfoScreenStyle';
const alertMessage1 = 'För Kortet .... .... .... 4499\n';
const alertMessage2 = 'För Kortet .... .... .... 3232\n';
export default class PaymentInfoScreen extends Component {
render() {
return (
<Content>
<Form>
<ListItem avatar onPress={() => Alert.alert('Bekräfta Betalning', alertMessage1)}>
<Left>
<Thumbnail source={require('./master.png')} />
</Left>
<Body>
<Text> .... .... .... 4499</Text>
<Text note>Master Card</Text>
</Body>
</ListItem>
<ListItem avatar onPress={() => Alert.alert('Bekräfta Betalning', alertMessage2)}>
<Left>
<Thumbnail source={require('./visa.png')} />
</Left>
<Body>
<Text> .... .... .... 3232</Text>
<Text note>Visa Card</Text>
</Body>
</ListItem>
</Form>
<View style={paymentInfoScreenStyle.addCardButton}>
<Button block light>
<Text>Lägg Till Kort</Text>
</Button>
</View>
</Content>
);
}
}
|
Use settings.containerClass and settings.paginatorClass on ajax call
otherwise we can't use multiple pagemore buttons and containers inside
the same page | (function($) {
$.fn.pagemore = function(options) {
var settings = $.extend( {
containerClass: 'pagemore-container',
paginatorClass: 'pagemore-paginator',
pageRequested: function(e) {
e.paginator.hide();
},
pageCompleted: function(e) {
e.paginator.toggle(! e.lastPage);
}
}, options);
return this.each(function() {
var container = $("." + settings.containerClass);
var paginator = $(this);
paginator.click(function() {
var event = { paginator: paginator };
settings.pageRequested(event);
$.get($(this).attr('href'),
function(resp) {
$(resp).find("." + settings.containerClass).children().appendTo(container);
var newPaginator = $(resp).find("." + settings.paginatorClass);
var lastPage = ! newPaginator.length;
var completedEvent = $.extend({}, event, {
lastPage: lastPage });
if (! lastPage) {
paginator.attr('href',
newPaginator.attr('href'));
}
settings.pageCompleted(completedEvent);
}
);
return false;
});
});
};
})(jQuery);
| (function($) {
$.fn.pagemore = function(options) {
var settings = $.extend( {
containerClass: 'pagemore-container',
paginatorClass: 'pagemore-paginator',
pageRequested: function(e) {
e.paginator.hide();
},
pageCompleted: function(e) {
e.paginator.toggle(! e.lastPage);
}
}, options);
return this.each(function() {
var container = $("." + settings.containerClass);
var paginator = $(this);
paginator.click(function() {
var event = { paginator: paginator };
settings.pageRequested(event);
$.get($(this).attr('href'),
function(resp) {
$(resp).find(".pagemore-container").children().appendTo(container);
var newPaginator = $(resp).find(".pagemore-paginator");
var lastPage = ! newPaginator.length;
var completedEvent = $.extend({}, event, {
lastPage: lastPage });
if (! lastPage) {
paginator.attr('href',
newPaginator.attr('href'));
}
settings.pageCompleted(completedEvent);
}
);
return false;
});
});
};
})(jQuery);
|
Fix cannot get branch name | 'use babel';
import SaveTabsWithBranchView from './save-tabs-with-branch-view';
import { CompositeDisposable } from 'atom';
function getBranch() {
const repos = atom.project.getRepositories();
if (!repos || repos.length === 0) {
return '';
}
const repo = repos[0];
return repo.getShortHead();
}
export default {
saveTabsWithBranchView: null,
modalPanel: null,
subscriptions: null,
activate(state) {
this.saveTabsWithBranchView = new SaveTabsWithBranchView(state.saveTabsWithBranchViewState);
this.modalPanel = atom.workspace.addModalPanel({
item: this.saveTabsWithBranchView.getElement(),
visible: false,
});
// Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
this.subscriptions = new CompositeDisposable();
// Register command that toggles this view
this.subscriptions.add(atom.commands.add('atom-workspace', {
'save-tabs-with-branch:toggle': () => this.toggle(),
}));
},
deactivate() {
this.modalPanel.destroy();
this.subscriptions.dispose();
this.saveTabsWithBranchView.destroy();
},
serialize() {
return {
saveTabsWithBranchViewState: this.saveTabsWithBranchView.serialize(),
};
},
toggle() {
console.log('SaveTabsWithBranch was toggled!');
console.log(getBranch());
return (
this.modalPanel.isVisible() ?
this.modalPanel.hide() :
this.modalPanel.show()
);
},
};
| 'use babel';
import SaveTabsWithBranchView from './save-tabs-with-branch-view';
import { CompositeDisposable } from 'atom';
function getBranch() {
const repos = atom.project.getRepositories();
if (!repos || repos.length === 0) {
return '';
}
const repo = repos[0];
return repo.getUpstreamBranch();
}
export default {
saveTabsWithBranchView: null,
modalPanel: null,
subscriptions: null,
activate(state) {
this.saveTabsWithBranchView = new SaveTabsWithBranchView(state.saveTabsWithBranchViewState);
this.modalPanel = atom.workspace.addModalPanel({
item: this.saveTabsWithBranchView.getElement(),
visible: false,
});
// Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
this.subscriptions = new CompositeDisposable();
// Register command that toggles this view
this.subscriptions.add(atom.commands.add('atom-workspace', {
'save-tabs-with-branch:toggle': () => this.toggle(),
}));
},
deactivate() {
this.modalPanel.destroy();
this.subscriptions.dispose();
this.saveTabsWithBranchView.destroy();
},
serialize() {
return {
saveTabsWithBranchViewState: this.saveTabsWithBranchView.serialize(),
};
},
toggle() {
console.log('SaveTabsWithBranch was toggled!');
console.log(getBranch());
return (
this.modalPanel.isVisible() ?
this.modalPanel.hide() :
this.modalPanel.show()
);
},
};
|
Fix for using NAG Fortran 95, due to James Graham <[email protected]> | import os
import sys
from numpy.distutils.cpuinfo import cpu
from numpy.distutils.fcompiler import FCompiler
class NAGFCompiler(FCompiler):
compiler_type = 'nag'
version_pattern = r'NAGWare Fortran 95 compiler Release (?P<version>[^\s]*)'
executables = {
'version_cmd' : ["f95", "-V"],
'compiler_f77' : ["f95", "-fixed"],
'compiler_fix' : ["f95", "-fixed"],
'compiler_f90' : ["f95"],
'linker_so' : ["f95"],
'archiver' : ["ar", "-cr"],
'ranlib' : ["ranlib"]
}
def get_flags_linker_so(self):
if sys.platform=='darwin':
return ['-unsharedf95','-Wl,-bundle,-flat_namespace,-undefined,suppress']
return ["-Wl,-shared"]
def get_flags_opt(self):
return ['-O4']
def get_flags_arch(self):
return ['-target=native']
def get_flags_debug(self):
return ['-g','-gline','-g90','-nan','-C']
if __name__ == '__main__':
from distutils import log
log.set_verbosity(2)
from numpy.distutils.fcompiler import new_fcompiler
compiler = new_fcompiler(compiler='nag')
compiler.customize()
print compiler.get_version()
| import os
import sys
from numpy.distutils.cpuinfo import cpu
from numpy.distutils.fcompiler import FCompiler
class NAGFCompiler(FCompiler):
compiler_type = 'nag'
version_pattern = r'NAGWare Fortran 95 compiler Release (?P<version>[^\s]*)'
executables = {
'version_cmd' : ["f95", "-V"],
'compiler_f77' : ["f95", "-fixed"],
'compiler_fix' : ["f95", "-fixed"],
'compiler_f90' : ["f95"],
'linker_so' : ["f95"],
'archiver' : ["ar", "-cr"],
'ranlib' : ["ranlib"]
}
def get_flags_linker_so(self):
if sys.platform=='darwin':
return ['-unsharedf95','-Wl,-bundle,-flat_namespace,-undefined,suppress']
return ["-Wl,shared"]
def get_flags_opt(self):
return ['-O4']
def get_flags_arch(self):
return ['-target=native']
def get_flags_debug(self):
return ['-g','-gline','-g90','-nan','-C']
if __name__ == '__main__':
from distutils import log
log.set_verbosity(2)
from numpy.distutils.fcompiler import new_fcompiler
compiler = new_fcompiler(compiler='nag')
compiler.customize()
print compiler.get_version()
|
Use cacheDirectory options to cache Babel build | /* eslint-disable no-var, prefer-template */
var webpack = require("webpack");
module.exports = function webpackConfig(opts) {
var env = JSON.stringify(opts.args.production ? "production" : "development");
var config = {
entry: {
background: __dirname + "/app/scripts/background.js",
options: __dirname + "/app/scripts/options.js",
popup: __dirname + "/app/scripts/popup.js",
},
output: {
path: __dirname + "/dist/" + opts.args.vendor + "/scripts",
filename: "[name].js",
publicPath: "/scripts/",
},
plugins: [
new webpack.DefinePlugin({
__ENV__: env,
__VENDOR__: JSON.stringify(opts.args.vendor),
LIVERELOAD: opts.watch,
}),
],
module: {
loaders: [
{
test: /\.js$/,
loader: "babel",
exclude: /(node_modules|bower_components)/,
query: {
cacheDirectory: true,
},
},
{
test: /\.json$/,
loader: "json",
},
],
},
devtool: opts.args.sourcemaps ? "inline-source-map" : null,
};
if (opts.args.production) {
config.plugins.push(
new webpack.optimize.DedupePlugin(),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })
);
}
return config;
};
| /* eslint-disable no-var, prefer-template */
var webpack = require("webpack");
module.exports = function webpackConfig(opts) {
var env = JSON.stringify(opts.args.production ? "production" : "development");
var config = {
entry: {
background: __dirname + "/app/scripts/background.js",
options: __dirname + "/app/scripts/options.js",
popup: __dirname + "/app/scripts/popup.js",
},
output: {
path: __dirname + "/dist/" + opts.args.vendor + "/scripts",
filename: "[name].js",
publicPath: "/scripts/",
},
plugins: [
new webpack.DefinePlugin({
__ENV__: env,
__VENDOR__: JSON.stringify(opts.args.vendor),
LIVERELOAD: opts.watch,
}),
],
module: {
loaders: [
{
test: /\.js$/,
loader: "babel",
exclude: /node_modules/,
},
{
test: /\.json$/,
loader: "json",
},
],
},
devtool: opts.args.sourcemaps ? "inline-source-map" : null,
};
if (opts.args.production) {
config.plugins.push(
new webpack.optimize.DedupePlugin(),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })
);
}
return config;
};
|
Use get() instead of setdefault(). |
class ObservableMemory:
def __init__(self, subject=None):
if subject is None:
subject = 0x10000 * [0x00]
self._subject = subject
self._read_subscribers = {}
self._write_subscribers = {}
def __setitem__(self, address, value):
callbacks = self._write_subscribers.get(address, [])
for callback in callbacks:
result = callback(address, value)
if result is not None:
value = result
self._subject[address] = value
def __getitem__(self, address):
callbacks = self._read_subscribers.get(address, [])
final_result = None
for callback in callbacks:
result = callback(address)
if result is not None:
final_result = result
if final_result is None:
return self._subject[address]
else:
return final_result
def __getattr__(self, attribute):
return getattr(self._subject, attribute)
def subscribe_to_write(self, address_range, callback):
for address in address_range:
callbacks = self._write_subscribers.setdefault(address, [])
if callback not in callbacks:
callbacks.append(callback)
def subscribe_to_read(self, address_range, callback):
for address in address_range:
callbacks = self._read_subscribers.setdefault(address, [])
if callback not in callbacks:
callbacks.append(callback)
def write(self, start_address, bytes):
self._subject[start_address:start_address+len(bytes)] = bytes
|
class ObservableMemory:
def __init__(self, subject=None):
if subject is None:
subject = 0x10000 * [0x00]
self._subject = subject
self._read_subscribers = {}
self._write_subscribers = {}
def __setitem__(self, address, value):
callbacks = self._write_subscribers.setdefault(address, [])
for callback in callbacks:
result = callback(address, value)
if result is not None:
value = result
self._subject[address] = value
def __getitem__(self, address):
callbacks = self._read_subscribers.setdefault(address, [])
final_result = None
for callback in callbacks:
result = callback(address)
if result is not None:
final_result = result
if final_result is None:
return self._subject[address]
else:
return final_result
def __getattr__(self, attribute):
return getattr(self._subject, attribute)
def subscribe_to_write(self, address_range, callback):
for address in address_range:
callbacks = self._write_subscribers.setdefault(address, [])
if callback not in callbacks:
callbacks.append(callback)
def subscribe_to_read(self, address_range, callback):
for address in address_range:
callbacks = self._read_subscribers.setdefault(address, [])
if callback not in callbacks:
callbacks.append(callback)
def write(self, start_address, bytes):
self._subject[start_address:start_address+len(bytes)] = bytes
|
Use Component/Type and PolyCollectionType for blocks | <?php
namespace Enhavo\Bundle\ShopBundle\Block;
use Enhavo\Bundle\BlockBundle\Model\BlockInterface;
use Enhavo\Bundle\ShopBundle\Entity\ProductListBlock;
use Enhavo\Bundle\ShopBundle\Factory\ProductListBlockFactory;
use Enhavo\Bundle\ShopBundle\Form\Type\ProductListBlockType as ProductListBlockFormType;
use Enhavo\Bundle\BlockBundle\Block\AbstractBlockType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ProductListBlockType extends AbstractBlockType
{
public function createViewData(BlockInterface $block, $resource, array $options)
{
$data = parent::createViewData($block, $resource, $options);
$data['products'] = $this->container->get('sylius.repository.product')->findAll();
return $data;
}
public function configureOptions(OptionsResolver $optionsResolver)
{
parent::configureOptions($optionsResolver);
$optionsResolver->setDefaults([
'model' => ProductListBlock::class,
'parent' => ProductListBlock::class,
'form' => ProductListBlockFormType::class,
'factory' => ProductListBlockFactory::class,
'repository' => 'ProductListBlock::class',
'template' => 'theme/block/product-list.html.twig',
'label' => 'ProductList',
'translation_domain' => 'EnhavoShopBundle',
'groups' => ['default', 'content']
]);
}
public function getType()
{
return 'shop_product_list';
}
}
| <?php
namespace Enhavo\Bundle\ShopBundle\Block;
use Enhavo\Bundle\BlockBundle\Model\BlockInterface;
use Enhavo\Bundle\ShopBundle\Entity\ProductListBlock;
use Enhavo\Bundle\ShopBundle\Factory\ProductListBlockFactory;
use Enhavo\Bundle\ShopBundle\Form\Type\ProductListBlockType as ProductListBlockFormType;
use Enhavo\Bundle\BlockBundle\Block\AbstractBlockType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ProductListBlockType extends AbstractBlockType
{
public function createViewData(BlockInterface $block, $resource, array $options)
{
$data = parent::createViewData($block, $resource, $options);
$data['products'] = $this->container->get('sylius.repository.product')->findAll();
return $data;
}
public function configureOptions(OptionsResolver $optionsResolver)
{
parent::configureOptions($optionsResolver);
$optionsResolver->setDefaults([
'model' => ProductListBlock::class,
'parent' => ProductListBlock::class,
'form' => ProductListBlockFormType::class,
'factory' => ProductListBlockFactory::class,
'repository' => 'ProductListBlock::class',
'template' => 'theme/block/product-list.html.twig',
'label' => 'ProductList',
'translationDomain' => 'EnhavoShopBundle',
'groups' => ['default', 'content']
]);
}
public function getType()
{
return 'shop_product_list';
}
}
|
Add some error handling in the crawler
The crawler will silently return nothing if it's disabled or if fetch or parser error happen. | <?php
/**
* Created by PhpStorm.
* User: Nabeel
* Date: 2015-10-16
* Time: 6:42 PM
*/
namespace app\components;
use yii\base\Component;
use yii\log\Logger;
class Crawler extends Component
{
public $enabled = true;
public function readTitle($url)
{
if (!$this->enabled)
return null;
try
{
$content = $this->fetchUrl($url);
}
catch (\Exception $e)
{
\Yii::getLogger()->log("Crawler fetchUrl exception: {$e->getMessage()}", Logger::LEVEL_ERROR);
return null;
}
try
{
$crawler = new \Symfony\Component\DomCrawler\Crawler();
$crawler->addHtmlContent($content);
$node = $crawler->filterXPath('html/head/title');
if ($node->count() > 0)
return $node->first()->text();
}
catch (\Exception $e)
{
\Yii::getLogger()->log("Crawler DOM extraction exception: {$e->getMessage()}", Logger::LEVEL_ERROR);
}
return null;
}
private function fetchUrl($url){
$curlOptions = [
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
];
$curl = curl_init($url);
foreach ($curlOptions as $option => $value) {
curl_setopt($curl, $option, $value);
}
$response = curl_exec($curl);
return $response;
}
}
| <?php
/**
* Created by PhpStorm.
* User: Nabeel
* Date: 2015-10-16
* Time: 6:42 PM
*/
namespace app\components;
use yii\base\Component;
class Crawler extends Component
{
public function readTitle($url)
{
$content = $this->fetchUrl($url);
$crawler = new \Symfony\Component\DomCrawler\Crawler();
$crawler->addHtmlContent($content);
$node = $crawler->filterXPath('html/head/title');
if ($node->count() > 0)
return $node->first()->text();
return null;
}
private function fetchUrl($url){
$curlOptions = [
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
];
$curl = curl_init($url);
foreach ($curlOptions as $option => $value) {
curl_setopt($curl, $option, $value);
}
$response = curl_exec($curl);
return $response;
}
}
|
Add support for different time units in the response time attribute | package io.undertow.attribute;
import io.undertow.server.HttpServerExchange;
import java.util.concurrent.TimeUnit;
/**
* The response time
*
* This will only work if {@link io.undertow.UndertowOptions#RECORD_REQUEST_START_TIME} has been set
*/
public class ResponseTimeAttribute implements ExchangeAttribute {
public static final String RESPONSE_TIME_MILLIS_SHORT = "%D";
public static final String RESPONSE_TIME_SECONDS_SHORT = "%T";
public static final String RESPONSE_TIME_MILLIS = "%{RESPONSE_TIME}";
private final TimeUnit timeUnit;
public ResponseTimeAttribute(TimeUnit timeUnit) {
this.timeUnit = timeUnit;
}
@Override
public String readAttribute(HttpServerExchange exchange) {
long requestStartTime = exchange.getRequestStartTime();
if(requestStartTime == -1) {
return null;
}
return String.valueOf(timeUnit.convert(System.nanoTime() - requestStartTime, TimeUnit.NANOSECONDS));
}
@Override
public void writeAttribute(HttpServerExchange exchange, String newValue) throws ReadOnlyAttributeException {
throw new ReadOnlyAttributeException("Response Time", newValue);
}
public static final class Builder implements ExchangeAttributeBuilder {
@Override
public String name() {
return "Response Time";
}
@Override
public ExchangeAttribute build(String token) {
if (token.equals(RESPONSE_TIME_MILLIS) || token.equals(RESPONSE_TIME_MILLIS_SHORT)) {
return new ResponseTimeAttribute(TimeUnit.MILLISECONDS);
}
if (token.equals(RESPONSE_TIME_SECONDS_SHORT)) {
return new ResponseTimeAttribute(TimeUnit.SECONDS);
}
return null;
}
}
}
| package io.undertow.attribute;
import io.undertow.server.HttpServerExchange;
/**
* The response time
*
* This will only work if {@link io.undertow.UndertowOptions#RECORD_REQUEST_START_TIME} has been set
*/
public class ResponseTimeAttribute implements ExchangeAttribute {
public static final String RESPONSE_TIME_SHORT = "%D";
public static final String RESPONSE_TIME = "%{RESPONSE_TIME}";
public static final ExchangeAttribute INSTANCE = new ResponseTimeAttribute();
private ResponseTimeAttribute() {}
@Override
public String readAttribute(HttpServerExchange exchange) {
long requestStartTime = exchange.getRequestStartTime();
if(requestStartTime == -1) {
return null;
}
return String.valueOf(System.nanoTime() - requestStartTime);
}
@Override
public void writeAttribute(HttpServerExchange exchange, String newValue) throws ReadOnlyAttributeException {
throw new ReadOnlyAttributeException("Response Time", newValue);
}
public static final class Builder implements ExchangeAttributeBuilder {
@Override
public String name() {
return "Response Time";
}
@Override
public ExchangeAttribute build(String token) {
if (token.equals(RESPONSE_TIME) || token.equals(RESPONSE_TIME_SHORT)) {
return ResponseTimeAttribute.INSTANCE;
}
return null;
}
}
}
|
Add bulleted and numbered list to CKEditor
Closes #180 | from .util import get_settings, load_local_settings, load_secret_key
from . import base
settings = get_settings(base)
load_local_settings(settings, "local_settings")
load_secret_key(settings)
if not settings["DEBUG"] and settings["JWT_AUTH"]["JWT_SECRET_KEY"] == "kerrokantasi":
raise ValueError("Refusing to run out of DEBUG mode with insecure JWT secret key.")
settings['CKEDITOR_CONFIGS'] = {
'default': {
'stylesSet': [
{
"name": 'Lead',
"element": 'p',
"attributes": {'class': 'lead'},
},
],
'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'],
'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);',
'extraPlugins': 'video',
'toolbar': [
['Styles', 'Format'],
['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'],
['Link', 'Unlink', 'Anchor'],
['BulletedList', 'NumberedList'],
['Image', 'Video', 'Flash', 'Table', 'HorizontalRule'],
['TextColor', 'BGColor'],
['Smiley', 'SpecialChar'],
['Source']
]
},
}
globals().update(settings) # Export the settings for Django to use.
| from .util import get_settings, load_local_settings, load_secret_key
from . import base
settings = get_settings(base)
load_local_settings(settings, "local_settings")
load_secret_key(settings)
if not settings["DEBUG"] and settings["JWT_AUTH"]["JWT_SECRET_KEY"] == "kerrokantasi":
raise ValueError("Refusing to run out of DEBUG mode with insecure JWT secret key.")
settings['CKEDITOR_CONFIGS'] = {
'default': {
'stylesSet': [
{
"name": 'Lead',
"element": 'p',
"attributes": {'class': 'lead'},
},
],
'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'],
'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);',
'extraPlugins': 'video',
'toolbar': [
['Styles', 'Format'],
['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'],
['Link', 'Unlink', 'Anchor'],
['Image', 'Video', 'Flash', 'Table', 'HorizontalRule'],
['TextColor', 'BGColor'],
['Smiley', 'SpecialChar'],
['Source']
]
},
}
globals().update(settings) # Export the settings for Django to use.
|
Decrease sensitivity of dark ground checking. |
class Rule(object):
def __init__(self, trigger, actions):
self.trigger = trigger
print "trigger: %s" % trigger
self.code = []
time = 0
for a in actions:
print "action: %s" % a
if a == 'back':
action = ('reverse', 40)
elif a == 'stop':
action = (None, 0)
else: # forward, left, right, speak, light-*
action = (a, 40)
self.code.append(time)
self.code.append(action)
time += 0.5
print "code: %s" % self.code
class RuleEngine(object):
def __init__(self, control):
self.control = control
self.rules = []
def check(self, color, touch, direction):
for rule in self.rules:
if (rule.trigger == 'collision' and touch) \
or (rule.trigger == 'dark ground' and color < 40) \
or (rule.trigger == 'light ground' and color >= 40):
self.control.program(*rule.code)
def activate(self, rules):
self.rules = rules
|
class Rule(object):
def __init__(self, trigger, actions):
self.trigger = trigger
print "trigger: %s" % trigger
self.code = []
time = 0
for a in actions:
print "action: %s" % a
if a == 'back':
action = ('reverse', 40)
elif a == 'stop':
action = (None, 0)
else: # forward, left, right, speak, light-*
action = (a, 40)
self.code.append(time)
self.code.append(action)
time += 0.5
print "code: %s" % self.code
class RuleEngine(object):
def __init__(self, control):
self.control = control
self.rules = []
def check(self, color, touch, direction):
for rule in self.rules:
if (rule.trigger == 'collision' and touch) \
or (rule.trigger == 'dark ground' and color < 10) \
or (rule.trigger == 'light ground' and color > 10):
self.control.program(*rule.code)
def activate(self, rules):
self.rules = rules
|
Add classifiers for py35 and py36 | #!/usr/bin/env python3
from setuptools import find_packages, setup
setup(
name='django-afip',
description='AFIP integration for django',
author='Hugo Osvaldo Barrera',
author_email='[email protected]',
url='https://gitlab.com/hobarrera/django-afip',
license='ISC',
packages=find_packages(),
include_package_data=True,
long_description=open('README.rst').read(),
install_requires=open('requirements.txt').read().splitlines() + [
'Django>=1.8.4'
],
extras_require={
'docs': ['Sphinx', 'sphinx-autobuild']
},
use_scm_version={
'version_scheme': 'post-release',
'write_to': 'django_afip/version.py',
},
setup_requires=['setuptools_scm'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.10',
'Framework :: Django :: 1.11',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| #!/usr/bin/env python3
from setuptools import find_packages, setup
setup(
name='django-afip',
description='AFIP integration for django',
author='Hugo Osvaldo Barrera',
author_email='[email protected]',
url='https://gitlab.com/hobarrera/django-afip',
license='ISC',
packages=find_packages(),
include_package_data=True,
long_description=open('README.rst').read(),
install_requires=open('requirements.txt').read().splitlines() + [
'Django>=1.8.4'
],
extras_require={
'docs': ['Sphinx', 'sphinx-autobuild']
},
use_scm_version={
'version_scheme': 'post-release',
'write_to': 'django_afip/version.py',
},
setup_requires=['setuptools_scm'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.10',
'Framework :: Django :: 1.11',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
|
Add mongo hq authentication for heroku | package pw.scho.battleship.persistence.configuration;
import com.mongodb.DB;
import com.mongodb.MongoURI;
import com.mongodb.ServerAddress;
import org.mongolink.MongoSession;
import org.mongolink.MongoSessionManager;
import org.mongolink.Settings;
import org.mongolink.UpdateStrategies;
import org.mongolink.domain.mapper.ContextBuilder;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MongoConfiguration {
public static void stop() {
Singleton.INSTANCE.mongoSessionManager.close();
}
public static MongoSession createSession() {
return Singleton.INSTANCE.mongoSessionManager.createSession();
}
private enum Singleton {
INSTANCE;
private final MongoSessionManager mongoSessionManager;
private Singleton() {
ContextBuilder builder = new ContextBuilder("pw.scho.battleship.persistence.mongo.mapping");
Settings settings = null;
try {
settings = Settings.defaultInstance()
.withDefaultUpdateStrategy(UpdateStrategies.DIFF)
.withDbName("battleship");
String mongoHqUrl = System.getenv("MONGOHQ_URL");
if(mongoHqUrl!= null){
MongoURI mongoURI = new MongoURI(mongoHqUrl);
List<ServerAddress> serverAdresses = new ArrayList<>();
for(String host : mongoURI.getHosts()){
serverAdresses.add(new ServerAddress(host, 27017));
}
settings = settings.withAddresses(serverAdresses)
.withAuthentication(mongoURI.getUsername(), mongoURI.getPassword().toString());
} else {
settings = settings.withAddresses(Arrays.asList(new ServerAddress("localhost", 27017)));
}
} catch (UnknownHostException e) {
}
mongoSessionManager = MongoSessionManager.create(builder, settings);
}
}
}
| package pw.scho.battleship.persistence.configuration;
import com.mongodb.ServerAddress;
import org.mongolink.MongoSession;
import org.mongolink.MongoSessionManager;
import org.mongolink.Settings;
import org.mongolink.UpdateStrategies;
import org.mongolink.domain.mapper.ContextBuilder;
import java.net.UnknownHostException;
import java.util.Arrays;
public class MongoConfiguration {
public static void stop() {
Singleton.INSTANCE.mongoSessionManager.close();
}
public static MongoSession createSession() {
return Singleton.INSTANCE.mongoSessionManager.createSession();
}
private enum Singleton {
INSTANCE;
private final MongoSessionManager mongoSessionManager;
private Singleton() {
ContextBuilder builder = new ContextBuilder("pw.scho.battleship.persistence.mongo.mapping");
Settings settings = null;
try {
settings = Settings.defaultInstance()
.withDefaultUpdateStrategy(UpdateStrategies.DIFF)
.withDbName("battleship")
.withAddresses(Arrays.asList(new ServerAddress("localhost", 27017)));
} catch (UnknownHostException e) {
}
mongoSessionManager = MongoSessionManager.create(builder, settings);
}
}
}
|
Change suffix for locator to 'loc' | """Kraken - base config module.
Classes:
BaseConfig -- Base config object used to configure builders.
"""
class BaseConfig(object):
"""Base Configuration for Kraken builders."""
def __init__(self):
super(BaseConfig, self).__init__()
self.nameTemplate = {
"locations": ['L', 'R', 'M'],
"separator": "_",
"types": {
"default": "null",
"Component": "cmp",
"ComponentInput": "cmpIn",
"ComponentOutput": "cmpOut",
"Container": "",
"Control": "ctrl",
"Curve": "crv",
"HierarchyGroup": "hrc",
"Joint": "def",
"Layer": "",
"Locator": "loc",
"SrtBuffer": "srtBuffer"
},
"formats":
{
"default": ['component', 'sep', 'location', 'sep', 'name', 'sep', 'type'],
"Container": ['name'],
"Layer": ['name'],
"Component": ['name', 'sep', 'location', 'sep', 'type']
}
}
def getNameTemplate(self):
"""Returns the naming template for this configuration.
Return:
Dict, naming template.
"""
return self.nameTemplate | """Kraken - base config module.
Classes:
BaseConfig -- Base config object used to configure builders.
"""
class BaseConfig(object):
"""Base Configuration for Kraken builders."""
def __init__(self):
super(BaseConfig, self).__init__()
self.nameTemplate = {
"locations": ['L', 'R', 'M'],
"separator": "_",
"types": {
"default": "null",
"Component": "cmp",
"ComponentInput": "cmpIn",
"ComponentOutput": "cmpOut",
"Container": "",
"Control": "ctrl",
"Curve": "crv",
"HierarchyGroup": "hrc",
"Joint": "def",
"Layer": "",
"Locator": "null",
"SrtBuffer": "srtBuffer"
},
"formats":
{
"default": ['component', 'sep', 'location', 'sep', 'name', 'sep', 'type'],
"Container": ['name'],
"Layer": ['name'],
"Component": ['name', 'sep', 'location', 'sep', 'type']
}
}
def getNameTemplate(self):
"""Returns the naming template for this configuration.
Return:
Dict, naming template.
"""
return self.nameTemplate |
Fix method description in account_cost_spread | # Copyright 2016-2018 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, models
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
@api.multi
def action_move_create(self):
"""Invoked when validating the invoices."""
res = super(AccountInvoice, self).action_move_create()
for rec in self:
rec.invoice_line_ids.compute_spread_board()
return res
@api.multi
def invoice_line_move_line_get(self):
res = super(AccountInvoice, self).invoice_line_move_line_get()
for line in res:
invl_id = line.get('invl_id')
invl = self.env['account.invoice.line'].browse(invl_id)
if invl.spread_account_id:
line['account_id'] = invl.spread_account_id.id
return res
@api.multi
def action_invoice_cancel(self):
res = self.action_cancel()
for invoice in self:
for invoice_line in invoice.invoice_line_ids:
for spread_line in invoice_line.spread_line_ids:
if spread_line.move_id:
spread_line.move_id.button_cancel()
spread_line.move_id.unlink()
spread_line.unlink()
return res
| # Copyright 2016-2018 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, models
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
@api.multi
def action_move_create(self):
"""Override, button Validate on invoices."""
res = super(AccountInvoice, self).action_move_create()
for rec in self:
rec.invoice_line_ids.compute_spread_board()
return res
@api.multi
def invoice_line_move_line_get(self):
res = super(AccountInvoice, self).invoice_line_move_line_get()
for line in res:
invl_id = line.get('invl_id')
invl = self.env['account.invoice.line'].browse(invl_id)
if invl.spread_account_id:
line['account_id'] = invl.spread_account_id.id
return res
@api.multi
def action_invoice_cancel(self):
res = self.action_cancel()
for invoice in self:
for invoice_line in invoice.invoice_line_ids:
for spread_line in invoice_line.spread_line_ids:
if spread_line.move_id:
spread_line.move_id.button_cancel()
spread_line.move_id.unlink()
spread_line.unlink()
return res
|
Tag Factory no understand full xpaths | <?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver;
use PHPExiftool\Exception;
use PHPExiftool\Tool\Command\ClassesBuilder;
/**
* Metadata Object for mapping a Tag to a value
*
* @author Romain Neutron - [email protected]
* @license http://opensource.org/licenses/MIT MIT
*/
class TagFactory
{
/**
* Build a Tag based on his Tagname
*
* @param string $tagname
* @return \PHPExiftool\Driver\Tag
* @throws \PHPExiftool\Exception\TagUnknown
*/
public static function getFromRDFTagname($tagname)
{
$classname = self::classnameFromTagname($tagname);
if ( ! class_exists($classname)) {
throw new Exception\TagUnknown(sprintf('Unknown tag %s', $tagname));
}
return new $classname;
}
public static function hasFromRDFTagname($tagname)
{
return class_exists(self::classnameFromTagname($tagname));
}
protected static function classnameFromTagname($tagname)
{
$tagname = str_replace('/rdf:RDF/rdf:Description/', '', $tagname);
$classname = '\PHPExiftool\Driver\Tag\\' . str_replace(':', '\\', $tagname);
return ClassesBuilder::generateNamespace($classname);
}
}
| <?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver;
use PHPExiftool\Exception;
use PHPExiftool\Tool\Command\ClassesBuilder;
/**
* Metadata Object for mapping a Tag to a value
*
* @author Romain Neutron - [email protected]
* @license http://opensource.org/licenses/MIT MIT
*/
class TagFactory
{
/**
* Build a Tag based on his Tagname
*
* @param string $tagname
* @return \PHPExiftool\Driver\Tag
* @throws \PHPExiftool\Exception\TagUnknown
*/
public static function getFromRDFTagname($tagname)
{
$classname = self::classnameFromTagname($tagname);
if ( ! class_exists($classname)) {
throw new Exception\TagUnknown(sprintf('Unknown tag %s', $tagname));
}
return new $classname;
}
public static function hasFromRDFTagname($tagname)
{
return class_exists(self::classnameFromTagname($tagname));
}
protected static function classnameFromTagname($tagname)
{
$classname = '\PHPExiftool\Driver\Tag\\' . str_replace(':', '\\', $tagname);
return ClassesBuilder::generateNamespace($classname);
}
}
|
Update context processors analyzer to target Django 1.4 | import ast
from .base import BaseAnalyzer, ModuleVisitor, Result
class ContextProcessorsVisitor(ast.NodeVisitor):
def __init__(self):
self.found = []
removed_items = {
'django.core.context_processors.auth':
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.PermWrapper':
'django.contrib.auth.context_processors.PermWrapper',
'django.core.context_processors.PermLookupDict':
'django.contrib.auth.context_processors.PermLookupDict',
}
def visit_Str(self, node):
if node.s in self.removed_items.keys():
self.found.append((node.s, node))
class ContextProcessorsAnalyzer(BaseAnalyzer):
def analyze_file(self, filepath, code):
if not isinstance(code, ast.AST):
return
visitor = ContextProcessorsVisitor()
visitor.visit(code)
for name, node in visitor.found:
propose = visitor.removed_items[name]
result = Result(
description = (
'%r function is removed in Django >=1.4, use %r instead'
% (name, propose)
),
path = filepath,
line = node.lineno)
lines = self.get_file_lines(filepath, node.lineno, node.lineno)
for lineno, important, text in lines:
result.source.add_line(lineno, text, important)
result.solution.add_line(lineno, text.replace(name, propose), important)
yield result
| import ast
from .base import BaseAnalyzer, ModuleVisitor, Result
class ContextProcessorsVisitor(ast.NodeVisitor):
def __init__(self):
self.found = []
deprecated_items = {
'django.core.context_processors.auth':
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.PermWrapper':
'django.contrib.auth.context_processors.PermWrapper',
'django.core.context_processors.PermLookupDict':
'django.contrib.auth.context_processors.PermLookupDict',
}
def visit_Str(self, node):
if node.s in self.deprecated_items.keys():
self.found.append((node.s, node))
class ContextProcessorsAnalyzer(BaseAnalyzer):
def analyze_file(self, filepath, code):
if not isinstance(code, ast.AST):
return
visitor = ContextProcessorsVisitor()
visitor.visit(code)
for name, node in visitor.found:
propose = visitor.deprecated_items[name]
result = Result(
description = (
'%r function is deprecated, use %r instead' % (name, propose)
),
path = filepath,
line = node.lineno)
lines = self.get_file_lines(filepath, node.lineno, node.lineno)
for lineno, important, text in lines:
result.source.add_line(lineno, text, important)
result.solution.add_line(lineno, text.replace(name, propose), important)
yield result
|
Build with PIC by default. | from conans import ConanFile, CMake, tools
class LibWFUTConan(ConanFile):
name = "libwfut"
version = "0.2.4"
license = "GPL-2.0+"
author = "Erik Ogenvik <[email protected]>"
homepage = "https://www.worldforge.org"
url = "https://github.com/worldforge/libwfut"
description = "A client side C++ implementation of WFUT (WorldForge Update Tool)."
topics = ("mmorpg", "worldforge")
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [False, True], "fPIC": [True, False]}
default_options = {"shared": False, "fPIC": True}
generators = "cmake"
requires = ["sigc++/2.10.0@worldforge/stable",
"zlib/1.2.11",
"libcurl/7.66.0@worldforge/stable"]
scm = {
"type": "git",
"url": "https://github.com/worldforge/libwfut.git",
"revision": "auto"
}
def build(self):
cmake = CMake(self)
cmake.configure(source_folder=".")
cmake.build()
cmake.install()
def package_info(self):
self.cpp_info.libs = tools.collect_libs(self)
self.cpp_info.includedirs = ["include/wfut-0.2"]
def package(self):
pass
| from conans import ConanFile, CMake, tools
class LibWFUTConan(ConanFile):
name = "libwfut"
version = "0.2.4"
license = "GPL-2.0+"
author = "Erik Ogenvik <[email protected]>"
homepage = "https://www.worldforge.org"
url = "https://github.com/worldforge/libwfut"
description = "A client side C++ implementation of WFUT (WorldForge Update Tool)."
topics = ("mmorpg", "worldforge")
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [False, True]}
default_options = {"shared": False}
generators = "cmake"
requires = ["sigc++/2.10.0@worldforge/stable",
"zlib/1.2.11",
"libcurl/7.66.0@worldforge/stable"]
scm = {
"type": "git",
"url": "https://github.com/worldforge/libwfut.git",
"revision": "auto"
}
def build(self):
cmake = CMake(self)
cmake.configure(source_folder=".")
cmake.build()
cmake.install()
def package_info(self):
self.cpp_info.libs = tools.collect_libs(self)
self.cpp_info.includedirs = ["include/wfut-0.2"]
def package(self):
pass
|
Set owner_id on new post. | List = new Meteor.Collection( 'List' );
List.allow({
insert: (userId, document) => true,
update: (userId, document) => document.owner_id === Meteor.userId(),
remove: (userId, document) => false
});
List.deny({
insert: (userId, document) => false,
update: (userId, document) => false,
remove: (userId, document) => false
});
List.schema = new SimpleSchema({
title: {
type: String,
label: 'Title',
optional: false,
min: 5,
},
description: {
type: String,
label: 'Details',
optional: true,
max: 1000,
autoform: {
type: 'markdown',
rows: 10,
}
},
owner_id: {
type: String,
optional: true,
autoValue: function() {
const userId = Meteor.userId() || '';
if (this.isInsert) {
return userId;
} else if (this.isUpsert) {
return {$setOnInsert: userId};
} else {
this.unset(); // Prevent user from supplying their own value
}
},
autoform: {
omit: true,
}
},
date_created: {
type: Date,
optional: true,
autoValue: function() {
if (this.isInsert) {
return new Date();
} else if (this.isUpsert) {
return {$setOnInsert: new Date()};
} else {
this.unset(); // Prevent user from supplying their own value
}
},
autoform: {
omit: true,
}
}
});
List.attachSchema( List.schema );
| List = new Meteor.Collection( 'List' );
List.allow({
insert: (userId, document) => true,
update: (userId, document) => document.owner_id === Meteor.userId(),
remove: (userId, document) => false
});
List.deny({
insert: (userId, document) => false,
update: (userId, document) => false,
remove: (userId, document) => false
});
List.schema = new SimpleSchema({
title: {
type: String,
label: 'Title',
optional: false,
min: 5,
},
description: {
type: String,
label: 'Details',
optional: true,
max: 1000,
autoform: {
type: 'markdown',
rows: 10,
}
},
owner_id: {
type: String,
optional: true,
autoform: {
omit: true,
}
},
date_created: {
type: Date,
optional: true,
autoValue: function() {
if (this.isInsert) {
return new Date();
} else if (this.isUpsert) {
return {$setOnInsert: new Date()};
} else {
this.unset(); // Prevent user from supplying their own value
}
},
autoform: {
omit: true,
}
}
});
List.attachSchema( List.schema );
|
Add link to manual in the footer.
Added link to a PDF manual in the footer. Remember to make corresponding
changes in nginx-config to make it work, similar to the logo and other
static resources. | import React from 'react';
import ExternalLink from './ExternalLink';
import Link from './Link';
import prefix from '../prefix';
export default class Footer extends React.Component {
static propTypes = {
requests: React.PropTypes.object,
}
render() {
const statistics = this.props.requests ? <div>{this.props.requests.local} / {this.props.requests.total}</div> : '';
return (
<div>
<hr />
<div style={{ maxWidth: 800, margin: '0 auto' }}>
<footer style={{ fontSize: 11, color: '#aaa', textAlign: 'center', paddingBottom: 50, margin: '0 10px' }}>
<Link to="about">About</Link> this service.<br />
<ExternalLink href={`${prefix}/static/manual.pdf`}>Read a short manual </ExternalLink> on how to use Fast-track <br />
GWAS data from <ExternalLink href="https://www.ebi.ac.uk/gwas/">NHGRI-EBI</ExternalLink>, downloaded 2016-10-12.<br />
The usual warnings about providing the service AS-IS applies.<br />
<ExternalLink href="https://www.ntnu.edu/huntgenes">K.G. Jebsen Center for Genetic Epidemiology</ExternalLink>, <ExternalLink href="http://www.ntnu.edu/ism">Department of public health and general practice (ISM)</ExternalLink>, <ExternalLink href="http://www.ntnu.edu/">Norwegian university of science and technology (NTNU)</ExternalLink>
<br />
{statistics}
</footer>
</div>
</div>
);
}
}
| import React from 'react';
import ExternalLink from './ExternalLink';
import Link from './Link';
export default class Footer extends React.Component {
static propTypes = {
requests: React.PropTypes.object,
}
render() {
const statistics = this.props.requests ? <div>{this.props.requests.local} / {this.props.requests.total}</div> : '';
return (
<div>
<hr />
<div style={{ maxWidth: 800, margin: '0 auto' }}>
<footer style={{ fontSize: 11, color: '#aaa', textAlign: 'center', paddingBottom: 50, margin: '0 10px' }}>
<Link to="about">About</Link> this service.<br />
GWAS data from <ExternalLink href="https://www.ebi.ac.uk/gwas/">NHGRI-EBI</ExternalLink>, downloaded 2016-10-12.<br />
The usual warnings about providing the service AS-IS applies.<br />
<ExternalLink href="https://www.ntnu.edu/huntgenes">K.G. Jebsen Center for Genetic Epidemiology</ExternalLink>, <ExternalLink href="http://www.ntnu.edu/ism">Department of public health and general practice (ISM)</ExternalLink>, <ExternalLink href="http://www.ntnu.edu/">Norwegian university of science and technology (NTNU)</ExternalLink>
<br />
{statistics}
</footer>
</div>
</div>
);
}
}
|
Make UglifyJSFilter docstring more consistent with other filters | import subprocess
from webassets.exceptions import FilterError
from webassets.filter import Filter
__all__ = ('UglifyJSFilter',)
class UglifyJSFilter(Filter):
"""
Minify Javascript using `UglifyJS <https://github.com/mishoo/UglifyJS/>`_.
UglifyJS is an external tool written for NodeJS; this filter assumes that
the ``uglifyjs`` executable is in the path. Otherwise, you may define
a ``UGLIFYJS_BIN`` setting.
Additional options may be passed to ``uglifyjs`` using the setting
``UGLIFYJS_EXTRA_ARGS``, which expects a list of strings.
"""
name = 'uglifyjs'
def setup(self):
self.binary = self.get_config(
'UGLIFYJS_BIN', require=False) or 'uglifyjs'
self.extra_args = self.get_config('UGLIFYJS_EXTRA_ARGS',
require=False)
def output(self, _in, out, **kw):
args = [self.binary]
if self.extra_args:
args.extend(self.extra_args)
proc = subprocess.Popen(
args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = proc.communicate(_in.read())
if proc.returncode != 0:
raise FilterError(('uglifyjs: subprocess had error: stderr=%s, '+
'stdout=%s, returncode=%s') % (
stderr, stdout, proc.returncode))
out.write(stdout)
| """Minify Javascript using `UglifyJS <https://github.com/mishoo/UglifyJS/>`_.
UglifyJS is an external tool written for NodeJS; this filter assumes that
the ``uglifyjs`` executable is in the path. Otherwise, you may define
a ``UGLIFYJS_BIN`` setting. Additional options may be passed to ``uglifyjs``
by setting ``UGLIFYJS_EXTRA_ARGS``, which expects a list of strings.
"""
import subprocess
from webassets.exceptions import FilterError
from webassets.filter import Filter
__all__ = ('UglifyJSFilter',)
class UglifyJSFilter(Filter):
name = 'uglifyjs'
def setup(self):
self.binary = self.get_config(
'UGLIFYJS_BIN', require=False) or 'uglifyjs'
self.extra_args = self.get_config('UGLIFYJS_EXTRA_ARGS',
require=False)
def output(self, _in, out, **kw):
args = [self.binary]
if self.extra_args:
args.extend(self.extra_args)
proc = subprocess.Popen(
args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = proc.communicate(_in.read())
if proc.returncode != 0:
raise FilterError(('uglifyjs: subprocess had error: stderr=%s, '+
'stdout=%s, returncode=%s') % (
stderr, stdout, proc.returncode))
out.write(stdout)
|
Use master branch of content instead of specific release | from setuptools import setup
setup(
name = 'marquee-composer',
version = '0.2.3-dev',
description = '',
long_description = file('README.md').read(),
url = 'https://github.com/marquee/composer',
author = 'Alec Perkins',
author_email = '[email protected]',
license = 'UNLICENSE',
packages = ['composer'],
zip_safe = False,
keywords = '',
install_requires = ['content==0.1.0'],
dependency_links = [
'git+https://github.com/marquee/content@master#egg=content-0.1.0',
],
package_data = {
'droptype-composer': ['../stylesheets/*'],
},
classifiers = [
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: Public Domain',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| from setuptools import setup
setup(
name = 'marquee-composer',
version = '0.2.3-dev',
description = '',
long_description = file('README.md').read(),
url = 'https://github.com/marquee/composer',
author = 'Alec Perkins',
author_email = '[email protected]',
license = 'UNLICENSE',
packages = ['composer'],
zip_safe = False,
keywords = '',
install_requires = ['content==0.1.0'],
dependency_links = [
'git+https://github.com/marquee/[email protected]#egg=content-0.1.0',
],
package_data = {
'droptype-composer': ['../stylesheets/*'],
},
classifiers = [
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: Public Domain',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
Add eaten Ghosts to game score | package com.pm.server.manager;
import com.pm.server.datatype.GameState;
import com.pm.server.datatype.Pacdot;
import com.pm.server.registry.GameStateRegistry;
import com.pm.server.registry.PacdotRegistry;
import com.pm.server.registry.PlayerRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class GameStateManagerImpl implements GameStateManager {
private GameStateRegistry gameStateRegistry;
private PacdotRegistry pacdotRegistry;
private PlayerRegistry playerRegistry;
@Autowired
public GameStateManagerImpl(
GameStateRegistry gameStateRegistry,
PacdotRegistry pacdotRegistry,
PlayerRegistry playerRegistry) {
this.gameStateRegistry = gameStateRegistry;
this.pacdotRegistry = pacdotRegistry;
this.playerRegistry = playerRegistry;
}
@Override
public Integer getScore() {
Integer score = 0;
List<Pacdot> pacdotList = pacdotRegistry.getAllPacdots();
for(Pacdot pacdot : pacdotList) {
if(pacdot.getEaten()) {
if(pacdot.getPowerdot()) {
score += 50;
}
else {
score += 10;
}
}
}
score += playerRegistry.getCapturedGhosts() * 50;
return score;
}
@Override
public GameState getCurrentState() {
return gameStateRegistry.getCurrentState();
}
}
| package com.pm.server.manager;
import com.pm.server.datatype.GameState;
import com.pm.server.datatype.Pacdot;
import com.pm.server.registry.GameStateRegistry;
import com.pm.server.registry.PacdotRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class GameStateManagerImpl implements GameStateManager {
private GameStateRegistry gameStateRegistry;
private PacdotRegistry pacdotRegistry;
@Autowired
public GameStateManagerImpl(
GameStateRegistry gameStateRegistry,
PacdotRegistry pacdotRegistry) {
this.gameStateRegistry = gameStateRegistry;
this.pacdotRegistry = pacdotRegistry;
}
@Override
public Integer getScore() {
Integer score = 0;
List<Pacdot> pacdotList = pacdotRegistry.getAllPacdots();
for(Pacdot pacdot : pacdotList) {
if(pacdot.getEaten()) {
if(pacdot.getPowerdot()) {
score += 50;
}
else {
score += 10;
}
}
}
return score;
}
@Override
public GameState getCurrentState() {
return gameStateRegistry.getCurrentState();
}
}
|
Use get_binary in tox tests. | from click import Option
import subprocess
from unleash.util import VirtualEnv
from .utils_tree import in_tmpexport
PLUGIN_NAME = 'tox_tests'
def setup(cli):
cli.commands['release'].params.append(Option(
['--tests/--no-tests', '-t/-T'], default=True,
help='Run unittests (default: enabled).'
))
def collect_info(ctx):
info = ctx['info']
info['tox_tests'] = ctx['opts']['tests']
if not ctx['commit'].path_exists('tox.ini'):
ctx['issues'].warn(
'No tox.ini found.',
'There was no tox.ini found in the project root. No tests will be '
'run on the release.')
info['tox_tests'] = False
def lint_release(ctx):
if not ctx['info']['tox_tests']:
return
ctx['log'].info('Running tox tests')
try:
ctx['log'].debug('Installing tox in a new virtualenv')
with VirtualEnv.temporary() as ve, in_tmpexport(ctx['commit']):
ve.pip_install('tox')
ctx['log'].debug('Running tests using tox')
ve.check_output(ve.get_binary('tox'))
except subprocess.CalledProcessError as e:
ctx['issues'].error('tox testing failed:\n{}'.format(e.output))
| from click import Option
import subprocess
from unleash.util import VirtualEnv
from .utils_tree import in_tmpexport
PLUGIN_NAME = 'tox_tests'
def setup(cli):
cli.commands['release'].params.append(Option(
['--tests/--no-tests', '-t/-T'], default=True,
help='Run unittests (default: enabled).'
))
def collect_info(ctx):
info = ctx['info']
info['tox_tests'] = ctx['opts']['tests']
if not ctx['commit'].path_exists('tox.ini'):
ctx['issues'].warn(
'No tox.ini found.',
'There was no tox.ini found in the project root. No tests will be '
'run on the release.')
info['tox_tests'] = False
def lint_release(ctx):
if not ctx['info']['tox_tests']:
return
ctx['log'].info('Running tox tests')
try:
ctx['log'].debug('Installing tox in a new virtualenv')
with VirtualEnv.temporary() as ve, in_tmpexport(ctx['commit']):
ve.pip_install('tox')
ctx['log'].debug('Running tests using tox')
ve.check_output(['tox'])
except subprocess.CalledProcessError as e:
ctx['issues'].error('tox testing failed:\n{}'.format(e.output))
|
Replace form type name with FQCN in getParent() methods. | <?php
/**
* @author Igor Nikolaev <[email protected]>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\Utils\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Blank;
/**
* Anti-spam form type
*/
class AntiSpamType extends AbstractType
{
const ANTI_SPAM_TYPE_CLASS = __CLASS__;
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'label' => false,
'attr' => array(
'class' => 'title_field',
),
'constraints' => new Blank(),
'mapped' => false,
'required' => false,
));
}
/**
* {@inheritdoc}
*/
public function getParent()
{
return 'Symfony\\Component\\Form\\Extension\\Core\\Type\\TextType';
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'darvin_utils_anti_spam';
}
}
| <?php
/**
* @author Igor Nikolaev <[email protected]>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\Utils\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Blank;
/**
* Anti-spam form type
*/
class AntiSpamType extends AbstractType
{
const ANTI_SPAM_TYPE_CLASS = __CLASS__;
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'label' => false,
'attr' => array(
'class' => 'title_field',
),
'constraints' => new Blank(),
'mapped' => false,
'required' => false,
));
}
/**
* {@inheritdoc}
*/
public function getParent()
{
return 'text';
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'darvin_utils_anti_spam';
}
}
|
Remove unnecessary backslashes in parse_json_items | import json
import ijson
class TimeSeriesJSON:
def __init__(self, f=None, fn=None, tag='item'):
"""
:param f: file object (_io.TextIOWrapper)
:param fn: file name as a string
:param tag: tag for dividing json items
default value is 'item' because this value is default in ijson
"""
if f is not None:
self.__type = 'file'
self.__file = f
elif fn is not None:
self.__type = 'file_name'
self.__file_name = fn
self.__file = open(fn)
self.__items = self.parse_json_items(tag)
def parse_json_items(self, tag, limit=0):
self.__items = []
self.__file.seek(0)
cnt = 0
objs = ijson.items(self.__file, tag)
for obj in objs:
item = json.dumps(obj,
sort_keys=True,
indent=4,
ensure_ascii=True)
self.__items.append(item)
cnt += 1
if limit != 0 and cnt >= limit:
break
return self.__items
| import json
import ijson
class TimeSeriesJSON:
def __init__(self, f=None, fn=None, tag='item'):
"""
:param f: file object (_io.TextIOWrapper)
:param fn: file name as a string
:param tag: tag for dividing json items
default value is 'item' because this value is default in ijson
"""
if f is not None:
self.__type = 'file'
self.__file = f
elif fn is not None:
self.__type = 'file_name'
self.__file_name = fn
self.__file = open(fn)
self.__items = self.parse_json_items(tag)
def parse_json_items(self, tag, limit=0):
self.__items = []
self.__file.seek(0)
cnt = 0
objs = ijson.items(self.__file, tag)
for obj in objs:
item = json.dumps(obj, \
sort_keys=True, \
indent=4, \
ensure_ascii=True)
self.__items.append(item)
cnt += 1
if limit != 0 and cnt >= limit:
break
return self.__items
|
Make parameters final that can be made final. | package com.hubspot.singularity.executor.config;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Optional;
import com.hubspot.singularity.executor.SingularityExecutorLogrotateFrequency;
public class SingularityExecutorLogrotateAdditionalFile {
private final String filename;
private final Optional<String> extension;
private final Optional<String> dateformat;
private final Optional<SingularityExecutorLogrotateFrequency> logrotateFrequencyOverride;
@JsonCreator
public static SingularityExecutorLogrotateAdditionalFile fromString(String value) {
return new SingularityExecutorLogrotateAdditionalFile(value, Optional.absent(), Optional.absent(), null);
}
@JsonCreator
public SingularityExecutorLogrotateAdditionalFile(@JsonProperty("filename") String filename,
@JsonProperty("extension") Optional<String> extension,
@JsonProperty("dateformat") Optional<String> dateformat,
@JsonProperty("logrotateFrequencyOverride") SingularityExecutorLogrotateFrequency logrotateFrequencyOverride) {
this.filename = filename;
this.extension = extension;
this.dateformat = dateformat;
this.logrotateFrequencyOverride = Optional.fromNullable(logrotateFrequencyOverride);
}
public String getFilename() {
return filename;
}
public Optional<String> getExtension() {
return extension;
}
public Optional<String> getDateformat() {
return dateformat;
}
public Optional<SingularityExecutorLogrotateFrequency> getLogrotateFrequencyOverride() {
return logrotateFrequencyOverride;
}
}
| package com.hubspot.singularity.executor.config;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Optional;
import com.hubspot.singularity.executor.SingularityExecutorLogrotateFrequency;
public class SingularityExecutorLogrotateAdditionalFile {
private final String filename;
private Optional<String> extension;
private Optional<String> dateformat;
private Optional<SingularityExecutorLogrotateFrequency> logrotateFrequencyOverride;
@JsonCreator
public static SingularityExecutorLogrotateAdditionalFile fromString(String value) {
return new SingularityExecutorLogrotateAdditionalFile(value, Optional.absent(), Optional.absent(), null);
}
@JsonCreator
public SingularityExecutorLogrotateAdditionalFile(@JsonProperty("filename") String filename,
@JsonProperty("extension") Optional<String> extension,
@JsonProperty("dateformat") Optional<String> dateformat,
@JsonProperty("logrotateFrequencyOverride") SingularityExecutorLogrotateFrequency logrotateFrequencyOverride) {
this.filename = filename;
this.extension = extension;
this.dateformat = dateformat;
this.logrotateFrequencyOverride = Optional.fromNullable(logrotateFrequencyOverride);
}
public String getFilename() {
return filename;
}
public Optional<String> getExtension() {
return extension;
}
public Optional<String> getDateformat() {
return dateformat;
}
public Optional<SingularityExecutorLogrotateFrequency> getLogrotateFrequencyOverride() {
return logrotateFrequencyOverride;
}
}
|
Add processing cmd to update routine | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Update to the latest CAL-ACCESS snapshot and bake static website pages.
"""
import logging
from django.core.management import call_command
from calaccess_raw.management.commands.updatecalaccessrawdata import Command as updatecommand
logger = logging.getLogger(__name__)
class Command(updatecommand):
"""
Update to the latest CAL-ACCESS snapshot and bake static website pages.
"""
help = 'Update to the latest CAL-ACCESS snapshot and bake static website pages'
def add_arguments(self, parser):
"""
Adds custom arguments specific to this command.
"""
super(Command, self).add_arguments(parser)
parser.add_argument(
"--publish",
action="store_true",
dest="publish",
default=False,
help="Publish baked content"
)
def handle(self, *args, **options):
"""
Make it happen.
"""
super(Command, self).handle(*args, **options)
call_command('processcalaccessdata')
self.header('Creating latest file links')
call_command('createlatestlinks')
self.header('Baking downloads-website content')
call_command('build')
if options['publish']:
self.header('Publishing baked content to S3 bucket.')
call_command('publish')
self.success("Done!")
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Update to the latest CAL-ACCESS snapshot and bake static website pages.
"""
import logging
from django.core.management import call_command
from calaccess_raw.management.commands.updatecalaccessrawdata import Command as updatecommand
logger = logging.getLogger(__name__)
class Command(updatecommand):
"""
Update to the latest CAL-ACCESS snapshot and bake static website pages.
"""
help = 'Update to the latest CAL-ACCESS snapshot and bake static website pages'
def add_arguments(self, parser):
"""
Adds custom arguments specific to this command.
"""
super(Command, self).add_arguments(parser)
parser.add_argument(
"--publish",
action="store_true",
dest="publish",
default=False,
help="Publish baked content"
)
def handle(self, *args, **options):
"""
Make it happen.
"""
super(Command, self).handle(*args, **options)
self.header('Creating latest file links')
call_command('createlatestlinks')
self.header('Baking downloads-website content')
call_command('build')
if options['publish']:
self.header('Publishing baked content to S3 bucket.')
call_command('publish')
self.success("Done!")
|
Fix suggestedMax in chart when there is no data to display |
"use strict";
$(function () {
//-----------------------
//- Dashboard > Authentication Requests Chart -
//-----------------------
try{
var authChartData = JSON.parse($("#authenticationChartJson").val());
console.log("authentication chart data");
console.log(authChartData);
var authenticationRequestsChartData = {
labels : authChartData.labels,
datasets : [
{
label : "Successful Login",
fill : false,
backgroundColor : "#00BE79",
data : authChartData.success
}, {
label : "Failed Attempts",
fill : false,
backgroundColor : "#F39C12",
data : authChartData.failure
}
]
};
var authenticationRequestsChartOptions = {
responsive: true,
scales: {
yAxes: [{
ticks: {
suggestedMin: 0,
suggestedMax: 10
}
}]
}
};
console.log(authenticationRequestsChartData);
console.log(authenticationRequestsChartOptions);
// Get context with jQuery - using jQuery's .get() method.
var authenticationRequestsChartCanvas = $("#authenticationRequestsChart").get(0).getContext("2d");
// This will get the first returned node in the jQuery collection.
//Create the line chart
var authenticationRequestsChart = new Chart(authenticationRequestsChartCanvas, {
type: 'line',
data: authenticationRequestsChartData,
options: authenticationRequestsChartOptions
});
}catch(error){
console.log(error);
}
}); |
"use strict";
$(function () {
//-----------------------
//- Dashboard > Authentication Requests Chart -
//-----------------------
try{
var authChartData = JSON.parse($("#authenticationChartJson").val());
console.log("authentication chart data");
console.log(authChartData);
var authenticationRequestsChartData = {
labels : authChartData.labels,
datasets : [
{
label : "Successful Login",
fill : false,
backgroundColor : "#00BE79",
data : authChartData.success
}, {
label : "Failed Attempts",
fill : false,
backgroundColor : "#F39C12",
data : authChartData.failure
}
]
};
var authenticationRequestsChartOptions = {
responsive: true,
scales: {
yAxes: [{
ticks: {
suggestedMin: 0,
suggestedMax: 1000
}
}]
}
};
console.log(authenticationRequestsChartData);
console.log(authenticationRequestsChartOptions);
// Get context with jQuery - using jQuery's .get() method.
var authenticationRequestsChartCanvas = $("#authenticationRequestsChart").get(0).getContext("2d");
// This will get the first returned node in the jQuery collection.
//Create the line chart
var authenticationRequestsChart = new Chart(authenticationRequestsChartCanvas, {
type: 'line',
data: authenticationRequestsChartData,
options: authenticationRequestsChartOptions
});
}catch(error){
console.log(error);
}
}); |
Add missing return type declarations | <?php
namespace Doctrine\DBAL\Driver\DrizzlePDOMySql;
use Doctrine\DBAL\Platforms\DrizzlePlatform;
use Doctrine\DBAL\Schema\DrizzleSchemaManager;
/**
* Drizzle driver using PDO MySql.
*/
class Driver extends \Doctrine\DBAL\Driver\PDOMySql\Driver
{
/**
* {@inheritdoc}
*/
public function connect(array $params, $username = null, $password = null, array $driverOptions = [])
{
return new Connection(
$this->constructPdoDsn($params),
$username,
$password,
$driverOptions
);
}
/**
* {@inheritdoc}
*/
public function createDatabasePlatformForVersion($version)
{
return $this->getDatabasePlatform();
}
/**
* {@inheritdoc}
*
* @return DrizzlePlatform
*/
public function getDatabasePlatform()
{
return new DrizzlePlatform();
}
/**
* {@inheritdoc}
*
* @return DrizzleSchemaManager
*/
public function getSchemaManager(\Doctrine\DBAL\Connection $conn)
{
return new DrizzleSchemaManager($conn);
}
/**
* {@inheritdoc}
*
* @deprecated
*/
public function getName()
{
return 'drizzle_pdo_mysql';
}
}
| <?php
namespace Doctrine\DBAL\Driver\DrizzlePDOMySql;
use Doctrine\DBAL\Platforms\DrizzlePlatform;
use Doctrine\DBAL\Schema\DrizzleSchemaManager;
/**
* Drizzle driver using PDO MySql.
*/
class Driver extends \Doctrine\DBAL\Driver\PDOMySql\Driver
{
/**
* {@inheritdoc}
*/
public function connect(array $params, $username = null, $password = null, array $driverOptions = [])
{
return new Connection(
$this->constructPdoDsn($params),
$username,
$password,
$driverOptions
);
}
/**
* {@inheritdoc}
*/
public function createDatabasePlatformForVersion($version)
{
return $this->getDatabasePlatform();
}
/**
* {@inheritdoc}
*/
public function getDatabasePlatform()
{
return new DrizzlePlatform();
}
/**
* {@inheritdoc}
*/
public function getSchemaManager(\Doctrine\DBAL\Connection $conn)
{
return new DrizzleSchemaManager($conn);
}
/**
* {@inheritdoc}
*
* @deprecated
*/
public function getName()
{
return 'drizzle_pdo_mysql';
}
}
|
Fix conflicting test. Test checks for categories/1/ | from django.test import TestCase
from pinax.forums.models import Forum, ForumCategory
class ForumCategoryTests(TestCase):
def test_unicode_method(self):
cat = ForumCategory(title="Software")
self.assertEquals(str(cat), cat.title)
def test_get_absolute_url(self):
cat = ForumCategory.objects.create(title="Software")
self.assertEquals(cat.get_absolute_url(), "/categories/1/")
def test_forums_ordered_properly(self):
cat = ForumCategory.objects.create(title="Software")
Forum.objects.create(category=cat, title="Python", description="Python software")
Forum.objects.create(category=cat, title="Swift", description="Swift software")
Forum.objects.create(category=cat, title="Basic", description="Old software")
forums = cat.forums
self.assertEquals(forums[0].title, "Basic")
self.assertEquals(forums[1].title, "Python")
self.assertEquals(forums[2].title, "Swift")
class ForumTests(TestCase):
def test_forum_thread_count_is_zero(self):
f = Forum.objects.create(title="Python", description="Python software")
self.assertEquals(f.thread_count, 0)
def test_inc_views(self):
f = Forum.objects.create(title="Python", description="Python software")
self.assertEquals(f.view_count, 0)
f.inc_views()
self.assertEquals(f.view_count, 1)
| from django.test import TestCase
from pinax.forums.models import Forum, ForumCategory
class ForumCategoryTests(TestCase):
def test_unicode_method(self):
cat = ForumCategory(title="Software")
self.assertEquals(str(cat), cat.title)
def test_get_absolute_url(self):
cat = ForumCategory.objects.create(title="Software")
self.assertEquals(cat.get_absolute_url(), "/category/1/")
def test_forums_ordered_properly(self):
cat = ForumCategory.objects.create(title="Software")
Forum.objects.create(category=cat, title="Python", description="Python software")
Forum.objects.create(category=cat, title="Swift", description="Swift software")
Forum.objects.create(category=cat, title="Basic", description="Old software")
forums = cat.forums
self.assertEquals(forums[0].title, "Basic")
self.assertEquals(forums[1].title, "Python")
self.assertEquals(forums[2].title, "Swift")
class ForumTests(TestCase):
def test_forum_thread_count_is_zero(self):
f = Forum.objects.create(title="Python", description="Python software")
self.assertEquals(f.thread_count, 0)
def test_inc_views(self):
f = Forum.objects.create(title="Python", description="Python software")
self.assertEquals(f.view_count, 0)
f.inc_views()
self.assertEquals(f.view_count, 1)
|
Replace `Layer` to `Clip` on Project structure spec` | import Project from '../../src/project/project'
import Asset from '../../src/project/asset'
import Composition from '../../src/project/composition'
import TimeLane from '../../src/project/timelane'
import Clip from '../../src/project/clip'
describe('project structure specs', () => {
describe('Project', () => {
let project
beforeEach(() => {
project = new Project()
})
afterEach(() => {
project = null
})
it('project construction flow', () => {
project.assets.add(new Asset)
project.assets.add(new Asset)
const comp1 = new Composition
project.compositions.add(comp1)
const lane1 = new TimeLane
comp1.timelanes.add(lane1)
lane1.layers.add(new Clip)
})
it('correctry serialize/deserialize the project', () => {
const comp1 = new Composition
project.compositions.add(comp1)
const lane1 = new TimeLane
comp1.timelanes.add(lane1)
const pbson = project.serialize()
expect(Project.deserialize(pbson).toJSON()).to.eql(project.toJSON())
})
})
})
| import Project from '../../src/project/project'
import Asset from '../../src/project/asset'
import Composition from '../../src/project/composition'
import TimeLane from '../../src/project/timelane'
import Layer from '../../src/project/layer'
describe('project structure specs', () => {
describe('Project', () => {
let project
beforeEach(() => {
project = new Project()
})
afterEach(() => {
project = null
})
it('project construction flow', () => {
project.assets.add(new Asset)
project.assets.add(new Asset)
const comp1 = new Composition
project.compositions.add(comp1)
const lane1 = new TimeLane
comp1.timelanes.add(lane1)
lane1.layers.add(new Layer)
})
it('correctry serialize/deserialize the project', () => {
const comp1 = new Composition
project.compositions.add(comp1)
const lane1 = new TimeLane
comp1.timelanes.add(lane1)
const pbson = project.serialize()
expect(Project.deserialize(pbson).toJSON()).to.eql(project.toJSON())
})
})
})
|
Add value to return if nothing is found | from django.db import models
from django.utils.timezone import now
from django.utils.translation import get_language
from django.utils.translation import ugettext_lazy as _
from rdmo.core.utils import get_languages
class Model(models.Model):
created = models.DateTimeField(editable=False, verbose_name=_('created'))
updated = models.DateTimeField(editable=False, verbose_name=_('updated'))
class Meta:
abstract = True
def save(self, *args, **kwargs):
if self.created is None:
self.created = now()
self.updated = now()
super(Model, self).save(*args, **kwargs)
class TranslationMixin(object):
def trans(self, field):
current_language = get_language()
languages = get_languages()
for lang_code, lang_string, lang_field in languages:
if lang_code == current_language:
return getattr(self, '%s_%s' % (field, lang_field))
r = ''
for i in range(1, 6):
try:
r = getattr(self, '%s_%s' % (field, 'lang' + str(i)))
except AttributeError:
pass
else:
if r != '':
return r
return r
primary_lang_field = languages[0][2]
return getattr(self, '%s_%s' % (field, primary_lang_field)) or ''
| from django.db import models
from django.utils.timezone import now
from django.utils.translation import get_language
from django.utils.translation import ugettext_lazy as _
from rdmo.core.utils import get_languages
class Model(models.Model):
created = models.DateTimeField(editable=False, verbose_name=_('created'))
updated = models.DateTimeField(editable=False, verbose_name=_('updated'))
class Meta:
abstract = True
def save(self, *args, **kwargs):
if self.created is None:
self.created = now()
self.updated = now()
super(Model, self).save(*args, **kwargs)
class TranslationMixin(object):
def trans(self, field):
current_language = get_language()
languages = get_languages()
for lang_code, lang_string, lang_field in languages:
if lang_code == current_language:
return getattr(self, '%s_%s' % (field, lang_field))
r = ''
for i in range(1, 6):
try:
r = getattr(self, '%s_%s' % (field, 'lang' + str(i)))
except AttributeError:
pass
else:
if r != '':
return r
primary_lang_field = languages[0][2]
return getattr(self, '%s_%s' % (field, primary_lang_field)) or ''
|
Replace non-ASCII character in comment | from django.contrib.admin import ModelAdmin
from django.core.exceptions import PermissionDenied
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.generic import View
from ..auth import has_permission
from ..compat import include, patterns, render, url
from .mixins import DjediContextMixin
class Admin(ModelAdmin):
verbose_name = 'CMS'
verbose_name_plural = verbose_name
def get_urls(self):
return patterns(
url(r'^', include('djedi.admin.urls', namespace='djedi')),
url(r'', lambda: None, name='djedi_cms_changelist') # Placeholder to show change link to CMS in admin
)
def has_change_permission(self, request, obj=None):
return has_permission(request)
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
# Hide Djedi in the admin, since that view is not finished yet.
# This only works in Django 1.8+, but shouldn't break older versions.
def has_module_permission(self, request):
return False
class DjediCMS(DjediContextMixin, View):
@xframe_options_exempt
def get(self, request):
if has_permission(request):
return render(request, 'djedi/cms/cms.html', self.get_context_data())
else:
raise PermissionDenied
| from django.contrib.admin import ModelAdmin
from django.core.exceptions import PermissionDenied
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.generic import View
from ..auth import has_permission
from ..compat import include, patterns, render, url
from .mixins import DjediContextMixin
class Admin(ModelAdmin):
verbose_name = 'CMS'
verbose_name_plural = verbose_name
def get_urls(self):
return patterns(
url(r'^', include('djedi.admin.urls', namespace='djedi')),
url(r'', lambda: None, name='djedi_cms_changelist') # Placeholder to show change link to CMS in admin
)
def has_change_permission(self, request, obj=None):
return has_permission(request)
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
# Hide Djedi in the admin, since that view is not finished yet.
# This only works in Django 1.8+, but shouldn’t break older versions.
def has_module_permission(self, request):
return False
class DjediCMS(DjediContextMixin, View):
@xframe_options_exempt
def get(self, request):
if has_permission(request):
return render(request, 'djedi/cms/cms.html', self.get_context_data())
else:
raise PermissionDenied
|
Set the embedded schema registry's compatibility mode to full | package forklift.integration.server;
import io.confluent.kafka.schemaregistry.rest.SchemaRegistryConfig;
import io.confluent.kafka.schemaregistry.rest.SchemaRegistryRestApplication;
import org.eclipse.jetty.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
/**
* Embedded SchemaRegistry server
*/
public class SchemaRegistryService implements Runnable {
private static final Logger log = LoggerFactory.getLogger(SchemaRegistryService.class);
private Server server;
private final int localZookeeperPort;
private final int listenPort;
public SchemaRegistryService(int localZookeeperPort, int listenPort) {
this.localZookeeperPort = localZookeeperPort;
this.listenPort = listenPort;
}
public void stop() throws Exception {
server.stop();
Thread.sleep(1500);
}
@Override
public void run() {
Properties properties = new Properties();
properties.setProperty("listeners", "http://localhost:" + listenPort);
properties.setProperty("kafkastore.connection.url", "localhost:" + localZookeeperPort);
properties.setProperty("host.name", "localhost");
properties.setProperty("avro.compatibility.level", "full");
try {
SchemaRegistryConfig config = new SchemaRegistryConfig(properties);
SchemaRegistryRestApplication app = new SchemaRegistryRestApplication(config);
server = app.createServer();
server.start();
server.join();
} catch (Exception e) {
log.error("Unable to start Schema Registry", e);
}
}
}
| package forklift.integration.server;
import io.confluent.kafka.schemaregistry.rest.SchemaRegistryConfig;
import io.confluent.kafka.schemaregistry.rest.SchemaRegistryRestApplication;
import org.eclipse.jetty.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
/**
* Embedded SchemaRegistry server
*/
public class SchemaRegistryService implements Runnable {
private static final Logger log = LoggerFactory.getLogger(SchemaRegistryService.class);
private Server server;
private final int localZookeeperPort;
private final int listenPort;
public SchemaRegistryService(int localZookeeperPort, int listenPort) {
this.localZookeeperPort = localZookeeperPort;
this.listenPort = listenPort;
}
public void stop() throws Exception {
server.stop();
Thread.sleep(1500);
}
@Override
public void run() {
Properties properties = new Properties();
properties.setProperty("listeners", "http://localhost:" + listenPort);
properties.setProperty("kafkastore.connection.url", "localhost:" + localZookeeperPort);
properties.setProperty("host.name", "localhost");
//properties.setProperty("kafkastore.topic", "_schemas");
//properties.setProperty("debug", "false");
try {
SchemaRegistryConfig config = new SchemaRegistryConfig(properties);
SchemaRegistryRestApplication app = new SchemaRegistryRestApplication(config);
server = app.createServer();
server.start();
server.join();
} catch (Exception e) {
log.error("Unable to start Schema Registry", e);
}
}
}
|
Allow data URIs to be set as the new tab page | /*global chrome,document,window */
(function init(angular) {
"use strict";
try {
chrome.storage.local.get(["url", "tab.selected", "always-tab-update"], function (items) {
var url = items.url;
if (url) {
url = (0 !== url.indexOf("about:") && 0 !== url.indexOf("data:") && -1 === url.indexOf("://")) ? ("http://" + url) : url;
if (/^http[s]?:/i.test(url) && items["always-tab-update"] !== true) {
document.location.href = url;
} else {
chrome.tabs.getCurrent(function (tab) {
// a keen user may open the extension's background page and set:
// chrome.storage.local.set({'tab.selected': false});
var selected = items["tab.selected"] === undefined ? true : (items["tab.selected"] == "true");
chrome.tabs.update(tab.id, {
"url": url,
"highlighted": selected
});
});
}
} else {
angular.resumeBootstrap();
}
});
} catch(e){
// If anything goes wrong with the redirection logic, fail to custom apps page.
console.error(e);
angular.resumeBootstrap();
}
})(angular);
| /*global chrome,document,window */
(function init(angular) {
"use strict";
try {
chrome.storage.local.get(["url", "tab.selected", "always-tab-update"], function (items) {
var url = items.url;
if (url) {
url = (0 !== url.indexOf("about:") && -1 === url.indexOf("://")) ? ("http://" + url) : url;
if (/^http[s]?:/i.test(url) && items["always-tab-update"] !== true) {
document.location.href = url;
} else {
chrome.tabs.getCurrent(function (tab) {
// a keen user may open the extension's background page and set:
// chrome.storage.local.set({'tab.selected': false});
var selected = items["tab.selected"] === undefined ? true : (items["tab.selected"] == "true");
chrome.tabs.update(tab.id, {
"url": url,
"highlighted": selected
});
});
}
} else {
angular.resumeBootstrap();
}
});
} catch(e){
// If anything goes wrong with the redirection logic, fail to custom apps page.
console.error(e);
angular.resumeBootstrap();
}
})(angular);
|
Remove unnecessary comments from webpack | const path = require("path");
module.exports = {
module: {
rules: [
{
test: /\.css$/,
include: path.resolve(__dirname, ".."),
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
sourceMap: true,
},
},
],
},
{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
{
"loader": "css-loader",
"options": {
"modules": true,
// "localIdentName": "[local]",
"localIdentName": "[local]__[hash:base64:5]",
"importLoaders": 1,
"sourceMap": false
}
},
"sass-loader", // compiles Sass to CSS, using Node Sass by default
],
include: path.resolve(__dirname, "..")
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: "file-loader"
},
{
test: /\.(?:png|jpg|svg)$/,
loader: "url-loader",
query: {
limit: 10000
}
}
]
}
};
| const path = require("path");
module.exports = {
module: {
rules: [
{
test: /\.css$/,
include: path.resolve(__dirname, ".."),
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
sourceMap: true,
},
},
],
},
// {
// test: /\.scss$/,
// loaders: ["style-loader", "css-loader", "sass-loader"],
// include: path.resolve(__dirname, ".."),
// },
{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
{
"loader": "css-loader",
"options": {
"modules": true,
// "localIdentName": "[local]",
"localIdentName": "[local]__[hash:base64:5]",
"importLoaders": 1,
"sourceMap": false
}
},
"sass-loader", // compiles Sass to CSS, using Node Sass by default
],
include: path.resolve(__dirname, "..")
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: "file-loader"
},
{
test: /\.(?:png|jpg|svg)$/,
loader: "url-loader",
query: {
limit: 10000
}
}
]
}
};
|
Comment for types of area that need importing | """
DIW
MTW
UTW
"""
import time
import requests
from bs4 import BeautifulSoup
from django.core.management.base import BaseCommand
from django.contrib.gis.geos import GEOSGeometry
from django.contrib.gis.geos import Point
from authorities.models import Authority, MapitArea
from authorities import constants
from authorities.helpers import geocode
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('mapit_type', type=str)
def handle(self, *args, **options):
print(options)
self.get_type_from_mapit(options['mapit_type'])
def get_type_from_mapit(self, mapit_type):
req = requests.get('%sareas/%s' % (
constants.MAPIT_URL, mapit_type))
for mapit_id, area in list(req.json().items()):
print(area)
authority = Authority.objects.get(mapit_id=area['parent_area'])
MapitArea.objects.get_or_create(
gss=area['codes']['gss'],
parent_authority=authority,
name=area['name'],
area_type=area['type'],
unit_id=area['codes']['unit_id'],
type_name=area['type_name'],
country_name=area['country_name'],
)
| import time
import requests
from bs4 import BeautifulSoup
from django.core.management.base import BaseCommand
from django.contrib.gis.geos import GEOSGeometry
from django.contrib.gis.geos import Point
from authorities.models import Authority, MapitArea
from authorities import constants
from authorities.helpers import geocode
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('mapit_type', type=str)
def handle(self, *args, **options):
print(options)
self.get_type_from_mapit(options['mapit_type'])
def get_type_from_mapit(self, mapit_type):
req = requests.get('%sareas/%s' % (
constants.MAPIT_URL, mapit_type))
for mapit_id, area in list(req.json().items()):
authority = Authority.objects.get(mapit_id=area['parent_area'])
MapitArea.objects.get_or_create(
gss=area['codes']['gss'],
parent_authority=authority,
name=area['name'],
area_type=area['type'],
unit_id=area['codes']['unit_id'],
type_name=area['type_name'],
country_name=area['country_name'],
)
|
Update swagger docs with product variants originalPrice | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\ApiBundle\Swagger;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/** @experimental */
final class ProductVariantDocumentationNormalizer implements NormalizerInterface
{
/** @var NormalizerInterface */
private $decoratedNormalizer;
public function __construct(NormalizerInterface $decoratedNormalizer)
{
$this->decoratedNormalizer = $decoratedNormalizer;
}
public function supportsNormalization($data, $format = null)
{
return $this->decoratedNormalizer->supportsNormalization($data, $format);
}
public function normalize($object, $format = null, array $context = [])
{
$docs = $this->decoratedNormalizer->normalize($object, $format, $context);
$docs['components']['schemas']['ProductVariant.jsonld-shop.product_variant.read']['properties']['price'] = [
'type' => 'int',
'readOnly' => true,
'default' => 0,
];
$docs['components']['schemas']['ProductVariant.jsonld-shop.product_variant.read']['properties']['inStock'] = [
'type' => 'boolean',
'readOnly' => true,
];
$docs['components']['schemas']['ProductVariant.jsonld-shop.product_variant.read']['properties']['originalPrice'] = [
'type' => 'int',
'readOnly' => true,
'default' => 0,
];
return $docs;
}
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\ApiBundle\Swagger;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/** @experimental */
final class ProductVariantDocumentationNormalizer implements NormalizerInterface
{
/** @var NormalizerInterface */
private $decoratedNormalizer;
public function __construct(NormalizerInterface $decoratedNormalizer)
{
$this->decoratedNormalizer = $decoratedNormalizer;
}
public function supportsNormalization($data, $format = null)
{
return $this->decoratedNormalizer->supportsNormalization($data, $format);
}
public function normalize($object, $format = null, array $context = [])
{
$docs = $this->decoratedNormalizer->normalize($object, $format, $context);
$docs['components']['schemas']['ProductVariant.jsonld-shop.product_variant.read']['properties']['price'] = [
'type' => 'int',
'readOnly' => true,
'default' => 0,
];
$docs['components']['schemas']['ProductVariant.jsonld-shop.product_variant.read']['properties']['inStock'] = [
'type' => 'boolean',
'readOnly' => true,
];
return $docs;
}
}
|
Fix argument order for Object.assign
Thanks @paulkaplan | const UPDATE_EDITING_TARGET = 'scratch-gui/targets/UPDATE_EDITING_TARGET';
const UPDATE_TARGET_LIST = 'scratch-gui/targets/UPDATE_TARGET_LIST';
const initialState = {
sprites: {},
stage: {}
};
const reducer = function (state, action) {
if (typeof state === 'undefined') state = initialState;
switch (action.type) {
case UPDATE_TARGET_LIST:
return Object.assign({}, state, {
sprites: action.targets
.filter(target => !target.isStage)
.reduce(
(targets, target, listId) => Object.assign(
targets,
{[target.id]: {order: listId, ...target}}
),
{}
),
stage: action.targets
.filter(target => target.isStage)[0] || {}
});
case UPDATE_EDITING_TARGET:
return Object.assign({}, state, {editingTarget: action.target});
default:
return state;
}
};
reducer.updateTargets = function (targetList) {
return {
type: UPDATE_TARGET_LIST,
targets: targetList,
meta: {
throttle: 30
}
};
};
reducer.updateEditingTarget = function (editingTarget) {
return {
type: UPDATE_EDITING_TARGET,
target: editingTarget,
meta: {
throttle: 30
}
};
};
module.exports = reducer;
| const UPDATE_EDITING_TARGET = 'scratch-gui/targets/UPDATE_EDITING_TARGET';
const UPDATE_TARGET_LIST = 'scratch-gui/targets/UPDATE_TARGET_LIST';
const initialState = {
sprites: {},
stage: {}
};
const reducer = function (state, action) {
if (typeof state === 'undefined') state = initialState;
switch (action.type) {
case UPDATE_TARGET_LIST:
return Object.assign({}, state, {
sprites: action.targets
.filter(target => !target.isStage)
.reduce(
(targets, target, listId) => Object.assign(
{[target.id]: {order: listId, ...target}},
targets
),
{}
),
stage: action.targets
.filter(target => target.isStage)[0] || {}
});
case UPDATE_EDITING_TARGET:
return Object.assign({}, state, {editingTarget: action.target});
default:
return state;
}
};
reducer.updateTargets = function (targetList) {
return {
type: UPDATE_TARGET_LIST,
targets: targetList,
meta: {
throttle: 30
}
};
};
reducer.updateEditingTarget = function (editingTarget) {
return {
type: UPDATE_EDITING_TARGET,
target: editingTarget,
meta: {
throttle: 30
}
};
};
module.exports = reducer;
|
Correct some more variables to private not static | <?php
class SchemaPoint
{
private $latitude;
private $longitude;
private $altitude;
public function __construct($parameters)
{
$this->latitude = @$parameters["latitude"];
$this->longitude = @$parameters["longitude"];
$this->altitude = @$parameters["altitude"];
}
public function __toString()
{
$string = "<u>Point:</u><blockquote>\n";
$string .= "latitude: ".$this->latitude."<br>\n";
$string .= "longitude: ".$this->longitude."<br>\n";
$string .= "altitude: ".$this->altitude;
$string .= "</blockquote>\n";
return $string;
}
public function __toXML()
{
$xml = "<geo:Point>\n";
if($this->latitude) $xml .= " <geo:lat>".htmlspecialchars($this->latitude)."</geo:lat>\n";
if($this->longitude) $xml .= " <geo:long>".htmlspecialchars($this->longitude)."</geo:long>\n";
if($this->altitude) $xml .= " <geo:alt>".htmlspecialchars($this->altitude)."</geo:alt>\n";
$xml .= "</geo:Point>\n";
return $xml;
}
}
?> | <?php
class SchemaPoint
{
static $latitude;
static $longitude;
static $altitude;
public function __construct($parameters)
{
$this->latitude = @$parameters["latitude"];
$this->longitude = @$parameters["longitude"];
$this->altitude = @$parameters["altitude"];
}
public function __toString()
{
$string = "<u>Point:</u><blockquote>\n";
$string .= "latitude: ".$this->latitude."<br>\n";
$string .= "longitude: ".$this->longitude."<br>\n";
$string .= "altitude: ".$this->altitude;
$string .= "</blockquote>\n";
return $string;
}
public function __toXML()
{
$xml = "<geo:Point>\n";
if($this->latitude) $xml .= " <geo:lat>".htmlspecialchars($this->latitude)."</geo:lat>\n";
if($this->longitude) $xml .= " <geo:long>".htmlspecialchars($this->longitude)."</geo:long>\n";
if($this->altitude) $xml .= " <geo:alt>".htmlspecialchars($this->altitude)."</geo:alt>\n";
$xml .= "</geo:Point>\n";
return $xml;
}
}
?> |
Fix view created without context. | /**
* @license
* Copyright 2020 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.u2.view',
name: 'ObjAltView',
extends: 'foam.u2.View',
documentation: "Like AltView, but for Objects instead of DAO's.",
css: `
^ { margin: auto; }
^ select { height: 26px }
`,
properties: [
{
name: 'of',
factory: function() { return this.data.of }
},
{
name: 'views',
factory: function() { return []; }
},
{
name: 'selectedView',
view: function(_, X) {
return foam.u2.view.ChoiceView.create({choices: X.data.views}, X);
}
},
{
name: 'data'
}
],
methods: [
function initE() {
this.SUPER();
var self = this;
this.selectedView = this.views[0][0];
this.addClass(this.myClass())
this.startContext({data: this})
this.start()
.add(this.SELECTED_VIEW)
.end()
.endContext()
.start('div')
.add(this.selectedView$.map(function(v) {
return self.E().tag(v, {data$: self.data$});
}))
.end();
}
]
});
| /**
* @license
* Copyright 2020 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.u2.view',
name: 'ObjAltView',
extends: 'foam.u2.View',
documentation: "Like AltView, but for Objects instead of DAO's.",
css: `
^ { margin: auto; }
^ select { height: 26px }
`,
properties: [
{
name: 'of',
factory: function() { return this.data.of }
},
{
name: 'views',
factory: function() { return []; }
},
{
name: 'selectedView',
view: function(_, X) {
return foam.u2.view.ChoiceView.create({choices: X.data.views});
}
},
{
name: 'data'
}
],
methods: [
function initE() {
this.SUPER();
var self = this;
this.selectedView = this.views[0][0];
this.addClass(this.myClass())
this.startContext({data: this})
this.start()
.add(this.SELECTED_VIEW)
.end()
.endContext()
.start('div')
.add(this.selectedView$.map(function(v) {
return self.E().tag(v, {data$: self.data$});
}))
.end();
}
]
});
|
Reduce frequency to 10 Hz instead of 2. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2015 Jean Nassar
# Released under BSD version 4
"""
Reduce /ardrone/image_color framerate from 30 Hz to 2 Hz.
"""
import rospy
from sensor_msgs.msg import Image
class FramerateReducer(object):
"""
Reduces the framerate of a video feed to one fifteenth of the original.
"""
def __init__(self):
self.image_subscriber = rospy.Subscriber("/ardrone/image_color",
Image, self.frame_callback,
queue_size=1)
self.image_publisher = rospy.Publisher("/ardrone/slow_image_raw",
Image, queue_size=1)
rospy.logdebug("Subscribed to /ardrone/image_color")
self.count = 0
def frame_callback(self, frame):
"""
Publish at a reduced rate.
"""
# Publish every fifteenth frame
if not self.count % 3:
self.image_publisher.publish(frame)
self.count += 1
def main():
"""
Main entry point for script.
"""
rospy.init_node("framerate_reducer", anonymous=True)
FramerateReducer()
rospy.loginfo("Reducing framerate")
rospy.spin()
if __name__ == "__main__":
main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2015 Jean Nassar
# Released under BSD version 4
"""
Reduce /ardrone/image_color framerate from 30 Hz to 2 Hz.
"""
import rospy
from sensor_msgs.msg import Image
class FramerateReducer(object):
"""
Reduces the framerate of a video feed to one fifteenth of the original.
"""
def __init__(self):
self.image_subscriber = rospy.Subscriber("/ardrone/image_color",
Image, self.frame_callback,
queue_size=1)
self.image_publisher = rospy.Publisher("/ardrone/slow_image_raw",
Image, queue_size=1)
rospy.logdebug("Subscribed to /ardrone/image_color")
self.count = 0
def frame_callback(self, frame):
"""
Publish at a reduced rate.
"""
# Publish every fifteenth frame
if not self.count % 15:
self.image_publisher.publish(frame)
self.count += 1
def main():
"""
Main entry point for script.
"""
rospy.init_node("framerate_reducer", anonymous=True)
FramerateReducer()
rospy.loginfo("Reducing framerate")
rospy.spin()
if __name__ == "__main__":
main()
|
Set liveness to 0 when broker tells us we are disconnected | module.exports = function() {
var dataBuffer = Array.prototype.slice.call(arguments),
data,
self = this;
data = dataBuffer.map(function(d) {
return d.toString();
});
// update timer for last message recieved
this.lastMsg = new Date();
switch(data[0]) {
case this.constants.HEARTBEAT:
console.log("I: HEARTBEAT");
var heartbeat = [
this.constants.PROTOCOL_WORKER, this.constants.HEARTBEAT
];
self.socket.send(heartbeat);
break;
case this.constants.REQUEST:
var req = {};
data.forEach(function(d, i) {
var attr = self.constants.MSG_ATTRS[i];
req[attr] = d.toString();
});
try {
if(req.params) {
req.params = JSON.parse(req.params);
}
} catch(err) {
console.log('Connot parse message', req.correlationId, err);
}
console.log("I: REQUEST", req);
this.events.emit('request', req);
break;
case this.constants.DISCONNECT:
console.log("E: DISCONNECTED", data[1]);
this.liveness = 0;
this.events.emit('disconnect', data[2]);
break;
default:
console.log("?: Unknown request type", data[0]);
}
}
| module.exports = function() {
var dataBuffer = Array.prototype.slice.call(arguments),
data,
self = this;
data = dataBuffer.map(function(d) {
return d.toString();
});
// update timer for last message recieved
this.lastMsg = new Date();
switch(data[0]) {
case this.constants.HEARTBEAT:
console.log("I: HEARTBEAT");
var heartbeat = [
this.constants.PROTOCOL_WORKER, this.constants.HEARTBEAT
];
self.socket.send(heartbeat);
break;
case this.constants.REQUEST:
var req = {};
data.forEach(function(d, i) {
var attr = self.constants.MSG_ATTRS[i];
req[attr] = d.toString();
});
try {
if(req.params) {
req.params = JSON.parse(req.params);
}
} catch(err) {
console.log('Connot parse message', req.correlationId, err);
}
console.log("I: REQUEST", req);
this.events.emit('request', req);
break;
case this.constants.DISCONNECT:
console.log("E: DISCONNECTED", data[1]);
this.events.emit('disconnect', data[2]);
break;
default:
console.log("?: Unknown request type", data[0]);
}
}
|
Fix bug in trace handler | package io.undertow.server.handlers;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HeaderValues;
import io.undertow.util.Headers;
import io.undertow.util.Methods;
/**
* A handler that handles HTTP trace requests
*
* @author Stuart Douglas
*/
public class HttpTraceHandler implements HttpHandler {
private final HttpHandler handler;
public HttpTraceHandler(final HttpHandler handler) {
this.handler = handler;
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
if(exchange.getRequestMethod().equals(Methods.TRACE)) {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "message/http");
StringBuilder body = new StringBuilder("TRACE ");
body.append(exchange.getRequestURI());
if(!exchange.getQueryString().isEmpty()) {
body.append('?');
body.append(exchange.getQueryString());
}
body.append(exchange.getProtocol().toString());
body.append("\r\n");
for(HeaderValues header : exchange.getRequestHeaders()) {
for(String value : header) {
body.append(header.getHeaderName());
body.append(": ");
body.append(value);
body.append("\r\n");
}
}
body.append("\r\n");
exchange.getResponseSender().send(body.toString());
} else {
handler.handleRequest(exchange);
}
}
}
| package io.undertow.server.handlers;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HeaderValues;
import io.undertow.util.Headers;
import io.undertow.util.Methods;
/**
* A handler that handles HTTP trace requests
*
* @author Stuart Douglas
*/
public class HttpTraceHandler implements HttpHandler {
private final HttpHandler handler;
public HttpTraceHandler(final HttpHandler handler) {
this.handler = handler;
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
if(exchange.getRequestMethod().equals(Methods.TRACE)) {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "message/http");
StringBuilder body = new StringBuilder("TRACE ");
body.append(exchange.getRequestURI());
if(!exchange.getQueryString().isEmpty()) {
body.append('?');
body.append(exchange.getQueryString());
}
body.append(exchange.getProtocol().toString());
body.append("\r\n");
for(HeaderValues header : exchange.getRequestHeaders()) {
for(String value : header) {
body.append(header.getHeaderName());
body.append(": ");
body.append(value);
body.append("\r\n");
}
}
body.append("\r\n");
} else {
handler.handleRequest(exchange);
}
}
}
|
Add index to access_token_id column | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateOauthRefreshTokensTable extends Migration
{
/**
* The database schema.
*
* @var \Illuminate\Database\Schema\Builder
*/
protected $schema;
/**
* Create a new migration instance.
*
* @return void
*/
public function __construct()
{
$this->schema = Schema::connection($this->getConnection());
}
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$this->schema->create('oauth_refresh_tokens', function (Blueprint $table) {
$table->string('id', 100)->primary();
$table->string('access_token_id', 100)->index();
$table->boolean('revoked');
$table->dateTime('expires_at')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
$this->schema->dropIfExists('oauth_refresh_tokens');
}
/**
* Get the migration connection name.
*
* @return string|null
*/
public function getConnection()
{
return config('passport.storage.database.connection');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateOauthRefreshTokensTable extends Migration
{
/**
* The database schema.
*
* @var \Illuminate\Database\Schema\Builder
*/
protected $schema;
/**
* Create a new migration instance.
*
* @return void
*/
public function __construct()
{
$this->schema = Schema::connection($this->getConnection());
}
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$this->schema->create('oauth_refresh_tokens', function (Blueprint $table) {
$table->string('id', 100)->primary();
$table->string('access_token_id', 100);
$table->boolean('revoked');
$table->dateTime('expires_at')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
$this->schema->dropIfExists('oauth_refresh_tokens');
}
/**
* Get the migration connection name.
*
* @return string|null
*/
public function getConnection()
{
return config('passport.storage.database.connection');
}
}
|
Rename old class name of kvs-schema | package io.github.droidkaigi.confsched.util;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Arrays;
import java.util.Locale;
import io.github.droidkaigi.confsched.prefs.DefaultPrefs;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(AndroidJUnit4.class)
public class LocaleUtilsTest {
@Test
public void testCurrentLanguageId() throws Exception {
Context context = InstrumentationRegistry.getContext();
// is not null value.
assertThat(LocaleUtil.getCurrentLanguageId(context)).isNotNull();
DefaultPrefs.get(context).putLanguageId("ja");
// eq to languageID is put in SharedPreferences.
assertThat(LocaleUtil.getCurrentLanguageId(context)).isEqualTo("ja");
DefaultPrefs.get(context).removeLanguageId();
String defaultLanguage = Locale.getDefault().getLanguage().toLowerCase();
if (Arrays.asList(LocaleUtil.SUPPORT_LANG).contains(defaultLanguage)) {
// eq to Locale.getDefault().getLanguage() when it is supported
assertThat(LocaleUtil.getCurrentLanguageId(context)).isEqualTo(defaultLanguage);
} else {
// eq to "en" when Locale.getDefault().getLanguage() is not supported
assertThat(LocaleUtil.getCurrentLanguageId(context)).isEqualTo("en");
}
}
}
| package io.github.droidkaigi.confsched.util;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Arrays;
import java.util.Locale;
import io.github.droidkaigi.confsched.prefs.DefaultPrefsSchema;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(AndroidJUnit4.class)
public class LocaleUtilsTest {
@Test
public void testCurrentLanguageId() throws Exception {
Context context = InstrumentationRegistry.getContext();
// is not null value.
assertThat(LocaleUtil.getCurrentLanguageId(context)).isNotNull();
DefaultPrefsSchema.get(context).putLanguageId("ja");
// eq to languageID is put in SharedPreferences.
assertThat(LocaleUtil.getCurrentLanguageId(context)).isEqualTo("ja");
DefaultPrefsSchema.get(context).removeLanguageId();
String defaultLanguage = Locale.getDefault().getLanguage().toLowerCase();
if (Arrays.asList(LocaleUtil.SUPPORT_LANG).contains(defaultLanguage)) {
// eq to Locale.getDefault().getLanguage() when it is supported
assertThat(LocaleUtil.getCurrentLanguageId(context)).isEqualTo(defaultLanguage);
} else {
// eq to "en" when Locale.getDefault().getLanguage() is not supported
assertThat(LocaleUtil.getCurrentLanguageId(context)).isEqualTo("en");
}
}
}
|
Fix anchor used to check if animations should run | package io.doist.recyclerviewext.flippers;
import android.support.v4.view.ViewCompat;
import android.view.View;
/**
* Flips between views with a common ancestor using a {@link FlipperAnimator}.
*/
public class Flipper {
private FlipperAnimator mFlipperAnimator = new DefaultFlipperAnimator();
public FlipperAnimator getFlipperAnimator() {
return mFlipperAnimator;
}
public void setFlipperAnimator(FlipperAnimator flipperAnimator) {
mFlipperAnimator = flipperAnimator;
}
public void replace(View outView, View inView) {
replaceInternal(outView, inView, true);
}
public void replaceNoAnimation(View outView, View inView) {
replaceInternal(outView, inView, false);
}
protected void replaceInternal(View outView, View inView, boolean animate) {
if (animate && mFlipperAnimator != null && ViewCompat.isLaidOut(outView)) {
mFlipperAnimator.animateFlip(outView, inView);
} else {
if (mFlipperAnimator != null && mFlipperAnimator.isAnimating()) {
outView.animate().cancel();
inView.animate().cancel();
}
outView.setVisibility(View.GONE);
inView.setVisibility(View.VISIBLE);
}
}
}
| package io.doist.recyclerviewext.flippers;
import android.support.v4.view.ViewCompat;
import android.view.View;
/**
* Flips between views with a common ancestor using a {@link FlipperAnimator}.
*/
public class Flipper {
private FlipperAnimator mFlipperAnimator = new DefaultFlipperAnimator();
public FlipperAnimator getFlipperAnimator() {
return mFlipperAnimator;
}
public void setFlipperAnimator(FlipperAnimator flipperAnimator) {
mFlipperAnimator = flipperAnimator;
}
public void replace(View outView, View inView) {
replaceInternal(outView, inView, true);
}
public void replaceNoAnimation(View outView, View inView) {
replaceInternal(outView, inView, false);
}
protected void replaceInternal(View outView, View inView, boolean animate) {
if (animate && mFlipperAnimator != null && ViewCompat.isLaidOut(inView)) {
mFlipperAnimator.animateFlip(outView, inView);
} else {
if (mFlipperAnimator != null && mFlipperAnimator.isAnimating()) {
outView.animate().cancel();
inView.animate().cancel();
}
outView.setVisibility(View.GONE);
inView.setVisibility(View.VISIBLE);
}
}
}
|
Switch project view when user picks a different project. | Application.Directives.directive("sidebarProjects", sidebarProjectsDirective);
function sidebarProjectsDirective() {
return {
restrict: "AE",
replace: true,
templateUrl: "index/sidebar-projects.html",
controller: "sidebarProjectsDirectiveController"
};
}
Application.Controllers.controller("sidebarProjectsDirectiveController",
["$scope", "current", "sidebarUtil",
"mcapi", "model.projects", "$state",
sidebarProjectsDirectiveController]);
function sidebarProjectsDirectiveController($scope, current, sidebarUtil, mcapi, Projects, $state) {
$scope.showProjects = false;
$scope.setProject = function(project) {
$scope.project = project;
current.setProject(project);
$scope.showProjects = false;
$scope.project.fileCount = sidebarUtil.projectFileCount($scope.project);
$scope.project.projectSize = sidebarUtil.projectSize($scope.project);
$state.go("projects.project.home", {id: project.id});
};
$scope.createProject = function(){
if ($scope.model.name === "") {
return;
}
mcapi('/projects')
.success(function (data) {
Projects.getList(true).then(function(projects) {
$scope.projects = projects;
});
}).post({'name': $scope.model.name});
};
}
| Application.Directives.directive("sidebarProjects", sidebarProjectsDirective);
function sidebarProjectsDirective() {
return {
restrict: "AE",
replace: true,
templateUrl: "index/sidebar-projects.html",
controller: "sidebarProjectsDirectiveController"
};
}
Application.Controllers.controller("sidebarProjectsDirectiveController",
["$scope", "current", "sidebarUtil",
"mcapi", "model.projects",
sidebarProjectsDirectiveController]);
function sidebarProjectsDirectiveController($scope, current, sidebarUtil, mcapi, Projects) {
$scope.showProjects = false;
$scope.setProject = function(project) {
$scope.project = project;
current.setProject(project);
$scope.showProjects = false;
$scope.project.fileCount = sidebarUtil.projectFileCount($scope.project);
$scope.project.projectSize = sidebarUtil.projectSize($scope.project);
};
$scope.createProject = function(){
if ($scope.model.name === "") {
return;
}
mcapi('/projects')
.success(function (data) {
console.dir(data);
Projects.getList(true).then(function(projects) {
$scope.projects = projects;
});
}).post({'name': $scope.model.name});
};
}
|
Revert 'Change required library with minified one' | let should = require('should');
let expect = require('chai').expect;
let jsdom = require('jsdom');
let {JSDOM} = jsdom;
let Shell;
describe('Shell', () => {
let {document} = (new JSDOM('<!doctype html><html><body></body></html>')).window;
global.document = document;
global.window = document.defaultView;
before(() => {
Shell = require('../lib/shell');
});
it('should initialize without error', () => {
(() => expect(new Shell()).to.be.an.instanceof(Shell) ).should.not.throw();
});
describe('Element', () => {
context('when not present', () => {
it('should be empty', () => {
expect(new Shell()).to.have.property('el', null);
});
});
context('when present', () => {
let div;
let shell;
before(() => {
div = document.createElement('div');
div.setAttribute('id', 'shell');
document.body.appendChild(div);
shell = new Shell('#shell');
});
it('should be the DOM object of the element', () => {
expect(shell.el[0]).to.not.be.undefined;
expect(shell.el[0]).to.equal(div);
});
});
});
}); | let should = require('should');
let expect = require('chai').expect;
let jsdom = require('jsdom');
let {JSDOM} = jsdom;
let Shell;
describe('Shell', () => {
let {document} = (new JSDOM('<!doctype html><html><body></body></html>')).window;
global.document = document;
global.window = document.defaultView;
before(() => {
Shell = require('../lib/shell.min');
});
it('should initialize without error', () => {
(() => expect(new Shell()).to.be.an.instanceof(Shell) ).should.not.throw();
});
describe('Element', () => {
context('when not present', () => {
it('should be empty', () => {
expect(new Shell()).to.have.property('el', null);
});
});
context('when present', () => {
let div;
let shell;
before(() => {
div = document.createElement('div');
div.setAttribute('id', 'shell');
document.body.appendChild(div);
shell = new Shell('#shell');
});
it('should be the DOM object of the element', () => {
expect(shell.el[0]).to.not.be.undefined;
expect(shell.el[0]).to.equal(div);
});
});
});
}); |
Fix for defaultcontroller when creating new item | <div class="group-defaultcontroller edit">
<?php
echo form_open();
$aFieldSets = [];
foreach ($CONFIG['FIELDS'] as $oField) {
if (in_array($oField->key, $CONFIG['EDIT_IGNORE_FIELDS'])) {
continue;
}
$sFieldSet = getFromArray('fieldset', (array) $oField, 'Basic Details');
if (!array_key_exists($sFieldSet, $aFieldSets)) {
$aFieldSets[$sFieldSet] = [];
}
$aFieldSets[$sFieldSet][] = $oField;
}
foreach ($aFieldSets as $sLegend => $aFields) {
?>
<fieldset>
<legend><?=$sLegend?></legend>
<?php
foreach ($aFields as $oField) {
$aField = (array) $oField;
$aField['default'] = !empty($item) && property_exists($item, $oField->key) ? $item->{$oField->key} : '';
if (!array_key_exists('required', $aFieldSets)) {
$aField['required'] = in_array('required', $oField->validation);
}
if (is_callable('form_field_' . $aField['type'])) {
echo call_user_func('form_field_' . $aField['type'], $aField);
} else {
echo form_field($aField);
}
}
?>
</fieldset>
<?php
}
?>
<p>
<button type="submit" class="btn btn-primary">
Save Changes
</button>
</p>
<?=form_close()?>
</div>
| <div class="group-defaultcontroller edit">
<?php
echo form_open();
$aFieldSets = [];
foreach ($CONFIG['FIELDS'] as $oField) {
if (in_array($oField->key, $CONFIG['EDIT_IGNORE_FIELDS'])) {
continue;
}
$sFieldSet = getFromArray('fieldset', (array) $oField, 'Basic Details');
if (!array_key_exists($sFieldSet, $aFieldSets)) {
$aFieldSets[$sFieldSet] = [];
}
$aFieldSets[$sFieldSet][] = $oField;
}
foreach ($aFieldSets as $sLegend => $aFields) {
?>
<fieldset>
<legend><?=$sLegend?></legend>
<?php
foreach ($aFields as $oField) {
$aField = (array) $oField;
$aField['default'] = property_exists($item, $oField->key) ? $item->{$oField->key} : null;
if (!array_key_exists('required', $aFieldSets)) {
$aField['required'] = in_array('required', $oField->validation);
}
if (is_callable('form_field_' . $aField['type'])) {
echo call_user_func('form_field_' . $aField['type'], $aField);
} else {
echo form_field($aField);
}
}
?>
</fieldset>
<?php
}
?>
<p>
<button type="submit" class="btn btn-primary">
Save Changes
</button>
</p>
<?=form_close()?>
</div>
|
Mark it Windows only before Linux implement ready. | package io.github.hcoona.utils;
import com.sun.jna.Platform;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class NamedMutexTest {
@BeforeClass
public static void beforeClass() throws Exception {
Assume.assumeTrue(Platform.isWindows());
}
@Test
public void testCannotWaitOne() throws Exception {
final String name = "test_named-mutex_cannot-wait-one";
try (NamedMutex ignored = NamedMutex.newInstance(true, name)) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Boolean> waitOneFuture = executor.submit(() -> {
try (NamedMutex mutex2 = NamedMutex.newInstance(true, name)) {
return mutex2.waitOne(500, TimeUnit.MILLISECONDS);
}
});
Assert.assertFalse(waitOneFuture.get());
}
}
@Test
public void testCanWaitOne() throws Exception {
final String name = "test_named-mutex_can-wait-one";
try (NamedMutex mutex_owned = NamedMutex.newInstance(true, name)) {
mutex_owned.release();
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Boolean> waitOneFuture = executor.submit(() -> {
try (NamedMutex mutex2 = NamedMutex.newInstance(true, name)) {
return mutex2.waitOne(5, TimeUnit.SECONDS);
}
});
Assert.assertTrue(waitOneFuture.get());
}
}
}
| package io.github.hcoona.utils;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class NamedMutexTest {
@Test
public void testCannotWaitOne() throws Exception {
final String name = "test_named-mutex_cannot-wait-one";
try (NamedMutex ignored = NamedMutex.newInstance(true, name)) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Boolean> waitOneFuture = executor.submit(() -> {
try (NamedMutex mutex2 = NamedMutex.newInstance(true, name)) {
return mutex2.waitOne(500, TimeUnit.MILLISECONDS);
}
});
Assert.assertFalse(waitOneFuture.get());
}
}
@Test
public void testCanWaitOne() throws Exception {
final String name = "test_named-mutex_can-wait-one";
try (NamedMutex mutex_owned = NamedMutex.newInstance(true, name)) {
mutex_owned.release();
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Boolean> waitOneFuture = executor.submit(() -> {
try (NamedMutex mutex2 = NamedMutex.newInstance(true, name)) {
return mutex2.waitOne(5, TimeUnit.SECONDS);
}
});
Assert.assertTrue(waitOneFuture.get());
}
}
}
|
Change Elements from Import And Export | package fr.synchrotron.soleil.ica.ci.lib.mongodb.domainobjects.project;
import fr.synchrotron.soleil.ica.ci.lib.mongodb.domainobjects.artifact.DeveloperDocument;
import java.util.List;
/**
* @author Gregory Boissinot
*/
public class ProjectDocument {
private String org;
private String name;
private List<DeveloperDocument> developers;
private String description;
private String scmConnection;
private String language;
public String getOrg() {
return org;
}
public void setOrg(String org) {
this.org = org;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DeveloperDocument> getDevelopers() {
return developers;
}
public void setDevelopers(List<DeveloperDocument> developers) {
this.developers = developers;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getScmConnection() {
return scmConnection;
}
public void setScmConnection(String scmConnection) {
this.scmConnection = scmConnection;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
}
| package fr.synchrotron.soleil.ica.ci.lib.mongodb.domainobjects.project;
import fr.synchrotron.soleil.ica.ci.lib.mongodb.domainobjects.artifact.DeveloperDocument;
import java.util.List;
/**
* @author Gregory Boissinot
*/
public class ProjectDocument {
private String org;
private String name;
private List<DeveloperDocument> developers;
private String description;
private String scmConnection;
private String language;
public String getOrg() {
return org;
}
public void setOrg(String org) {
this.org = org;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DeveloperDocument> getDevelopers() {
return developers;
}
public void setDevelopers(List<DeveloperDocument> developers) {
this.developers = developers;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getScmConnection() {
return scmConnection;
}
public void setScmConnection(String scmConnection) {
this.scmConnection = scmConnection;
}
public MavenProjectInfo getMaven() {
return maven;
}
public void setMaven(MavenProjectInfo maven) {
this.maven = maven;
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.