text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Hide certain values from initial view to logged in user | 'use strict';
var errorHandler = require('./errors.server.controller');
/**
* Render the main application page
*/
exports.renderIndex = function(req, res) {
var currentUser = null;
// Expose user
if(req.user) {
currentUser = req.user;
// Don't just expose everything to the view...
delete currentUser.resetPasswordToken;
delete currentUser.resetPasswordExpires;
delete currentUser.emailToken;
delete currentUser.password;
delete currentUser.salt;
}
res.render('modules/core/server/views/index', {
user: currentUser
});
};
/**
* Render the server not found responses
* Performs content-negotiation on the Accept HTTP header
*/
exports.renderNotFound = function(req, res) {
res.status(404).format({
'text/html': function() {
res.render('modules/core/server/views/404');
},
'application/json': function() {
res.json({ message: errorHandler.getErrorMessageByKey('not-found') });
},
'default': function() {
res.send( errorHandler.getErrorMessageByKey('not-found') );
}
});
};
| 'use strict';
var errorHandler = require('./errors.server.controller');
/**
* Render the main application page
*/
exports.renderIndex = function(req, res) {
var currentUser = null;
// Expose user
if(req.user) {
currentUser = req.user;
// Don't just expose everything to the view...
delete currentUser.emailToken;
}
res.render('modules/core/server/views/index', {
user: currentUser
});
};
/**
* Render the server not found responses
* Performs content-negotiation on the Accept HTTP header
*/
exports.renderNotFound = function(req, res) {
res.status(404).format({
'text/html': function() {
res.render('modules/core/server/views/404');
},
'application/json': function() {
res.json({ message: errorHandler.getErrorMessageByKey('not-found') });
},
'default': function() {
res.send( errorHandler.getErrorMessageByKey('not-found') );
}
});
};
|
Fix up a parse error
The non-generic ParseQueryAdapter class fails when results are read due
to a cast error:
java.lang.ClassCastException: com.parse.ParseObject cannot be cast to org.ashanet.typedef.Event
at org.ashanet.adapter.EventListAdapter.getItemView(EventListAdapter.java:20)
at com.parse.ParseQueryAdapter.getView(ParseQueryAdapter.java:546)
at android.widget.AbsListView.obtainView(AbsListView.java:2033)
at android.widget.ListView.makeAndAddView(ListView.java:1772)
at android.widget.ListView.fillDown(ListView.java:672)
at android.widget.ListView.fillFromTop(ListView.java:732)
...
This is because the type parameter was not registered. Register it in
the Application class. | package org.ashanet;
import android.app.Application;
import android.content.res.Resources;
import android.util.Log;
import com.parse.Parse;
import com.parse.ParseObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import org.ashanet.typedef.Event;
import org.ashanet.typedef.Project;
public class AshaNetApp extends Application {
public String parseAppId;
@Override
public void onCreate() {
super.onCreate();
LineNumberReader lnr = new LineNumberReader
(new InputStreamReader
(getResources().openRawResource(R.raw.keys)));
registerClasses();
String parseClientKey;
try {
parseAppId = lnr.readLine();
parseClientKey = lnr.readLine();
Parse.initialize(this, parseAppId, parseClientKey);
Log.d("DEBUG", "Successfully initialized");
}
catch (IOException ioe) {
Log.e("DEBUG", "Failed to read keys", ioe);
}
}
private void registerClasses() {
ParseObject.registerSubclass(Project.class);
ParseObject.registerSubclass(Event.class);
}
}
| package org.ashanet;
import android.app.Application;
import android.content.res.Resources;
import android.util.Log;
import com.parse.Parse;
import com.parse.ParseObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import org.ashanet.typedef.Project;
public class AshaNetApp extends Application {
public String parseAppId;
@Override
public void onCreate() {
super.onCreate();
LineNumberReader lnr = new LineNumberReader
(new InputStreamReader
(getResources().openRawResource(R.raw.keys)));
registerClasses();
String parseClientKey;
try {
parseAppId = lnr.readLine();
parseClientKey = lnr.readLine();
Parse.initialize(this, parseAppId, parseClientKey);
Log.d("DEBUG", "Successfully initialized");
}
catch (IOException ioe) {
Log.e("DEBUG", "Failed to read keys", ioe);
}
}
private void registerClasses() {
ParseObject.registerSubclass(Project.class);
}
}
|
Add site footer to each documentation generator | var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-typography/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-typography/tachyons-typography.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_typography.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8')
var template = fs.readFileSync('./templates/docs/measure/times/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs,
siteFooter: siteFooter
})
fs.writeFileSync('./docs/typography/measure/times/index.html', html)
| var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-typography/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-typography/tachyons-typography.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_typography.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/measure/times/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/typography/measure/times/index.html', html)
|
Remove redundant method call to get() | <?php
namespace MyBB\Core\Database\Repositories\Eloquent;
use Illuminate\Support\Collection;
use MyBB\Core\Database\Models\ProfileFieldGroup;
use MyBB\Core\Database\Repositories\ProfileFieldGroupRepositoryInterface;
class ProfileFieldGroupRepository implements ProfileFieldGroupRepositoryInterface
{
/**
* @var ProfileFieldGroup
*/
protected $profileFieldGroup;
/**
* @param ProfileFieldGroup $profileFieldGroup
*/
public function __construct(ProfileFieldGroup $profileFieldGroup)
{
$this->profileFieldGroup = $profileFieldGroup;
}
/**
* @param string $slug
* @return ProfileFieldGroup
*/
public function getBySlug($slug)
{
return $this->profileFieldGroup->where('slug', $slug)->first();
}
/**
* @return Collection
*/
public function getAll()
{
return $this->profileFieldGroup->all();
}
}
| <?php
namespace MyBB\Core\Database\Repositories\Eloquent;
use Illuminate\Support\Collection;
use MyBB\Core\Database\Models\ProfileFieldGroup;
use MyBB\Core\Database\Repositories\ProfileFieldGroupRepositoryInterface;
class ProfileFieldGroupRepository implements ProfileFieldGroupRepositoryInterface
{
/**
* @var ProfileFieldGroup
*/
protected $profileFieldGroup;
/**
* @param ProfileFieldGroup $profileFieldGroup
*/
public function __construct(ProfileFieldGroup $profileFieldGroup)
{
$this->profileFieldGroup = $profileFieldGroup;
}
/**
* @param string $slug
* @return ProfileFieldGroup
*/
public function getBySlug($slug)
{
return $this->profileFieldGroup->where('slug', $slug)->get()->first();
}
/**
* @return Collection
*/
public function getAll()
{
return $this->profileFieldGroup->all();
}
}
|
Add r,g,b-from-int color extractor methods | package com.haxademic.core.draw.color;
import processing.core.PApplet;
import com.haxademic.core.app.P;
public class ColorUtil {
public static int colorWithIntAndAlpha( PApplet p, int color, int alpha ) {
// from: http://processing.org/discourse/beta/num_1261125421.html
return (color & 0xffffff) | (alpha << 24);
}
public static int colorFromHex( String hex ) {
return P.unhex("FF"+hex.substring(1));
}
public final static int alphaFromColorInt( int c ) { return (c >> 24) & 0xFF; }
public final static int redFromColorInt( int c ) { return (c >> 16) & 0xFF; }
public final static int greenFromColorInt( int c ) { return (c >> 8) & 0xFF; }
public final static int blueFromColorInt( int c ) { return c & 0xFF; }
}
| package com.haxademic.core.draw.color;
import processing.core.PApplet;
import com.haxademic.core.app.P;
public class ColorUtil {
public static int colorWithIntAndAlpha( PApplet p, int color, int alpha ) {
// float a = (color >> 24) & 0xFF;
// float r = color >> 16 & 0xFF; // Faster way of getting red(argb)
// float g = color >> 8 & 0xFF; // Faster way of getting green(argb)
// float b = color & 0xFF; // Faster way of getting blue(argb)
// float r = color >> 16 & 0xFF; // Faster way of getting red(argb)
// float g = color >> 8 & 0xFF; // Faster way of getting green(argb)
// float b = color & 0xFF; // Faster way of getting blue(argb)
// float r = p.red(color);
// float g = p.green(color);
// float b = p.blue(color);
// return p.color(r, g, b, alpha);
// from: http://processing.org/discourse/beta/num_1261125421.html
return (color & 0xffffff) | (alpha << 24);
}
public static int colorFromHex( String hex ) {
return P.unhex("FF"+hex.substring(1));
}
}
|
Revert deletion of clean_orientation function
The clean_orientation function is needed for the active configuration
plot. I am yet to change that to using the plot function. | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 Malcolm Ramsay <malramsay64@gmail.com>
#
# Distributed under terms of the MIT license.
"""Create functions to colourize figures."""
import logging
import numpy as np
from hsluv import hpluv_to_hex
from ..analysis.order import get_z_orientation
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
HEX_VALUES_DARK = np.array([hpluv_to_hex((value, 85, 65)) for value in range(360)])
HEX_VALUES_LIGHT = np.array([hpluv_to_hex((value, 85, 85)) for value in range(360)])
def clean_orientation(snapshot):
"""Convert an orientation to a sensible format."""
orientations = get_z_orientation(snapshot.particles.orientation)
nmol = max(snapshot.particles.body)+1
o_dict = {body: orient for body, orient in zip(
snapshot.particles.body[:nmol],
orientations
)}
orientation = np.array([o_dict[body] for body in snapshot.particles.body])
return orientation
def colour_orientation(orientations, light_colours=False):
"""Get a colour from an orientation."""
orientations = orientations % 2 * np.pi
if light_colours:
return HEX_VALUES_LIGHT[np.floor(orientations / np.pi * 180).astype(int)]
return HEX_VALUES_DARK[np.floor(orientations / np.pi * 180).astype(int)]
| #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 Malcolm Ramsay <malramsay64@gmail.com>
#
# Distributed under terms of the MIT license.
"""Create functions to colourize figures."""
import logging
import numpy as np
from hsluv import hpluv_to_hex
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
HEX_VALUES_DARK = np.array([hpluv_to_hex((value, 85, 65)) for value in range(360)])
HEX_VALUES_LIGHT = np.array([hpluv_to_hex((value, 85, 85)) for value in range(360)])
def colour_orientation(orientations, light_colours=False):
"""Get a colour from an orientation."""
orientations = orientations % 2 * np.pi
if light_colours:
return HEX_VALUES_LIGHT[np.floor(orientations / np.pi * 180).astype(int)]
return HEX_VALUES_DARK[np.floor(orientations / np.pi * 180).astype(int)]
|
feat(client): Hide breadcrumbs bar on front page | import React, {Component, PropTypes} from 'react'
import BreadcrumbBar from '../components/breadcrumb-bar'
import Footer from './footer'
import Navigation from '../containers/navigation'
export default class Application extends Component {
static propTypes = {
// actions
navigateToLogin: PropTypes.func.isRequired,
// props
userIsLoggedIn: PropTypes.bool.isRequired
}
componentWillMount () {
const {navigateToLogin, userIsLoggedIn} = this.props
if (process.env.NODE_ENV !== 'test' && !userIsLoggedIn) {
navigateToLogin()
}
}
render () {
const {children, userIsLoggedIn} = this.props
const path = process.env.NODE_ENV === 'test' ? window.fakePath : window.location.pathname
return userIsLoggedIn
? (
<div>
<Navigation />
{path !== '/' && <BreadcrumbBar {...this.props} />}
{children}
<Footer />
</div>
)
: <div />
}
}
| import React, {Component, PropTypes} from 'react'
import BreadcrumbBar from '../components/breadcrumb-bar'
import Footer from './footer'
import Navigation from '../containers/navigation'
export default class Application extends Component {
static propTypes = {
// actions
navigateToLogin: PropTypes.func.isRequired,
// props
userIsLoggedIn: PropTypes.bool.isRequired
}
componentWillMount () {
const {navigateToLogin, userIsLoggedIn} = this.props
if (process.env.NODE_ENV !== 'test' && !userIsLoggedIn) {
navigateToLogin()
}
}
render () {
const {children, userIsLoggedIn} = this.props
return userIsLoggedIn
? (
<div>
<Navigation />
<BreadcrumbBar
{...this.props}
/>
{children}
<Footer />
</div>
)
: <div />
}
}
|
Add persistent flag to reset. | <?php
/**
* Site Kit Cache CLI Commands
*
* @package Google\Site_Kit\Core\CLI
* @copyright 2021 Google LLC
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
* @link https://sitekit.withgoogle.com
*/
namespace Google\Site_Kit\Core\CLI;
use Google\Site_Kit\Core\Util\Reset;
use Google\Site_Kit\Core\Util\Reset_Persistent;
use WP_CLI;
/**
* Resets Site Kit Settings and Data.
*
* @since 1.11.0
* @access private
* @ignore
*/
class Reset_CLI_Command extends CLI_Command {
/**
* Deletes options, user stored options, transients and clears object cache for stored options.
*
* ## OPTIONS
*
* [--persistent]
* : Remove persistent site kit options too.
*
* ## EXAMPLES
*
* wp google-site-kit reset
* wp google-site-kit reset --persistent
*
* @since 1.11.0
*
* @param Array $args Args.
* @param Array $assoc_args Additional flags.
*/
public function __invoke( $args, $assoc_args ) {
$reset = new Reset( $this->context );
$reset->all();
if ( isset( $assoc_args['persistent'] ) && true === $assoc_args['persistent'] ) {
$reset_persistent = new Reset_Persistent( $this->context );
$reset_persistent->all();
}
WP_CLI::success( 'Settings successfully reset.' );
}
}
| <?php
/**
* Site Kit Cache CLI Commands
*
* @package Google\Site_Kit\Core\CLI
* @copyright 2021 Google LLC
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
* @link https://sitekit.withgoogle.com
*/
namespace Google\Site_Kit\Core\CLI;
use Google\Site_Kit\Core\Util\Reset;
use WP_CLI;
/**
* Resets Site Kit Settings and Data.
*
* @since 1.11.0
* @access private
* @ignore
*/
class Reset_CLI_Command extends CLI_Command {
/**
* Deletes options, user stored options, transients and clears object cache for stored options.
*
* ## OPTIONS
*
* ## EXAMPLES
*
* wp google-site-kit reset
*
* @since 1.11.0
*/
public function __invoke() {
$reset = new Reset( $this->context );
$reset->all();
WP_CLI::success( 'Settings successfully reset.' );
}
}
|
Fix bug when less artists than one page | /* global app:true */
'use strict';
app.controller('MusicCtrl', ['$scope', 'Music', 'PER_PAGE', function($scope, Music, PER_PAGE) {
var artistNum = 0;
var finished = false;
var size = PER_PAGE;
$scope.waiting = false;
$scope.artists = [];
$scope.nextPage = function() {
if (finished) {
return ;
}
$scope.waiting = true;
Music.artists(artistNum, size).then(function(data) {
for (var i = 0; i < data.artists.length; i++) {
$scope.artists.push(data.artists[i]);
}
artistNum += size;
if (artistNum + size > data.limits.total) {
size = data.limits.total - artistNum;
if (size <= 0) {
finished = true;
}
}
$scope.waiting = false;
});
};
}]);
| /* global app:true */
'use strict';
app.controller('MusicCtrl', ['$scope', 'Music', 'PER_PAGE', function($scope, Music, PER_PAGE) {
var artistNum = 0;
var finished = false;
var size = PER_PAGE;
$scope.waiting = false;
$scope.artists = [];
$scope.nextPage = function() {
if (finished) {
return ;
}
$scope.waiting = true;
Music.artists(artistNum, size).then(function(data) {
for (var i = 0; i < data.artists.length; i++) {
$scope.artists.push(data.artists[i]);
}
artistNum += size;
if (artistNum + size > data.limits.total) {
size = data.limits.total - artistNum;
if (size === 0) {
finished = true;
}
}
$scope.waiting = false;
});
};
}]);
|
Fix publishing our config file. | <?php
namespace Prolougetech\Big;
use Illuminate\Support\ServiceProvider;
class BigServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
$configPath = __DIR__ . '/../config/prologue-big.php';
$this->publishes([
$configPath => config_path('prologue-big.php'),
], 'config');
}
/**
* Register bindings for our big wrapper in our container
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(__DIR__ . '/../config/prologue-big.php', 'prologue-big');
$this->app->singleton(Big::class, function ($app) {
return new Big();
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [Big::class];
}
}
| <?php
namespace Prolougetech\Big;
use Illuminate\Support\ServiceProvider;
class BigServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
$this->mergeConfigFrom(__DIR__ . '/../config/prologue-big.php', 'services');
}
/**
* Register bindings for our big wrapper in our container
*
* @return void
*/
public function register()
{
$this->app->singleton(Big::class, function ($app) {
return new Big();
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [Big::class];
}
}
|
Set server IP Address to '0.0.0.0' to work on Heroku. | const express = require('express');
const path = require('path');
const chalk = require('chalk');
const initServer = require('./initServer');
const app = express();
const DOCS_PATH = '../../docs/';
const PORT = process.env.PORT || 8082;
const IP_ADDRESS = '0.0.0.0';
app.set('port', PORT);
app.set('ipAddress', IP_ADDRESS);
app.use(express.static(path.join(__dirname, DOCS_PATH)));
initServer(app);
app.get('/', (req, res) => res.sendFile(path.join(__dirname, DOCS_PATH, 'index.html')));
/* eslint-disable no-console */
app.listen(PORT, IP_ADDRESS, () =>
console.log(`
=====================================================
-> Server (${chalk.bgBlue('SPA')}) 🏃 (running) on ${chalk.green(IP_ADDRESS)}:${chalk.green(
PORT,
)}
=====================================================
`),
);
/* eslint-enable no-console */
| const express = require('express');
const path = require('path');
const chalk = require('chalk');
const initServer = require('./initServer');
const app = express();
const DOCS_PATH = '../../docs/';
const PORT = process.env.PORT || 8082;
const IP_ADRESS = 'localhost';
app.set('port', PORT);
app.set('ipAdress', IP_ADRESS);
app.use(express.static(path.join(__dirname, DOCS_PATH)));
initServer(app);
app.get('/', (req, res) => res.sendFile(path.join(__dirname, DOCS_PATH, 'index.html')));
/* eslint-disable no-console */
app.listen(
PORT,
IP_ADRESS,
() => console.log(`
=====================================================
-> Server (${chalk.bgBlue('SPA')}) 🏃 (running) on ${chalk.green(IP_ADRESS)}:${chalk.green(PORT)}
=====================================================
`),
);
/* eslint-enable no-console */
|
Make sure @ notify is the first decorator
fixes #91 | """Example of integration between Fabric and Datadog.
"""
from fabric.api import *
from fabric.colors import *
from dogapi.fab import setup, notify
setup(api_key = "YOUR API KEY HERE")
# Make sure @notify is just below @task
@notify
@task(default=True, alias="success")
def sweet_task(some_arg, other_arg):
"""Always succeeds"""
print(green("My sweet task always runs properly."))
@notify
@task(alias="failure")
def boring_task(some_arg):
"""Always fails"""
print(red("My boring task is designed to fail."))
raise Exception("failure!!!")
env.roledefs.update({
'webserver': ['localhost']
})
@notify
@task(alias="has_roles")
@roles('webserver')
@hosts('localhost')
def roles_task(arg_1, arg_2):
run('touch /tmp/fab_test')
| """Example of integration between Fabric and Datadog.
"""
from fabric.api import *
from fabric.colors import *
from dogapi.fab import setup, notify
setup(api_key = "YOUR API KEY HERE")
# Make sure @notify is just below @task
@task(default=True, alias="success")
@notify
def sweet_task(some_arg, other_arg):
"""Always succeeds"""
print(green("My sweet task always runs properly."))
@task(alias="failure")
@notify
def boring_task(some_arg):
"""Always fails"""
print(red("My boring task is designed to fail."))
raise Exception("failure!!!")
env.roledefs.update({
'webserver': ['localhost']
})
@task(alias="has_roles")
@notify
@roles('webserver')
@hosts('localhost')
def roles_task(arg_1, arg_2):
run('touch /tmp/fab_test')
|
Make shared secret translatable again
Signed-off-by: Julius Härtl <bf353fa4999f2f148afcc6d8ee6cb1ee74cc07c3@bitgrid.net> | <?php
/** @var array $_ */
/** @var \OCP\IL10N $l */
script('spreed', ['admin/signaling-server']);
style('spreed', ['settings-admin']);
?>
<div class="videocalls section signaling-server">
<h3><?php p($l->t('Signaling server')) ?></h3>
<p class="settings-hint"><?php p($l->t('An external signaling server can optionally be used for larger installations. Leave empty to use the internal signaling server.')) ?></p>
<div class="signaling-servers" data-servers="<?php p($_['signalingServers']) ?>">
</div>
<div class="signaling-secret">
<h4><?php p($l->t('Shared secret')) ?></h4>
<input type="text" id="signaling_secret"
name="signaling_secret" placeholder="<?php p($l->t('Shared secret')) ?>" aria-label="<?php p($l->t('Shared secret')) ?>"/>
</div>
</div>
| <?php
/** @var array $_ */
/** @var \OCP\IL10N $l */
script('spreed', ['admin/signaling-server']);
style('spreed', ['settings-admin']);
?>
<div class="videocalls section signaling-server">
<h3><?php p($l->t('Signaling server')) ?></h3>
<p class="settings-hint"><?php p($l->t('An external signaling server can optionally be used for larger installations. Leave empty to use the internal signaling server.')) ?></p>
<div class="signaling-servers" data-servers="<?php p($_['signalingServers']) ?>">
</div>
<div class="signaling-secret">
<h4>Shared secret</h4>
<input type="text" id="signaling_secret"
name="signaling_secret" placeholder="<?php p($l->t('Shared secret')) ?>" aria-label="<?php p($l->t('Shared secret')) ?>"/>
</div>
</div>
|
Make indexing on real time | import datetime
from haystack.indexes import SearchIndex, RealTimeSearchIndex
from haystack.indexes import CharField, DateTimeField
from haystack import site
from models import Author, Material
class AuthorIndex(RealTimeSearchIndex):
# the used template contains fullname and author bio
# Zniper thinks this line below also is OK:
# text = CharField(document=True, model_attr='text')
fullname = CharField(model_attr='fullname')
text = CharField(document=True, use_template=True)
def index_queryset(self):
"""Used when entire index for model is updated"""
return Author.objects.all()
class MaterialIndex(RealTimeSearchIndex):
# "text" combines normal body, title, description and keywords
text = CharField(document=True, use_template=True)
material_id = CharField(model_attr='material_id')
title = CharField(model_attr='title')
description = CharField(model_attr='description')
modified = DateTimeField(model_attr='modified')
material_type = DateTimeField(model_attr='modified')
def index_queryset(self):
"""When entired index for model is updated"""
return Material.objects.all()
site.register(Author, AuthorIndex)
site.register(Material, MaterialIndex)
| import datetime
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
from models import Author, Material
class AuthorIndex(SearchIndex):
# the used template contains fullname and author bio
# Zniper thinks this line below also is OK:
# text = CharField(document=True, model_attr='text')
fullname = CharField(model_attr='fullname')
text = CharField(document=True, use_template=True)
def index_queryset(self):
"""Used when entire index for model is updated"""
return Author.objects.all()
class MaterialIndex(SearchIndex):
# "text" combines normal body, title, description and keywords
text = CharField(document=True, use_template=True)
material_id = CharField(model_attr='material_id')
title = CharField(model_attr='title')
description = CharField(model_attr='description')
modified = DateTimeField(model_attr='modified')
material_type = DateTimeField(model_attr='modified')
def index_queryset(self):
"""When entired index for model is updated"""
return Material.objects.all()
site.register(Author, AuthorIndex)
site.register(Material, MaterialIndex)
|
Add homepage to plugin details | <?php namespace Responsiv\Uploader;
use System\Classes\PluginBase;
/**
* Uploader Plugin Information File
*/
class Plugin extends PluginBase
{
/**
* Returns information about this plugin.
*
* @return array
*/
public function pluginDetails()
{
return [
'name' => 'Uploader',
'description' => 'Tools for uploading files and photos',
'author' => 'Responsiv Internet',
'icon' => 'icon-leaf',
'homepage' => 'https://github.com/responsiv/uploader-plugin'
];
}
public function registerComponents()
{
return [
'Responsiv\Uploader\Components\FileUploader' => 'fileUploader',
'Responsiv\Uploader\Components\ImageUploader' => 'imageUploader',
];
}
}
| <?php namespace Responsiv\Uploader;
use System\Classes\PluginBase;
/**
* Uploader Plugin Information File
*/
class Plugin extends PluginBase
{
/**
* Returns information about this plugin.
*
* @return array
*/
public function pluginDetails()
{
return [
'name' => 'Uploader',
'description' => 'Tools for uploading files and photos',
'author' => 'Responsiv Internet',
'icon' => 'icon-leaf'
];
}
public function registerComponents()
{
return [
'Responsiv\Uploader\Components\FileUploader' => 'fileUploader',
'Responsiv\Uploader\Components\ImageUploader' => 'imageUploader',
];
}
}
|
Fix missing renaming of logout => logoutLink
During development, this was previously named `logout`. This cleans up a
remaining instance of `logout`, renaming it to the preferred
`logoutLink` to remain consistent with the rest of the codebase. | import axios from 'axios'
let links
export default async function AJAX({
url,
resource,
id,
method = 'GET',
data = {},
params = {},
headers = {},
}) {
try {
const basepath = window.basepath || ''
let response
url = `${basepath}${url}`
if (!links) {
const linksRes = (response = await axios({
url: `${basepath}/chronograf/v1`,
method: 'GET',
}))
links = linksRes.data
}
if (resource) {
url = id
? `${basepath}${links[resource]}/${id}`
: `${basepath}${links[resource]}`
}
response = await axios({
url,
method,
data,
params,
headers,
})
const {auth} = links
return {
...response,
auth: {links: auth},
logoutLink: links.logout,
}
} catch (error) {
const {response} = error
const {auth} = links
throw {...response, auth: {links: auth}, logout: links.logout} // eslint-disable-line no-throw-literal
}
}
| import axios from 'axios'
let links
export default async function AJAX({
url,
resource,
id,
method = 'GET',
data = {},
params = {},
headers = {},
}) {
try {
const basepath = window.basepath || ''
let response
url = `${basepath}${url}`
if (!links) {
const linksRes = (response = await axios({
url: `${basepath}/chronograf/v1`,
method: 'GET',
}))
links = linksRes.data
}
if (resource) {
url = id
? `${basepath}${links[resource]}/${id}`
: `${basepath}${links[resource]}`
}
response = await axios({
url,
method,
data,
params,
headers,
})
const {auth} = links
return {
...response,
auth: {links: auth},
logout: links.logout,
}
} catch (error) {
const {response} = error
const {auth} = links
throw {...response, auth: {links: auth}, logout: links.logout} // eslint-disable-line no-throw-literal
}
}
|
Add missing dependency for form.Field class | <?php
class Kwc_Basic_Link_Trl_Component extends Kwc_Abstract_Composite_Trl_Component
{
public static function getSettings($mainComponentClass)
{
$ret = parent::getSettings($mainComponentClass);
$ret['ownModel'] = Kwc_Abstract::getSetting($mainComponentClass, 'ownModel');
$ret['assets']['dep'][] = 'ExtFormFields';
$ret['assets']['files'][] = 'kwf/Kwc/Basic/Link/Trl/CopyButton.js';
$ret['throwHasContentChangedOnRowColumnsUpdate'] = 'text';
return $ret;
}
public function getTemplateVars()
{
$ret = parent::getTemplateVars();
$ret['text'] = $this->_getRow()->text;
return $ret;
}
public function hasContent()
{
if (!$this->_getRow()->text) return false;
return parent::hasContent();
}
}
| <?php
class Kwc_Basic_Link_Trl_Component extends Kwc_Abstract_Composite_Trl_Component
{
public static function getSettings($mainComponentClass)
{
$ret = parent::getSettings($mainComponentClass);
$ret['ownModel'] = Kwc_Abstract::getSetting($mainComponentClass, 'ownModel');
$ret['assets']['files'][] = 'kwf/Kwc/Basic/Link/Trl/CopyButton.js';
$ret['throwHasContentChangedOnRowColumnsUpdate'] = 'text';
return $ret;
}
public function getTemplateVars()
{
$ret = parent::getTemplateVars();
$ret['text'] = $this->_getRow()->text;
return $ret;
}
public function hasContent()
{
if (!$this->_getRow()->text) return false;
return parent::hasContent();
}
}
|
Add exception for wrong type of db | from sqlalchemy import create_engine
from sqlalchemy_utils import functions
from sqlalchemy.orm import sessionmaker
from .base import Base
class Connection:
def __init__(self, db, name, password, ip, port):
if db == "postgresql":
connection = "postgresql+psycopg2://" + name + ":" + password + "@" + ip + ":" + port
elif db == "mysql":
connection = "mysql://" + name + ":" + password + "@" + ip + ":" + port
else:
raise ValueError("db type only support \"mysql\" or \"postgresql\" argument.")
db_name = 'wikilink'
# Turn off echo
engine = create_engine(connection + "/" + db_name + '?charset=utf8', echo=False, encoding='utf-8')
if not functions.database_exists(engine.url):
functions.create_database(engine.url)
self.session = sessionmaker(bind=engine)()
# If table don't exist, Create.
if (not engine.dialect.has_table(engine, 'link') and not engine.dialect.has_table(engine, 'page')):
Base.metadata.create_all(engine) | from sqlalchemy import create_engine
from sqlalchemy_utils import functions
from sqlalchemy.orm import sessionmaker
from .base import Base
class Connection:
def __init__(self, db, name, password, ip, port):
if db == "postgresql":
connection = "postgresql+psycopg2://" + name + ":" + password + "@" + ip + ":" + port
elif db == "mysql":
connection = "mysql://" + name + ":" + password + "@" + ip + ":" + port
db_name = 'wikilink'
# Turn off echo
engine = create_engine(connection + "/" + db_name + '?charset=utf8', echo=False, encoding='utf-8')
if not functions.database_exists(engine.url):
functions.create_database(engine.url)
self.session = sessionmaker(bind=engine)()
# If table don't exist, Create.
if (not engine.dialect.has_table(engine, 'link') and not engine.dialect.has_table(engine, 'page')):
Base.metadata.create_all(engine) |
Fix transposed 'expected' and 'actual' arguments
Also: No need to pass address of pointer to json.Unmarshal | package atom_test
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"strings"
"testing"
"github.com/mmcdole/gofeed/atom"
"github.com/stretchr/testify/assert"
)
// Tests
func TestParser_Parse(t *testing.T) {
files, _ := filepath.Glob("../testdata/parser/atom/*.xml")
for _, f := range files {
base := filepath.Base(f)
name := strings.TrimSuffix(base, filepath.Ext(base))
fmt.Printf("Testing %s... ", name)
// Get actual source feed
ff := fmt.Sprintf("../testdata/parser/atom/%s.xml", name)
f, _ := ioutil.ReadFile(ff)
// Parse actual feed
fp := &atom.Parser{}
actual, _ := fp.Parse(bytes.NewReader(f))
// Get json encoded expected feed result
ef := fmt.Sprintf("../testdata/parser/atom/%s.json", name)
e, _ := ioutil.ReadFile(ef)
// Unmarshal expected feed
expected := &atom.Feed{}
json.Unmarshal(e, expected)
if assert.Equal(t, expected, actual, "Feed file %s.xml did not match expected output %s.json", name, name) {
fmt.Printf("OK\n")
} else {
fmt.Printf("Failed\n")
}
}
}
// TODO: Examples
| package atom_test
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"strings"
"testing"
"github.com/mmcdole/gofeed/atom"
"github.com/stretchr/testify/assert"
)
// Tests
func TestParser_Parse(t *testing.T) {
files, _ := filepath.Glob("../testdata/parser/atom/*.xml")
for _, f := range files {
base := filepath.Base(f)
name := strings.TrimSuffix(base, filepath.Ext(base))
fmt.Printf("Testing %s... ", name)
// Get actual source feed
ff := fmt.Sprintf("../testdata/parser/atom/%s.xml", name)
f, _ := ioutil.ReadFile(ff)
// Parse actual feed
fp := &atom.Parser{}
actual, _ := fp.Parse(bytes.NewReader(f))
// Get json encoded expected feed result
ef := fmt.Sprintf("../testdata/parser/atom/%s.json", name)
e, _ := ioutil.ReadFile(ef)
// Unmarshal expected feed
expected := &atom.Feed{}
json.Unmarshal(e, &expected)
if assert.Equal(t, actual, expected, "Feed file %s.xml did not match expected output %s.json", name, name) {
fmt.Printf("OK\n")
} else {
fmt.Printf("Failed\n")
}
}
}
// TODO: Examples
|
Add meta tests for odd values | var tap = require("../")
, test = tap.test
test("meta success", { skip: false }, function (t) {
// this also tests the ok/notOk functions
t.once("end", section2)
t.ok(true, "true is ok")
t.ok(function () {}, "function is ok")
t.ok({}, "object is ok")
t.ok(t, "t is ok")
t.ok(100, "number is ok")
t.ok("asdf", "string is ok")
t.notOk(false, "false is notOk")
t.notOk(0, "0 is notOk")
t.notOk(null, "null is notOk")
t.notOk(undefined, "undefined is notOk")
t.notOk(NaN, "NaN is notOk")
t.notOk("", "empty string is notOk")
t.end()
function section2 () {
var results = t.results
t.clear()
t.ok(true, "ok")
t.ok(results.ok, "ok")
t.equal(results.tests, 12, "12 tests.")
t.equal(results.passTotal, 12, "12 pass total")
t.equal(results.fail, 0, "0 fail")
t.type(results.ok, "boolean", "ok is boolean")
t.type(results.skip, "number", "skip is number")
t.type(results, "Results", "results isa Results")
t.type(t, "Test", "test isa Test")
t.type(t, "Harness", "test isa Harness")
t.end()
}
})
| var tap = require("../")
, test = tap.test
test("meta success", { skip: false }, function (t) {
t.once("end", section2)
t.ok(true, "true is ok")
t.notOk(false, "false is notOk")
t.end()
function section2 () {
var results = t.results
t.clear()
t.ok(true, "ok")
t.ok(results.ok, "ok")
t.equal(results.tests, 2, "2 tests.")
t.equal(results.passTotal, 2, "2 pass total")
t.equal(results.fail, 0, "0 fail")
t.type(results.ok, "boolean", "ok is boolean")
t.type(results.skip, "number", "skip is number")
t.type(results, "Results", "results isa Results")
t.type(t, "Test", "test isa Test")
t.type(t, "Harness", "test isa Harness")
t.end()
}
})
|
Change import order for package.json | #!/usr/bin/env node
'use strict';
const meow = require('meow');
const chalk = require('chalk');
const updateNotifier = require('update-notifier');
const pkg = require('./package.json');
const quote = require('./index.js');
const cli = meow({
help: [
'Usage',
' $ quote-cli',
'',
'Options',
' qotd Display quote of the day',
'',
'Examples',
' $ quote-cli',
' To be or not be, that is the question. - William Shakespeare',
' $ quote-cli qotd',
' Wars teach us not to love our enemies, but to hate our allies. - W. L. George'
]
});
updateNotifier({pkg: pkg}).notify();
quote(cli.input[0], function (err, result) {
if (err) {
console.log(chalk.bold.red(err));
process.exit(1);
}
console.log(chalk.cyan(chalk.yellow(result.quote.body) + ' - ' + result.quote.author));
process.exit();
});
| #!/usr/bin/env node
'use strict';
var meow = require('meow');
var chalk = require('chalk');
var updateNotifier = require('update-notifier');
var quote = require('./index.js');
var pkg = require('./package.json');
var cli = meow({
help: [
'Usage',
' $ quote-cli',
'',
'Options',
' qotd Display quote of the day',
'',
'Examples',
' $ quote-cli',
' To be or not be, that is the question. - William Shakespeare',
' $ quote-cli qotd',
' Wars teach us not to love our enemies, but to hate our allies. - W. L. George'
]
});
updateNotifier({pkg: pkg}).notify();
quote(cli.input[0], function (err, result) {
if (err) {
console.log(chalk.bold.red(err));
process.exit(1);
}
console.log(chalk.cyan(chalk.yellow(result.quote.body) + ' - ' + result.quote.author));
process.exit();
});
|
Add coverage to test dependancies | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = [
'pyramid',
'pyramid_debugtoolbar',
'waitress',
]
test_requires = requires + [
'webtest',
'mock',
'coverage',
]
setup(name='topdfserver',
version='0.0',
description='topdfserver',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='',
author_email='',
url='',
keywords='web pyramid pylons',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=requires,
tests_require=test_requires,
test_suite="topdfserver",
entry_points = """\
[paste.app_factory]
main = topdfserver:main
""",
)
| import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = [
'pyramid',
'pyramid_debugtoolbar',
'waitress',
]
test_requires = requires + [
'webtest',
'mock',
]
setup(name='topdfserver',
version='0.0',
description='topdfserver',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='',
author_email='',
url='',
keywords='web pyramid pylons',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=requires,
tests_require=test_requires,
test_suite="topdfserver",
entry_points = """\
[paste.app_factory]
main = topdfserver:main
""",
)
|
Save role when adding new person | <?
include '../scat.php';
$name= $_REQUEST['name'];
$company= $_REQUEST['company'];
$phone= $_REQUEST['phone'];
if (empty($name) && empty($company) && empty($phone))
die_jsonp("You need to supply at least a name, company, or phone number.");
$list= array();
foreach(array('name', 'role', 'company', 'address',
'email', 'phone', 'tax_id') as $field) {
$list[]= "$field = '" . $db->escape($_REQUEST[$field]) . "', ";
}
if ($_REQUEST['phone']) {
$list[]= "loyalty_number = '" .
preg_replace('/[^\d]/', '', $_REQUEST['phone']) .
"', ";
}
$fields= join('', $list);
$q= "INSERT INTO person
SET $fields
active = 1";
$r= $db->query($q)
or die_query($db, $q);
echo jsonp(array('person' => $db->insert_id));
| <?
include '../scat.php';
$name= $_REQUEST['name'];
$company= $_REQUEST['company'];
$phone= $_REQUEST['phone'];
if (empty($name) && empty($company) && empty($phone))
die_jsonp("You need to supply at least a name, company, or phone number.");
$list= array();
foreach(array('name', 'company', 'address',
'email', 'phone', 'tax_id') as $field) {
$list[]= "$field = '" . $db->escape($_REQUEST[$field]) . "', ";
}
if ($_REQUEST['phone']) {
$list[]= "loyalty_number = '" .
preg_replace('/[^\d]/', '', $_REQUEST['phone']) .
"', ";
}
$fields= join('', $list);
$q= "INSERT INTO person
SET $fields
active = 1";
$r= $db->query($q)
or die_query($db, $q);
echo jsonp(array('person' => $db->insert_id));
|
Enable submission of new songs via form. | #!/usr/bin/env python
import os
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
genres = ('Hip Hop', 'Electronic', 'R&B')
songs = [\
{ 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Hip Hop' },\
{ 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\
{ 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'Electronic' }\
]
@app.route('/')
def index():
return render_template('index.html', genres=genres, genre=genres[0], songs=songs)
@app.route('/submit')
def submit():
title = request.args.get('Song Title')
artist = request.args.get('Artist')
year = request.args.get('Year')
genre = request.args.get('Genre')
songs.append({ 'rank':str(len(songs) + 1), 'title':title, 'artist':artist, 'year':year, 'genre':genre })
return redirect(url_for('index'))
if __name__ == "__main__":
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
| #!/usr/bin/env python
import os
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def root():
genres = ('Hip Hop', 'Electronic', 'R&B')
songs = [\
{ 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Rap' },\
{ 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\
{ 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'House' }\
]
return render_template('index.html', genres=genres, genre=genres[0], songs=songs)
if __name__ == "__main__":
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
Fix select form component values | <div class="form-group">
<label>{{ $label }}</label>
<?php if (isset($value)): $val = $value; elseif (is_bool(Form::getValueAttribute($name))): $val = (int) Form::getValueAttribute($name); else: $val = null; endif; ?>
@if (isset($options) && is_array($options))
{!! Form::select($name, $options, $val, ['class' => sprintf('form-control %s', isset($class) ? $class : null)]) !!}
@elseif (isset($type))
{!! Form::select($name, [
'1' => trans(sprintf('mconsole::forms.options.%s.enabled', $type)),
'0' => trans(sprintf('mconsole::forms.options.%s.disabled', $type)),
], $val, ['class' => sprintf('form-control %s', isset($class) ? $class : null)]) !!}
@endif
</div> | <div class="form-group">
<label>{{ $label }}</label>
@if (isset($options) && is_array($options))
<?php if (isset($value)): $val = $value; elseif (is_bool(Form::getValueAttribute($name))): $val = (int) Form::getValueAttribute($name); else: $val = null; endif; ?>
{!! Form::select($name, $options, $val, ['class' => sprintf('form-control %s', isset($class) ? $class : null)]) !!}
@elseif (isset($type))
{!! Form::select($name, [
'1' => trans(sprintf('mconsole::forms.options.%s.enabled', $type)),
'0' => trans(sprintf('mconsole::forms.options.%s.disabled', $type)),
], (isset($value)) ? $value : is_bool(Form::getValueAttribute($name)) ? (int) Form::getValueAttribute($name) : null, ['class' => sprintf('form-control %s', isset($class) ? $class : null)]) !!}
@endif
</div> |
Fix tests after markdown library change
Addendum to da03b3f033cce2b957a71cf6cb334a8c207c5047 | from adhocracy.tests import TestController
from adhocracy.tests.testtools import tt_make_user
class TestText(TestController):
def test_render(self):
from adhocracy.lib.text import render
source = ('header\n'
'========')
result = render(source)
self.assertEqual(result, u'<h1>header</h1>')
def test_render_no_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=False)
self.assertEqual(result, u'<p>@pudo</p>')
def test_render_user_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=True)
self.assertTrue(u'/user/pudo"' in result)
| from adhocracy.tests import TestController
from adhocracy.tests.testtools import tt_make_user
class TestText(TestController):
def test_render(self):
from adhocracy.lib.text import render
source = ('header\n'
'========')
result = render(source)
self.assertEqual(result, u'<h1>header</h1>\n')
def test_render_no_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=False)
self.assertEqual(result, u'<p>@pudo</p>\n')
def test_render_user_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=True)
self.assertTrue(u'/user/pudo"' in result)
|
Remove max-width from guestbook capture | /** @jsxImportSource theme-ui */
import { Box, Button } from 'theme-ui'
import Link from 'next/link'
import Sparkle from './sparkle'
import Spicy from './spicy'
// email
export default function GuestbookCapture({ props }) {
return (
<Box
sx={{
position: 'relative',
p: [3, 3, 4],
bg: 'elevated',
height: 'fit-content',
borderRadius: '4px',
}}
>
<h3>
<Spicy>Sign the web3 guestbook!</Spicy>
</h3>
<p>
Connect with your favorite wallet, and sign the Web3 Guestbook with a
gasless meta-transaction.
</p>
<Link href="/guestbook">
<Button title="Discuss on Twitter">
<Sparkle>Guestbook</Sparkle>
</Button>
</Link>
</Box>
)
}
| /** @jsxImportSource theme-ui */
import { Box, Button } from 'theme-ui'
import Link from 'next/link'
import Sparkle from './sparkle'
import Spicy from './spicy'
// email
export default function GuestbookCapture({ props }) {
return (
<Box
sx={{
position: 'relative',
p: [3, 3, 4],
bg: 'elevated',
height: 'fit-content',
borderRadius: '4px',
maxWidth: ['100%', '50%'],
}}
>
<h3>
<Spicy>Sign the web3 guestbook!</Spicy>
</h3>
<p>
Connect with your favorite wallet, and sign the Web3 Guestbook with a
gasless meta-transaction.
</p>
<Link href="/guestbook">
<Button title="Discuss on Twitter">
<Sparkle>Guestbook</Sparkle>
</Button>
</Link>
</Box>
)
}
|
Update namespace to currently used convention | 'use strict';
Darwinator.Weapon = function (game, x, y, coolDown, bulletSpeed, bullets, damage) {
this.game = game;
this.x = x;
this.y = y;
this.coolDown = coolDown;
this.nextFire = 0;
this.bullets = bullets;
this.bulletSpeed = bulletSpeed;
this.damage = damage;
}
Darwinator.Weapon.prototype.updateManually = function (x, y) {
this.x = x;
this.y = y;
this.game.physics.angleToPointer(this);
if (this.game.input.activePointer.isDown) {
this.fire();
}
};
Darwinator.Weapon.prototype.fire = function() {
if (this.game.time.now > this.nextFire && this.bullets.countDead() > 0) {
this.nextFire = this.game.time.now + this.coolDown;
var bullet = this.bullets.getFirstDead();
this.resetBullet(bullet);
}
};
Darwinator.Weapon.prototype.resetBullet = function (bullet) {
bullet.reset(this.x, this.y); // resets sprite and body
bullet.rotation = this.game.physics.moveToPointer(bullet, this.bulletSpeed);
};
| (function() {
'use strict';
function Weapon(game, x, y, coolDown, bulletSpeed, bullets, damage) {
this.game = game;
this.x = x;
this.y = y;
this.coolDown = coolDown;
this.nextFire = 0;
this.bullets = bullets;
this.bulletSpeed = bulletSpeed;
this.damage = damage;
}
Weapon.prototype = {
updateManually: function(x, y){
this.x = x;
this.y = y;
this.game.physics.angleToPointer(this);
if (this.game.input.activePointer.isDown){
this.fire();
}
},
fire: function(){
if (this.game.time.now > this.nextFire && this.bullets.countDead() > 0){
this.nextFire = this.game.time.now + this.coolDown;
var bullet = this.bullets.getFirstDead();
this.resetBullet(bullet);
}
},
resetBullet: function(bullet){
bullet.reset(this.x, this.y); // resets sprite and body
bullet.rotation = this.game.physics.moveToPointer(bullet, this.bulletSpeed);
}
};
window.Darwinator = window.Darwinator || {};
window.Darwinator.Weapon = Weapon;
}());
|
[telemetry] Disable power and smoke unit tests on Mac 10.9.
powermetrics is failing on the bots.
BUG=423688
TEST=trybots
R=tonyg
Review URL: https://codereview.chromium.org/746793002
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#305147} | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import time
import unittest
from telemetry import decorators
from telemetry.core import platform as platform_module
class PlatformBackendTest(unittest.TestCase):
@decorators.Disabled('mavericks') # crbug.com/423688
def testPowerMonitoringSync(self):
# Tests that the act of monitoring power doesn't blow up.
platform = platform_module.GetHostPlatform()
can_monitor_power = platform.CanMonitorPower()
self.assertIsInstance(can_monitor_power, bool)
if not can_monitor_power:
logging.warning('Test not supported on this platform.')
return
browser_mock = lambda: None
# Android needs to access the package of the monitored app.
if platform.GetOSName() == 'android':
# pylint: disable=W0212
browser_mock._browser_backend = lambda: None
# Monitor the launcher, which is always present.
browser_mock._browser_backend.package = 'com.android.launcher'
platform.StartMonitoringPower(browser_mock)
time.sleep(0.001)
output = platform.StopMonitoringPower()
self.assertTrue(output.has_key('energy_consumption_mwh'))
self.assertTrue(output.has_key('identifier'))
| # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import time
import unittest
from telemetry.core import platform as platform_module
class PlatformBackendTest(unittest.TestCase):
def testPowerMonitoringSync(self):
# Tests that the act of monitoring power doesn't blow up.
platform = platform_module.GetHostPlatform()
can_monitor_power = platform.CanMonitorPower()
self.assertIsInstance(can_monitor_power, bool)
if not can_monitor_power:
logging.warning('Test not supported on this platform.')
return
browser_mock = lambda: None
# Android needs to access the package of the monitored app.
if platform.GetOSName() == 'android':
# pylint: disable=W0212
browser_mock._browser_backend = lambda: None
# Monitor the launcher, which is always present.
browser_mock._browser_backend.package = 'com.android.launcher'
platform.StartMonitoringPower(browser_mock)
time.sleep(0.001)
output = platform.StopMonitoringPower()
self.assertTrue(output.has_key('energy_consumption_mwh'))
self.assertTrue(output.has_key('identifier'))
|
Remove host in default doc fetch URL
This host is unnecessary because it is equal to the current host, which
is equivalent to not specifying it at all.
If using the webjar, then the doc endpoint in on the same server at
/jsondoc, so "/jsondoc" is sufficient for the fetch to work.
If using an independent UI, then it is likely that the app server URL
ends in /jsondoc, so this string helps anyway because the user just has
to prepend the host. | // @flow
import type { Livedoc } from './livedoc';
import type { ResponseMetaData } from './playground';
export type LoaderState = {
+loading: boolean,
+loadingError: ?string,
+url: ?string
}
export const newLoaderState = () => ({
loading: false,
loadingError: null,
url: computeInitialUrl(),
});
function computeInitialUrl(): string {
const url = new URL(window.location.href);
const specifiedUrl = url.searchParams.get('url');
if (specifiedUrl) {
return specifiedUrl;
}
// if using the webjar, then the doc endpoint in on the same server at /jsondoc, so "/jsondoc" is sufficient
// if using an independent UI, then it is likely that the app server URL ends in /jsondoc, so this string helps anyway
return '/jsondoc';
}
export type PlaygroundState = {
+waitingResponse: boolean,
+streamingResponse: boolean,
+responseMeta: ?ResponseMetaData,
+responseBody: ?string,
+error: any,
}
export function newPlaygroundState(): PlaygroundState {
return {
waitingResponse: false,
streamingResponse: false,
responseMeta: null,
responseBody: null,
error: null,
};
}
export type State = {
+loader: LoaderState,
+livedoc: ?Livedoc,
+playground: PlaygroundState,
}
export const newState = () => ({
loader: newLoaderState(),
livedoc: null,
playground: newPlaygroundState(),
});
| // @flow
import type { Livedoc } from './livedoc';
import type { ResponseMetaData } from './playground';
export type LoaderState = {
+loading: boolean,
+loadingError: ?string,
+url: ?string
}
export const newLoaderState = () => ({
loading: false,
loadingError: null,
url: computeInitialUrl(),
});
function computeInitialUrl(): string {
const url = new URL(window.location.href);
const specifiedUrl = url.searchParams.get('url');
if (specifiedUrl) {
return specifiedUrl;
}
return window.location.origin + '/jsondoc';
}
export type PlaygroundState = {
+waitingResponse: boolean,
+streamingResponse: boolean,
+responseMeta: ?ResponseMetaData,
+responseBody: ?string,
+error: any,
}
export function newPlaygroundState(): PlaygroundState {
return {
waitingResponse: false,
streamingResponse: false,
responseMeta: null,
responseBody: null,
error: null,
};
}
export type State = {
+loader: LoaderState,
+livedoc: ?Livedoc,
+playground: PlaygroundState,
}
export const newState = () => ({
loader: newLoaderState(),
livedoc: null,
playground: newPlaygroundState(),
});
|
Improve solution by using enumerate | import sys
def lowest_unique(int_list):
numbers = {}
for index, number in enumerate(int_list):
group = numbers.setdefault(int(number), [])
group.append(index)
for number in sorted(numbers.keys()):
retval = numbers[number]
if len(retval) == 1:
return retval[0] + 1
return 0
if __name__ == '__main__':
inputfile = sys.argv[1]
with open(inputfile, 'r') as f:
for line in f:
line_list = line.rstrip().split()
if line_list:
print str(lowest_unique(line_list))
| import sys
def lowest_unique(int_list):
numbers = {}
for index in range(len(int_list)):
group = numbers.setdefault(int(int_list[index]), [])
group.append(index)
for number in numbers:
retval = numbers[number]
if len(retval) == 1:
return retval[0] + 1
return 0
if __name__ == '__main__':
inputfile = sys.argv[1]
with open(inputfile, 'r') as f:
for line in f:
line_list = line.rstrip().split()
if line_list:
print str(lowest_unique(line_list))
|
Fix path for saving imgs | import os
import json
from flask import Flask, request, Response
from flask import render_template, send_from_directory, url_for
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname('data'))
basedir_img = os.path.abspath(os.path.dirname('angular_flask'))
app.config["SECRET_KEY"] = "\xed\x9c\xac\xcd4\x83k\xd1\x17\xd54\xe71\x03\xaf\xd8\x04\xe3\xcd\xaa\xf4\x97\x82\x1e"
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///' + os.path.join(basedir, 'data/posts.db')
app.config["DEBUG"] = True
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config['UPLOAD_FOLDER'] = os.path.join(basedir_img, 'angular_flask/static/img')
import angular_flask.core
import angular_flask.models
import angular_flask.controllers
| import os
import json
from flask import Flask, request, Response
from flask import render_template, send_from_directory, url_for
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname('data'))
app.config["SECRET_KEY"] = "\xed\x9c\xac\xcd4\x83k\xd1\x17\xd54\xe71\x03\xaf\xd8\x04\xe3\xcd\xaa\xf4\x97\x82\x1e"
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///' + os.path.join(basedir, 'data/posts.db')
app.config["DEBUG"] = True
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config['UPLOAD_FOLDER'] = '/home/alex/dev/blog/angular_flask/static/img'
import angular_flask.core
import angular_flask.models
import angular_flask.controllers
|
Fix healthz test error handling | /*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package healthz
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestInstallHandler(t *testing.T) {
mux := http.NewServeMux()
InstallHandler(mux)
req, err := http.NewRequest("GET", "http://example.com/healthz", nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected %v, got %v", http.StatusOK, w.Code)
}
if w.Body.String() != "ok" {
t.Errorf("Expected %v, got %v", "ok", w.Body.String())
}
}
| /*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package healthz
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestInstallHandler(t *testing.T) {
mux := http.NewServeMux()
InstallHandler(mux)
req, err := http.NewRequest("GET", "http://example.com/healthz", nil)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected %v, got %v", http.StatusOK, w.Code)
}
if w.Body.String() != "ok" {
t.Errorf("Expected %v, got %v", "ok", w.Body.String())
}
}
|
Use KTemplate instead of KDocument to load script | <?php
/**
* @version $Id$
* @category Koowa
* @package Koowa_Toolbar
* @subpackage Button
* @copyright Copyright (C) 2007 - 2009 Johan Janssens and Mathias Verraes. All rights reserved.
* @license GNU GPL <http://www.gnu.org/licenses/gpl.html>
*/
/**
* POST button class for a toolbar
*
* @author Mathias Verraes <mathias@koowa.org>
* @category Koowa
* @package Koowa_Toolbar
* @subpackage Button
*/
abstract class KToolbarButtonPost extends KToolbarButtonAbstract
{
protected $_fields = array();
public function __construct(array $options = array())
{
parent::__construct($options);
$this->setMethod('post');
KTemplate::loadHelper('script', Koowa::getURL('js').'koowa.js');
}
public function getOnClick()
{
$js = '';
foreach($this->_fields as $name => $value) {
$js .= "Koowa.Form.addField('$name', '$value');";
}
$js .= "Koowa.Form.submit('{$this->_method}');";
return $js;
}
public function setField($name, $value)
{
$this->_fields[$name] = $value;
return $this;
}
} | <?php
/**
* @version $Id$
* @category Koowa
* @package Koowa_Toolbar
* @subpackage Button
* @copyright Copyright (C) 2007 - 2009 Johan Janssens and Mathias Verraes. All rights reserved.
* @license GNU GPL <http://www.gnu.org/licenses/gpl.html>
*/
/**
* POST button class for a toolbar
*
* @author Mathias Verraes <mathias@koowa.org>
* @category Koowa
* @package Koowa_Toolbar
* @subpackage Button
*/
abstract class KToolbarButtonPost extends KToolbarButtonAbstract
{
protected $_fields = array();
public function __construct(array $options = array())
{
parent::__construct($options);
$this->setMethod('post');
$script = Koowa::getURL('js').'koowa.js';
KFactory::get('lib.joomla.document')->addScript($script);
}
public function getOnClick()
{
$js = '';
foreach($this->_fields as $name => $value) {
$js .= "Koowa.Form.addField('$name', '$value');";
}
$js .= "Koowa.Form.submit('{$this->_method}');";
return $js;
}
public function setField($name, $value)
{
$this->_fields[$name] = $value;
return $this;
}
} |
Use swellrt credentials in e2e-test | 'use strict';
var gulpConfig = require(__dirname + '/../gulpfile').config;
exports.config = {
allScriptsTimeout: 90000,
specs: [
'e2e/*.js'
],
capabilities: {
'browserName': 'chrome'
},
baseUrl: 'http://' + gulpConfig.serverTest.host + ':' + gulpConfig.serverTest.port + '/',
framework: 'jasmine2',
jasmineNodeOpts: {
defaultTimeoutInterval: 90000
},
// Create user and wave before tests
onPrepare: function() {
browser.driver.get(gulpConfig.swellrt.server + '/auth/register');
browser.driver.findElement(by.id('address')).sendKeys(gulpConfig.swellrt.user);
browser.driver.findElement(by.id('password')).sendKeys(gulpConfig.swellrt.pass);
browser.driver.findElement(by.id('verifypass')).sendKeys(gulpConfig.swellrt.pass);
browser.driver.findElement(by.css('input[value="Register"]')).click();
}
};
| 'use strict';
var gulpConfig = require(__dirname + '/../gulpfile').config;
exports.config = {
allScriptsTimeout: 90000,
specs: [
'e2e/*.js'
],
capabilities: {
'browserName': 'chrome'
},
baseUrl: 'http://' + gulpConfig.serverTest.host + ':' + gulpConfig.serverTest.port + '/',
framework: 'jasmine2',
jasmineNodeOpts: {
defaultTimeoutInterval: 90000
},
// Create user and wave before tests
onPrepare: function() {
browser.driver.get(gulpConfig.swellrt.server + '/auth/register');
browser.driver.findElement(by.id('address')).sendKeys('test');
browser.driver.findElement(by.id('password')).sendKeys('test');
browser.driver.findElement(by.id('verifypass')).sendKeys('test');
browser.driver.findElement(by.css('input[value="Register"]')).click();
}
};
|
Rename gulp develop task to dev | var gulp = require('gulp'),
livereload = require('gulp-livereload'),
nodemon = require('gulp-nodemon'),
fs = require('fs');
gulp.task('dev', function () {
livereload.listen();
nodemon({
script: 'server.js',
stdout: false,
ext: 'js jade css',
execMap: {
js: 'node --debug-brk=5560'
}
}).on('readable', function() {
this.stdout.pipe(fs.createWriteStream('output.txt'));
this.stderr.pipe(fs.createWriteStream('err.txt'));
livereload.reload();
});
});
gulp.task('default', function () {
nodemon({
script: 'server.js',
ext: 'js jade css'
});
});
| var gulp = require('gulp'),
livereload = require('gulp-livereload'),
nodemon = require('gulp-nodemon'),
fs = require('fs');
gulp.task('develop', function () {
livereload.listen();
nodemon({
script: 'server.js',
stdout: false,
ext: 'js jade css',
execMap: {
js: 'node --debug-brk=5560'
}
}).on('readable', function() {
this.stdout.pipe(fs.createWriteStream('output.txt'));
this.stderr.pipe(fs.createWriteStream('err.txt'));
livereload.reload();
}
)});
gulp.task('default', function () {
nodemon({
script: 'server.js',
ext: 'js jade css'
});
});
|
Make sure the cloud_federation_api routes are loaded
Signed-off-by: Joas Schilling <ab43a7c9cb5b2380afc4ddf8b3e2583169b39a02@schilljs.com> | <?php
/**
* @copyright Copyright (c) 2018 Bjoern Schiessle <bjoern@schiessle.org>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
require_once __DIR__ . '/../lib/base.php';
header('Content-Type: application/json');
$server = \OC::$server;
$isEnabled = $server->getAppManager()->isEnabledForUser('cloud_federation_api');
if ($isEnabled) {
// Make sure the routes are loaded
\OC_App::loadApp('cloud_federation_api');
$capabilities = new OCA\CloudFederationAPI\Capabilities($server->getURLGenerator());
header('Content-Type: application/json');
echo json_encode($capabilities->getCapabilities()['ocm']);
} else {
header($_SERVER["SERVER_PROTOCOL"]." 501 Not Implemented", true, 501);
exit("501 Not Implemented");
}
| <?php
/**
* @copyright Copyright (c) 2018 Bjoern Schiessle <bjoern@schiessle.org>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
require_once __DIR__ . '/../lib/base.php';
header('Content-Type: application/json');
$server = \OC::$server;
$isEnabled = $server->getAppManager()->isEnabledForUser('cloud_federation_api');
if ($isEnabled) {
$capabilities = new OCA\CloudFederationAPI\Capabilities($server->getURLGenerator());
header('Content-Type: application/json');
echo json_encode($capabilities->getCapabilities()['ocm']);
} else {
header($_SERVER["SERVER_PROTOCOL"]." 501 Not Implemented", true, 501);
exit("501 Not Implemented");
}
|
Add missing package_data to file (v1.0.1) | from distutils.core import setup
import os
package_data = []
BASE_DIR = os.path.dirname(__file__)
walk_generator = os.walk(os.path.join(BASE_DIR, "project_template"))
paths_and_files = [(paths, files) for paths, dirs, files in walk_generator]
for path, files in paths_and_files:
prefix = path[len("project_template/"):]
if files:
package_data.append(os.path.join(prefix, "*.*"))
setup(
name="armstrong.templates.standard",
version="1.0.1",
description="Provides a basic project template for an Armstrong project",
long_description=open("README.rst").read(),
author='Texas Tribune & Bay Citizen',
author_email='dev@armstrongcms.org',
packages=[
"armstrong.templates.standard",
],
package_dir={
"armstrong.templates.standard": "project_template",
},
package_data={
"armstrong.templates.standard": package_data,
},
namespace_packages=[
"armstrong",
"armstrong.templates",
"armstrong.templates.standard",
],
entry_points={
"armstrong.templates": [
"standard = armstrong.templates.standard",
],
},
)
| from distutils.core import setup
setup(
name="armstrong.templates.standard",
version="1.0.0",
description="Provides a basic project template for an Armstrong project",
long_description=open("README.rst").read(),
author='Texas Tribune & Bay Citizen',
author_email='dev@armstrongcms.org',
packages=[
"armstrong.templates.standard",
],
package_dir={
"armstrong.templates.standard": "project_template",
},
namespace_packages=[
"armstrong",
"armstrong.templates",
"armstrong.templates.standard",
],
entry_points={
"armstrong.templates": [
"standard = armstrong.templates.standard",
],
},
)
|
Fix minibug in recover script | <?php
require_once '../moteur/dbconfig.php';
function recover_utilisateurs(int $admin, string $table, array $fields): string {
return ("update $table as T
set T.$fields[0] = $admin,
T.$fields[1] = $admin
where not exists (select 1
from utilisateurs U
where U.id = T.$fields[0]);
");
}
function recover(PDO $bdd, string $database_name, int $admin) {
$tables = $bdd->query("SELECT table_name FROM information_schema.tables
where table_schema=\"$database_name\"");
$fields = [ 'id_createur', 'id_last_hero'];
foreach ($tables as $t) {
$name = $t['table_name'];
if ($name === NULL || $name === 'utilisateurs') {
continue;
}
$sql = recover_utilisateurs($admin, $name, $fields);
$bdd->query($sql);
}
}
/*
* Ce script récupére les utilisateurs supprimées et les réapparentes à un utilisateur
* administrateur.
* Modifier la variable $admin pour changer cet utilisateur.
*/
function main() {
global $bdd;
global $base;
$database_name = $base;
// Note: Cas de la petite rockette
$req = $bdd->query('select id from utilisateurs where mail = "inconnu@localhost"');
$id = $req->fetch()['id'];
$req->closeCursor();
recover($bdd, $database_name, $id);
}
main();
| <?php
require_once '../moteur/dbconfig.php';
function recover_utilisateurs(int $admin, string $table, array $fields): string {
return ("update $table as T
set T.$fields[0] = $admin,
T.$fields[1] = $admin
where not exists (select 1
from utilisateurs U
where U.id = T.$fields[0]);
");
}
function recover(PDO $bdd, string $database_name, int $admin) {
$tables = $bdd->query("SELECT table_name FROM information_schema.tables
where table_schema=\"$database_name\"");
$fields = [ 'id_createur', 'id_last_hero'];
foreach ($tables as $t) {
$name = $t['table_name'];
if ($name === NULL || $name === 'utilisateurs') {
continue;
}
$sql = recover_utilisateurs($admin, $name, $fields);
$bdd->query($sql);
}
}
/*
* Ce script récupére les utilisateurs supprimées et les réapparentes à un utilisateur
* administrateur.
* Modifier la variable $admin pour changer cet utilisateur.
*/
function main() {
global $bdd;
global $base;
$database_name = $base;
// Note: Cas de la petite rockette
$admin = $bdd->query("select id from utilisateurs where mail = inconnu@localhost");
recover($bdd, $database_name, $admin);
}
main();
|
Add strides and is_grad_required() check | import pytest
import numpy.testing
import xchainer
# NumPy-like assertion functions that accept both NumPy and xChainer arrays
def assert_array_equal(x, y, rtol=1e-7, atol=0, err_msg='', verbose=True):
"""Raises an AssertionError if two array_like objects are not equal.
Args:
x(numpy.ndarray or xchainer.Array): The actual object to check.
y(numpy.ndarray or xchainer.Array): The desired, expected object.
err_msg(str): The error message to be printed in case of failure.
verbose(bool): If ``True``, the conflicting values
are appended to the error message.
.. seealso:: :func:`numpy.testing.assert_allclose`
"""
assert x.strides == y.strides
# TODO(sonots): Remove following explicit `to_device` transfer if conversion from
# xchainer.Array to numpy.ndarray via buffer protocol supports the device transfer.
if isinstance(x, xchainer.Array):
assert not x.is_grad_required()
x = x.to_device('native:0')
if isinstance(y, xchainer.Array):
assert not x.is_grad_required()
y = y.to_device('native:0')
numpy.testing.assert_allclose(
x, y, rtol, atol, err_msg=err_msg, verbose=verbose)
| import numpy.testing
import xchainer
# NumPy-like assertion functions that accept both NumPy and xChainer arrays
def assert_array_equal(x, y, rtol=1e-7, atol=0, err_msg='', verbose=True):
"""Raises an AssertionError if two array_like objects are not equal.
Args:
x(numpy.ndarray or xchainer.Array): The actual object to check.
y(numpy.ndarray or xchainer.Array): The desired, expected object.
err_msg(str): The error message to be printed in case of failure.
verbose(bool): If ``True``, the conflicting values
are appended to the error message.
.. seealso:: :func:`numpy.testing.assert_allclose`
"""
# TODO(sonots): Remove following explicit `to_device` transfer if conversion from
# xchainer.Array to numpy.ndarray via buffer protocol supports the device transfer.
if isinstance(x, xchainer.Array):
x = x.to_device('native:0')
if isinstance(y, xchainer.Array):
y = y.to_device('native:0')
numpy.testing.assert_allclose(
x, y, rtol, atol, err_msg=err_msg, verbose=verbose)
|
Remove event from scene highlight params
Dumb style stuff. | (function sceneHighlight() {
'use strict';
function highlightLines(query) {
var elements = document.querySelectorAll(query);
Array.from(document.querySelectorAll('.highlight')).forEach(function removePreviousHighlight(element) {
element.classList.remove('.highlight');
});
Array.from(elements).forEach(function iterateElements(element) {
element.classList.add('highlight');
});
elements[0].scrollIntoView({behavior: 'smooth'});
}
window.addEventListener('hashchange', function hashChangeCallback(event) {
var query = '.' + event.newURL.split('#')[1];
highlightLines(query);
});
window.addEventListener('load', function loadCallback() {
var query = window.location.hash;
if (query) {
highlightLines('.' + query.split('#')[1]);
}
});
})();
| (function sceneHighlight() {
'use strict';
function highlightLines(query) {
var elements = document.querySelectorAll(query);
Array.from(document.querySelectorAll('.highlight')).forEach(function removePreviousHighlight(element) {
element.classList.remove('.highlight');
});
Array.from(elements).forEach(function iterateElements(element) {
element.classList.add('highlight');
});
elements[0].scrollIntoView({behavior: 'smooth'});
}
window.addEventListener('hashchange', function hashChangeCallback(event) {
var query = '.' + event.newURL.split('#')[1];
highlightLines(query);
});
window.addEventListener('load', function loadCallback(event) {
var query = window.location.hash;
if (query) {
highlightLines('.' + query.split('#')[1]);
}
});
})();
|
Use GroupedOperation for merging PlatformPhyisicsOperation | from UM.Operations.Operation import Operation
from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
from UM.Operations.TranslateOperation import TranslateOperation
from UM.Operations.GroupedOperation import GroupedOperation
## A specialised operation designed specifically to modify the previous operation.
class PlatformPhysicsOperation(Operation):
def __init__(self, node, translation):
super().__init__()
self._node = node
self._transform = node.getLocalTransformation()
self._position = node.getPosition() + translation
self._always_merge = True
def undo(self):
self._node.setLocalTransformation(self._transform)
def redo(self):
self._node.setPosition(self._position)
def mergeWith(self, other):
group = GroupedOperation()
group.addOperation(self)
group.addOperation(other)
return group
def __repr__(self):
return 'PlatformPhysicsOperation(t = {0})'.format(self._position)
| from UM.Operations.Operation import Operation
from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
from UM.Operations.TranslateOperation import TranslateOperation
## A specialised operation designed specifically to modify the previous operation.
class PlatformPhysicsOperation(Operation):
def __init__(self, node, translation):
super().__init__()
self._node = node
self._translation = translation
def undo(self):
pass
def redo(self):
pass
def mergeWith(self, other):
if type(other) is AddSceneNodeOperation:
other._node.translate(self._translation)
return other
elif type(other) is TranslateOperation:
other._translation += self._translation
return other
else:
return False
|
Add login support to demo app | <?php
/**
* Demo app with SAML auth
*/
if (isset($_GET['signin'])) {
require("/vagrant/SP/lib/_autoload.php");
$as = new SimpleSAML_Auth_Simple('default-sp');
$as->requireAuth();
if ($as->isAuthenticated()) {
$saml_attributes = $as->getAttributes();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>SSO Sign In Demo</title>
<link href="styles/css/bootstrap.css" rel="stylesheet">
<link href="styles/css/signin.css" rel="stylesheet">
</head>
<body>
<div class="container">
<?php if (!isset($saml_attributes)) { ?>
<form class="form-signin" method="GET" action="?">
<input type="hidden" name="signin" value="" />
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
<?php } else {
$name = $saml_attributes['name'][0];
print "<p>Welcome {$name}!</p>";
} ?>
</div>
</body>
</html>
| <?php
/**
* Demo app with SAML auth
*/
if (isset($_GET['signin'])) {
require("/vagrant/SP/lib/_autoload.php");
$as = new SimpleSAML_Auth_Simple('default-sp');
$as->requireAuth();
if ($as->isAuthenticated()) {
$saml_attributes = $as->getAttributes();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Signin Template for Bootstrap</title>
<link href="styles/css/bootstrap.css" rel="stylesheet">
<link href="styles/css/signin.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form class="form-signin" method="GET" action="?">
<input type="hidden" name="signin" value="" />
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div>
</body>
</html>
|
Fix php time not equal to nodejs getTime() | <?php
namespace Vohinc\BotanalyticsPhp\Drivers;
/**
* Class Facebook
* @package Vohinc\BotanalyticsPhp\Drivers
*/
class Facebook extends DriverAbstract
{
/**
* @var string
*/
protected $endpoint = 'https://botanalytics.co/api/v1/messages/facebook-messenger';
/**
* Make request body
*
* @return array
*/
public function make()
{
return [
'recipient' => $this->message['recipient'],
'message' => $this->message['message'],
'timestamp' => time() * 1000,
];
}
/**
* Send user profile to Botanalytics
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function user()
{
return $this->request('https://botanalytics.co/api/v1/facebook-messenger/users/', $this->message);
}
}
| <?php
namespace Vohinc\BotanalyticsPhp\Drivers;
/**
* Class Facebook
* @package Vohinc\BotanalyticsPhp\Drivers
*/
class Facebook extends DriverAbstract
{
/**
* @var string
*/
protected $endpoint = 'https://botanalytics.co/api/v1/messages/facebook-messenger';
/**
* Make request body
*
* @return array
*/
public function make()
{
return [
'recipient' => $this->message['recipient'],
'message' => $this->message['message'],
'timestamp' => time(),
];
}
/**
* Send user profile to Botanalytics
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function user()
{
return $this->request('https://botanalytics.co/api/v1/facebook-messenger/users/', $this->message);
}
}
|
Include all packages (and become 0.9.3 in the process) | # encoding=utf8
from setuptools import setup, find_packages
setup(
name='django-form-designer-ai',
version='0.9.3',
url='http://github.com/andersinno/django-form-designer-ai',
license='BSD',
maintainer='Anders Innovations Ltd',
maintainer_email='info@anders.fi',
packages=find_packages('.', include=[
'form_designer',
'form_designer.*',
]),
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
],
install_requires=[
'django-picklefield>=0.3.2,<0.4',
],
zip_safe=False,
)
| # encoding=utf8
from setuptools import setup
setup(
name='django-form-designer-ai',
version='0.9.2',
url='http://github.com/andersinno/django-form-designer-ai',
license='BSD',
maintainer='Anders Innovations Ltd',
maintainer_email='info@anders.fi',
packages=[
'form_designer',
'form_designer.migrations',
'form_designer.templatetags',
'form_designer.contrib',
'form_designer.contrib.exporters',
'form_designer.contrib.cms_plugins',
'form_designer.contrib.cms_plugins.form_designer_form',
],
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
],
install_requires=[
'django-picklefield>=0.3.2,<0.4',
],
zip_safe=False,
)
|
Add cli tests, fix related bugs | from plim import syntax
from plim.console import plimc
from plim.util import PY3K
from . import TestCaseBase
class TestCLI(TestCaseBase):
def setUp(self):
super(TestCLI, self).setUp()
self.mako_syntax = syntax.Mako()
if PY3K:
from io import BytesIO
self.stdout = BytesIO()
else:
from StringIO import StringIO
self.stdout = StringIO()
def test_cli_mako_output(self):
plimc(['tests/fixtures/unicode_attributes_test.plim'], stdout=self.stdout)
def test_cli_html_output(self):
plimc(['--html', 'tests/fixtures/unicode_attributes_test.plim'], stdout=self.stdout)
| from plim import syntax
from plim.console import plimc
from plim.util import PY3K
from . import TestCaseBase
class TestCLI(TestCaseBase):
def setUp(self):
super(TestCLI, self).setUp()
self.mako_syntax = syntax.Mako()
if PY3K:
from io import BytesIO
self.stdout = BytesIO()
else:
from StringIO import StringIO
self.stdout = StringIO()
def test_cli_mako_output(self):
plimc(['tests/fixtures/unicode_attributes_test.plim'], stdout=self.stdout)
def test_cli_html_output(self):
plimc(['--html', 'tests/fixtures/unicode_attributes_test.plim'], stdout=self.stdout)
|
Fix signature because of test failure | """
This signature contains tests to see if the site is running on Hippo CMS.
"""
__author__ = "Jeroen Reijn"
__copyright__ = "CM Fieldguide"
__credits__ = ["Jeroen Reijn",]
__license__ = "Unlicense"
__version__ = "0.1"
__maintainer__ = "Jeroen Reijn"
__email__ = "j.reijn@onehippo.com"
__status__ = "Experimental"
from cmfieldguide.cmsdetector.signatures import BaseSignature
class Signature(BaseSignature):
NAME = 'Hippo CMS'
WEBSITE = 'http://www.onehippo.com/en/products/cms'
KNOWN_POSITIVE = 'http://www.onehippo.com'
TECHNOLOGY = 'JAVA'
def test_binaries_file_paths(self, site):
"""
Hippo CMS exposes image data generally from the binaries path.
"""
if site.home_page.contains_any_pattern(
['/binaries/content/gallery/']
):
return 1
else:
return 0
| """
This signature contains tests to see if the site is running on Hippo CMS.
"""
__author__ = "Jeroen Reijn"
__copyright__ = "CM Fieldguide"
__credits__ = ["Jeroen Reijn",]
__license__ = "Unlicense"
__version__ = "0.1"
__maintainer__ = "Jeroen Reijn"
__email__ = "j.reijn@onehippo.com"
__status__ = "Experimental"
from cmfieldguide.cmsdetector.signatures import BaseSignature
class Signature(BaseSignature):
NAME = 'Hippo CMS'
WEBSITE = 'http://www.onehippo.com/en/products/cms'
KNOWN_POSITIVE = 'www.onehippo.com'
TECHNOLOGY = 'JAVA'
def test_binaries_file_paths(self, site):
"""
Hippo CMS exposes image data generally from the binaries path.
"""
if site.home_page.contains_any_pattern(
['/binaries/content/gallery/']
):
return 1
else:
return 0
|
kompomaatti: Add more test data; improve feedback on failing case | from django.test import TestCase
from Instanssi.kompomaatti.models import Entry
VALID_YOUTUBE_URLS = [
# must handle various protocols and hostnames in the video URL
"http://www.youtube.com/v/asdf123456",
"https://www.youtube.com/v/asdf123456/",
"//www.youtube.com/v/asdf123456",
"www.youtube.com/v/asdf123456",
"youtube.com/v/asdf123456/",
# must handle various other ways to define the video
"www.youtube.com/watch?v=asdf123456",
"http://youtu.be/asdf123456",
"https://youtu.be/asdf123456/"
]
class KompomaattiTests(TestCase):
def setUp(self):
pass
def test_youtube_urls(self):
"""Test YouTube video id extraction from URLs."""
for url in VALID_YOUTUBE_URLS:
self.assertEqual(Entry.youtube_url_to_id(url), "asdf123456",
msg="failing URL: %s" % url)
| from django.test import TestCase
from Instanssi.kompomaatti.models import Entry
VALID_YOUTUBE_URLS = [
# must handle various protocols in the video URL
"http://www.youtube.com/v/asdf123456",
"https://www.youtube.com/v/asdf123456/",
"//www.youtube.com/v/asdf123456",
"www.youtube.com/v/asdf123456",
# must handle various other ways to define the video
"www.youtube.com/watch?v=asdf123456",
"http://youtu.be/asdf123456",
"http://youtu.be/asdf123456/"
]
class KompomaattiTests(TestCase):
def setUp(self):
pass
def test_youtube_urls(self):
"""Test that various YouTube URLs are parsed properly."""
for url in VALID_YOUTUBE_URLS:
print("Test URL: %s" % url)
self.assertEqual(Entry.youtube_url_to_id(url), "asdf123456")
|
Add reset methods to ExtractAttribute | import logging
from operator import attrgetter
from .base_NEW import TohuUltraBaseGenerator
__all__ = ['ExtractAttribute']
logger = logging.getLogger('tohu')
class ExtractAttribute(TohuUltraBaseGenerator):
"""
Generator which produces items that are attributes extracted from
the items produced by a different generator.
"""
def __init__(self, g, attr_name):
logger.debug(f"Extracting attribute '{attr_name}' from parent={g}")
self.parent = g
self.gen = g.clone()
self.attr_name = attr_name
self.attrgetter = attrgetter(attr_name)
def __repr__(self):
return f"<ExtractAttribute '{self.attr_name}' from {self.parent} >"
def spawn(self, dependency_mapping):
logger.warning(f'ExtractAttribute.spawn(): dependency_mapping={dependency_mapping}')
raise NotImplementedError()
def __next__(self):
return self.attrgetter(next(self.gen))
def reset(self, seed):
logger.debug(f"Ignoring explicit reset() on derived generator: {self}")
def reset_clone(self, seed):
logger.warning("TODO: rename method reset_clone() to reset_dependent_generator() because ExtractAttribute is not a direct clone")
self.gen.reset(seed)
| import logging
from operator import attrgetter
from .base_NEW import TohuUltraBaseGenerator
__all__ = ['ExtractAttribute']
logger = logging.getLogger('tohu')
class ExtractAttribute(TohuUltraBaseGenerator):
"""
Generator which produces items that are attributes extracted from
the items produced by a different generator.
"""
def __init__(self, g, attr_name):
logger.debug(f"Extracting attribute '{attr_name}' from parent={g}")
self.parent = g
self.gen = g.clone()
self.attr_name = attr_name
self.attrgetter = attrgetter(attr_name)
def __repr__(self):
return f"<ExtractAttribute '{self.attr_name}' from {self.parent} >"
def spawn(self, dependency_mapping):
logger.warning(f'ExtractAttribute.spawn(): dependency_mapping={dependency_mapping}')
raise NotImplementedError()
def __next__(self):
return self.attrgetter(next(self.gen))
|
Fix file headers for missing BSD license.
git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@1713 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e | /*
* Copyright (C) 2009 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 15. August 2009 by Joerg Schaible
*/
package com.thoughtworks.xstream.io.xml;
/**
* A XmlFriendlyNameCoder to support backward compatibility with XStream 1.1.
*
* @author Jörg Schaible
* @since upcoming
*/
public class XStream11NameCoder extends XmlFriendlyNameCoder {
/**
* {@inheritDoc} Noop implementation that does not decode. Used for XStream 1.1
* compatibility.
*/
public String decodeAttribute(String attributeName) {
return attributeName;
}
/**
* {@inheritDoc} Noop implementation that does not decode. Used for XStream 1.1
* compatibility.
*/
public String decodeNode(String elementName) {
return elementName;
}
}
| /*
* Copyright (C) 2009 XStream Committers.
* All rights reserved.
*
* Created on 15. August 2009 by Joerg Schaible
*/
package com.thoughtworks.xstream.io.xml;
/**
* A XmlFriendlyNameCoder to support backward compatibility with XStream 1.1.
*
* @author Jörg Schaible
* @since upcoming
*/
public class XStream11NameCoder extends XmlFriendlyNameCoder {
/**
* {@inheritDoc} Noop implementation that does not decode. Used for XStream 1.1
* compatibility.
*/
public String decodeAttribute(String attributeName) {
return attributeName;
}
/**
* {@inheritDoc} Noop implementation that does not decode. Used for XStream 1.1
* compatibility.
*/
public String decodeNode(String elementName) {
return elementName;
}
}
|
Fix error from unchanged name | var util = require("./util");
var colorify = util.colorify;
var argsToString = util.argsToString
module.exports = new Olg;
function Olg () {}
// log to server
Olg.prototype.log = function(){
// get call stack
var callStack = new Error().stack;
// use knowledge that second call in stack is where wog.log was invoked
callStack = callStack.split("\n");
var callIndex = 2
var callFrame = callStack[callIndex];
var callInfoIndex = callFrame.indexOf("(");
var callInfo = callFrame.slice(callInfoIndex+1);
// split the call info by colons
var details = callInfo.split(":");
// first element will be the file
var callerFile = details[0];
// second will be the line number
var lineNum = details[1];
// pass arguments to converter to be treated as same array-like object
var output = argsToString.apply(this, arguments);
// trim callerFile of user's home path
var home = process.env.HOME || '';
if (home) {
callerFile = callerFile.replace(home, "~");
}
// color
callerFile = colorify(callerFile, "teal");
lineNum = colorify(lineNum, "purple");
// smart log
console.log(output + " ---logged from " + callerFile + " at line " + lineNum);
}
| var util = require("./util");
var colorify = util.colorify;
var argsToString = util.argsToString
module.exports = new Wog;
function Olg () {}
// log to server
Olg.prototype.log = function(){
// get call stack
var callStack = new Error().stack;
// use knowledge that second call in stack is where wog.log was invoked
callStack = callStack.split("\n");
var callIndex = 2
var callFrame = callStack[callIndex];
var callInfoIndex = callFrame.indexOf("(");
var callInfo = callFrame.slice(callInfoIndex+1);
// split the call info by colons
var details = callInfo.split(":");
// first element will be the file
var callerFile = details[0];
// second will be the line number
var lineNum = details[1];
// pass arguments to converter to be treated as same array-like object
var output = argsToString.apply(this, arguments);
// trim callerFile of user's home path
var home = process.env.HOME || '';
if (home) {
callerFile = callerFile.replace(home, "~");
}
// color
callerFile = colorify(callerFile, "teal");
lineNum = colorify(lineNum, "purple");
// smart log
console.log(output + " ---logged from " + callerFile + " at line " + lineNum);
}
|
Remove `destroy` method which is already inherited from extended interface | /*
* #%L
* mosaic-cloudlets
* %%
* Copyright (C) 2010 - 2012 Institute e-Austria Timisoara (Romania)
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package eu.mosaic_cloud.cloudlets.connectors.core;
import eu.mosaic_cloud.tools.callbacks.core.CallbackCompletion;
import eu.mosaic_cloud.tools.callbacks.core.Callbacks;
/**
* Interface for all resource accessors used by cloudlets.
*
* @author Georgiana Macariu
*
* @param <C>
* the type of the cloudlet context
*/
public interface IConnector<C> extends eu.mosaic_cloud.connectors.core.IConnector {
/**
* Returns the current status of the accessor.
*
* @return the current status of the accessor
*/
// !!!!
// ConnectorStatus getStatus();
}
| /*
* #%L
* mosaic-cloudlets
* %%
* Copyright (C) 2010 - 2012 Institute e-Austria Timisoara (Romania)
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package eu.mosaic_cloud.cloudlets.connectors.core;
import eu.mosaic_cloud.tools.callbacks.core.CallbackCompletion;
import eu.mosaic_cloud.tools.callbacks.core.Callbacks;
/**
* Interface for all resource accessors used by cloudlets.
*
* @author Georgiana Macariu
*
* @param <C>
* the type of the cloudlet context
*/
public interface IConnector<C> extends eu.mosaic_cloud.connectors.core.IConnector {
/**
* Destroys the accessor.
*/
CallbackCompletion<Void> destroy();
/**
* Returns the current status of the accessor.
*
* @return the current status of the accessor
*/
// !!!!
// ConnectorStatus getStatus();
}
|
Add Multiple Strings Example for Console and Scanner prototype | /**
* @file TreeStory.java
* @author Valery Samovich
* @version 1
* @date 2015/05/11
*/
package com.samovich.basics.concepts.strings.treehouse;
import java.io.Console;
import java.util.Scanner;
public class TreeStory {
public static void main(String[] args) {
// Console console = System.console();
// String name = console.readLine("Enter your name: ");
// String adjective = console.readLine("Enter an adjective: ");
// console.printf("%s is very %s", name, adjective);
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Enter an adjective: ");
String adjective = scanner.nextLine();
System.out.println(name + " is very " + adjective + "!");
}
}
| /**
* @file TreeStory.java
* @author Valery Samovich
* @version 1
* @date 2015/05/11
*/
package com.samovich.basics.concepts.strings.treehouse;
import java.io.Console;
import java.util.Scanner;
public class TreeStory {
public static void main(String[] args) {
// Console console = System.console();
// String name = console.readLine("Enter your name: ");
// String adjective = console.readLine("Enter an adjective: ");
// console.printf("%s is very %s", name, adjective);
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Enter an adjective: ");
String adjective = scanner.nextLine();
System.out.println(name + " is very " + adjective + "!");
}
}
|
Update wiki to be a little more flexible with naming | # -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
from django.conf.urls.defaults import *
patterns = patterns('eforge.wiki.views',
url(r'^(?P<name>[\w]+)$', 'wiki_page', name='wiki-page'),
url(r'^$', 'wiki_page', name='wiki-home'),
) | # -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
from django.conf.urls.defaults import *
patterns = patterns('eforge.wiki.views',
url(r'^(?P<name>[a-zA-Z_/ ]+)$', 'wiki_page', name='wiki-page'),
url(r'^$', 'wiki_page', name='wiki-home'),
) |
Reduce logger from ERROR to WARN for Validators - we can receive invalid blocks and this doesn't mean program malfunction | package org.ethereum.validator;
import org.slf4j.Logger;
import java.util.LinkedList;
import java.util.List;
/**
* Holds errors list to share between all rules
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public abstract class AbstractValidationRule implements ValidationRule {
protected List<String> errors = new LinkedList<>();
@Override
public List<String> getErrors() {
return errors;
}
public void logErrors(Logger logger) {
if (logger.isErrorEnabled())
for (String msg : errors) {
logger.warn("{} invalid: {}", getEntityClass().getSimpleName(), msg);
}
}
abstract public Class getEntityClass();
}
| package org.ethereum.validator;
import org.slf4j.Logger;
import java.util.LinkedList;
import java.util.List;
/**
* Holds errors list to share between all rules
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public abstract class AbstractValidationRule implements ValidationRule {
protected List<String> errors = new LinkedList<>();
@Override
public List<String> getErrors() {
return errors;
}
public void logErrors(Logger logger) {
if (logger.isErrorEnabled())
for (String msg : errors) {
logger.error("{} invalid: {}", getEntityClass().getSimpleName(), msg);
}
}
abstract public Class getEntityClass();
}
|
Add comments for cash input. | importScripts('/js/sha256.js');
onmessage = function(e) {
console.log('received work!');
var date = (new Date()).yyyymmdd();
var bits = 0;
var rand = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
var name = e.data[0];
var difficulty = e.data[1];
for (var counter = 0; bits < difficulty; counter++) {
var chunks = [
'2', // Hashcash version number. Note that this is 2, as opposed to 1.
difficulty, // asserted number of bits that this cash matches
'sha256', // ADDITION FOR VERSION 2: specify the hash function used
date, // YYYYMMDD format. specification doesn't indicate HHMMSS or lower?
name, // Input format protocol change, recommend casting any input to hex.
'', // empty "meta" field
rand, // random seed
counter // our randomized input, the nonce (actually sequential)
];
var cash = chunks.join(':');
hash = CryptoJS.SHA256(cash).toString();
var match = hash.match(/^(0+)/);
bits = (match) ? match[0].length : 0;
}
postMessage(cash);
close();
}
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + (mm[1]?mm:'0'+mm[0]) + (dd[1]?dd:'0'+dd[0]); // padding
};
| importScripts('/js/sha256.js');
onmessage = function(e) {
console.log('received work!');
var date = (new Date()).yyyymmdd();
var bits = 0;
var rand = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
var name = e.data[0];
var difficulty = e.data[1];
for (var counter = 0; bits < difficulty; counter++) {
var chunks = [
'2', difficulty , 'sha256', date, name, '', rand, counter
];
var cash = chunks.join(':');
hash = CryptoJS.SHA256(cash).toString();
var match = hash.match(/^(0+)/);
bits = (match) ? match[0].length : 0;
}
postMessage(cash);
close();
}
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + (mm[1]?mm:'0'+mm[0]) + (dd[1]?dd:'0'+dd[0]); // padding
};
|
Add utility function to get the robot that a given user currently has booked out (or None). | from datetime import datetime
from .exceptions import ClientError
from .models import Booking, RobotTerminal
def get_robot_terminal_or_error(robot_id, user):
# Check if the user is logged in
if not user.is_authenticated():
raise ClientError("USER_HAS_TO_LOGIN")
# get the robot_terminal with the given id
try:
robot = RobotTerminal.objects.get(pk=robot_id)
except RobotTerminal.DoesNotExist:
raise ClientError("ROBOT_INVALID")
# Check permissions
now = datetime.now()
has_booking = len(Booking.objects.filter(user=user, start_time__lte=now, end_time__gte=now)) > 0
if not (user.is_staff or has_booking):
raise ClientError("ROBOT_ACCESS_DENIED")
return robot
def get_booked_robot(user):
now = datetime.now()
has_booking = len(Booking.objects.filter(user=user, start_time__lte=now, end_time__gte=now)) > 0
if has_booking or user.is_staff:
# TODO: To support multiple robots, we will need to pull in the robot_id from the booking
return RobotTerminal.objects.first()
| from datetime import datetime
from .exceptions import ClientError
from .models import Booking, RobotTerminal
def get_robot_terminal_or_error(robot_id, user):
# Check if the user is logged in
if not user.is_authenticated():
raise ClientError("USER_HAS_TO_LOGIN")
# get the robot_terminal with the given id
try:
robot = RobotTerminal.objects.get(pk=robot_id)
except RobotTerminal.DoesNotExist:
raise ClientError("ROBOT_INVALID")
# Check permissions
now = datetime.now()
has_booking = len(Booking.objects.filter(user=user, start_time__lte=now, end_time__gte=now)) > 0
if not (user.is_staff or has_booking):
raise ClientError("ROBOT_ACCESS_DENIED")
return robot
|
Insert jobs in a single statement
While writing code we should always ask ourselves: "Is there a better way to do
this? Do we really needed replication?" A quick look at MongoDB's documentation
I found out that MongoDB allows to insert an array of elements. | Jobs = new Mongo.Collection('jobs'); //both on client and server
Applications = new Mongo.Collection('applications');
// added repoz channel
Meteor.startup(function() {
// console.log('Jobs.remove({})');
// Jobs.remove({});
var jobCount = Jobs.find().count();
if (jobCount === 0) {
console.log('job count === ', jobCount, 'inserting jobs');
Jobs.insert([
{title: 'Select a job position...'},
{title: 'Haiti Village Photographer'},
{title: 'Rapallo On The Beach'}
]);
} else {
console.log('server/getreel.js:', 'job count > 0 (', jobCount, '): no insert needed');
}
});
Meteor.methods({
apply: function(args) {
if (!Meteor.userId()) {
throw new Meteor.Error('not-authorized');
}
console.log(args);
Applications.insert({
createdAt: new Date(),
applicant: Meteor.userId(),
firstname: args.firstname,
lastname: args.lastname,
job: args.job,
resume: args.resume,
videofile: args.videofile,
videolink: args.videolink
});
}
});
| Jobs = new Mongo.Collection('jobs'); //both on client and server
Applications = new Mongo.Collection('applications');
// added repoz channel
Meteor.startup(function() {
// console.log('Jobs.remove({})');
// Jobs.remove({});
var jobCount = Jobs.find().count();
if (jobCount === 0) {
console.log('job count === ', jobCount, 'inserting jobs');
Jobs.insert({title: 'Select a job position...'});
Jobs.insert({title: 'Haiti Village Photographer'});
Jobs.insert({title: 'Rapallo On The Beach'});
} else {
console.log('server/getreel.js:', 'job count > 0 (', jobCount, '): no insert needed');
}
});
Meteor.methods({
apply: function(args) {
if (!Meteor.userId()) {
throw new Meteor.Error('not-authorized');
}
console.log(args);
Applications.insert({
createdAt: new Date(),
applicant: Meteor.userId(),
firstname: args.firstname,
lastname: args.lastname,
job: args.job,
resume: args.resume,
videofile: args.videofile,
videolink: args.videolink
});
}
});
|
Add helper to remove all sessions | <?php
namespace eien\Helpers;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class Session
{
/**
* @return mixed
*/
public function getCurrentUserSessions()
{
return DB::table('sessions')
->where('user_id', Auth::user()->id)
->get();
}
public function lastSeen($sessionId)
{
$last_activity = DB::table('sessions')
->where('id', $sessionId)
->value('last_activity');
return $diff = Carbon::createFromTimestamp($last_activity)
->diffForHumans();
}
public function removeSession($sessionId)
{
DB::table('sessions')
->where('id', $sessionId)
->delete();
}
public function removeAllSessions($userId)
{
DB::table('sessions')
->where('user_id', $userId)
->delete();
}
} | <?php
namespace eien\Helpers;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class Session
{
/**
* @return mixed
*/
public function getCurrentUserSessions()
{
return DB::table('sessions')
->where('user_id', Auth::user()->id)
->get();
}
public function lastSeen($sessionId)
{
$last_activity = DB::table('sessions')
->where('id', $sessionId)
->value('last_activity');
return $diff = Carbon::createFromTimestamp($last_activity)
->diffForHumans();
}
public function removeSession($sessionId)
{
DB::table('sessions')
->where('id', $sessionId)
->delete();
}
} |
Fix mdk runtime to encode/decode file contents | import os
import tempfile
"""
TODO: This is all semi-broken since in Python quark.String is not Unicode
all the time.
"""
__all__ = ["_mdk_mktempdir", "_mdk_writefile", "_mdk_deletefile",
"_mdk_file_contents", "_mdk_readfile"]
def _mdk_mktempdir():
"""Create temporary directory."""
return tempfile.mkdtemp()
def _mdk_writefile(path, contents):
"""Write a file to disk."""
with open(path, "wb") as f:
f.write(contents.encode("utf-8"))
def _mdk_readfile(path):
"""Read a file's contents."""
with open(path, "r") as f:
return f.read().decode("utf-8")
def _mdk_deletefile(path):
"""Delete a file."""
os.remove(path)
def _mdk_file_contents(path):
"""List contents of directory, or just the file if it's a file."""
if os.path.isdir(path):
return [os.path.join(path, name) for name in os.listdir(path)]
else:
return [path]
| import os
import tempfile
"""
TODO: This is all semi-broken since in Python quark.String is not Unicode
all the time.
"""
__all__ = ["_mdk_mktempdir", "_mdk_writefile", "_mdk_deletefile",
"_mdk_file_contents", "_mdk_readfile"]
def _mdk_mktempdir():
"""Create temporary directory."""
return tempfile.mkdtemp()
def _mdk_writefile(path, contents):
"""Write a file to disk."""
with open(path, "wb") as f:
f.write(contents)
def _mdk_readfile(path):
"""Read a file's contents."""
with open(path, "rb") as f:
return f.read()
def _mdk_deletefile(path):
"""Delete a file."""
os.remove(path)
def _mdk_file_contents(path):
"""List contents of directory, or just the file if it's a file."""
if os.path.isdir(path):
return [os.path.join(path, name) for name in os.listdir(path)]
else:
return [path]
|
Extend cd context manager to decorator. |
import os
import subprocess
from contextlib import ContextDecorator
class cd(ContextDecorator):
"""Context manager/decorator for changing the current working directory."""
def __init__(self, new_path):
self.new_path = os.path.expanduser(new_path)
def __enter__(self):
self.previous_path = os.getcwd()
os.chdir(self.new_path)
return self
def __exit__(self, *exc):
os.chdir(self.previous_path)
return False
# TODO use same context for all methods
class git:
"""Minimal git wrapper, providing only funtions to init add and commit."""
path = ''
def __init__(self, path):
assert os.path.isabs(path)
self.path = path
@cd(path)
def init(self):
print('current dir: {}'.format(os.getcwd()))
subprocess.call('git init')
def add(self, filenames):
for filename in filenames:
assert os.path.isfile(filename) # needs entire path
subprocess.call('git add ' + filename)
def commit(self, date, message=''):
subprocess.call(
"git commit -m '{m}' --date {d}".format(m=message, d=date)
)
|
import os
import subprocess
class cd:
"""Context manager for changing the current working directory."""
def __init__(self, new_path):
self.new_path = os.path.expanduser(new_path)
def __enter__(self):
self.previous_path = os.getcwd()
os.chdir(self.new_path)
def __exit__(self, etype, value, traceback):
os.chdir(self.previous_path)
# TODO use same context for all methods
class git:
"""Minimal git wrapper, providing only funtions to init add and commit."""
def __init__(self, path):
assert os.path.isabs(path)
self.path = path
def init(self):
with cd(self.path):
subprocess.call('git init')
def add(self, filenames):
for filename in filenames:
assert os.path.isfile(filename) # needs entire path
subprocess.call('git add ' + filename)
def commit(self, date, message=''):
subprocess.call(
"git commit -m '{m}' --date {d}".format(m=message, d=date)
)
|
Allow access to dev env from anywhere | <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1')) || php_sapi_name() === 'cli-server')
) {
//header('HTTP/1.0 403 Forbidden');
//exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
| <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1')) || php_sapi_name() === 'cli-server')
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
Fix broken function reference in Chai helper | "use strict";
const Chai = require("chai");
const {util} = Chai;
let overwritten, unindentPattern;
/**
* Strip leading tabulation from string blocks when running "equal" method.
*
* Enables use of ES6 template strings like triple-quoted strings (Python/CoffeeScript).
*
* @param {Number} columns - Number of leading tabs to strip from each line
* @param {String} char - What defines a "tab". Defaults to a hard tab.
*/
Chai.unindent = function(columns, char = "\t"){
/** If Chai.unindent hasn't been run yet, overwrite the necessary methods */
if(!overwritten){
overwritten = true;
for(const method of ["equal", "string"]){
Chai.Assertion.overwriteMethod(method, function(__super){
return function(input, ...rest){
let obj = util.flag(this, "object");
if("[object String]" === Object.prototype.toString.call(input)){
const trimmed = input.replace(unindentPattern, "");
__super.apply(this, [trimmed, ...rest]);
}
else __super.apply(this, arguments);
}
});
}
}
unindentPattern = columns
? new RegExp("^(?:"+char+"){0,"+columns+"}", "gm")
: null;
};
| "use strict";
const Chai = require("chai");
const {util} = Chai;
let overwritten, unindentPattern;
/**
* Strip leading tabulation from string blocks when running "equal" method.
*
* Enables use of ES6 template strings like triple-quoted strings (Python/CoffeeScript).
*
* @param {Number} columns - Number of leading tabs to strip from each line
* @param {String} char - What defines a "tab". Defaults to a hard tab.
*/
Chai.unindent = function(columns, char = "\t"){
/** If Chai.unindent hasn't been run yet, overwrite the necessary methods */
if(!overwritten){
overwritten = true;
for(const method of ["equal", "string"]){
Chai.Assertion.overwriteMethod(method, function(__super){
return function(input, ...rest){
let obj = util.flag(this, "object");
if("[object String]" === Object.prototype.call(input)){
const trimmed = input.replace(unindentPattern, "");
__super.apply(this, [trimmed, ...rest]);
}
else __super.apply(this, arguments);
}
});
}
}
unindentPattern = columns
? new RegExp("^(?:"+char+"){0,"+columns+"}", "gm")
: null;
};
|
Add method onShow(boolean) to LayoutPanelbased page. It indicates the first show of the page.
git-svn-id: 1119f77b1e9a9b65230954af94f4d37570a443ef@918 7ef67a20-634e-90e6-9ab5-3f2075439470 | package com.inepex.ineFrame.client.page;
import java.util.Map;
import org.apache.tools.ant.taskdefs.condition.IsFileSelected;
import com.google.gwt.user.client.ui.Widget;
import com.inepex.ineFrame.client.misc.HandlerAwareLayoutPanel;
import com.inepex.ineFrame.client.navigation.InePlace;
public class LayoutPanelBasedPage extends HandlerAwareLayoutPanel implements InePage{
protected InePlace currentPlace;
protected Boolean isFirstShow = true;
public LayoutPanelBasedPage() {}
@Override
public void setCurrentPlace(InePlace place) {
this.currentPlace = place;
}
@Override
public void setUrlParameters(Map<String, String> urlParams,
UrlParamsParsedCallback callback) throws Exception {
callback.onUrlParamsParsed();
}
@Override
public void onShow() {
if(isFirstShow){
isFirstShow = false;
onShow(true);
}else{
onShow(false);
}
}
@Override
public Widget asWidget() {
return this;
}
public InePlace getCurrentPlace() {
return currentPlace;
}
public void onShow(boolean isfirstShow){
}
}
| package com.inepex.ineFrame.client.page;
import java.util.Map;
import com.google.gwt.user.client.ui.Widget;
import com.inepex.ineFrame.client.misc.HandlerAwareLayoutPanel;
import com.inepex.ineFrame.client.navigation.InePlace;
public class LayoutPanelBasedPage extends HandlerAwareLayoutPanel implements InePage{
protected InePlace currentPlace;
public LayoutPanelBasedPage() {}
@Override
public void setCurrentPlace(InePlace place) {
this.currentPlace = place;
}
@Override
public void setUrlParameters(Map<String, String> urlParams,
UrlParamsParsedCallback callback) throws Exception {
callback.onUrlParamsParsed();
}
@Override
public void onShow() {
// TODO Auto-generated method stub
}
@Override
public Widget asWidget() {
return this;
}
public InePlace getCurrentPlace() {
return currentPlace;
}
}
|
Allow all origins by default | <?php
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS Defaults
|--------------------------------------------------------------------------
|
| The defaults are the default values applied to all the paths that match,
| unless overridden in a specific URL configuration.
| If you want them to apply to everything, you must define a path with *.
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to ['*']
| to accept any value, the allowed methods however have to be explicitly listed.
|
*/
'defaults' => [
'supportsCredentials' => true,
'allowedOrigins' => ['*'],
'allowedHeaders' => [],
'allowedMethods' => [],
'exposedHeaders' => [],
'maxAge' => 0,
'hosts' => [],
],
'paths' => [
'api/v1/*' => [
'allowedOrigins' => [],
'allowedHeaders' => ['X-Cachet-Token'],
'allowedMethods' => ['*'],
'maxAge' => 3600,
],
],
];
| <?php
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS Defaults
|--------------------------------------------------------------------------
|
| The defaults are the default values applied to all the paths that match,
| unless overridden in a specific URL configuration.
| If you want them to apply to everything, you must define a path with *.
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to ['*']
| to accept any value, the allowed methods however have to be explicitly listed.
|
*/
'defaults' => [
'supportsCredentials' => true,
'allowedOrigins' => [],
'allowedHeaders' => [],
'allowedMethods' => [],
'exposedHeaders' => [],
'maxAge' => 0,
'hosts' => [],
],
'paths' => [
'api/v1/*' => [
'allowedOrigins' => [],
'allowedHeaders' => ['X-Cachet-Token'],
'allowedMethods' => ['*'],
'maxAge' => 3600,
],
],
];
|
Make the sever.js work with zombie 2 | var net = require('net');
var Browser = require('zombie');
// Defaults
var ping = 'pong'
var browser = null;
var ELEMENTS = [];
//
// Store global client states indexed by ZombieProxyClient (memory address):
//
// {
// 'CLIENTID': [X, Y]
// }
//
// ...where X is some zombie.Browser instance...
//
// ...and Y is a per-browser cache (a list) used to store NodeList results.
// Subsequent TCP API calls will reference indexes to retrieve DOM
// attributes/properties accumulated in previous browser.querySelectorAll()
// calls.
//
//
var CLIENTS = {};
//
// Simple proxy server implementation
// for proxying streamed (Javascript) content via HTTP
// to a running Zombie.js
//
// Borrowed (heavily) from the Capybara-Zombie project
// https://github.com/plataformatec/capybara-zombie
//
//
function ctx_switch(id){
if(!CLIENTS[id])
CLIENTS[id] = [new Browser(), []];
return CLIENTS[id];
}
net.createServer(function (stream){
stream.setEncoding('utf8');
stream.on('data', function (data){
eval(data);
});
}).listen(process.argv[2], function(){
console.log('Zombie.js server running on ' + process.argv[2] + '...');
});
| var net = require('net');
var zombie = require('zombie');
// Defaults
var ping = 'pong'
var browser = null;
var ELEMENTS = [];
//
// Store global client states indexed by ZombieProxyClient (memory address):
//
// {
// 'CLIENTID': [X, Y]
// }
//
// ...where X is some zombie.Browser instance...
//
// ...and Y is a per-browser cache (a list) used to store NodeList results.
// Subsequent TCP API calls will reference indexes to retrieve DOM
// attributes/properties accumulated in previous browser.querySelectorAll()
// calls.
//
//
var CLIENTS = {};
//
// Simple proxy server implementation
// for proxying streamed (Javascript) content via HTTP
// to a running Zombie.js
//
// Borrowed (heavily) from the Capybara-Zombie project
// https://github.com/plataformatec/capybara-zombie
//
//
function ctx_switch(id){
if(!CLIENTS[id])
CLIENTS[id] = [new zombie.Browser(), []];
return CLIENTS[id];
}
net.createServer(function (stream){
stream.setEncoding('utf8');
stream.on('data', function (data){
eval(data);
});
}).listen(process.argv[2], function(){
console.log('Zombie.js server running on ' + process.argv[2] + '...');
});
|
SAML2: Support metadata overrides of SingleLogoutService for IdP initiated SLO. | <?php
require_once('../../../www/_include.php');
$config = SimpleSAML_Configuration::getInstance();
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$session = SimpleSAML_Session::getInstance();
SimpleSAML_Logger::info('SAML2.0 - IdP.initSLO: Accessing SAML 2.0 IdP endpoint init Single Logout');
if (!$config->getValue('enable.saml20-idp', false)) {
SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOACCESS');
}
if (!isset($_GET['RelayState'])) {
SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NORELAYSTATE');
}
$returnTo = $_GET['RelayState'];
$slo = $metadata->getGenerated('SingleLogoutService', 'saml20-idp-hosted');
/* We turn processing over to the SingleLogoutService script. */
SimpleSAML_Utilities::redirect($slo, array('ReturnTo' => $returnTo));
?> | <?php
require_once('../../../www/_include.php');
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getInstance();
SimpleSAML_Logger::info('SAML2.0 - IdP.initSLO: Accessing SAML 2.0 IdP endpoint init Single Logout');
if (!$config->getValue('enable.saml20-idp', false)) {
SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOACCESS');
}
if (!isset($_GET['RelayState'])) {
SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NORELAYSTATE');
}
$returnTo = $_GET['RelayState'];
/* We turn processing over to the SingleLogoutService script. */
SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'saml2/idp/SingleLogoutService.php',
array('ReturnTo' => $returnTo));
?> |
WebRTC: Make trybots use HEAD instead of LKGR
It's about time we make this change, which turned out
to be very simple.
Review URL: https://codereview.chromium.org/776233003
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@293261 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class WebRTCTryServer(Master.Master4):
project_name = 'WebRTC Try Server'
master_port = 8070
slave_port = 8170
master_port_alt = 8270
try_job_port = 8370
from_address = 'tryserver@webrtc.org'
reply_to = 'chrome-troopers+tryserver@google.com'
svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try-webrtc'
base_app_url = 'https://webrtc-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
last_good_url = None
code_review_site = 'https://webrtc-codereview.appspot.com'
buildbot_url = 'http://build.chromium.org/p/tryserver.webrtc/'
| # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class WebRTCTryServer(Master.Master4):
project_name = 'WebRTC Try Server'
master_port = 8070
slave_port = 8170
master_port_alt = 8270
try_job_port = 8370
from_address = 'tryserver@webrtc.org'
reply_to = 'chrome-troopers+tryserver@google.com'
svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try-webrtc'
base_app_url = 'https://webrtc-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
last_good_url = base_app_url + '/lkgr'
code_review_site = 'https://webrtc-codereview.appspot.com'
buildbot_url = 'http://build.chromium.org/p/tryserver.webrtc/'
|
Allow multiple tensorflow instances in js |
import { NativeModules } from 'react-native';
const { RNTensorflow } = NativeModules;
class Tensorflow {
static initWithModel(modelFileName, cb) {
tensorflow = new Tensorflow(modelFileName)
cb(tensorflow)
tensorflow.close()
}
constructor(modelFileName) {
super()
RNTensorflow.initTensorflow(modelFileName)
}
feedWithDims(inputName, src, dims) {
RNTensorflow.feed(inputName, src, dims);
}
feed(inputName, src) {
RNTensorflow.feed(inputName, src);
}
run(outputNames) {
RNTensorflow.run(outputNames);
}
runWithStats(outputNames) {
RNTensorflow.run(outputNames, true);
}
fetch(outputName, outputSize) {
return RNTensorflow.fetch(outputName, dst);
}
graph() {
return RNTensorflow.graph();
}
stats() {
return RNTensorflow.stats();
}
close() {
RNTensorflow.close();
}
}
export default Tensorflow;
|
import { NativeModules } from 'react-native';
const { RNTensorflow } = NativeModules;
class Tensorflow {
initWithModel(modelFileName) {
RNTensorflow.initTensorflow(modelFileName)
}
feedWithDims(inputName, src, dims) {
RNTensorflow.feed(inputName, src, dims);
}
feed(inputName, src) {
RNTensorflow.feed(inputName, src);
}
run(outputNames) {
RNTensorflow.run(outputNames);
}
runWithStats(outputNames) {
RNTensorflow.run(outputNames, true);
}
fetch(outputName, outputSize) {
return RNTensorflow.fetch(outputName, dst);
}
graph() {
return RNTensorflow.graph();
}
graphOperation(operationName) {
return RNTensorflow.graphOperation(operationName);
}
stats() {
return RNTensorflow.stats();
}
close() {
RNTensorflow.close();
}
}
export default new Tensorflow();
|
Add type hints to addListener and removeListener | <?php
namespace Glitch\Interpreter;
class EventValue
{
private $listeners = array();
public function addListener(EventValue $listener)
{
$this->listeners[] = $listener;
}
public function removeListener(EventValue $listener)
{
$listeners = array();
foreach ($this->listeners as $listener) {
if ($listener !== $listener) {
$listeners[] = $listener;
}
}
$this->listeners = $listeners;
}
public function fire($value)
{
foreach ($this->listeners as $listener) {
$listener->fire($value);
}
}
}
| <?php
namespace Glitch\Interpreter;
class EventValue
{
private $listeners = array();
public function addListener($listener)
{
$this->listeners[] = $listener;
}
public function removeListener($listener)
{
$listeners = array();
foreach ($this->listeners as $listener) {
if ($listener !== $listener) {
$listeners[] = $listener;
}
}
$this->listeners = $listeners;
}
public function fire($value)
{
foreach ($this->listeners as $listener) {
$listener->fire($value);
}
}
}
|
Add test for regular function loopers | import Ember from 'ember';
import { csp, channel, looper } from 'ember-processes';
module('Unit: Loopers');
function testLooper(testName, makeHandler) {
test('loopers take a channel name (' + testName + ')', function(assert) {
QUnit.stop();
assert.expect(3);
let outch = csp.chan();
let MyObject = Ember.Object.extend({
myChannel: channel(),
doStuff: looper('myChannel', makeHandler(outch)),
});
let obj;
Ember.run(() => {
obj = MyObject.create();
let chan = obj.get('myChannel');
csp.putAsync(chan, 1);
csp.putAsync(chan, 2);
csp.putAsync(chan, 3);
});
csp.go(function * () {
assert.equal(yield outch, 1);
assert.equal(yield outch, 2);
assert.equal(yield outch, 3);
QUnit.start();
});
Ember.run(obj, 'destroy');
});
}
testLooper("generator", function(outch) {
return function * (value) {
yield csp.put(outch, value);
};
});
testLooper("regular function", function(outch) {
return function(value) {
csp.putAsync(outch, value);
};
});
| import Ember from 'ember';
import { csp, channel, looper } from 'ember-processes';
module('Unit: Loopers');
test('loopers take a channel name', function(assert) {
QUnit.stop();
assert.expect(3);
let outch = csp.chan();
let MyObject = Ember.Object.extend({
myChannel: channel(),
doStuff: looper('myChannel', function * (value) {
yield csp.putAsync(outch, value);
}),
});
let obj;
Ember.run(() => {
obj = MyObject.create();
let chan = obj.get('myChannel');
csp.putAsync(chan, 1);
csp.putAsync(chan, 2);
csp.putAsync(chan, 3);
});
csp.go(function * () {
assert.equal(yield outch, 1);
assert.equal(yield outch, 2);
assert.equal(yield outch, 3);
QUnit.start();
});
Ember.run(obj, 'destroy');
});
|
Update getHashidConnection to use getTable
If $table is not set on the model then we get the error
```InvalidArgumentException with message 'Connection [table.] not configured.'```
by using ```$model->getTable()``` will get a default from the model rather than just having a blank value. | <?php namespace Naabster\EloquentHashids;
use Illuminate\Database\Eloquent\Model;
use Vinkla\Hashids\Facades\Hashids;
/**
* Class EloquentHashids
*
* @package Naabster\EloquentHashids
*/
trait EloquentHashids
{
/**
* Boot Eloquent Hashids trait for the model.
*
* @return void
*/
public static function bootEloquentHashids()
{
static::created(function (Model $model)
{
$model->{static::getHashidColumn($model)} = Hashids::connection(static::getHashidConnection($model))->encode(static::getHashidEncodingValue($model));
$model->save();
});
}
/**
* @param Model $model
* @return string
*/
public static function getHashidConnection(Model $model)
{
return 'table.' . $model->getTable();
}
/**
* @param Model $model
* @return string
*/
public static function getHashidColumn(Model $model)
{
return 'uid';
}
/**
* @param Model $model
* @return mixed
*/
public static function getHashidEncodingValue(Model $model)
{
return $model->getKey();
}
}
| <?php namespace Naabster\EloquentHashids;
use Illuminate\Database\Eloquent\Model;
use Vinkla\Hashids\Facades\Hashids;
/**
* Class EloquentHashids
*
* @package Naabster\EloquentHashids
*/
trait EloquentHashids
{
/**
* Boot Eloquent Hashids trait for the model.
*
* @return void
*/
public static function bootEloquentHashids()
{
static::created(function (Model $model)
{
$model->{static::getHashidColumn($model)} = Hashids::connection(static::getHashidConnection($model))->encode(static::getHashidEncodingValue($model));
$model->save();
});
}
/**
* @param Model $model
* @return string
*/
public static function getHashidConnection(Model $model)
{
return 'table.' . $model->table;
}
/**
* @param Model $model
* @return string
*/
public static function getHashidColumn(Model $model)
{
return 'uid';
}
/**
* @param Model $model
* @return mixed
*/
public static function getHashidEncodingValue(Model $model)
{
return $model->getKey();
}
}
|
Update _data_list structure for charts |
var _data_list = [];
function fetchDataAndRenderContent () {
console.log("fetchDataAndRenderContent first time!");
_data_list = [];
renderCharts();
extractDataAndUpdateContent();
}
function extractDataAndUpdateContent () {
updateFetchProgress(100);
renderGaugeRowItemsWithAnimation(extractGauageRowData());
updateCharts();
updateFetchCounter();
updateFetchProgress(0);
}
function extractGauageRowData () {
if (!_data_list.length) {
fetchMockupData();
}
var _set = _data_list.slice(-1)[0];
var _data = $.extend(true, {}, gauge_data);
$.each(_data, function (index, item) {
item.time = _set[item.id].time;
item.value = _set[item.id].value;
});
return _data;
}
function fetchMockupData () {
var _set = [];
$.each(gauge_data, function (index, item) {
var _item = {};
_item.time = new Date();
_item.value = item.value * (1 + (Math.random() - 0.5) * 0.1);
_set[item.id] = _item;
});
_data_list.push(_set);
}
|
var _data_list = [];
function fetchDataAndRenderContent () {
console.log("fetchDataAndRenderContent first time!");
_data_list = [];
renderCharts();
extractDataAndUpdateContent();
}
function extractDataAndUpdateContent () {
updateFetchProgress(100);
renderGaugeRowItemsWithAnimation(extractGauageRowData());
updateCharts();
updateFetchCounter();
updateFetchProgress(0);
}
function extractGauageRowData () {
if (!_data_list.length) {
fetchMockupData();
}
var _list = _data_list.slice(-1)[0];
var _data = $.extend(true, {}, gauge_data);
$.each(_data, function (index, item) {
item.time = _list[index].time;
item.value = _list[index].value;
});
return _data;
}
function fetchMockupData () {
var _list = [];
$.each(gauge_data, function (index, item) {
var _item = {};
_item.time = new Date();
_item.value = item.value * (1 + (Math.random() - 0.5) * 0.1);
_list.push(_item);
});
_data_list.push(_list);
}
|
[22030] Install missing jbig2-imageio compression format | package ch.elexis.core.pdfbox;
import javax.imageio.spi.IIORegistry;
import javax.imageio.spi.ImageReaderSpi;
import org.apache.pdfbox.jbig2.JBIG2ImageReaderSpi;
import org.apache.pdfbox.jbig2.util.log.LoggerFactory;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
@Override
public void start(BundleContext context) throws Exception{
// PDFBox uses Serviceloader to access the JGIB2 implementation
// we don't have a separate service loader plugin, so we directly
// register within IIORegistry
IIORegistry defaultInstance = IIORegistry.getDefaultInstance();
boolean registerServiceProvider = defaultInstance
.registerServiceProvider(new JBIG2ImageReaderSpi(), ImageReaderSpi.class);
LoggerFactory.getLogger(getClass()).debug("IIORegistry registered "
+ JBIG2ImageReaderSpi.class.getName() + " " + registerServiceProvider);
}
@Override
public void stop(BundleContext context) throws Exception{}
}
| package ch.elexis.core.pdfbox;
import javax.imageio.spi.IIORegistry;
import javax.imageio.spi.ImageReaderSpi;
import org.apache.pdfbox.jbig2.JBIG2ImageReaderSpi;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
@Override
public void start(BundleContext context) throws Exception{
// PDFBox uses Serviceloader to access the JGIB2 implementation
// we don't have a separate service loader plugin, so we d
IIORegistry defaultInstance = IIORegistry.getDefaultInstance();
boolean registerServiceProvider = defaultInstance
.registerServiceProvider(new JBIG2ImageReaderSpi(), ImageReaderSpi.class);
System.out.println("registered " + registerServiceProvider);
}
@Override
public void stop(BundleContext context) throws Exception{}
}
|
core: Load modules in engine context. | import rave.events
import rave.modularity
import rave.backends
import rave.resources
import rave.rendering
def init_game(game):
rave.modularity.load_all()
rave.events.emit('game.init', game)
with game.env:
rave.backends.select_all()
def run_game(game):
running = True
# Stop the event loop when a stop event was caught.
def stop(event):
nonlocal running
running = False
game.events.hook('game.stop', stop)
rave.events.emit('game.start', game)
with game.env:
# Typical handle events -> update game state -> render loop.
while running:
with game.active_lock:
# Suspend main loop while lock is active: useful for when the OS requests an application suspend.
pass
rave.backends.handle_events(game)
if game.mixer:
game.mixer.render(None)
if game.window:
game.window.render(None)
| import rave.events
import rave.modularity
import rave.backends
import rave.resources
import rave.rendering
def init_game(game):
rave.events.emit('game.init', game)
with game.env:
rave.modularity.load_all()
rave.backends.select_all()
def run_game(game):
running = True
# Stop the event loop when a stop event was caught.
def stop(event):
nonlocal running
running = False
game.events.hook('game.stop', stop)
rave.events.emit('game.start', game)
with game.env:
# Typical handle events -> update game state -> render loop.
while running:
with game.active_lock:
# Suspend main loop while lock is active: useful for when the OS requests an application suspend.
pass
rave.backends.handle_events(game)
if game.mixer:
game.mixer.render(None)
if game.window:
game.window.render(None)
|
Fix argument ordering in Mistress of Pain
Fixes #71 | from ..utils import *
##
# Minions
# Mistress of Pain
class GVG_018:
events = [
Damage().on(
lambda self, target, amount, source: source is self and [Heal(FRIENDLY_HERO, amount)] or []
)
]
# Fel Cannon
class GVG_020:
events = [
OWN_TURN_END.on(Hit(RANDOM(ALL_MINIONS - MECH), 2))
]
# Anima Golem
class GVG_077:
events = [
TURN_END.on(
lambda self, player: self.controller.field != [self] and [Destroy(SELF)] or []
)
]
# Floating Watcher
class GVG_100:
events = [
Damage(FRIENDLY_HERO).on(
lambda self, target, amount, source: self.controller.current_player and [Buff(SELF, "GVG_100e")] or []
)
]
##
# Spells
# Darkbomb
class GVG_015:
action = [Hit(TARGET, 3)]
# Demonheart
class GVG_019:
def action(self, target):
if target.controller == self.controller and target.race == Race.DEMON:
return [Buff(TARGET, "GVG_019e")]
else:
return [Hit(TARGET, 5)]
| from ..utils import *
##
# Minions
# Mistress of Pain
class GVG_018:
events = [
Damage().on(
lambda self, source, target, amount: source is self and [Heal(FRIENDLY_HERO, amount)] or []
)
]
# Fel Cannon
class GVG_020:
events = [
OWN_TURN_END.on(Hit(RANDOM(ALL_MINIONS - MECH), 2))
]
# Anima Golem
class GVG_077:
events = [
TURN_END.on(
lambda self, player: self.controller.field != [self] and [Destroy(SELF)] or []
)
]
# Floating Watcher
class GVG_100:
events = [
Damage(FRIENDLY_HERO).on(
lambda self, target, amount, source: self.controller.current_player and [Buff(SELF, "GVG_100e")] or []
)
]
##
# Spells
# Darkbomb
class GVG_015:
action = [Hit(TARGET, 3)]
# Demonheart
class GVG_019:
def action(self, target):
if target.controller == self.controller and target.race == Race.DEMON:
return [Buff(TARGET, "GVG_019e")]
else:
return [Hit(TARGET, 5)]
|
Fix solution to the locks problem. | import sys
def do_lock_pass(locked):
for i in xrange(1, len(locked), 2):
locked[i] = True
def do_flip_pass(locked):
for i in xrange(2, len(locked), 3):
locked[i] = not locked[i]
def count_unlocked(locked):
result = 0
for l in locked:
if not l: result += 1
return result
def main():
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
test = test.strip()
num_locks = int(test.split(' ')[0])
num_iterations = int(test.split(' ')[1])
locked = [False] * num_locks
for i in xrange(num_iterations-1):
do_lock_pass(locked)
do_flip_pass(locked)
locked[-1] = not locked[-1]
print count_unlocked(locked)
test_cases.close()
main()
| import sys
def do_lock_pass(locked):
for i in xrange(0, len(locked), 2):
locked[i] = True
def do_flip_pass(locked):
for i in xrange(0, len(locked), 3):
locked[i] = not locked[i]
def count_unlocked(locked):
result = 0
for l in locked:
if not l: result += 1
return result
def main():
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
test = test.strip()
num_locks = int(test.split(' ')[0])
num_iterations = int(test.split(' ')[1])
locked = [False] * num_locks
for i in xrange(num_iterations-1):
do_lock_pass(locked)
do_flip_pass(locked)
locked[-1] = True
print count_unlocked(locked)
test_cases.close()
main()
|
Fix path to data file | from __future__ import division
import time
import serial
import csv
from datetime import datetime as dt
DEBUG = True
def timestamp():
ts = dt.now()
return time.mktime(ts.timetuple())+(ts.microsecond/1e6)
bufsize = 1 if DEBUG else -1
with open('db/rec.csv', 'wa', bufsize) as f:
writer = csv.writer(f)
with serial.Serial('/dev/ttyACM0', 57600, timeout=1.0) as ser:
# Empty whatever is in the buffer
ser.flushInput()
while ser.inWaiting():
ser.read()
while True:
values = []
for _ in range(50):
line = ser.readline().strip()
try:
values.append(int(line))
except ValueError:
print str(dt.now()), 'NaN:', line
print timestamp(), min(values), max(values)
writer.writerow([timestamp(), min(values), max(values)])
| from __future__ import division
import time
import serial
import csv
from datetime import datetime as dt
DEBUG = True
def timestamp():
ts = dt.now()
return time.mktime(ts.timetuple())+(ts.microsecond/1e6)
bufsize = 1 if DEBUG else -1
with open('rec.csv', 'wa', bufsize) as f:
writer = csv.writer(f)
with serial.Serial('/dev/ttyACM0', 57600, timeout=1.0) as ser:
# Empty whatever is in the buffer
ser.flushInput()
while ser.inWaiting():
ser.read()
while True:
values = []
for _ in range(50):
line = ser.readline().strip()
try:
values.append(int(line))
except ValueError:
print str(dt.now()), 'NaN:', line
print timestamp(), min(values), max(values)
writer.writerow([timestamp(), min(values), max(values)])
|
Break on any amount of whitespace instead of on one space only | var lodash = require('lodash'),
knife = require('../knife'),
Issue = require('../issue');
module.exports = {
name: 'id-class-style',
on: ['attr'],
filter: ['id', 'class']
};
module.exports.lint = function (attr, opts) {
var format = opts[this.name];
if (!format) {
return [];
}
var v = attr.value;
// Breaks if there is an SOH character in your class or id name.
// Don't do that.
var ignore = opts['id-class-ignore-regex'];
if (ignore) { v = v.replace(new RegExp(ignore), '\u0001'); }
var verify = knife.getFormatTest(format);
var cssclasses = v.split(/\s+/);
return lodash.flatten(cssclasses.map(function(c) {
return (c.indexOf('\u0001') !== -1 || verify(c)) ? [] :
new Issue('E011', attr.valueLineCol, { format: format });
}));
};
| var lodash = require('lodash'),
knife = require('../knife'),
Issue = require('../issue');
module.exports = {
name: 'id-class-style',
on: ['attr'],
filter: ['id', 'class']
};
module.exports.lint = function (attr, opts) {
var format = opts[this.name];
if (!format) {
return [];
}
var v = attr.value;
// Breaks if there is an SOH character in your class or id name.
// Don't do that.
var ignore = opts['id-class-ignore-regex'];
if (ignore) { v = v.replace(new RegExp(ignore), '\u0001'); }
var verify = knife.getFormatTest(format);
var cssclasses = v.split(' ');
return lodash.flatten(cssclasses.map(function(c) {
return (c.indexOf('\u0001') !== -1 || verify(c)) ? [] :
new Issue('E011', attr.valueLineCol, { format: format });
}));
};
|
Fix host parameter name for the service check API | __all__ = [
'ServiceCheckApi',
]
import logging
import time
from dogapi.constants import CheckStatus
from dogapi.exceptions import ApiError
logger = logging.getLogger('dd.dogapi')
class ServiceCheckApi(object):
def service_check(self, check, host, status, timestamp=None, message=None, tags=None):
if status not in CheckStatus.ALL:
raise ApiError('Invalid status, expected one of: %s' \
% ', '.join(CheckStatus.ALL))
body = {
'check': check,
'host_name': host,
'timestamp': timestamp or time.time(),
'status': status
}
if message:
body['message'] = message
if tags:
body['tags'] = tags
return self.http_request('POST', '/check_run', body)
| __all__ = [
'ServiceCheckApi',
]
import logging
import time
from dogapi.constants import CheckStatus
from dogapi.exceptions import ApiError
logger = logging.getLogger('dd.dogapi')
class ServiceCheckApi(object):
def service_check(self, check, host, status, timestamp=None, message=None, tags=None):
if status not in CheckStatus.ALL:
raise ApiError('Invalid status, expected one of: %s' \
% ', '.join(CheckStatus.ALL))
body = {
'check': check,
'host': host,
'timestamp': timestamp or time.time(),
'status': status
}
if message:
body['message'] = message
if tags:
body['tags'] = tags
return self.http_request('POST', '/check_run', body)
|
Fix story bug for Tab | import React from 'react'
import { storiesOf } from '@storybook/react'
import { action } from '@storybook/addon-actions'
import Tab from 'components/Tab/Tab'
import DraggableTab from 'components/Tab/DraggableTab'
import Icon from 'components/Tab/Icon'
import windows from '../.storybook/windows'
const tabs = [].concat(...windows.map(x => x.tabs))
const tabProps = () => ({
...tabs[Math.floor(Math.random() * tabs.length)],
dragPreview: action('dragPreview'),
getWindowList: action('getWindowList'),
faked: true
})
storiesOf('Tab', module)
.add('DraggableTab', () => (
<DraggableTab {...tabProps()} />
))
.add('Tab', () => (
<Tab {...tabProps()} />
))
.add('Pinned DraggableTab', () => (
<DraggableTab {...tabProps()} pinned />
))
.add('Pinned Tab', () => (
<Tab {...tabProps()} pinned />
))
const iconStory = storiesOf('Icon', module)
;[
'bookmarks',
'chrome',
'crashes',
'downloads',
'extensions',
'flags',
'history',
'settings'
].map((x) => {
iconStory.add(`Chrome Icon ${x}`, () => (
<Icon {...tabProps()} url={`chrome://${x}`} />
))
})
| import React from 'react'
import { storiesOf } from '@storybook/react'
import { action } from '@storybook/addon-actions'
import Tab from 'components/Tab/Tab'
import DraggableTab from 'components/Tab/DraggableTab'
import Icon from 'components/Tab/Icon'
import store from '../.storybook/mock-store'
const { tabs } = store.windowStore
const tabProps = () => ({
...tabs[Math.floor(Math.random() * tabs.length)],
dragPreview: action('dragPreview'),
getWindowList: action('getWindowList'),
faked: true
})
storiesOf('Tab', module)
.add('DraggableTab', () => (
<DraggableTab {...tabProps()} />
))
.add('Tab', () => (
<Tab {...tabProps()} />
))
.add('Pinned DraggableTab', () => (
<DraggableTab {...tabProps()} pinned />
))
.add('Pinned Tab', () => (
<Tab {...tabProps()} pinned />
))
const iconStory = storiesOf('Icon', module)
;[
'bookmarks',
'chrome',
'crashes',
'downloads',
'extensions',
'flags',
'history',
'settings'
].map((x) => {
iconStory.add(`Chrome Icon ${x}`, () => (
<Icon {...tabProps()} url={`chrome://${x}`} />
))
})
|
Fix some unit test after the implementation allowing grouped rules
without the group definition declared as executable | package com.opnitech.rules.core.test.engine.test_validators;
import org.junit.Test;
import com.opnitech.rules.core.test.engine.AbstractRuleEngineExecutorTest;
import com.opnitech.rules.core.test.engine.test_validators.group.InvalidGroupDefinition;
import com.opnitech.rules.core.test.engine.test_validators.group.ValidGroupDefinition;
import com.opnitech.rules.core.test.engine.test_validators.rules.group.InvalidGroupRule;
import com.opnitech.rules.core.test.engine.test_validators.rules.group.ValidGroupRule;
/**
* @author Rigre Gregorio Garciandia Sonora
*/
public class GroupRuleValidatorTest extends AbstractRuleEngineExecutorTest {
@Test
public void testValidRule() throws Exception {
// Group need to be defined
validateRule(ValidGroupDefinition.class, new ValidGroupRule());
}
@Test
public void testValidRuleButNoGroupDefinition() throws Exception {
// Group need to be defined
validateRule(new ValidGroupRule());
}
@Test
public void testInvalidRuleButNoGroupDefinition() throws Exception {
validateExceptionRule(new InvalidGroupRule());
}
@Test
public void testInvalidRule() throws Exception {
validateExceptionRule(InvalidGroupDefinition.class, new InvalidGroupRule());
}
}
| package com.opnitech.rules.core.test.engine.test_validators;
import org.junit.Test;
import com.opnitech.rules.core.test.engine.AbstractRuleEngineExecutorTest;
import com.opnitech.rules.core.test.engine.test_validators.group.InvalidGroupDefinition;
import com.opnitech.rules.core.test.engine.test_validators.group.ValidGroupDefinition;
import com.opnitech.rules.core.test.engine.test_validators.rules.group.InvalidGroupRule;
import com.opnitech.rules.core.test.engine.test_validators.rules.group.ValidGroupRule;
/**
* @author Rigre Gregorio Garciandia Sonora
*/
public class GroupRuleValidatorTest extends AbstractRuleEngineExecutorTest {
@Test
public void testValidRule() throws Exception {
// Group need to be defined
validateRule(ValidGroupDefinition.class, new ValidGroupRule());
}
@Test
public void testValidRuleButNoGroupDefinition() throws Exception {
// Group need to be defined
validateExceptionRule(new ValidGroupRule());
}
@Test
public void testInvalidRuleButNoGroupDefinition() throws Exception {
validateExceptionRule(new InvalidGroupRule());
}
@Test
public void testInvalidRule() throws Exception {
validateExceptionRule(InvalidGroupDefinition.class, new InvalidGroupRule());
}
}
|
Fix api key call to be renmamed key | # Copyright 2015, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
# law or agreed to in writing, software distributed under the License is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and
# limitations under the License.
import urllib2
import json
from google.appengine.ext import vendor
vendor.add('lib')
from flask import Flask
app = Flask(__name__)
from api_key import key
@app.route('/get_author/<title>')
def get_author(title):
host = 'https://www.googleapis.com/books/v1/volume?q={}&key={}&country=US'.format(title, key)
request = urllib2.Request(host)
response = urllib2.urlopen(request)
html = response.read()
author = json.loads(html)['items'][0]['volumeInfo']['authors'][0]
return author
if __name__ == '__main__':
app.run(debug=True)
| # Copyright 2015, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
# law or agreed to in writing, software distributed under the License is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and
# limitations under the License.
import urllib2
import json
from google.appengine.ext import vendor
vendor.add('lib')
from flask import Flask
app = Flask(__name__)
from api_key import key
@app.route('/get_author/<title>')
def get_author(title):
host = 'https://www.googleapis.com/books/v1/volume?q={}&key={}&country=US'.format(title, api_key)
request = urllib2.Request(host)
response = urllib2.urlopen(request)
html = response.read()
author = json.loads(html)['items'][0]['volumeInfo']['authors'][0]
return author
if __name__ == '__main__':
app.run(debug=True)
|
Use correct FPS display implementation. | import pyglet
from life import WIDTH, HEIGHT, CELL_SIZE, DISPLAY_FPS, FULLSCREEN
from life.creator import Creator
from life.view import Field
creator = Creator(width=WIDTH, height=HEIGHT)
if FULLSCREEN:
window = pyglet.window.Window(fullscreen=True)
cell_size = min(window.width // WIDTH, window.height // HEIGHT)
field = Field(
field_creator=creator,
cell_size=cell_size,
dx=(window.width - WIDTH * cell_size) // 2,
dy=(window.height - HEIGHT * cell_size) // 2)
else:
field = Field(field_creator=creator, cell_size=CELL_SIZE)
window = pyglet.window.Window(width=field.width, height=field.height)
if DISPLAY_FPS:
fps_display = pyglet.window.FPSDisplay(window)
fps_display.update_period = 1.
else:
fps_display = None
@window.event
def on_draw():
window.clear()
field.draw()
if fps_display:
fps_display.draw()
creator.start()
pyglet.app.run()
| import pyglet
from life import WIDTH, HEIGHT, CELL_SIZE, DISPLAY_FPS, FULLSCREEN
from life.creator import Creator
from life.view import Field
creator = Creator(width=WIDTH, height=HEIGHT)
if FULLSCREEN:
window = pyglet.window.Window(fullscreen=True)
cell_size = min(window.width // WIDTH, window.height // HEIGHT)
field = Field(
field_creator=creator,
cell_size=cell_size,
dx=(window.width - WIDTH * cell_size) // 2,
dy=(window.height - HEIGHT * cell_size) // 2)
else:
field = Field(field_creator=creator, cell_size=CELL_SIZE)
window = pyglet.window.Window(width=field.width, height=field.height)
if DISPLAY_FPS:
fps_display = pyglet.clock.ClockDisplay()
else:
fps_display = None
@window.event
def on_draw():
window.clear()
field.draw()
if fps_display:
fps_display.draw()
creator.start()
pyglet.app.run()
|
Test case for loading stream from instance field
git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@2608 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3 | import java.io.*;
public class OpenStream {
public OutputStream os;
public static void main(String[] argv) throws Exception {
FileInputStream in = null;
try {
in = new FileInputStream(argv[0]);
} finally {
// Not guaranteed to be closed here!
if (Boolean.getBoolean("inscrutable"))
in.close();
}
FileInputStream in2 = null;
try {
in2 = new FileInputStream(argv[1]);
} finally {
// This one will be closed
if (in2 != null)
in2.close();
}
// oops! exiting the method without closing the stream
}
public void byteArrayStreamDoNotReport() {
ByteArrayOutputStream b = new ByteArrayOutputStream();
PrintStream out = new PrintStream(b);
out.println("Hello, world!");
}
public void systemInDoNotReport() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println(reader.readLine());
}
public void socketDoNotReport(java.net.Socket socket) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(reader.readLine());
}
public void paramStreamDoNotReport(java.io.OutputStream os) throws IOException {
PrintStream ps = new PrintStream(os);
ps.println("Hello");
}
public void loadFromFieldDoNotReport() throws IOException {
PrintStream ps = new PrintStream(os);
ps.println("Hello");
}
}
// vim:ts=4
| import java.io.*;
public class OpenStream {
public static void main(String[] argv) throws Exception {
FileInputStream in = null;
try {
in = new FileInputStream(argv[0]);
} finally {
// Not guaranteed to be closed here!
if (Boolean.getBoolean("inscrutable"))
in.close();
}
FileInputStream in2 = null;
try {
in2 = new FileInputStream(argv[1]);
} finally {
// This one will be closed
if (in2 != null)
in2.close();
}
// oops! exiting the method without closing the stream
}
public void byteArrayStreamDoNotReport() {
ByteArrayOutputStream b = new ByteArrayOutputStream();
PrintStream out = new PrintStream(b);
out.println("Hello, world!");
}
public void systemInDoNotReport() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println(reader.readLine());
}
public void socketDoNotReport(java.net.Socket socket) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(reader.readLine());
}
public void paramStreamDoNotReport(java.io.OutputStream os) throws IOException {
PrintStream ps = new PrintStream(os);
ps.println("Hello");
}
}
// vim:ts=4
|
Add go doc style comment | package main
import (
"github.com/codegangsta/cli"
"os"
"path"
)
type File struct {
ImdbID string
Format string
FileName string
FullPath string
}
func (f *File) IsValid() bool {
return f.ImdbID != "" && f.Present()
}
// Present checks to see if the file is present on disk.
func (f *File) Present() bool {
return fileExists(f.FullPath)
}
func NewFile(c *cli.Context) File {
var fileName, format, id, fullPath string
if len(c.Args()) == 1 {
fullPath = c.Args()[0]
base := path.Base(fullPath)
format = path.Ext(fullPath)
fileName = base[:len(base)-len(format)]
id = c.String("id")
}
return File{ImdbID: id, FileName: fileName, Format: format, FullPath: fullPath}
}
func fileExists(path string) bool {
exists := false
if _, err := os.Stat(path); err == nil {
exists = true
}
return exists
}
| package main
import (
"github.com/codegangsta/cli"
"os"
"path"
)
type File struct {
ImdbID string
Format string
FileName string
FullPath string
}
func (f *File) IsValid() bool {
return f.ImdbID != "" && f.Present()
}
// Is the file is present on disk
func (f *File) Present() bool {
return fileExists(f.FullPath)
}
func NewFile(c *cli.Context) File {
var fileName, format, id, fullPath string
if len(c.Args()) == 1 {
fullPath = c.Args()[0]
base := path.Base(fullPath)
format = path.Ext(fullPath)
fileName = base[:len(base)-len(format)]
id = c.String("id")
}
return File{ImdbID: id, FileName: fileName, Format: format, FullPath: fullPath}
}
func fileExists(path string) bool {
exists := false
if _, err := os.Stat(path); err == nil {
exists = true
}
return exists
}
|
Use ENV variables for SSH | /* Copyright 2017 Agneta Network Applications, LLC.
*
* Source file: portal/services/boot/git/credentials.js
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const nodegit = require('nodegit');
const Promise = require('bluebird');
module.exports = function(app) {
return Promise.resolve()
.then(function() {
if (!process.env.GIT_PUB || !process.env.GIT_PUB) {
throw new Error('Git must have SSH credentials');
}
var sshPublicKey = process.env.GIT_PUB;
var sshPrivateKey = process.env.GIT_KEY.replace(/\\n/g,'\n');
app.git.credentials = function(url, username) {
return nodegit.Cred.sshKeyMemoryNew(username, sshPublicKey, sshPrivateKey, '');
};
});
};
| /* Copyright 2017 Agneta Network Applications, LLC.
*
* Source file: portal/services/boot/git/credentials.js
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const nodegit = require('nodegit');
const path = require('path');
module.exports = function(app) {
var base_dir = process.cwd();
var sshDir = path.join(base_dir, 'ssh');
var sshPublicKey = path.join(sshDir, 'id_rsa.pub');
var sshPrivateKey = path.join(sshDir, 'id_rsa');
app.git.credentials = function(url, username) {
return nodegit.Cred.sshKeyNew(username, sshPublicKey, sshPrivateKey, '');
};
};
|
:bug: Remove href attribute from link decorator of WysiwygEditor | import React, { useState } from 'react';
import { IconExternalLinkSmallOutline } from '@teamleader/ui-icons';
import Box from '../../box';
import Link from '../../link';
import theme from './theme.css';
const findLinkEntities = (contentBlock, callback, contentState) => {
contentBlock.findEntityRanges((character) => {
const entityKey = character.getEntity();
return entityKey !== null && contentState.getEntity(entityKey).getType() === 'LINK';
}, callback);
};
const LinkEntity = ({ entityKey, contentState, children }) => {
const [showOpenLinkIcon, setShowOpenLinkIcon] = useState();
const { url } = contentState.getEntity(entityKey).getData();
const openLink = () => {
let prefixedUrl = url;
if (!url.includes('//')) {
prefixedUrl = '//' + url;
}
window.open(prefixedUrl, '_blank');
};
const toggleShowOpenLinkIcon = () => {
setShowOpenLinkIcon(!showOpenLinkIcon);
};
return (
<Box display="inline-block" onMouseEnter={toggleShowOpenLinkIcon} onMouseLeave={toggleShowOpenLinkIcon}>
<Link className={theme['link']} inherit={false} onClick={(event) => event.preventDefault()}>
{children}
</Link>
{showOpenLinkIcon && <IconExternalLinkSmallOutline onClick={openLink} className={theme['icon']} />}
</Box>
);
};
export default {
strategy: findLinkEntities,
component: LinkEntity,
};
| import React, { useState } from 'react';
import { IconExternalLinkSmallOutline } from '@teamleader/ui-icons';
import Box from '../../box';
import Link from '../../link';
import theme from './theme.css';
const findLinkEntities = (contentBlock, callback, contentState) => {
contentBlock.findEntityRanges((character) => {
const entityKey = character.getEntity();
return entityKey !== null && contentState.getEntity(entityKey).getType() === 'LINK';
}, callback);
};
const LinkEntity = ({ entityKey, contentState, children }) => {
const [showOpenLinkIcon, setShowOpenLinkIcon] = useState();
const { url } = contentState.getEntity(entityKey).getData();
const openLink = () => {
let prefixedUrl = url;
if (!url.includes('//')) {
prefixedUrl = '//' + url;
}
window.open(prefixedUrl, '_blank');
};
const toggleShowOpenLinkIcon = () => {
setShowOpenLinkIcon(!showOpenLinkIcon);
};
return (
<Box display="inline-block" onMouseEnter={toggleShowOpenLinkIcon} onMouseLeave={toggleShowOpenLinkIcon}>
<Link className={theme['link']} href="" inherit={false} onClick={(event) => event.preventDefault()}>
{children}
</Link>
{showOpenLinkIcon && <IconExternalLinkSmallOutline onClick={openLink} className={theme['icon']} />}
</Box>
);
};
export default {
strategy: findLinkEntities,
component: LinkEntity,
};
|
Update URL for the minimalistGradleEditor update-site. | /*
* Copyright 2019 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.diffplug.gradle.oomph.thirdparty;
import com.diffplug.gradle.oomph.IUs;
import com.diffplug.gradle.oomph.OomphIdeExtension;
/**
* Adds the [minimalist gradle editor](https://github.com/Nodeclipse/nodeclipse-1/tree/master/org.nodeclipse.enide.editors.gradle).
*/
public class ConventionMinimalistGradleEditor extends WithRepoConvention {
public static final String REPO = "https://nodeclipse.github.io/updates/gradle-ide-pack/";
public static final String FEATURE = "org.nodeclipse.enide.editors.gradle.feature";
ConventionMinimalistGradleEditor(OomphIdeExtension extension) {
super(extension, REPO);
requireIUs(IUs.featureGroup(FEATURE));
}
}
| /*
* Copyright 2019 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.diffplug.gradle.oomph.thirdparty;
import com.diffplug.gradle.oomph.IUs;
import com.diffplug.gradle.oomph.OomphIdeExtension;
/**
* Adds the [minimalist gradle editor](https://github.com/Nodeclipse/nodeclipse-1/tree/master/org.nodeclipse.enide.editors.gradle).
*/
public class ConventionMinimalistGradleEditor extends WithRepoConvention {
public static final String REPO = "https://www.nodeclipse.org/updates/gradle-ide-pack/";
public static final String FEATURE = "org.nodeclipse.enide.editors.gradle.feature";
ConventionMinimalistGradleEditor(OomphIdeExtension extension) {
super(extension, REPO);
requireIUs(IUs.featureGroup(FEATURE));
}
}
|
Add standalone field to browserify build
closes #29 | 'use strict';
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var streamify = require('gulp-streamify');
var size = require('gulp-size');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var del = require('del');
var config = {
src: {
js: {
all: './src/**/*.js',
main: './index.js',
watch: './public/js/**/*.js',
output: 'app.built.js',
min: 'app.built.min.js'
}
},
options: {
standalone: 'creditCardType'
},
dist: {js: 'dist/js'}
};
gulp.task('js', function () {
return browserify(config.src.js.main, config.options)
.bundle()
.pipe(source(config.src.js.output))
.pipe(streamify(size()))
.pipe(gulp.dest(config.dist.js))
.pipe(streamify(uglify()))
.pipe(streamify(size()))
.pipe(rename(config.src.js.min))
.pipe(gulp.dest(config.dist.js));
});
gulp.task('watch', ['js'], function () {
gulp.watch(config.src.js.watch, ['js']);
});
gulp.task('clean', function (done) {
del([config.dist.js], done);
});
gulp.task('build', ['clean', 'js']);
| 'use strict';
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var streamify = require('gulp-streamify');
var size = require('gulp-size');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var del = require('del');
var config = {
namespace: 'braintree',
src: {
js: {
all: './src/**/*.js',
main: './index.js',
watch: './public/js/**/*.js',
output: 'app.built.js',
min: 'app.built.min.js'
}
},
dist: {js: 'dist/js'}
};
gulp.task('js', function () {
return browserify(config.src.js.main)
.bundle()
.pipe(source(config.src.js.output))
.pipe(streamify(size()))
.pipe(gulp.dest(config.dist.js))
.pipe(streamify(uglify()))
.pipe(streamify(size()))
.pipe(rename(config.src.js.min))
.pipe(gulp.dest(config.dist.js));
});
gulp.task('watch', ['js'], function () {
gulp.watch(config.src.js.watch, ['js']);
});
gulp.task('clean', function (done) {
del([config.dist.js], done);
});
gulp.task('build', ['clean', 'js']);
|
Drop a timeout time to its previous value | import mbuild as mb
import parmed as pmd
import pytest
from foyer import Forcefield
from foyer.tests.utils import get_fn
from foyer.utils.io import has_mbuild
@pytest.mark.timeout(1)
def test_fullerene():
fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True)
forcefield = Forcefield(get_fn('fullerene.xml'))
forcefield.apply(fullerene, assert_dihedral_params=False)
@pytest.mark.skipif(not has_mbuild, reason="mbuild is not installed")
@pytest.mark.timeout(15)
def test_surface():
surface = mb.load(get_fn('silica.mol2'))
forcefield = Forcefield(get_fn('opls-silica.xml'))
forcefield.apply(surface, assert_bond_params=False)
@pytest.mark.skipif(not has_mbuild, reason="mbuild is not installed")
@pytest.mark.timeout(45)
def test_polymer():
peg100 = mb.load(get_fn('peg100.mol2'))
forcefield = Forcefield(name='oplsaa')
forcefield.apply(peg100)
| import mbuild as mb
import parmed as pmd
import pytest
from foyer import Forcefield
from foyer.tests.utils import get_fn
from foyer.utils.io import has_mbuild
@pytest.mark.timeout(1)
def test_fullerene():
fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True)
forcefield = Forcefield(get_fn('fullerene.xml'))
forcefield.apply(fullerene, assert_dihedral_params=False)
@pytest.mark.skipif(not has_mbuild, reason="mbuild is not installed")
@pytest.mark.timeout(15)
def test_surface():
surface = mb.load(get_fn('silica.mol2'))
forcefield = Forcefield(get_fn('opls-silica.xml'))
forcefield.apply(surface, assert_bond_params=False)
@pytest.mark.skipif(not has_mbuild, reason="mbuild is not installed")
@pytest.mark.timeout(60)
def test_polymer():
peg100 = mb.load(get_fn('peg100.mol2'))
forcefield = Forcefield(name='oplsaa')
forcefield.apply(peg100)
|
Fix detecting if it's a dynamic files... script tags from the original html were previously incorrectly identified as dynamic files. | /*
Keep track of
*/
import Backbone from "backbone"
import _ from "underscore"
export default class DynamicCodeRegistry {
constructor(){
_.extend(this, Backbone.Events)
this._content = {};
this._origins = {}
}
register(filename, content, origin){
this._content[filename] = content
if (origin) {
this._origins[filename] = origin
}
this.trigger("register", {
[filename]: content
})
}
getContent(filename){
return this._content[filename]
}
getOrigin(filename){
return this._origins[filename]
}
fileIsDynamicCode(filename){
return filename.indexOf("DynamicFunction") !== -1;
}
}
| /*
Keep track of
*/
import Backbone from "backbone"
import _ from "underscore"
export default class DynamicCodeRegistry {
constructor(){
_.extend(this, Backbone.Events)
this._content = {};
this._origins = {}
}
register(filename, content, origin){
this._content[filename] = content
if (origin) {
this._origins[filename] = origin
}
this.trigger("register", {
[filename]: content
})
}
getContent(filename){
return this._content[filename]
}
getOrigin(filename){
return this._origins[filename]
}
fileIsDynamicCode(filename){
return this._content[filename] !== undefined
}
}
|
Fix trigger pixel for saddlebags | package com.minelittlepony.pony.data;
import java.util.ArrayList;
import java.util.List;
public enum PonyWearable implements ITriggerPixelMapped<PonyWearable> {
NONE(0),
SADDLE_BAGS(255),
HAT(100);
private int triggerValue;
PonyWearable(int pixel) {
triggerValue = pixel;
}
@Override
public int getTriggerPixel() {
return triggerValue;
}
public static PonyWearable[] flags(boolean[] flags) {
List<PonyWearable> wears = new ArrayList<PonyWearable>();
PonyWearable[] values = values();
for (int i = 0; i < values.length; i++) {
if (flags[i]) wears.add(values[i]);
}
return wears.toArray(new PonyWearable[wears.size()]);
}
}
| package com.minelittlepony.pony.data;
import java.util.ArrayList;
import java.util.List;
public enum PonyWearable implements ITriggerPixelMapped<PonyWearable> {
NONE(0),
SADDLE_BAGS(0xff0000),
HAT(0x00ff00);
private int triggerValue;
PonyWearable(int pixel) {
triggerValue = pixel;
}
@Override
public int getTriggerPixel() {
return triggerValue;
}
public static PonyWearable[] flags(boolean[] flags) {
List<PonyWearable> wears = new ArrayList<PonyWearable>();
PonyWearable[] values = values();
for (int i = 0; i < values.length; i++) {
if (flags[i]) wears.add(values[i]);
}
return wears.toArray(new PonyWearable[wears.size()]);
}
}
|
Use normalizer as plugin in example. | /**
* Module dependencies
*/
var Zeditor = require('zeditor');
var ZeditorPaste = require('zeditor-paste');
var ZeditorNormalizer = require('zeditor-normalizer');
/**
* Get DOM nodes
*/
var editorNode = document.getElementById('editor');
/**
* Instantiate editor
*/
Zeditor(editorNode);
ZeditorNormalizer(editorNode);
ZeditorPaste(editorNode);
/**
* Other functionality
*/
Zeditor(editorNode).on('error', function (err) {
// for now, any "error" event log to the console
console.error('editor "error" event: %o', err);
});
var outputNode = document.getElementById('output');
var showEditorButtonNode = document.getElementById('showEditor');
var showOutputButtonNode = document.getElementById('showOutput');
showEditorButtonNode.addEventListener('click', function (e) {
e.preventDefault();
showEditorButtonNode.style.display = 'none';
editorNode.style.display = 'block';
showOutputButtonNode.style.display = 'inline';
outputNode.style.display = 'none';
}, false);
showOutputButtonNode.addEventListener('click', function (e) {
e.preventDefault();
showEditorButtonNode.style.display = 'inline';
editorNode.style.display = 'none';
showOutputButtonNode.style.display = 'none';
outputNode.style.display = 'block';
outputNode.textContent = editor.serializer.serializeRoot();
}, false); | /**
* Module dependencies
*/
var Zeditor = require('zeditor');
var ZeditorPaste = require('zeditor-paste');
/**
* Get DOM nodes
*/
var editorNode = document.getElementById('editor');
/**
* Instantiate editor
*/
Zeditor(editorNode);
ZeditorPaste(editorNode);
/**
* Other functionality
*/
Zeditor(editorNode).on('error', function (err) {
// for now, any "error" event log to the console
console.error('editor "error" event: %o', err);
});
var outputNode = document.getElementById('output');
var showEditorButtonNode = document.getElementById('showEditor');
var showOutputButtonNode = document.getElementById('showOutput');
showEditorButtonNode.addEventListener('click', function (e) {
e.preventDefault();
showEditorButtonNode.style.display = 'none';
editorNode.style.display = 'block';
showOutputButtonNode.style.display = 'inline';
outputNode.style.display = 'none';
}, false);
showOutputButtonNode.addEventListener('click', function (e) {
e.preventDefault();
showEditorButtonNode.style.display = 'inline';
editorNode.style.display = 'none';
showOutputButtonNode.style.display = 'none';
outputNode.style.display = 'block';
outputNode.textContent = editor.serializer.serializeRoot();
}, false); |
Delete children when deleting dms folder | package com.axelor.dms.db.repo;
import java.util.List;
import java.util.Map;
import org.joda.time.LocalDateTime;
import com.axelor.db.JpaRepository;
import com.axelor.dms.db.DMSFile;
public class DMSFileRepository extends JpaRepository<DMSFile> {
public DMSFileRepository() {
super(DMSFile.class);
}
@Override
public void remove(DMSFile entity) {
// remove all children
if (entity.getIsDirectory() == Boolean.TRUE) {
final List<DMSFile> children = all().filter("self.parent.id = ?", entity.getId()).fetch();
for (DMSFile child : children) {
if (child != entity) {
remove(child);;
}
}
}
super.remove(entity);
}
@Override
public Map<String, Object> populate(Map<String, Object> json) {
final Object id = json.get("id");
if (id == null) {
return json;
}
final DMSFile file = find((Long) id);
if (file == null) {
return json;
}
boolean isFile = file.getIsDirectory() != Boolean.TRUE;
LocalDateTime dt = file.getUpdatedOn();
if (dt == null) {
dt = file.getCreatedOn();
}
json.put("typeIcon", isFile ? "fa fa-file" : "fa fa-folder");
json.put("lastModified", dt);
return json;
}
}
| package com.axelor.dms.db.repo;
import java.util.Map;
import org.joda.time.LocalDateTime;
import com.axelor.db.JpaRepository;
import com.axelor.dms.db.DMSFile;
public class DMSFileRepository extends JpaRepository<DMSFile> {
public DMSFileRepository() {
super(DMSFile.class);
}
@Override
public Map<String, Object> populate(Map<String, Object> json) {
final Object id = json.get("id");
if (id == null) {
return json;
}
final DMSFile file = find((Long) id);
if (file == null) {
return json;
}
boolean isFile = file.getIsDirectory() != Boolean.TRUE;
LocalDateTime dt = file.getUpdatedOn();
if (dt == null) {
dt = file.getCreatedOn();
}
json.put("typeIcon", isFile ? "fa fa-file" : "fa fa-folder");
json.put("lastModified", dt);
return json;
}
}
|
Add role to user table | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->tinyInteger('role');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
|
Remove default description on user model | const Sequelize = require('sequelize');
const db = require('../db.js');
const Users = db.define('users',
{
id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV1,
primaryKey: true,
},
facebook_id: {
type: Sequelize.STRING,
},
first_name: {
type: Sequelize.STRING,
},
last_name: {
type: Sequelize.STRING,
},
photo_url: {
type: Sequelize.STRING,
},
description: {
type: Sequelize.STRING(256),
},
// would like to add counter cache for request count and connection count
},
{
freezeTableName: true,
}
);
module.exports = Users;
| const Sequelize = require('sequelize');
const db = require('../db.js');
const Users = db.define('users',
{
id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV1,
primaryKey: true,
},
facebook_id: {
type: Sequelize.STRING,
},
first_name: {
type: Sequelize.STRING,
},
last_name: {
type: Sequelize.STRING,
},
photo_url: {
type: Sequelize.STRING,
},
description: {
type: Sequelize.STRING(256),
defaultValue: 'Click here to edit!',
},
// would like to add counter cache for request count and connection count
},
{
freezeTableName: true,
}
);
module.exports = Users;
|
Add student information to connection socket event | //var Teachers = require('../models/teachers');
//var TeacherClasses = require('../models/Teacher_classes');
//var Classes = require('../models/classes');
//var ClassLessons = require('../models/class_lessons');
// var Lessons = require('../models/lessons');
//var RequestedResponses = require('../models/requested_responses');
module.exports = {
readyStage : function(io, req, res, next) {
//var studentInformation = req.body.studentData
var pollResponse = {
responseId: 1,
type: 'thumbs',
datetime: new Date(),
lessonId: 13,
};
io.on('connection', function(student){
student.emit('studentStandby', studentInformation);
student.on('teacherConnect', function() {
student.emit('teacherConnect');
});
student.on('newPoll', function(data) {
student.emit(data);
});
setTimeout(function(){
io.sockets.emit('responseFromStudent', pollResponse);
}, 5000);
});
res.status(200).send('Hello from the other side');
}
}; | //var Teachers = require('../models/teachers');
//var TeacherClasses = require('../models/Teacher_classes');
//var Classes = require('../models/classes');
//var ClassLessons = require('../models/class_lessons');
// var Lessons = require('../models/lessons');
//var RequestedResponses = require('../models/requested_responses');
module.exports = {
readyStage : function(io, req, res, next) {
// io.on('connection', function(client){
// console.log('Hey, server! A student is ready to learn!');
// client.emit('greeting', 'Hello, student!');
// client.on('responseRecorded', function(data){
// io.sockets.emit('responseRecordedFromStudent', data);
// });
// });
res.status(200).send('Hello from the other side');
}
}; |
Add uuid to update user serializer | #from phonenumber_field.serializerfields import PhoneNumberField
from rest_framework import serializers
from drf_extra_fields.geo_fields import PointField
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from semillas_backend.users.serializers import UserSerializer
JSONRenderer().render(UserSerializer(user_instance).data)
"""
location = PointField()
class Meta:
model = User
fields = ('uuid', 'name', 'picture', 'location', 'username', 'last_login')
class UpdateUserSerializer(serializers.ModelSerializer):
name = serializers.CharField(required=False)
#phone = PhoneNumberField(required=False)
email = serializers.CharField(required=False)
picture = serializers.ImageField(required=False)
uuid = serializers.CharField(read_only=True)
class Meta:
model = User
fields = ('name', 'picture', 'phone', 'email', 'uuid')
from wallet.serializers import WalletSerializer
class FullUserSerializer(UserSerializer):
wallet = WalletSerializer()
class Meta:
model = User
fields = ('uuid', 'name', 'picture', 'location', 'username', 'last_login', 'wallet', 'email', 'phone')
| #from phonenumber_field.serializerfields import PhoneNumberField
from rest_framework import serializers
from drf_extra_fields.geo_fields import PointField
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from semillas_backend.users.serializers import UserSerializer
JSONRenderer().render(UserSerializer(user_instance).data)
"""
location = PointField()
class Meta:
model = User
fields = ('uuid', 'name', 'picture', 'location', 'username', 'last_login')
class UpdateUserSerializer(serializers.ModelSerializer):
name = serializers.CharField(required=False)
#phone = PhoneNumberField(required=False)
email = serializers.CharField(required=False)
picture = serializers.ImageField(required=False)
class Meta:
model = User
fields = ('name', 'picture', 'phone', 'email')
from wallet.serializers import WalletSerializer
class FullUserSerializer(UserSerializer):
wallet = WalletSerializer()
class Meta:
model = User
fields = ('uuid', 'name', 'picture', 'location', 'username', 'last_login', 'wallet', 'email', 'phone')
|
Add safe knex closing when architect will close | /*jslint node : true, nomen: true, plusplus: true, vars: true, eqeq: true,*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
module.exports = function setup(options, imports, register) {
var knex = require('knex');
if (!options.settings) {
register(new Error("No settings found"));
}
var builder = new knex(options.settings);
register(null, {
onDestruct: function (callback) {
knex.destroy(callback);
},
knex: builder
});
};
| /*jslint node : true, nomen: true, plusplus: true, vars: true, eqeq: true,*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
module.exports = function setup(options, imports, register) {
var knex = require('knex');
if (!options.settings) {
register(new Error("No settings found"));
}
var builder = new knex(options.settings);
register(null, {knex: builder});
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.