text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix broken newsflow on launch
Former-commit-id: 3edc20d576b57a0e30ed53d61c3ff960cb891853 | <?
defined('C5_EXECUTE') or die("Access Denied.");
$this->inc('elements/header.php', array('enableEditing' => true));
?>
<div class="ccm-ui">
<div class="newsflow" id="newsflow-main">
<? $this->inc('elements/header_newsflow.php'); ?>
<table class="newsflow-layout">
<tr>
<td class="newsflow-em1" style="width: 66%" rowspan="3">
<div id="ccm-dashboard-welcome-back">
<? $a = new Area('Primary'); $a->display($c); ?>
</div>
</td>
<td><? $a = new Area('Secondary 1'); $a->display($c); ?></td>
</tr>
<tr>
<td style="width: 34%"><? $a = new Area('Secondary 2'); $a->display($c); ?></td>
</tr>
<tr>
<td style="width: 34%"><? $a = new Area('Secondary 5'); $a->display($c); ?></td>
</tr>
</table>
</div>
</div>
<? $this->inc('elements/footer.php'); ?> | <?
defined('C5_EXECUTE') or die("Access Denied.");
$this->inc('elements/header.php', array('enableEditing' => true));
?>
<div class="ccm-ui">
<div class="newsflow" id="newsflow-main">
<? $this->inc('elements/header_newsflow.php'); ?>
<table class="newsflow-layout">
<tr>
<td class="newsflow-em1" style="width: 66%" colspan="2" rowspan="2">
<div id="ccm-dashboard-welcome-back">
<? $a = new Area('Primary'); $a->display($c); ?>
</div>
</td>
<td><? $a = new Area('Secondary 1'); $a->display($c); ?></td>
</tr>
<tr>
<td style="width: 34%"><? $a = new Area('Secondary 2'); $a->display($c); ?></td>
</tr>
<tr>
<td style="width: 33%"><? $a = new Area('Secondary 3'); $a->display($c); ?></td>
<td style="width: 33%"><? $a = new Area('Secondary 4'); $a->display($c); ?></td>
<td style="width: 34%"><? $a = new Area('Secondary 5'); $a->display($c); ?></td>
</tr>
</table>
</div>
</div>
<? $this->inc('elements/footer.php'); ?> |
Add name property to plugin object | /* eslint-disable no-console */
import { createFilter } from 'rollup-pluginutils';
import { resolve } from 'source-map-resolve';
import { readFile } from 'fs';
import { promisify } from './utils';
const readFileAsync = promisify(readFile);
const resolveSourceMapAsync = promisify(resolve);
export default function sourcemaps({ include, exclude } = {}) {
const filter = createFilter(include, exclude);
return {
name: 'sourcemaps',
async load(id) {
if (!filter(id)) {
return null;
}
let code;
try {
code = await readFileAsync(id, 'utf8');
} catch (err) {
// Failed, let Rollup deal with it
return null;
}
let sourceMap;
try {
sourceMap = await resolveSourceMapAsync(code, id, readFile);
} catch (err) {
console.error(`rollup-plugin-sourcemaps: Failed resolving source map from ${id}: ${err}`);
return code;
}
// No source map detected, return code
if (sourceMap === null) {
return code;
}
const { map, sourcesContent } = sourceMap;
map.sourcesContent = sourcesContent;
return { code, map };
},
};
}
| /* eslint-disable no-console */
import { createFilter } from 'rollup-pluginutils';
import { resolve } from 'source-map-resolve';
import { readFile } from 'fs';
import { promisify } from './utils';
const readFileAsync = promisify(readFile);
const resolveSourceMapAsync = promisify(resolve);
export default function sourcemaps({ include, exclude } = {}) {
const filter = createFilter(include, exclude);
return {
async load(id) {
if (!filter(id)) {
return null;
}
let code;
try {
code = await readFileAsync(id, 'utf8');
} catch (err) {
// Failed, let Rollup deal with it
return null;
}
let sourceMap;
try {
sourceMap = await resolveSourceMapAsync(code, id, readFile);
} catch (err) {
console.error(`rollup-plugin-sourcemaps: Failed resolving source map from ${id}: ${err}`);
return code;
}
// No source map detected, return code
if (sourceMap === null) {
return code;
}
const { map, sourcesContent } = sourceMap;
map.sourcesContent = sourcesContent;
return { code, map };
},
};
}
|
Change variable names. Change from name to firstName in the contact information example. | <?php
require 'vendor/autoload.php';
// Replace /comphppuebla/guzzle for the path to your negotiation.php file to try this route.
// curl --header "Accept: application/xml" http://localhost/comphppuebla/guzzle/negotiation.php
use Negotiation\Negotiator;
use Faker\Factory;
use Twig_Loader_Filesystem as FilesystemLoader;
use Twig_Environment as Environment;
$negotiator = new Negotiator();
$headers = getallheaders();
$format = $negotiator->getBest($headers['Accept']);
$type = $format->getValue();
$template = 'contacts/show.json.twig';
if ('application/xml' === $type) {
$template = 'contacts/show.xml.twig';
}
$viewLoader = new FilesystemLoader('views');
$view = new Environment($viewLoader);
$faker = Factory::create();
echo $view->render($template, [
'contact' => [
'contact_id' => $faker->randomDigit,
'name' => $faker->firstName,
'last_name' => $faker->lastName,
]
]); | <?php
require 'vendor/autoload.php';
// Replace /comphppuebla/guzzle for the path to your negotiation.php file to try this route.
// curl --header "Accept: application/xml" http://localhost/comphppuebla/guzzle/negotiation.php
use Negotiation\Negotiator;
use Faker\Factory;
use Twig_Loader_Filesystem as FilesystemLoader;
use Twig_Environment as Environment;
$negotiator = new Negotiator();
$headers = getallheaders();
$format = $negotiator->getBest($headers['Accept']);
$type = $format->getValue();
$template = 'contacts/show.json.twig';
if ('application/xml' === $type) {
$template = 'contacts/show.xml.twig';
}
$loader = new FilesystemLoader('views');
$environment = new Environment($loader);
$faker = Factory::create();
echo $environment->render($template, [
'contact' => [
'contact_id' => $faker->randomDigit, 'name' => $faker->name, 'last_name' => $faker->lastName,
]
]); |
Add a missing @abc.abstractmethod declaration
PiperOrigin-RevId: 424036906
Change-Id: I3979c35ec30caa4b684d43376b2a36d21f7e79df | # Copyright 2018 DeepMind Technologies Limited. 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.
"""Metrics observers."""
import abc
from typing import Dict, Union
import dm_env
import numpy as np
Number = Union[int, float]
class EnvLoopObserver(abc.ABC):
"""An interface for collecting metrics/counters in EnvironmentLoop."""
@abc.abstractmethod
def observe_first(self, env: dm_env.Environment, timestep: dm_env.TimeStep
) -> None:
"""Observes the initial state."""
@abc.abstractmethod
def observe(self, env: dm_env.Environment, timestep: dm_env.TimeStep,
action: np.ndarray) -> None:
"""Records one environment step."""
@abc.abstractmethod
def get_metrics(self) -> Dict[str, Number]:
"""Returns metrics collected for the current episode."""
| # Copyright 2018 DeepMind Technologies Limited. 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.
"""Metrics observers."""
import abc
from typing import Dict, Union
import dm_env
import numpy as np
Number = Union[int, float]
class EnvLoopObserver(abc.ABC):
"""An interface for collecting metrics/counters in EnvironmentLoop."""
def observe_first(self, env: dm_env.Environment, timestep: dm_env.TimeStep
) -> None:
"""Observes the initial state."""
@abc.abstractmethod
def observe(self, env: dm_env.Environment, timestep: dm_env.TimeStep,
action: np.ndarray) -> None:
"""Records one environment step."""
@abc.abstractmethod
def get_metrics(self) -> Dict[str, Number]:
"""Returns metrics collected for the current episode."""
|
Move warning about missing config entry to relevant subcommand | import click
import logging
from taca.server_status import server_status as status
from taca.utils.config import CONFIG
from taca.server_status import cronjobs as cj # to avoid similar names with command, otherwise exception
@click.group(name='server_status')
def server_status():
""" Monitor server status """
# server status subcommands
@server_status.command()
@click.option('--statusdb', is_flag=True, help="Update the statusdb")
def nases(statusdb):
""" Checks the available space on all the nases
"""
if not CONFIG.get('server_status', ''):
logging.warning("Configuration missing required entries: server_status")
disk_space = status.get_nases_disk_space()
if statusdb:
status.update_status_db(disk_space, server_type='nas')
@server_status.command()
def cronjobs():
""" Monitors cronjobs and updates statusdb
"""
cj.update_cronjob_db()
| import click
import logging
from taca.server_status import server_status as status
from taca.utils.config import CONFIG
from taca.server_status import cronjobs as cj # to avoid similar names with command, otherwise exception
@click.group(name='server_status')
def server_status():
""" Monitor server status """
if not CONFIG.get('server_status', ''):
logging.warning("Configuration missing required entries: server_status")
# server status subcommands
@server_status.command()
@click.option('--statusdb', is_flag=True, help="Update the statusdb")
def nases(statusdb):
""" Checks the available space on all the nases
"""
disk_space = status.get_nases_disk_space()
if statusdb:
status.update_status_db(disk_space, server_type='nas')
@server_status.command()
def cronjobs():
""" Monitors cronjobs and updates statusdb
"""
cj.update_cronjob_db()
|
ADD campo data_public e reorganização do código | <?php
require_once("conexao/conexao.php");
$conexao = conectar();
//REQUISIÇÕES VINDAS DA PÁGINA SINAL_FORMULARIO.PHP
$titulo = addslashes(trim($_POST['titulo' ]));
$categoria = addslashes(trim($_POST['categoria' ]));
$descricao = addslashes(trim($_POST['descricao' ]));
$longitude = addslashes(trim($_POST['longitude' ]));
$latitude = addslashes(trim($_POST['latitude' ]));
$data_public = addslashes(trim($_POST['data_public']));
$addsinal = $conexao -> prepare("INSERT INTO sinalizacao (titulo, descricao, latitude, longitude, categoria, data_public) values(:titulo, :descricao, :latitude, :longitude, :categoria, :data_public)");
$addsinal->bindValue(":titulo" , $titulo );
$addsinal->bindValue(":descricao" , $descricao );
$addsinal->bindValue(":latitude" , $latitude );
$addsinal->bindValue(":longitude" , $longitude );
$addsinal->bindValue(":categoria" , $categoria );
$addsinal->bindValue(":data_public" , $data_public );
$addsinal->execute();
if($addsinal) {
echo "sinal add com sucesso";
}else {
echo "faio";
}
?>
| <?php
require_once("conexao/conexao.php");
$titulo = addslashes(trim($_POST['titulo'] ));
$categoria = addslashes(trim($_POST['categoria']));
$descricao = addslashes(trim($_POST['descricao']));
$longitude = addslashes(trim($_POST['longitude']));
$latitude = addslashes(trim($_POST['latitude'] ));
$addsinal = $conexao -> prepare("INSERT sinalizacao (titulo, latitude, longitude, categoria, descricao) values(:titulo, :latitude, :longitude, :categoria, :descricao)");
$addsinal->bindValue(":titulo" , $titulo );
$addsinal->bindValue(":latitude" , $latitude );
$addsinal->bindValue(":longitude" , $longitude);
$addsinal->bindValue(":categoria" , $categoria);
$addsinal->bindValue(":descricao" , $descricao);
$addsinal->execute();
if($addsinal) {
echo "sinal add com sucesso";
echo var_dump($addsinal);
}else {
echo "faio";
}
?>
|
Fix typo in property name | # Copyright (c) 2013, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import cybox
import cybox.bindings.cybox_core as core_binding
from cybox.common import VocabString, StructuredText, MeasureSource
from cybox.core import Actions, Frequency
class EventType(VocabString):
_XSI_TYPE = 'cyboxVocabs:EventTypeVocab-1.0.1'
class Event(cybox.Entity):
_binding = core_binding
_binding_class = core_binding.EventType
_namespace = 'http://cybox.mitre.org/cybox-2'
id_ = cybox.TypedField("id")
idref = cybox.TypedField("idref")
type_ = cybox.TypedField("Type", EventType)
description = cybox.TypedField("Description", StructuredText)
observation_method = cybox.TypedField("Observation_Method", MeasureSource)
actions = cybox.TypedField("Actions", Actions)
frequency = cybox.TypedField("Frequency", Frequency)
event = cybox.TypedField("Event", multiple=True)
# Allow recursive definition of events
Event.event.type_ = Event
| # Copyright (c) 2013, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import cybox
import cybox.bindings.cybox_core as core_binding
from cybox.common import VocabString, StructuredText, MeasureSource
from cybox.core import Actions, Frequency
class EventType(VocabString):
_XSI_TYPE = 'cyboxVocabs:EventTypeVocab-1.0.1'
class Event(cybox.Entity):
_binding = core_binding
_binding_class = core_binding.EventType
_namespace = 'http://cybox.mitre.org/cybox-2'
id_ = cybox.TypedField("id")
idref = cybox.TypedField("idref")
type_ = cybox.TypedField("Type", EventType)
description = cybox.TypedField("Description", StructuredText)
observation_method = cybox.TypedField("Observation_Method", MeasureSource)
actions = cybox.TypedField("Actions", Actions)
frequency = cybox.TypedField("Frequency", Frequency)
events = cybox.TypedField("Event", multiple=True)
# Allow recursive definition of events
Event.events.type_ = Event
|
Allow piping in the response event |
module.exports = HTTPDuplex
var util = require('util')
, http = require('http')
, https = require('https')
, stream = require('stream')
util.inherits(HTTPDuplex, stream.Duplex)
function HTTPDuplex (protocol) {
stream.Duplex.call(this)
this._req = null
this._res = null
this._client = null
if (protocol === 'https:') {
this._client = https
}
else if (protocol === 'http:') {
this._client = http
}
}
HTTPDuplex.prototype.start = function (options) {
var self = this
self._req = self._client.request(options)
self._req.on('response', function (res) {
self._res = res
self.emit('response', res)
self._res.on('data', function (chunk) {
if (!self.push(chunk)) {
self._res.pause()
}
})
self._res.on('end', function () {
self.push(null)
})
})
}
HTTPDuplex.prototype._read = function (n) {
if (this._res) {
this._res.resume()
}
}
HTTPDuplex.prototype._write = function (chunk, encoding, cb) {
return this._req.write(chunk, encoding, cb)
}
HTTPDuplex.prototype.end = function (chunk, encoding, cb) {
return this._req.end(chunk, encoding, cb)
}
|
module.exports = HTTPDuplex
var util = require('util')
, http = require('http')
, https = require('https')
, stream = require('stream')
util.inherits(HTTPDuplex, stream.Duplex)
function HTTPDuplex (protocol) {
stream.Duplex.call(this)
this._req = null
this._res = null
this._client = null
if (protocol === 'https:') {
this._client = https
}
else if (protocol === 'http:') {
this._client = http
}
}
HTTPDuplex.prototype.start = function (options) {
var self = this
self._req = self._client.request(options)
self._req.on('response', function (res) {
self._res = res
self.emit('response', res)
res.on('data', function (chunk) {
if (!self.push(chunk)) {
self._res.pause()
}
})
res.on('end', function () {
self.push(null)
})
})
}
HTTPDuplex.prototype._read = function (n) {
if (this._res) {
this._res.resume()
}
}
HTTPDuplex.prototype._write = function (chunk, encoding, cb) {
return this._req.write(chunk, encoding, cb)
}
HTTPDuplex.prototype.end = function (chunk, encoding, cb) {
return this._req.end(chunk, encoding, cb)
}
|
Remove HttpOnly for now as it causes auth issues | <?php
namespace Movim;
class Cookie
{
public static function set()
{
if (SESSION_ID == false) {
self::renew();
} else {
self::setCookie(SESSION_ID);
}
}
public static function refresh()
{
if (isset($_COOKIE['MOVIM_SESSION_ID'])) {
self::setCookie($_COOKIE['MOVIM_SESSION_ID']);
}
}
public static function renew()
{
self::setCookie(generateKey(32));
}
public static function getTime()
{
return time()+604800;
}
private static function setCookie($key)
{
if (!headers_sent()) {
header_remove('Set-Cookie');
setcookie('MOVIM_SESSION_ID', $key, self::getTime(), '/', '', true);
}
}
}
| <?php
namespace Movim;
class Cookie
{
public static function set()
{
if (SESSION_ID == false) {
self::renew();
} else {
self::setCookie(SESSION_ID);
}
}
public static function refresh()
{
if (isset($_COOKIE['MOVIM_SESSION_ID'])) {
self::setCookie($_COOKIE['MOVIM_SESSION_ID']);
}
}
public static function renew()
{
self::setCookie(generateKey(32));
}
public static function getTime()
{
return time()+604800;
}
private static function setCookie($key)
{
if (!headers_sent()) {
header_remove('Set-Cookie');
setcookie('MOVIM_SESSION_ID', $key, self::getTime(), '/', '', true, true);
}
}
}
|
WIP: Create config directory if not present | 'use strict';
// Load requirements
const fs = require('fs'),
path = require('path');
// Define the config directory
let configDir = path.resolve('./config');
// Create config directory if we don't have one
if ( ! fs.existsSync(configDir) ) {
fs.mkdirSync(configDir);
}
module.exports = {
get: function(task) {
return new Promise((resolve, reject) => {
// Check type
if ( task.type === undefined || ! ['show', 'move'].includes(task.type) ) {
return reject('Invalid job type "' + task.type + '" specified');
}
// Get metadata, auth with trakt and get media information
this.metadata.get(task.file).then((meta) => {
task.meta = meta;
return this[task.type](task.basename);
}).then((info) => {
task.details = info;
return resolve(task);
}).catch((err) => {
return reject(err);
});
});
},
metadata: require('./metadata'),
show: require('./show'),
movie: require('./movie')
};
| 'use strict';
module.exports = {
get: function(task) {
return new Promise((resolve, reject) => {
// Check type
if ( task.type === undefined || ! ['show', 'move'].includes(task.type) ) {
return reject('Invalid job type "' + task.type + '" specified');
}
// Get metadata, auth with trakt and get media information
this.metadata.get(task.file).then((meta) => {
task.meta = meta;
return this[task.type](task.basename);
}).then((info) => {
task.details = info;
return resolve(task);
}).catch((err) => {
return reject(err);
});
});
},
metadata: require('./metadata'),
show: require('./show'),
movie: require('./movie')
};
|
Call superclass constructor for Workspace | from geoserver.support import atom_link, xml_property, write_bool, ResourceInfo
import string
def workspace_from_index(catalog, node):
name = node.find("name")
return Workspace(catalog, name.text)
class Workspace(ResourceInfo):
resource_type = "workspace"
def __init__(self, catalog, name):
super(Workspace, self).__init__()
self.catalog = catalog
self.name = name
@property
def href(self):
return "%s/workspaces/%s.xml" % (self.catalog.service_url, self.name)
@property
def coveragestore_url(self):
return "%s/workspaces/%s/coveragestores.xml" % (self.catalog.service_url, self.name)
@property
def datastore_url(self):
return "%s/workspaces/%s/datastores.xml" % (self.catalog.service_url, self.name)
enabled = xml_property("enabled", "enabled", lambda x: string.lower(x) == 'true')
writers = dict(
enabled = write_bool("enabled")
)
def __repr__(self):
return "%s @ %s" % (self.name, self.href)
| from geoserver.support import atom_link, xml_property, write_bool, ResourceInfo
import string
def workspace_from_index(catalog, node):
name = node.find("name")
return Workspace(catalog, name.text)
class Workspace(ResourceInfo):
resource_type = "workspace"
def __init__(self, catalog, name):
assert isinstance(name, basestring)
self.catalog = catalog
self.name = name
@property
def href(self):
return "%s/workspaces/%s.xml" % (self.catalog.service_url, self.name)
@property
def coveragestore_url(self):
return "%s/workspaces/%s/coveragestores.xml" % (self.catalog.service_url, self.name)
@property
def datastore_url(self):
return "%s/workspaces/%s/datastores.xml" % (self.catalog.service_url, self.name)
enabled = xml_property("enabled", "enabled", lambda x: string.lower(x) == 'true')
writers = dict(
enabled = write_bool("enabled")
)
def __repr__(self):
return "%s @ %s" % (self.name, self.href)
|
Remove syncHistoryWithStore from example code | import { AppContainer } from 'react-hot-loader'
import { applyMiddleware, compose, createStore } from 'redux'
import { createBrowserHistory } from 'history'
import { routerMiddleware } from 'connected-react-router'
import { Provider } from 'react-redux'
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import rootReducer from './reducers/root'
const history = createBrowserHistory()
const store = createStore(
rootReducer,
compose(
applyMiddleware(
routerMiddleware(history),
),
),
)
const renderWithHotReload = (AppComponent) => {
ReactDOM.render(
<AppContainer>
<Provider store={store}>
<AppComponent history={history} />
</Provider>
</AppContainer>,
document.getElementById('react-root')
)
}
renderWithHotReload(App)
// For functional component hot reloading
if (module.hot) {
module.hot.accept('./App', () => {
const NextApp = require('./App').default
renderWithHotReload(NextApp)
})
}
| import { AppContainer } from 'react-hot-loader'
import { applyMiddleware, compose, createStore } from 'redux'
import { createBrowserHistory } from 'history'
import { routerMiddleware, syncHistoryWithStore } from 'connected-react-router'
import { Provider } from 'react-redux'
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import rootReducer from './reducers/root'
const history = createBrowserHistory()
const store = createStore(
rootReducer,
compose(
applyMiddleware(
routerMiddleware(history),
),
),
)
syncHistoryWithStore(history, store)
const renderWithHotReload = (AppComponent) => {
ReactDOM.render(
<AppContainer>
<Provider store={store}>
<AppComponent history={history} />
</Provider>
</AppContainer>,
document.getElementById('react-root')
)
}
renderWithHotReload(App)
// For functional component hot reloading
if (module.hot) {
module.hot.accept('./App', () => {
const NextApp = require('./App').default
renderWithHotReload(NextApp)
})
}
|
[Form] Implement Twig helpers to get field variables | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
use Symfony\Bridge\Twig\Extension\FormExtension;
use Symfony\Bridge\Twig\Form\TwigRendererEngine;
use Symfony\Component\Form\FormRenderer;
return static function (ContainerConfigurator $container) {
$container->services()
->set('twig.extension.form', FormExtension::class)
->args([service('translator')->nullOnInvalid()])
->set('twig.form.engine', TwigRendererEngine::class)
->args([param('twig.form.resources'), service('twig')])
->set('twig.form.renderer', FormRenderer::class)
->args([service('twig.form.engine'), service('security.csrf.token_manager')->nullOnInvalid()])
->tag('twig.runtime')
;
};
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
use Symfony\Bridge\Twig\Extension\FormExtension;
use Symfony\Bridge\Twig\Form\TwigRendererEngine;
use Symfony\Component\Form\FormRenderer;
return static function (ContainerConfigurator $container) {
$container->services()
->set('twig.extension.form', FormExtension::class)
->set('twig.form.engine', TwigRendererEngine::class)
->args([param('twig.form.resources'), service('twig')])
->set('twig.form.renderer', FormRenderer::class)
->args([service('twig.form.engine'), service('security.csrf.token_manager')->nullOnInvalid()])
->tag('twig.runtime')
;
};
|
Add printing err to STD out | package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
)
func executeCmd(command string, args ...string) {
cmd := exec.Command(command, args...)
cmdReader, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(os.Stderr, "Error creating StdoutPipe for Cmd", err)
}
defer cmdReader.Close()
scanner := bufio.NewScanner(cmdReader)
go func() {
for scanner.Scan() {
fmt.Printf("%s\n", scanner.Text())
}
}()
err = cmd.Start()
if err != nil {
log.Fatal(os.Stderr, "Error starting Cmd", err)
}
err = cmd.Wait()
// go generate command will fail when no generate command find.
if err != nil {
if err.Error() != "exit status 1" {
fmt.Println(err)
log.Fatal(err)
}
}
}
| package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
)
func executeCmd(command string, args ...string) {
cmd := exec.Command(command, args...)
cmdReader, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(os.Stderr, "Error creating StdoutPipe for Cmd", err)
}
defer cmdReader.Close()
scanner := bufio.NewScanner(cmdReader)
go func() {
for scanner.Scan() {
fmt.Printf("%s\n", scanner.Text())
}
}()
err = cmd.Start()
if err != nil {
log.Fatal(os.Stderr, "Error starting Cmd", err)
}
err = cmd.Wait()
// go generate command will fail when no generate command find.
if err != nil {
if err.Error() != "exit status 1" {
log.Fatal(err)
}
}
}
|
:fire: Remove un-used argument in Main::Action |
"use strict";
var Main = module.parent.exports;
Main.ActionSet = function(Child, Request){
Main.ValidateArguments(Main.ARGS_EVEN, Request.length);
for(let Number = 0; Number < Request.length; Number += 2){
let Value = Main.NormalizeType(Request[Number + 1]);
this.Database.set(Request[Number], Value);
}
return {Type: 'OK'};
};
Main.ActionGET = function(Child, Request){
if(Request.length === 1){
return this.Database.get(Request[0]) || null;
}
return Request.map(function(Name){
return this.Database.get(Name) || null;
}.bind(this));
};
Main.ActionINCR = function(Child, Request){
if(Request.length === 1){
let Value = this.Database.get(Request[0]) || 0;
Main.Validate(Main.VAL_NUMERIC, 'INCR', Value);
this.Database.set(Request[0], ++Value);
return Value;
}
return Request.map(function(Name){
let Value = this.Database.get(Name) || 0;
Main.Validate(Main.VAL_NUMERIC, 'INCR', Value);
this.Database.set(Request[0], ++Value);
return Value;
}.bind(this));
}; |
"use strict";
var Main = module.parent.exports;
Main.ActionSet = function(Child, Request, Message){
Main.ValidateArguments(Main.ARGS_EVEN, Request.length);
for(let Number = 0; Number < Request.length; Number += 2){
let Value = Main.NormalizeType(Request[Number + 1]);
this.Database.set(Request[Number], Value);
}
return {Type: 'OK'};
};
Main.ActionGET = function(Child, Request, Message){
if(Request.length === 1){
return this.Database.get(Request[0]) || null;
}
return Request.map(function(Name){
return this.Database.get(Name) || null;
}.bind(this));
};
Main.ActionINCR = function(Child, Request, Message){
if(Request.length === 1){
let Value = this.Database.get(Request[0]) || 0;
Main.Validate(Main.VAL_NUMERIC, 'INCR', Value);
this.Database.set(Request[0], ++Value);
return Value;
}
return Request.map(function(Name){
let Value = this.Database.get(Name) || 0;
Main.Validate(Main.VAL_NUMERIC, 'INCR', Value);
this.Database.set(Request[0], ++Value);
return Value;
}.bind(this));
}; |
Package requires at least Python 3.5 | from setuptools import setup
setup(
name='libgen.py',
version='0.1.0',
license='MIT',
author='Adolfo Silva',
author_email='code@adolfosilva.org',
url='https://github.com/adolfosilva/libgen.py',
description='A script to download books from gen.lib.rus.ec',
classifiers=[
'License :: OSI Approved :: MIT License',
],
keywords='libgen',
include_package_data=True, # include files listed in MANIFEST.in
tests_requires=['pytest'],
py_modules=['libgen'],
python_requires='~=3.5',
entry_points={
'console_scripts': ['libgen=libgen:main'],
},
install_requires=['beautifulsoup4', 'tabulate', 'requests']
)
| from setuptools import setup
setup(
name='libgen.py',
version='0.1.0',
license='MIT',
author='Adolfo Silva',
author_email='code@adolfosilva.org',
url='https://github.com/adolfosilva/libgen.py',
description='A script to download books from gen.lib.rus.ec',
classifiers=[
'License :: OSI Approved :: MIT License',
],
keywords='libgen',
include_package_data=True, # include files listed in MANIFEST.in
tests_requires=['pytest'],
py_modules=['libgen'],
entry_points={
'console_scripts': ['libgen=libgen:main'],
},
install_requires=['beautifulsoup4', 'tabulate', 'requests']
)
|
Change ref from string to callback | import React from 'react'
import { Component } from 'react'
class InputHeader extends Component {
focus = () => {
this._input.focus()
}
blur = () => {
this._input.blur()
}
render() {
return (
<div className="selectize-input items not-full has-options">
<input type="text" className="search-field" placeholder="Enter a location..."
ref={(c) => this._input = c}
value={this.props.search}
onChange={this.props.searchChange}
onKeyDown={this.props.handleKeyPress}
onFocus={this.props.handleFocus}
onBlur={this.props.handleBlur}
/>
</div>
)
}
}
export default InputHeader
| import React from 'react'
import { Component } from 'react'
class InputHeader extends Component {
focus = () => {
this.refs.inputHeader.focus()
}
blur = () => {
this.refs.inputHeader.blur()
}
render() {
return (
<div className="selectize-input items not-full has-options">
<input type="text" className="search-field" placeholder="Enter a location..."
ref="inputHeader"
value={this.props.search}
onChange={this.props.searchChange}
onKeyDown={this.props.handleKeyPress}
onFocus={this.props.handleFocus}
onBlur={this.props.handleBlur}
/>
</div>
)
}
}
export default InputHeader
|
Add new column: records table. | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRecordsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('records', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('book_id');
$table->integer('time');
$table->integer('return_time');
$table->boolean('enable');
$table->boolean('notified');
$table->index('user_id');
$table->index('return_time');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('records');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRecordsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('records', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('book_id');
$table->integer('time');
$table->integer('return_time');
$table->boolean('enable');
$table->index('user_id');
$table->index('return_time');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('records');
}
}
|
Add destructuring comment to home container | import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {fetchHome} from '../actions/homeActions';
class Home extends Component {
// Ajax call to get API data before the component mounts
componentWillMount() {
this.props.fetchHome("home");
}
render() {
// Destructure the home object
const {name, slogan, image_url} = this.props.home;
return(
<div id="home">
<h1>{name}</h1>
<h3>{slogan}</h3>
<img src={image_url} />
</div>
);
}
}
// Map State To Props
function mapStateToProps({home}) {
return {home};
}
// Bind actions and dispatch them
function mapDispatchToProps(dispatch) {
return bindActionCreators({fetchHome}, dispatch);
}
// Home Props Validation
Home.propTypes = {
fetchHome: PropTypes.func,
home: PropTypes.object
};
export default connect(mapStateToProps, mapDispatchToProps)(Home); | import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {fetchHome} from '../actions/homeActions';
class Home extends Component {
// Ajax call to get API data before the component mounts
componentWillMount() {
this.props.fetchHome("home");
}
render() {
const {name, slogan, image_url} = this.props.home;
return(
<div id="home">
<h1>{name}</h1>
<h3>{slogan}</h3>
<img src={image_url} />
</div>
);
}
}
// Map State To Props
function mapStateToProps({home}) {
return {home};
}
// Bind actions and dispatch them
function mapDispatchToProps(dispatch) {
return bindActionCreators({fetchHome}, dispatch);
}
// Home Props Validation
Home.propTypes = {
fetchHome: PropTypes.func,
home: PropTypes.object
};
export default connect(mapStateToProps, mapDispatchToProps)(Home); |
Exclude publishing tests from unit tests | 'use strict';
module.exports = function (config) {
config.set({
basePath: '../',
frameworks: ['browserify', 'mocha'],
plugins: [
'karma-browserify',
'karma-phantomjs-launcher',
'karma-mocha',
'karma-mocha-reporter'
],
browsers: ['PhantomJS'],
port: 7357,
reporters: ['mocha'],
preprocessors: {
'**/*.js': ['browserify']
},
browserify: {
extensions: ['.js', '.json'],
transform: require('../../package.json').browserify.transform,
ignore: [],
watch: true,
debug: true,
noParse: []
},
files: [
'**/*.js'
],
exclude: [
'**/*.swp',
'**/publishing/*.js'
]
});
};
| 'use strict';
module.exports = function (config) {
config.set({
basePath: '../',
frameworks: ['browserify', 'mocha'],
plugins: [
'karma-browserify',
'karma-phantomjs-launcher',
'karma-mocha',
'karma-mocha-reporter'
],
browsers: ['PhantomJS'],
port: 7357,
reporters: ['mocha'],
preprocessors: {
'**/*.js': ['browserify']
},
browserify: {
extensions: ['.js', '.json'],
transform: require('../../package.json').browserify.transform,
ignore: [],
watch: true,
debug: true,
noParse: []
},
files: [
'**/*.js'
],
exclude: ['**/*.swp']
});
};
|
Use Ember.computed instead of using prototype extension
- This will work with consumer applications that must run with
the Prototype Extensions turned off. | import Ember from 'ember';
import layout from '../templates/components/ember-favourite-heart';
export default Ember.Component.extend({
layout: layout,
liked: false,
likeCount: 0,
heartClass: Ember.computed('liked', function() {
if(this.get('liked')){
return "heart heartAnimation";
}else{
return "heart";
}
}),
heartStyle: Ember.computed('liked', function() {
if(this.get('liked')){
return "";
}else{
return "background-position: 0% 50%;";
}
}),
like: function(){
this.set('liked', true);
this.set('likeCount', this.get('likeCount') + 1);
},
unlike: function(){
this.set('liked', false);
this.set('likeCount', this.get('likeCount') - 1);
},
actions: {
toggleFav: function(){
if(this.get('liked')){
this.unlike();
}else{
this.like();
}
this.sendAction();
}
}
});
| import Ember from 'ember';
import layout from '../templates/components/ember-favourite-heart';
export default Ember.Component.extend({
layout: layout,
liked: false,
likeCount: 0,
heartClass: function(){
if(this.get('liked')){
return "heart heartAnimation";
}else{
return "heart";
}
}.property('liked'),
heartStyle: function(){
if(this.get('liked')){
return "";
}else{
return "background-position: 0% 50%;";
}
}.property('liked'),
like: function(){
this.set('liked', true);
this.set('likeCount', this.get('likeCount') + 1);
},
unlike: function(){
this.set('liked', false);
this.set('likeCount', this.get('likeCount') - 1);
},
actions: {
toggleFav: function(){
if(this.get('liked')){
this.unlike();
}else{
this.like();
}
this.sendAction();
}
}
});
|
Refactor displayStream. Add background-image and onClick | //onReady
$(function() {
//temporary testing functionality
$('#refreshBtn').on('click', function() {
updateStreams();
});
});
function updateStreams() {
// Clear out the stale data
$('#mainContainer').html("");
// And fetch the fresh
var streamList = $('#streamList').val().split('\n');
for (var i = 0, len = streamList.length; i < len; i++) {
fetchStreamData(streamList[i]);
}
}
function fetchStreamData( streamName ) {
$.getJSON('https://api.twitch.tv/kraken/streams/' + streamName + '?callback=?', function(data){
var streamObj = {};
streamObj.streamName = data.stream.channel.display_name;
streamObj.preview = data.stream.preview.medium;
streamObj.status = data.stream.channel.status;
streamObj.logo = data.stream.channel.logo;
streamObj.url = data.stream.channel.url;
displayStream(streamObj);
});
}
function displayStream( streamObj ) {
$('<div class="twitchContainer col-xs-12 col-sm-4">' +
'<img class="streamLogo" src="' + streamObj.logo + '" alt="logo">' +
'<h2>' + streamObj.streamName + '</h2>' +
'<p>' + streamObj.status + '</p>' +
'</div>'
)
.css('background-image', 'url(' + streamObj.preview + ')')
.on('click', function() {
window.open(streamObj.url, '_blank');
})
.appendTo($('#mainContainer'));
}
| //onReady
$(function() {
//temporary testing functionality
$('#refreshBtn').on('click', function() {
updateStreams();
});
});
function updateStreams() {
// Clear out the stale data
$('#mainContainer').html("");
// And fetch the fresh
var streamList = $('#streamList').val().split('\n');
for (var i = 0, len = streamList.length; i < len; i++) {
fetchStreamData(streamList[i]);
}
}
function fetchStreamData( streamName ) {
$.getJSON('https://api.twitch.tv/kraken/streams/' + streamName + '?callback=?', function(data){
var streamObj = {};
streamObj.streamName = data.stream.channel.display_name;
streamObj.preview = data.stream.preview.medium;
streamObj.status = data.stream.channel.status;
streamObj.logo = data.stream.channel.logo;
streamObj.url = data.stream._links.self;
displayStream(streamObj);
});
}
function displayStream( streamObj ) {
$('#mainContainer').append(
'<div class="twitchContainer col-xs-12 col-sm-4">' +
'<img class="streamLogo" src="' + streamObj.logo + '" alt="logo">' +
'<h2>' + streamObj.streamName + '</h2>' +
'<p>' + streamObj.status + '</p>' +
'</div>'
);
}
|
Revert "Java.inc now included from a cache so that it is debuggable"
This reverts commit ad4c67b356187883ba050056aab430a4f83cd14c. | <?php
/*
* This file is part of the Eulogix\Lib package.
*
* (c) Eulogix <http://www.eulogix.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eulogix\Lib\Java;
/**
* @author Pietro Baricco <pietro@eulogix.com>
*/
class Bridge {
/**
* @var string
*/
private $url = "";
/**
* @param string $url
*/
public function __construct($url) {
$this->url = $url;
require_once("$url/java/Java.inc");
}
/**
* @param string $class
* @return object
*/
public function instanceJavaClass($class)
{
return new \java($class);
}
} | <?php
/*
* This file is part of the Eulogix\Lib package.
*
* (c) Eulogix <http://www.eulogix.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eulogix\Lib\Java;
/**
* @author Pietro Baricco <pietro@eulogix.com>
*/
class Bridge {
/**
* @var string
*/
private $url = "", $dir = "";
/**
* @param string $url
*/
public function __construct($url, $dir) {
$this->url = $url;
$this->dir = $dir;
$javaInc = $dir.DIRECTORY_SEPARATOR."Java.inc";
if(!file_exists($javaInc)) {
copy("$url/java/Java.inc", $javaInc);
}
require_once($javaInc);
}
/**
* @param string $class
* @return object
*/
public function instanceJavaClass($class)
{
return new \java($class);
}
} |
Fix `blur` and `focus` events. | "use strict";
var read = require("./listener/read").read
var readers = require("./listener/read").readers
var Input = require("./signal").Input
var receive = require("./signal").receive
var eventTypes = Object.keys(readers);
var findEventTarget = function(event, root) {
var targetAttribute = "data-reflex-event-" + event.type
var node = event.target
while (node !== root &&
!node.hasAttribute(targetAttribute)) {
node = node.parentNode
}
return node === root ? null : node
}
var listen = function(root) {
var input = new Input()
var listener = function(event) {
var target = findEventTarget(event, root)
if (target) {
var path = target.getAttribute("data-reflex-path")
var message = read(event)
message.path = path
message.type = event.type
receive(input, message)
return false
}
}
eventTypes.forEach(function(type) {
root.addEventListener(type, listener, true)
})
return input
}
exports.listen = listen
| "use strict";
var read = require("./listener/read").read
var readers = require("./listener/read").readers
var Input = require("./signal").Input
var receive = require("./signal").receive
var eventTypes = Object.keys(readers);
var findEventTarget = function(event, root) {
var targetAttribute = "data-reflex-event-" + event.type
var node = event.target
while (node !== root &&
!node.hasAttribute(targetAttribute)) {
node = node.parentNode
}
return node === root ? null : node
}
var listen = function(root) {
var input = new Input()
var listener = function(event) {
var target = findEventTarget(event, root)
if (target) {
var path = target.getAttribute("data-reflex-path")
var message = read(event)
message.path = path
message.type = event.type
receive(input, message)
return false
}
}
eventTypes.forEach(function(type) {
root.addEventListener(type, listener, false)
})
return input
}
exports.listen = listen
|
Change 'language' to 'syntax', that is more precise terminology. | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter-contrib-gjslint
# License: MIT
#
"""This module exports the GJSLint plugin linter class."""
from SublimeLinter.lint import Linter
class GJSLint(Linter):
"""Provides an interface to the gjslint executable."""
syntax = ('javascript', 'html')
cmd = 'gjslint --nobeep --nosummary'
regex = r'^Line (?P<line>\d+), (?:(?P<error>E)|(?P<warning>W)):\d+: (?P<message>[^"]+(?P<near>"[^"]+")?)$'
comment_re = r'\s*/[/*]'
defaults = {
'--jslint_error:,+': '',
'--disable:,': '',
'--max_line_length:': None
}
inline_settings = 'max_line_length'
inline_overrides = 'disable'
tempfile_suffix = 'js'
selectors = {
'html': 'source.js.embedded.html'
}
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter-contrib-gjslint
# License: MIT
#
"""This module exports the GJSLint plugin linter class."""
from SublimeLinter.lint import Linter
class GJSLint(Linter):
"""Provides an interface to the gjslint executable."""
language = ('javascript', 'html')
cmd = 'gjslint --nobeep --nosummary'
regex = r'^Line (?P<line>\d+), (?:(?P<error>E)|(?P<warning>W)):\d+: (?P<message>[^"]+(?P<near>"[^"]+")?)$'
comment_re = r'\s*/[/*]'
defaults = {
'--jslint_error:,+': '',
'--disable:,': '',
'--max_line_length:': None
}
inline_settings = 'max_line_length'
inline_overrides = 'disable'
tempfile_suffix = 'js'
selectors = {
'html': 'source.js.embedded.html'
}
|
Allow descendents of BaseImageStep to override source Image. | from typing import Any, NamedTuple, Optional
import numpy as np
from data.image import image
from puzzle.steps import step
class ImageChangeEvent(NamedTuple):
pass
class BaseImageStep(step.Step):
_source: image.Image
_result: Optional[image.Image]
def __init__(self,
source: image.Image,
dependencies: Optional[step.Dependencies] = None,
constraints: Optional[step.Constraints] = None) -> None:
super(BaseImageStep, self).__init__(
dependencies=dependencies,
constraints=constraints)
if constraints:
for constraint in constraints:
constraint.subscribe(self._on_constraints_changed)
self._source = source
self._result = None
def get_result(self) -> image.Image:
if self._result is None:
self._result = self._modify_result(self._get_new_source())
return self._result
def get_debug_data(self) -> np.ndarray:
return self.get_result().get_debug_data()
def _get_new_source(self) -> image.Image:
return self._source.fork()
def _modify_result(self, result: image.Image) -> image.Image:
raise NotImplementedError()
def _on_constraints_changed(self, change: Any) -> None:
del change
self._result = None
self._subject.on_next(ImageChangeEvent())
| from typing import Any, NamedTuple, Optional
import numpy as np
from data.image import image
from puzzle.steps import step
class ImageChangeEvent(NamedTuple):
pass
class BaseImageStep(step.Step):
_source: image.Image
_result: Optional[image.Image]
def __init__(self,
source: image.Image,
dependencies: Optional[step.Dependencies] = None,
constraints: Optional[step.Constraints] = None) -> None:
super(BaseImageStep, self).__init__(
dependencies=dependencies,
constraints=constraints)
if constraints:
for constraint in constraints:
constraint.subscribe(self._on_constraints_changed)
self._source = source
self._result = None
def get_result(self) -> image.Image:
if self._result is None:
self._result = self._modify_result(self._source.fork())
return self._result
def get_debug_data(self) -> np.ndarray:
return self.get_result().get_debug_data()
def _modify_result(self, result: image.Image) -> image.Image:
raise NotImplementedError()
def _on_constraints_changed(self, change: Any) -> None:
del change
self._result = None
self._subject.on_next(ImageChangeEvent())
|
Allow for input from stdin and output to stdout | const {convert} = require('stencila-convert')
module.exports = cli => {
cli
.command('convert', 'Convert files or folders to other formats')
.argument('[input]', 'Input file or folder to convert from (or "-" for standard input)', null, '-')
.argument('[output]', 'Input file or folder to convert to (or "-" for standard output)', null, '-')
.option('--from', 'Format to convert from (overrides file name extensions)')
.option('--to', 'Format to convert to (overrides file name extensions)')
.action(async (args, options, logger) => {
const {input, output} = args
const {from, to} = options
logger.debug(`Converting "${input}" to "${output}"`)
try {
await convert(input, output, null, null, from, to)
logger.ok(`Success converting "${input}" to "${output}"`)
} catch (err) {
logger.error(`Error converting "${input}" to "${output}": ${err.message}`)
}
})
}
| const {convert} = require('stencila-convert')
module.exports = cli => {
cli
.command('convert', 'Convert files or folders to other formats')
.argument('<input>', 'Input file or folder to convert from')
.argument('<output>', 'Input file or folder to convert to')
.option('--from', 'Format to convert from (overrides file name extensions)')
.option('--to', 'Format to convert to (overrides file name extensions)')
.action(async (args, options, logger) => {
const {input, output} = args
const {from, to} = options
logger.debug(`Converting "${input}" to "${output}"`)
try {
await convert(input, output, null, null, from, to)
logger.ok(`Success converting "${input}" to "${output}"`)
} catch (err) {
logger.error(`Error converting "${input}" to "${output}": ${err.message}`)
}
})
}
|
Fix bug when calling `setupCalendar` | import setupCalendar from './utils/setup';
import Calendar from '@/components/Calendar';
import DatePicker from '@/components/DatePicker';
// Export components individually
export { setupCalendar, Calendar, DatePicker };
// Installs the library as a plugin
const components = {
Calendar,
DatePicker,
};
// Declare install function executed by Vue.use()
export default function install(Vue, opts) {
// Don't install more than once
if (install.installed) return;
install.installed = true;
// Manually setup calendar with options
const defaults = setupCalendar(opts);
// Register components
Object.keys(components).forEach(k =>
Vue.component(`${defaults.componentPrefix}${k}`, components[k]),
);
}
// Create module definition for Vue.use()
const plugin = {
install,
};
// Use automatically when global Vue instance detected
let GlobalVue = null;
if (typeof window !== 'undefined') {
GlobalVue = window.Vue;
} else if (typeof global !== 'undefined') {
GlobalVue = global.Vue;
}
if (GlobalVue) {
GlobalVue.use(plugin);
}
| import setupCalendar from './utils/setup';
import Calendar from '@/components/Calendar';
import DatePicker from '@/components/DatePicker';
// Export components individually
export { setupCalendar, Calendar, DatePicker };
// Installs the library as a plugin
const components = {
Calendar,
DatePicker,
};
// Declare install function executed by Vue.use()
export default function install(Vue, opts) {
// Don't install more than once
if (install.installed) return;
install.installed = true;
// Manually setup calendar with options
const defaults = setupCalendar(Vue, opts);
// Register components
Object.keys(components).forEach(k =>
Vue.component(`${defaults.componentPrefix}${k}`, components[k]),
);
}
// Create module definition for Vue.use()
const plugin = {
install,
};
// Use automatically when global Vue instance detected
let GlobalVue = null;
if (typeof window !== 'undefined') {
GlobalVue = window.Vue;
} else if (typeof global !== 'undefined') {
GlobalVue = global.Vue;
}
if (GlobalVue) {
GlobalVue.use(plugin);
}
|
Rewrite using modern JavaScript features | class FakeStorage {
#data = {};
get length() {
return Object.keys(this.#data).length;
}
key(n) {
return Object.keys(this.#data)[Number.parseInt(n, 10)] ?? null;
}
getItem(key) {
const _data = this.#data;
const _key = `${key}`;
return Object.prototype.hasOwnProperty.call(_data, _key)
? _data[_key]
: null;
}
setItem(key, value) {
return (this.#data[`${key}`] = `${value}`);
}
removeItem(key, value) {
const _data = this.#data;
const _key = `${key}`;
if (Object.prototype.hasOwnProperty.call(_data, _key)) {
delete _data[_key];
}
}
clear(key, value) {
this.#data = {};
}
}
export default FakeStorage;
| function FakeStorage() {
this.clear();
}
FakeStorage.prototype = {
key(index) {
// sanitise index as int
index = parseInt(index);
// return early if index isn't a positive number or larger than length
if (isNaN(index) || index < 0 || index >= this.length) {
return null;
}
// loop through data object until at nth key
let i = 0;
for (const key in this._data) {
if (this._data.hasOwnProperty(key)) {
if (i === index) {
return key;
}
i++;
}
}
// otherwise return null
return null;
},
getItem(key) {
// only get if there's something to get
return this._data.hasOwnProperty(key) ? this._data[key] : null;
},
setItem(key, value) {
// if we're adding a new item, increment the length
if (!this._data.hasOwnProperty(key)) {
this.length++;
}
// always store the value as a string
this._data[key] = value.toString();
},
removeItem(key) {
// only remove if there's something to remove
if (this._data.hasOwnProperty(key)) {
delete this._data[key];
this.length--;
}
},
clear() {
this._data = {};
this.length = 0;
},
};
export default FakeStorage;
|
Set max frame size to 15MB in the cli to avoid OOM.
Patch by Tyler Hobbs, reviewed by brandonwilliams for CASSANDRA-4969 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.cli.transport;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportFactory;
public class FramedTransportFactory extends TTransportFactory
{
public static final int DEFAULT_MAX_FRAME_SIZE = 15 * 1024 * 1024; // 15 MiB
public TTransport getTransport(TTransport base)
{
return new TFramedTransport(base, DEFAULT_MAX_FRAME_SIZE);
}
}
| /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.cli.transport;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportFactory;
public class FramedTransportFactory extends TTransportFactory
{
public TTransport getTransport(TTransport base)
{
return new TFramedTransport(base);
}
}
|
Fix shaka.polyfill missing in externs
The generated externs did not include shaka.polyfill because we used
the wrong annotation on the class. This fixes it.
Raised in PR #1273
Change-Id: I348064a117a7e1878b439ad8bd1ce49df56bfd39 | /** @license
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
goog.provide('shaka.polyfill');
goog.require('shaka.util.Iterables');
/**
* @summary A one-stop installer for all polyfills.
* @see http://enwp.org/polyfill
* @exportInterface
*/
shaka.polyfill = class {
/**
* Install all polyfills.
* @export
*/
static installAll() {
for (const polyfill of shaka.polyfill.polyfills_) {
polyfill.callback();
}
}
/**
* Registers a new polyfill to be installed.
*
* @param {function()} polyfill
* @param {number=} priority An optional number priority. Higher priorities
* will be executed before lower priority ones. Default is 0.
* @export
*/
static register(polyfill, priority) {
const newItem = {priority: priority || 0, callback: polyfill};
const enumerate = (it) => shaka.util.Iterables.enumerate(it);
for (const {i, item} of enumerate(shaka.polyfill.polyfills_)) {
if (item.priority < newItem.priority) {
shaka.polyfill.polyfills_.splice(i, 0, newItem);
return;
}
}
shaka.polyfill.polyfills_.push(newItem);
}
};
/**
* Contains the polyfills that will be installed.
* @private {!Array.<{priority: number, callback: function()}>}
*/
shaka.polyfill.polyfills_ = [];
| /** @license
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
goog.provide('shaka.polyfill');
goog.require('shaka.util.Iterables');
/**
* @summary A one-stop installer for all polyfills.
* @see http://enwp.org/polyfill
* @exportDoc
*/
shaka.polyfill = class {
/**
* Install all polyfills.
* @export
*/
static installAll() {
for (const polyfill of shaka.polyfill.polyfills_) {
polyfill.callback();
}
}
/**
* Registers a new polyfill to be installed.
*
* @param {function()} polyfill
* @param {number=} priority An optional number priority. Higher priorities
* will be executed before lower priority ones. Default is 0.
* @export
*/
static register(polyfill, priority) {
const newItem = {priority: priority || 0, callback: polyfill};
const enumerate = (it) => shaka.util.Iterables.enumerate(it);
for (const {i, item} of enumerate(shaka.polyfill.polyfills_)) {
if (item.priority < newItem.priority) {
shaka.polyfill.polyfills_.splice(i, 0, newItem);
return;
}
}
shaka.polyfill.polyfills_.push(newItem);
}
};
/**
* Contains the polyfills that will be installed.
* @private {!Array.<{priority: number, callback: function()}>}
*/
shaka.polyfill.polyfills_ = [];
|
Normalize newlines in comparison strings to ensure proper comparison | var jsdiff = require('diff');
// Taken from diff.js
function removeEmpty(array) {
var ret = [];
for (var i = 0; i < array.length; i++) {
if (array[i]) {
ret.push(array[i]);
}
}
return ret;
}
// Custom differ that includes newlines and sentence breaks
var wikiDiff = new jsdiff.Diff();
wikiDiff.tokenize = function (value) {
return removeEmpty(value.split(/(\S.+?[.!?\n])(?=\s+|$)/));
};
var diff = function(beforeText, afterText) {
beforeText = beforeText.replace(/(?:\r\n|\r|\n)/g, '\n');
afterText = afterText.replace(/(?:\r\n|\r|\n)/g, '\n');
var diffList = wikiDiff.diff(beforeText, afterText);
var fragment = document.createDocumentFragment();
diffList.forEach(function(part) {
var color = part.added ? 'text-success' : part.removed ? 'text-danger' : '';
var span = part.removed ? document.createElement('s') : document.createElement('span');
span.className = color;
span.appendChild(document.createTextNode(part.value));
fragment.appendChild(span);
});
var output = $('<div>').append(fragment).html();
return output;
};
module.exports = {
diff: diff
}; | var jsdiff = require('diff');
// Taken from diff.js
function removeEmpty(array) {
var ret = [];
for (var i = 0; i < array.length; i++) {
if (array[i]) {
ret.push(array[i]);
}
}
return ret;
}
// Custom differ that includes newlines and sentence breaks
var wikiDiff = new jsdiff.Diff();
wikiDiff.tokenize = function (value) {
return removeEmpty(value.split(/(\S.+?[.!?\n])(?=\s+|$)/));
};
var diff = function(beforeText, afterText) {
var diffList = wikiDiff.diff(beforeText, afterText);
var fragment = document.createDocumentFragment();
diffList.forEach(function(part) {
var color = part.added ? 'text-success' : part.removed ? 'text-danger' : '';
var span = part.removed ? document.createElement('s') : document.createElement('span');
span.className = color;
span.appendChild(document.createTextNode(part.value));
fragment.appendChild(span);
});
var output = $('<div>').append(fragment).html();
return output;
};
module.exports = {
diff: diff
}; |
Reorganize bot start sequence, including custom naming | package main // import "cirello.io/gochatbot"
import (
"log"
"os"
"cirello.io/gochatbot/bot"
"cirello.io/gochatbot/brain"
"cirello.io/gochatbot/providers"
"cirello.io/gochatbot/rules/cron"
"cirello.io/gochatbot/rules/regex"
)
func main() {
name := os.Getenv("GOCHATBOT_NAME")
if name == "" {
name = "gochatbot"
}
provider := providers.Detect(os.Getenv)
if err := provider.Error(); err != nil {
log.SetOutput(os.Stderr)
log.Fatalln("error in message provider:", err)
}
memory := brain.Detect(os.Getenv)
if err := memory.Error(); err != nil {
log.SetOutput(os.Stderr)
log.Fatalln("error in brain memory:", err)
}
bot.New(
name,
memory,
bot.MessageProvider(provider),
bot.RegisterRuleset(regex.New()),
bot.RegisterRuleset(cron.New()),
).Process()
}
| package main // import "cirello.io/gochatbot"
import (
"log"
"os"
"cirello.io/gochatbot/bot"
"cirello.io/gochatbot/brain"
"cirello.io/gochatbot/providers"
"cirello.io/gochatbot/rules/cron"
"cirello.io/gochatbot/rules/regex"
)
func main() {
provider := providers.Detect(os.Getenv)
memory := brain.Detect(os.Getenv)
robot := bot.New(
"gochatbot",
memory,
bot.MessageProvider(provider),
bot.RegisterRuleset(regex.New()),
bot.RegisterRuleset(cron.New()),
)
if err := provider.Error(); err != nil {
log.SetOutput(os.Stderr)
log.Fatalln("error in message provider:", err)
}
if err := memory.Error(); err != nil {
log.SetOutput(os.Stderr)
log.Fatalln("error in brain memory:", err)
}
robot.Process()
}
|
Add some comments and refine echo command |
const Discord = require('discord.js');
const client = new Discord.Client();
const config = require("./config.json");
client.on('ready', () => {
console.log("I am ready!");
});
client.on('message', (message) => {
if (!message.content.startsWith(config.prefix) || message.author.bot) return; // Ignore messages not
// starting with your prefix
let msg = message.content.slice(config.prefix.length);
if (msg.startsWith('ping')) {
message.reply('pong');
}
if (msg.startsWith('echo')) {
if (msg.length > 5 && msg[4] === ' ') { // If msg starts with 'echo '
message.channel.send(msg.slice(5)); // Echo the rest of msg.
} else {
message.channel.send("Please provide valid text to echo!");
}
}
if (msg.startsWith('die')) {
message.channel.send("Shutting down...");
client.destroy((err) => {
console.log(err);
});
}
});
client.on('disconnected', () => {
console.log("Disconnected!");
process.exit(0);
});
client.login(config.token); |
const Discord = require('discord.js');
const client = new Discord.Client();
const config = require("./config.json");
client.on('ready', () => {
console.log("I am ready!");
// client.channels.get('spam').send("Soup is ready!")
});
client.on('message', (message) => {
if (!message.content.startsWith(config.prefix) || message.author.bot) return;
let msg = message.content.slice(config.prefix.length);
if (msg.startsWith('ping')) {
message.reply('pong');
}
if (msg.startsWith('echo')) {
if (msg.length > 5) {
message.channel.send(msg.slice(5));
} else {
message.channel.send("Please provide valid text to echo!");
}
}
if (msg.startsWith('die')) {
message.channel.send("Shutting down...");
client.destroy((err) => {
console.log(err);
});
}
});
client.on('disconnected', () => {
console.log("Disconnected!");
process.exit(0);
});
client.login(config.token); |
Sort content items by DEC _id | 'use strict';
const _ = require('lodash');
const Bluebird = require('bluebird');
const mongoose = require('mongoose');
const mongooseDelete = require('mongoose-delete');
const ShortId = require('mongoose-shortid-nodeps');
const Settings = require('../../settings');
const Content = require('./content');
const validations = require('./validations');
const schema = new mongoose.Schema({
code: {
type : ShortId,
index : true // Added to make the code unique
},
name: String,
active: { type: Boolean, default: true },
content: [ Content ]
});
schema.plugin(validations);
schema.plugin(mongooseDelete, { overrideMethods: 'all' });
function transform(doc, ret) {
let result = _.cloneDeep(ret);
result = _.pick(ret, Settings.ContentCode.paths);
// Sort by created date. It would be better to add a created_at field.
result.content = _.sortBy(result.content, (ci) => {
return -ci._id.getTimestamp();
});
return result;
}
schema.set('toJSON', { transform });
schema.set('toObject', { transform });
// Promisify mongoose-delete methods
Bluebird.promisifyAll(schema.methods);
module.exports = schema;
| 'use strict';
const _ = require('lodash');
const Bluebird = require('bluebird');
const mongoose = require('mongoose');
const mongooseDelete = require('mongoose-delete');
const ShortId = require('mongoose-shortid-nodeps');
const Settings = require('../../settings');
const Content = require('./content');
const validations = require('./validations');
const schema = new mongoose.Schema({
code: {
type : ShortId,
index : true // Added to make the code unique
},
name: String,
active: { type: Boolean, default: true },
content: [ Content ]
});
schema.plugin(validations);
schema.plugin(mongooseDelete, { overrideMethods: 'all' });
function transform(doc, ret) {
return _.pick(ret, Settings.ContentCode.paths);
}
schema.set('toJSON', { transform });
schema.set('toObject', { transform });
// Promisify mongoose-delete methods
Bluebird.promisifyAll(schema.methods);
module.exports = schema;
|
Add initial support for growl
If growl lib isn't available, prints to console instead. | #!/usr/bin/env python
import urllib2
import ssl
try:
import gntp.notifier as notify
except ImportError:
notify = None
def poll(sites, timeout, ok, error):
for site in sites:
ok('polling ' + site)
try:
response = urllib2.urlopen(site, timeout=timeout)
response.read()
except urllib2.URLError as e:
error(site + ' ' + e.code)
except ssl.SSLError as e:
error(site + ' ' + e.message)
else:
ok('ok')
def empty(data):
pass
def output(data):
if notify:
notify.mini(data)
else:
print data
if __name__ == '__main__':
poll(sites=(
'https://redmine.codegrove.org',
'http://koodilehto.fi',
'http://vakiopaine.net',
), timeout=5, ok=empty, error=output)
| #!/usr/bin/env python
import urllib2
import ssl
def poll(sites, timeout):
for site in sites:
print 'polling ' + site
try:
response = urllib2.urlopen(site, timeout=timeout)
response.read()
except urllib2.URLError as e:
print e.code
except ssl.SSLError as e:
print e.message
else:
print 'ok'
if __name__ == '__main__':
poll(sites=(
'https://redmine.codegrove.org',
'http://koodilehto.fi',
'http://vakiopaine.net',
), timeout=5)
|
Fix rough command for correcting operator regions | from django.core.management.base import BaseCommand
from busstops.models import Operator, Region
class Command(BaseCommand):
@staticmethod
def maybe_move_operator(operator, regions):
if bool(regions) and operator.region not in regions:
if len(regions) == 1:
print 'moving', operator, 'from', operator.region, 'to', regions[0]
operator.region = regions[0]
operator.save()
else:
print operator, operator.region, regions
def handle(self, *args, **options):
for operator in Operator.objects.all():
# move Anglian Bus to the East Anglia
regions = Region.objects.filter(service__operator=operator).distinct()
self.maybe_move_operator(operator, regions)
# move Cumbria to the North West
regions = Region.objects.filter(adminarea__locality__stoppoint__service__operator=operator).distinct()
self.maybe_move_operator(operator, regions)
| from django.core.management.base import BaseCommand
from busstops.models import Operator, Region
class Command(BaseCommand):
@staticmethod
def maybe_move_operator(operator, regions)
if bool(regions) and operator.region not in regions:
if len(regions) == 1:
print 'moving', operator, 'from', operator.region, 'to', regions[0]
operator.region = regions[0]
operator.save()
else:
print operator, operator.region, regions
def handle(self, *args, **options):
for operator in Operator.objects.all():
# move Anglian Bus to the East Anglia
regions = Region.objects.filter(service__operator=operator).distinct()
maybe_move_operator(operator, regions)
# move Cumbria to the North West
regions = Region.objects.filter(adminarea__locality__stoppoint__service__operator=operator).distinct()
maybe_move_operator(operator, regions)
|
Remove unnecessary tests from i18n instance-initializer tests | import I18nInstanceInitializer from 'ember-flexberry/instance-initializers/i18n';
import { module, test } from 'qunit';
import startApp from '../../helpers/start-app';
import destroyApp from '../../helpers/destroy-app';
let application;
let appInstance;
let fakeLocale;
module('Unit | Instance Initializer | i18n', {
beforeEach: function() {
application = startApp();
appInstance = application.buildInstance();
// Set 'fake-locale' as default i18n-service locale.
let i18n = appInstance.lookup('service:i18n');
fakeLocale = 'fake-locale';
i18n.set('locale', fakeLocale);
},
afterEach: function() {
destroyApp(appInstance);
destroyApp(application);
}
});
test('Configures i18n service for locale', function(assert) {
assert.expect(2);
let i18n = appInstance.lookup('service:i18n');
assert.strictEqual(i18n.get('locale'), fakeLocale, 'Default i18n-service locale is \'' + fakeLocale + '\'');
var browserCurrentLocale = window.navigator.languages ? window.navigator.languages[0] : (window.navigator.language || window.navigator.userLanguage);
I18nInstanceInitializer.initialize(appInstance);
assert.strictEqual(i18n.get('locale'), browserCurrentLocale, 'Current i18n-service locale is \'' + browserCurrentLocale + '\'');
});
| import Ember from 'ember';
import I18nInstanceInitializer from 'ember-flexberry/instance-initializers/i18n';
import { module, test } from 'qunit';
import startApp from '../../helpers/start-app';
import destroyApp from '../../helpers/destroy-app';
let application;
let appInstance;
module('Unit | Instance Initializer | i18n', {
beforeEach: function() {
application = startApp();
appInstance = application.buildInstance();
},
afterEach: function() {
Ember.run(appInstance, 'destroy');
destroyApp(appInstance);
}
});
test('It works', function(assert) {
assert.expect(1);
I18nInstanceInitializer.initialize(appInstance);
assert.ok(true);
});
test('Add true logic', function(assert) {
assert.expect(2);
assert.strictEqual(appInstance.__container__.factoryCache['service:i18n'], undefined);
I18nInstanceInitializer.initialize(appInstance);
assert.strictEqual(appInstance.__container__.factoryCache['service:i18n']._toString, 'dummy@service:i18n:');
});
test('Configures i18n service for locale', function(assert) {
assert.expect(1);
var controlValue = window.navigator.languages ? window.navigator.languages[0] : (window.navigator.language || window.navigator.userLanguage);
I18nInstanceInitializer.initialize(appInstance);
assert.strictEqual(appInstance.__container__.cache['service:i18n'].locale, controlValue);
});
|
Resolve route allow empty / nullable path | <?php
namespace App\Http\Requests\Api\v1\Route;
use Gate;
use App\Models\Page;
use Illuminate\Validation\Rule;
use App\Http\Requests\FormRequest;
class ResolveRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'path' => ['string','nullable'],
'host' => 'required'
];
}
/**
* Get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
return [
];
}
}
| <?php
namespace App\Http\Requests\Api\v1\Route;
use Gate;
use App\Models\Page;
use Illuminate\Validation\Rule;
use App\Http\Requests\FormRequest;
class ResolveRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'path' => 'required',
'host' => 'required'
];
}
/**
* Get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
return [
];
}
}
|
Change pre from 'save' to 'validate'
Validate is called before save or udpate so now I don't get plain
passwords on update. That's good... | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt');
var SALT_WORK_FACTOR = 10;
var UserSchema = new Schema({
"username": { type: String, unique: true, required: true },
"password": { type: String, required: true }
});
UserSchema.pre('validate', function(next) {
var user = this;
if (!user.isModified('password')) return next();
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword, callback) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return callback(err);
callback(null, isMatch);
});
};
mongoose.model('User', UserSchema);
| var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt');
var SALT_WORK_FACTOR = 10;
var UserSchema = new Schema({
"username": { type: String, unique: true, required: true },
"password": { type: String, required: true }
});
UserSchema.pre('save', function(next) {
var user = this;
if (!user.isModified('password')) return next();
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword, callback) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return callback(err);
callback(null, isMatch);
});
};
mongoose.model('User', UserSchema);
|
Add command prefix len for substr optimization | package co.phoenixlab.discord;
import java.util.HashSet;
import java.util.Set;
public class Configuration {
private String email;
private String password;
private String commandPrefix;
private transient int prefixLength;
private Set<String> blacklist;
public Configuration() {
email = "";
password = "";
commandPrefix = "!";
prefixLength = 0;
blacklist = new HashSet<>();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCommandPrefix() {
return commandPrefix;
}
public int getPrefixLength() {
// Lazy load after we load from config file
if (prefixLength == 0) {
prefixLength = commandPrefix.length();
}
return prefixLength;
}
public void setCommandPrefix(String commandPrefix) {
this.commandPrefix = commandPrefix;
prefixLength = this.commandPrefix.length();
}
public Set<String> getBlacklist() {
return blacklist;
}
}
| package co.phoenixlab.discord;
import java.util.HashSet;
import java.util.Set;
public class Configuration {
private String email;
private String password;
private String commandPrefix;
private Set<String> blacklist;
public Configuration() {
email = "";
password = "";
commandPrefix = "!";
blacklist = new HashSet<>();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCommandPrefix() {
return commandPrefix;
}
public void setCommandPrefix(String commandPrefix) {
this.commandPrefix = commandPrefix;
}
public Set<String> getBlacklist() {
return blacklist;
}
}
|
Update support data for CSS Font Loading API. | define([], function () {
return {
name: 'CSS Font Loading',
description: 'The [CSS3 font loading module](http://dev.w3.org/csswg/css-font-loading/) defines a new interface for managing web fonts. It can be used to load fonts, manipulate fonts already in the document and gives you JavaScript events for font load states.',
specification: 'http://dev.w3.org/csswg/css-font-loading/',
keywords: ['font events', 'font loading', 'font', 'loading', 'event'],
browsers: [
{ name: "ie", range: "-", support: "no" },
{ name: "edge", range: "-", support: "no" },
{ name: "chrome", range: "-34", support: "no" },
{ name: "chrome", range: "35-", support: "yes" },
{ name: "firefox", range: "-40", support: "no" },
{ name: "firefox", range: "41-", support: "yes" },
{ name: "opera", range: "-21", support: "no" },
{ name: "opera", range: "22-", support: "yes" },
{ name: "safari", range: "-", support: "no" },
{ name: "ios", range: "-", support: "no" },
{ name: "android", range: "-", support: "no" }
]
};
});
| define([], function () {
return {
name: 'CSS Font Loading',
description: 'The [CSS3 font loading module](http://dev.w3.org/csswg/css-font-loading/) defines a new interface for managing web fonts. It can be used to load fonts, manipulate fonts already in the document and gives you JavaScript events for font load states.',
specification: 'http://dev.w3.org/csswg/css-font-loading/',
keywords: ['font events', 'font loading', 'font', 'loading', 'event'],
browsers: [
{ name: "ie", range: "-", support: "no" },
{ name: "chrome", range: "-34", support: "no" },
{ name: "chrome", range: "35-", support: "yes" },
{ name: "firefox", range: "-", support: "no", note: "Support for the CSS Font Loading API should be available in Firefox 35 ([source](https://bugzilla.mozilla.org/show_bug.cgi?id=1028497))." },
{ name: "opera", range: "-21", support: "no" },
{ name: "opera", range: "22-", support: "yes" },
{ name: "safari", range: "-", support: "no" },
{ name: "ios", range: "-", support: "no" },
{ name: "android", range: "-", support: "no" }
]
};
});
|
Add stateProvider state for user | (function(){
'use strict';
angular
.module('secondLead',
['ngDragDrop',
'ui.bootstrap',
'ui.router',
'gridster',
'restangular',
'angularUtils.directives.dirPagination',
'secondLead.common',
'templates'])
.config(function(paginationTemplateProvider) {
paginationTemplateProvider.setPath('/dirPagination.html');
})
.config(['$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('dramas-model', {
url:'/dramas',
templateUrl: 'dramas-index.html',
controller:'DramasCtrl',
controllerAs: 'dramas'
});
.state('users-model', {
url:'/users',
templateUrl: 'user-show.html',
controller:'UserCtrl',
controllerAs: 'user'
});
$urlRouterProvider.otherwise('/');
}]);
})();
| (function(){
'use strict';
angular
.module('secondLead',
['ngDragDrop',
'ui.bootstrap',
'ui.router',
'gridster',
'restangular',
'angularUtils.directives.dirPagination',
'secondLead.common',
'templates'])
.config(function(paginationTemplateProvider) {
paginationTemplateProvider.setPath('/dirPagination.html');
})
.config(['$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('dramas-model', {
url:'/dramas',
templateUrl: 'dramas-index.html',
controller:'DramasCtrl',
controllerAs: 'dramas'
});
$urlRouterProvider.otherwise('/');
}]);
})();
|
Add a helper method to get a query instance | <?php
/**
* Solr data helper
*
* @category Asm
* @package Asm_Solr
* @author Ingo Renner <ingo@infielddesign.com>
*/
class Asm_Solr_Helper_Data extends Mage_Core_Helper_Abstract
{
/**
* Gets the current Solr query
*
* @return Asm_Solr_Model_Solr_Query
*/
public function getQuery()
{
return Mage::getSingleton('solr/solr_query');
}
/**
* Generates a document id for documents representing product records.
*
* @param integer $productId Product ID
* @return string The document id for that product
*/
public function getProductDocumentId($productId) {
$baseUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
$host = parse_url($baseUrl, PHP_URL_HOST);
$siteHash = $this->getSiteHashForDomain($host);
$documentId = $siteHash . '/' . Mage_Catalog_Model_Product::ENTITY . '/' . $productId;
return $documentId;
}
/**
* Gets the site hash for a domain
*
* @param string $domain Domain to calculate the site hash for.
* @return string site hash for $domain
*/
public function getSiteHashForDomain($domain) {
$encryptionKey = Mage::getStoreConfig('global/crypt/key');
$siteHash = sha1(
$domain .
$encryptionKey .
'Asm_Solr'
);
return $siteHash;
}
}
| <?php
/**
* Solr data helper
*
* @category Asm
* @package Asm_Solr
* @author Ingo Renner <ingo@infielddesign.com>
*/
class Asm_Solr_Helper_Data extends Mage_Core_Helper_Abstract
{
/**
* Generates a document id for documents representing product records.
*
* @param integer $productId Product ID
* @return string The document id for that product
*/
public function getProductDocumentId($productId) {
$baseUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
$host = parse_url($baseUrl, PHP_URL_HOST);
$siteHash = $this->getSiteHashForDomain($host);
$documentId = $siteHash . '/' . Mage_Catalog_Model_Product::ENTITY . '/' . $productId;
return $documentId;
}
/**
* Gets the site hash for a domain
*
* @param string $domain Domain to calculate the site hash for.
* @return string site hash for $domain
*/
public function getSiteHashForDomain($domain) {
$encryptionKey = Mage::getStoreConfig('global/crypt/key');
$siteHash = sha1(
$domain .
$encryptionKey .
'Asm_Solr'
);
return $siteHash;
}
}
|
Remove the glob matcher for Windows compat
https://github.com/philipwalton/analyticsjs-boilerplate/issues/7#issuecomment-282106560 | const glob = require('glob');
const path = require('path');
module.exports = {
entry: {
'index': './src/index.js',
'test': ['babel-polyfill', ...glob.sync('./test/*-test.js')],
},
output: {
path: path.resolve(__dirname, 'build'),
publicPath: '/build/',
filename: '[name].js',
},
devtool: '#source-map',
module: {
rules: [
{
use: {
loader: 'babel-loader',
options: {
presets: [['es2015', {'modules': false}]],
plugins: ['dynamic-import-system-import'],
},
},
resource: {
test: /\.js$/,
exclude: /node_modules\/(?!(autotrack|dom-utils))/,
},
},
],
},
stats: 'minimal',
};
| const glob = require('glob');
const path = require('path');
module.exports = {
entry: {
'index': './src/index.js',
'test': ['babel-polyfill', ...glob.sync('./test/**/*-test.js')],
},
output: {
path: path.resolve(__dirname, 'build'),
publicPath: '/build/',
filename: '[name].js',
},
devtool: '#source-map',
module: {
rules: [
{
use: {
loader: 'babel-loader',
options: {
presets: [['es2015', {'modules': false}]],
plugins: ['dynamic-import-system-import'],
},
},
resource: {
test: /\.js$/,
exclude: /node_modules\/(?!(autotrack|dom-utils))/,
},
},
],
},
stats: 'minimal',
};
|
Fix pylint complaining about spaces and other stuff | from django.contrib import admin
from .models import Depot, Item
# make items modifiable by admin
admin.site.register(Item)
class DepotAdmin(admin.ModelAdmin):
list_display = ['name', 'active']
ordering = ['name']
actions = ["make_archived", "make_restored"]
@staticmethod
def format_message(num_changed, change):
if num_changed == 1:
message = "1 depot was"
else:
message = "%s depots were" % num_changed
return "%s successfully marked as %s" % (message, change)
def make_archived(self, request, queryset):
depots_archived = queryset.update(active=False)
self.message_user(request, DepotAdmin.format_message(depots_archived, "archived"))
make_archived.short_description = "Archive selected depots"
def make_restored(self, request, queryset):
depots_restored = queryset.update(active=True)
self.message_user(request, DepotAdmin.format_message(depots_restored, "restored"))
make_restored.short_description = "Restore selected depots"
# make depots modifiable by admin
admin.site.register(Depot, DepotAdmin)
| from django.contrib import admin
from .models import Depot, Item
# make items modifiable by admin
admin.site.register(Item)
class DepotAdmin(admin.ModelAdmin):
list_display = ['name', 'active']
ordering = ['name']
actions = ["make_archived", "make_restored"]
def make_message(self, num_changed, change):
if num_changed == 1:
message = "1 depot was"
else:
message = "%s depots were" % num_changed
return "%s successfully marked as %s" % (message, change)
def make_archived(self, request, queryset):
depots_archived = queryset.update(active = False)
self.message_user(request, self.make_message(depots_archived, "archived"))
make_archived.short_description = "Archive selected depots"
def make_restored(self, request, queryset):
depots_restored = queryset.update(active = True)
self.message_user(request, self.make_message(depots_restored, "restored"))
make_restored.short_description = "Restore selected depots"
# make depots modifiable by admin
admin.site.register(Depot, DepotAdmin)
|
Fix class name to be psr compliant else the migration will fail to find the class | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNotifications extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('seat_notifications', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id');
$table->string('type')->default('system');
$table->string('title');
$table->string('text');
$table->integer('read')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('seat_notifications');
}
} | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNotificationsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('seat_notifications', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id');
$table->string('type')->default('system');
$table->string('title');
$table->string('text');
$table->integer('read')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('seat_notifications');
}
} |
Update to use the Facade
Update TCPDF.php | <?php
namespace Elibyy\TCPDF;
use Illuminate\Support\Facades\Config;
class TCPDF
{
protected static $format;
protected $app;
/** @var TCPDFHelper */
protected $tcpdf;
public function __construct($app)
{
$this->app = $app;
$this->reset();
}
public function reset()
{
$this->tcpdf = new TCPDFHelper(
Config::get('tcpdf.page_orientation', 'P'),
Config::get('tcpdf.page_units', 'mm'),
static::$format ? static::$format : Config::get('tcpdf.page_format', 'A4'),
Config::get('tcpdf.unicode', true),
Config::get('tcpdf.encoding', 'UTF-8')
);
}
public static function changeFormat($format)
{
static::$format = $format;
}
public function __call($method, $args)
{
if (method_exists($this->tcpdf, $method)) {
return call_user_func_array([$this->tcpdf, $method], $args);
}
throw new \RuntimeException(sprintf('the method %s does not exists in TCPDF', $method));
}
public function setHeaderCallback($headerCallback)
{
$this->tcpdf->setHeaderCallback($headerCallback);
}
public function setFooterCallback($footerCallback)
{
$this->tcpdf->setFooterCallback($footerCallback);
}
}
| <?php
namespace Elibyy\TCPDF;
use Config;
class TCPDF
{
protected static $format;
protected $app;
/** @var TCPDFHelper */
protected $tcpdf;
public function __construct($app)
{
$this->app = $app;
$this->reset();
}
public function reset()
{
$this->tcpdf = new TCPDFHelper(
Config::get('tcpdf.page_orientation', 'P'),
Config::get('tcpdf.page_units', 'mm'),
static::$format ? static::$format : Config::get('tcpdf.page_format', 'A4'),
Config::get('tcpdf.unicode', true),
Config::get('tcpdf.encoding', 'UTF-8')
);
}
public static function changeFormat($format)
{
static::$format = $format;
}
public function __call($method, $args)
{
if (method_exists($this->tcpdf, $method)) {
return call_user_func_array([$this->tcpdf, $method], $args);
}
throw new \RuntimeException(sprintf('the method %s does not exists in TCPDF', $method));
}
public function setHeaderCallback($headerCallback)
{
$this->tcpdf->setHeaderCallback($headerCallback);
}
public function setFooterCallback($footerCallback)
{
$this->tcpdf->setFooterCallback($footerCallback);
}
}
|
Remove DB session after task | from __future__ import absolute_import
from celery import Celery
from ..extensions import db
__celery = None
def create_celery(app):
global __celery
if __celery:
return __celery
celery = Celery(
app.import_name,
broker=app.config['CELERY_BROKER_URL']
)
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
db.session = db.create_scoped_session()
try:
response = TaskBase.__call__(self, *args, **kwargs)
finally:
db.session.remove()
return response
celery.Task = ContextTask
__celery = celery
return __celery
| from __future__ import absolute_import
from celery import Celery
__celery = None
def create_celery(app):
global __celery
if __celery:
return __celery
celery = Celery(
app.import_name,
broker=app.config['CELERY_BROKER_URL']
)
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
__celery = celery
return __celery
|
Add NullHandler to the 'spotify' logger | from __future__ import unicode_literals
import logging
import os
import weakref
import cffi
__version__ = '2.0.0a1'
# Log to nowhere by default. For details, see:
# http://docs.python.org/2/howto/logging.html#library-config
logging.getLogger('spotify').addHandler(logging.NullHandler())
_header_file = os.path.join(os.path.dirname(__file__), 'api.processed.h')
_header = open(_header_file).read()
_header += '#define SPOTIFY_API_VERSION ...\n'
ffi = cffi.FFI()
ffi.cdef(_header)
lib = ffi.verify('#include "libspotify/api.h"', libraries=[str('spotify')])
# Mapping between keys and objects that should be kept alive as long as the key
# is alive. May be used to keep objects alive when there isn't a more
# convenient place to keep a reference to it. The keys are weakrefs, so entries
# disappear from the dict when the key is garbage collected, potentially
# causing objects associated to the key to be garbage collected as well. For
# further details, refer to the CFFI docs.
global_weakrefs = weakref.WeakKeyDictionary()
from spotify.error import * # noqa
| from __future__ import unicode_literals
import os
import weakref
import cffi
__version__ = '2.0.0a1'
_header_file = os.path.join(os.path.dirname(__file__), 'api.processed.h')
_header = open(_header_file).read()
_header += '#define SPOTIFY_API_VERSION ...\n'
ffi = cffi.FFI()
ffi.cdef(_header)
lib = ffi.verify('#include "libspotify/api.h"', libraries=[str('spotify')])
# Mapping between keys and objects that should be kept alive as long as the key
# is alive. May be used to keep objects alive when there isn't a more
# convenient place to keep a reference to it. The keys are weakrefs, so entries
# disappear from the dict when the key is garbage collected, potentially
# causing objects associated to the key to be garbage collected as well. For
# further details, refer to the CFFI docs.
global_weakrefs = weakref.WeakKeyDictionary()
from spotify.error import * # noqa
|
Delete commented out example reference to a sptring bean triggered by time | /**
* PtMatchAdapter - a patient matching system adapter
* Copyright (C) 2016 The MITRE Corporation. ALl rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mitre.ptmatchadapter;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.apache.camel.spring.boot.FatJarRouter;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@ImportResource("beans-config.xml")
public class PtmatchAdapter extends FatJarRouter {
@Override
public void configure() {
}
}
| /**
* PtMatchAdapter - a patient matching system adapter
* Copyright (C) 2016 The MITRE Corporation. ALl rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mitre.ptmatchadapter;
import org.apache.camel.spring.boot.FatJarRouter;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@ImportResource("beans-config.xml")
public class PtmatchAdapter extends FatJarRouter {
@Override
public void configure() {
// from("timer:trigger").transform().simple("ref:myBean").to("log:out");
}
// @Bean
// String myBean() {
// return "I'm Spring bean!";
// }
}
|
Use ApplicationManager.getApplication().acquireReadActionLock() instead of ApplicationManager.getApplication().runReadAction() | package org.jetbrains.plugins.groovy.springloaded;
import com.intellij.debugger.PositionManager;
import com.intellij.debugger.PositionManagerFactory;
import com.intellij.debugger.engine.DebugProcess;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.JavaPsiFacade;
/**
* Factory for position manager to debug classes reloaded by com.springsource.springloaded
* @author Sergey Evdokimov
*/
public class SpringLoadedPositionManagerFactory extends PositionManagerFactory {
@Override
public PositionManager createPositionManager(final DebugProcess process) {
AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock();
try {
if (JavaPsiFacade.getInstance(process.getProject()).findPackage("com.springsource.loaded") != null) {
return new SpringLoadedPositionManager(process);
}
return null;
}
finally {
accessToken.finish();
}
}
}
| package org.jetbrains.plugins.groovy.springloaded;
import com.intellij.debugger.PositionManager;
import com.intellij.debugger.PositionManagerFactory;
import com.intellij.debugger.engine.DebugProcess;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.NullableComputable;
import com.intellij.psi.JavaPsiFacade;
/**
* Factory for position manager to debug classes reloaded by com.springsource.springloaded
* @author Sergey Evdokimov
*/
public class SpringLoadedPositionManagerFactory extends PositionManagerFactory {
@Override
public PositionManager createPositionManager(final DebugProcess process) {
return ApplicationManager.getApplication().runReadAction(new NullableComputable<PositionManager>() {
@Override
public PositionManager compute() {
if (JavaPsiFacade.getInstance(process.getProject()).findPackage("com.springsource.loaded") != null) {
return new SpringLoadedPositionManager(process);
}
return null;
}
});
}
}
|
Use default seed for the test. |
from PIL import Image # Depends on the Pillow lib
from opensimplex import OpenSimplexNoise
WIDTH = 512
HEIGHT = 512
FEATURE_SIZE = 24
def main():
simplex = OpenSimplexNoise()
im = Image.new('L', (WIDTH, HEIGHT))
for y in range(0, HEIGHT):
for x in range(0, WIDTH):
#value = simplex.noise2d(x / FEATURE_SIZE, y / FEATURE_SIZE)
value = simplex.noise2d(x * 0.05, y * 0.05)
color = int((value + 1) * 128)
im.putpixel((x, y), color)
im.show()
if __name__ == '__main__':
main()
| import random
import time
from PIL import Image # Depends on the Pillow lib
from opensimplex import OpenSimplexNoise
WIDTH = 512
HEIGHT = 512
FEATURE_SIZE = 24
def main():
random.seed(time.time())
seed = random.randint(0, 100000)
simplex = OpenSimplexNoise(seed)
im = Image.new('L', (WIDTH, HEIGHT))
for y in range(0, HEIGHT):
for x in range(0, WIDTH):
#value = simplex.noise2d(x / FEATURE_SIZE, y / FEATURE_SIZE)
value = simplex.noise2d(x * 0.05, y * 0.05)
color = int((value + 1) * 128)
im.putpixel((x, y), color)
im.show()
if __name__ == '__main__':
main()
|
game/itemsets: Add maxItems to ItemSet and remove debug output | # -*- coding: utf-8 -*-
"""
Item Sets
- ItemSet.dbc
"""
from .. import *
from ..globalstrings import *
class ItemSet(Model):
pass
class ItemSetTooltip(Tooltip):
def tooltip(self):
items = self.obj.getItems()
maxItems = len(items)
self.append("name", ITEM_SET_NAME % (self.obj.getName(), 0, maxItems), color=YELLOW)
for item in items:
self.append("item", item.getName(), color=GREY)
ret = self.values
self.values = []
return ret
class ItemSetProxy(object):
"""
WDBC proxy for item sets
"""
def __init__(self, cls):
from pywow import wdbc
self.__file = wdbc.get("ItemSet.dbc", build=-1)
def get(self, id):
return self.__file[id]
def getItems(self, row):
from ..items import Item, ItemProxy
Item.initProxy(ItemProxy)
ret = []
for i in range(1, 11):
id = row._raw("item_%i" % (i))
if id:
ret.append(Item(id))
return ret
def getName(self, row):
return row.name_enus
| # -*- coding: utf-8 -*-
"""
Item Sets
- ItemSet.dbc
"""
from .. import *
from ..globalstrings import *
class ItemSet(Model):
pass
class ItemSetTooltip(Tooltip):
def tooltip(self):
self.append("name", ITEM_SET_NAME % (self.obj.getName(), 0, 0), color=YELLOW)
items = self.obj.getItems()
for item in items:
self.append("item", item.getName())
ret = self.values
self.values = []
return ret
class ItemSetProxy(object):
"""
WDBC proxy for item sets
"""
def __init__(self, cls):
from pywow import wdbc
self.__file = wdbc.get("ItemSet.dbc", build=-1)
def get(self, id):
return self.__file[id]
def getItems(self, row):
from ..items import Item, ItemProxy
Item.initProxy(ItemProxy)
ret = []
for i in range(1, 11):
id = row._raw("item_%i" % (i))
if id:
print id, Item(id)
ret.append(Item(id))
return ret
def getName(self, row):
return row.name_enus
|
Remove unnecessary log from Tidy. | package main
import (
"io"
"io/ioutil"
"os"
"os/exec"
)
// Errors & warnings are deliberately suppressed as tidy throws warnings very easily
func Tidy(r io.Reader, xmlIn bool) ([]byte, error) {
f, err := ioutil.TempFile("/tmp", "sajari-convert-")
if err != nil {
return nil, err
}
defer os.Remove(f.Name())
io.Copy(f, r)
var output []byte
if xmlIn {
output, err = exec.Command("tidy", "-xml", "-numeric", "-asxml", "-quiet", "-utf8", f.Name()).Output()
} else {
output, err = exec.Command("tidy", "-numeric", "-asxml", "-quiet", "-utf8", f.Name()).Output()
}
if err != nil && err.Error() != "exit status 1" {
return nil, err
}
return output, nil
}
| package main
import (
"io"
"io/ioutil"
"log"
"os"
"os/exec"
)
// Errors & warnings are deliberately suppressed as tidy throws warnings very easily
func Tidy(r io.Reader, xmlIn bool) ([]byte, error) {
f, err := ioutil.TempFile("/tmp", "sajari-convert-")
if err != nil {
log.Println("TempFile:", err)
return nil, err
}
defer os.Remove(f.Name())
io.Copy(f, r)
var output []byte
if xmlIn {
output, err = exec.Command("tidy", "-xml", "-numeric", "-asxml", "-quiet", "-utf8", f.Name()).Output()
} else {
output, err = exec.Command("tidy", "-numeric", "-asxml", "-quiet", "-utf8", f.Name()).Output()
}
if err != nil && err.Error() != "exit status 1" {
return nil, err
}
return output, nil
}
|
Check to see if we're collaborating properly. | var controllers = OPAL.module('opal.controllers', [
'ngCookies',
'opal.services',
'ui.event',
'ui.bootstrap',
'ngProgressLite',
'mgcrea.ngStrap.typeahead',
'mgcrea.ngStrap.helpers.dimensions',
'mgcrea.ngStrap.helpers.parseOptions',
'mgcrea.ngStrap.tooltip',
'mgcrea.ngStrap.helpers.dateParser',
'mgcrea.ngStrap.datepicker',
'mgcrea.ngStrap.timepicker',
]);
controllers.controller('RootCtrl', function($scope, $location) {
$scope.$location = $location;
$scope.keydown = function(e) {
$scope.$broadcast('keydown', e);
};
if(typeof collaborator != 'undefined'){ collaborator($scope) };
});
controllers.config(function($datepickerProvider) {
angular.extend($datepickerProvider.defaults, {
autoclose: true,
dateFormat: 'dd/MM/yyyy',
dateType: 'string'
});
})
| var controllers = OPAL.module('opal.controllers', [
'ngCookies',
'opal.services',
'ui.event',
'ui.bootstrap',
'ngProgressLite',
'mgcrea.ngStrap.typeahead',
'mgcrea.ngStrap.helpers.dimensions',
'mgcrea.ngStrap.helpers.parseOptions',
'mgcrea.ngStrap.tooltip',
'mgcrea.ngStrap.helpers.dateParser',
'mgcrea.ngStrap.datepicker',
'mgcrea.ngStrap.timepicker',
]);
controllers.controller('RootCtrl', function($scope, $location) {
$scope.$location = $location;
$scope.keydown = function(e) {
$scope.$broadcast('keydown', e);
};
if(collaborator){ collaborator($scope) };
});
controllers.config(function($datepickerProvider) {
angular.extend($datepickerProvider.defaults, {
autoclose: true,
dateFormat: 'dd/MM/yyyy',
dateType: 'string'
});
})
|
Add another PyPI package classifier of Python 3.5 programming language | #!/usr/bin/env python
import setuptools
import sys
if not ((sys.version_info.major >= 3 and sys.version_info.minor >= 5)
or sys.version_info.major > 3):
exit("Sorry, Python's version must be later than 3.5.")
import shakyo
setuptools.setup(
name=shakyo.__name__,
version=shakyo.__version__,
description="a tool to learn about something just by copying it by hand",
license="Public Domain",
author="raviqqe",
author_email="raviqqe@gmail.com",
url="http://github.com/raviqqe/shakyo/",
py_modules=[shakyo.__name__],
entry_points={"console_scripts" : ["shakyo=shakyo:main"]},
install_requires=["text_unidecode", "validators"],
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Console :: Curses",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: Public Domain",
"Operating System :: POSIX",
"Programming Language :: Python :: 3.5",
"Topic :: Education :: Computer Aided Instruction (CAI)",
"Topic :: Games/Entertainment",
],
)
| #!/usr/bin/env python
import setuptools
import sys
if not ((sys.version_info.major >= 3 and sys.version_info.minor >= 5)
or sys.version_info.major > 3):
exit("Sorry, Python's version must be later than 3.5.")
import shakyo
setuptools.setup(
name=shakyo.__name__,
version=shakyo.__version__,
description="a tool to learn about something just by copying it by hand",
license="Public Domain",
author="raviqqe",
author_email="raviqqe@gmail.com",
url="http://github.com/raviqqe/shakyo/",
py_modules=[shakyo.__name__],
entry_points={"console_scripts" : ["shakyo=shakyo:main"]},
install_requires=["text_unidecode", "validators"],
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Console :: Curses",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: Public Domain",
"Operating System :: POSIX",
"Topic :: Education :: Computer Aided Instruction (CAI)",
"Topic :: Games/Entertainment",
],
)
|
Update console link, intent-->task in comments | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Create a new task named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
intent = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.intents \
.create(unique_name='tell-a-joke')
# Provide actions for the new task
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke task to use this 'say' action.
client.preview.understand \
.assistants(assistant_sid) \
.intents(intent.sid) \
.intent_actions().update(joke_actions)
print(intent.sid)
| # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Create a new intent named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/assistant/list
intent = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.intents \
.create(unique_name='tell-a-joke')
# Provide actions for the new intent
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke intent to use this 'say' action.
client.preview.understand \
.assistants(assistant_sid) \
.intents(intent.sid) \
.intent_actions().update(joke_actions)
print(intent.sid)
|
MMLC-122: Add in staging URL for the tests to eventually use. | // With Frisby installed globally, we need the full path to find it
var frisby = require('/usr/local/lib/node_modules/frisby');
// Local testing
var base_url = 'http://localhost:1337';
// Server testing
//var base_url = 'http://mathml-staging.cloudapp.net';
xdescribe("User login", function() {
// TODO: Need to ensure that this user already exists
frisby.create("Admin login")
.post(base_url + '/auth/process', {
username : 'admin@benetech.org',
password : '123456'
})
.expectStatus(302)
.expectHeaderContains("Location", "/admin")
.toss();
// TODO: Need to ensure that this user already exists
frisby.create("User login")
.post(base_url + '/auth/process', {
username : 'user@benetech.org',
password : '123456'
})
.expectStatus(302)
.expectHeaderContains("Location", "/")
.toss();
frisby.create("Bad login")
.post(base_url + '/auth/process', {
username : 'foo@bar.com',
password : 'abcde'
})
.expectStatus(200)
.expectHeaderContains("Location", "/login")
expectJSON({
message : "login failed"
})
.toss();
});
| // With Frisby installed globally, we need the full path to find it
var frisby = require('/usr/local/lib/node_modules/frisby');
// Local testing
var base_url = 'http://localhost:1337';
xdescribe("User login", function() {
// TODO: Need to ensure that this user already exists
frisby.create("Admin login")
.post(base_url + '/auth/process', {
username : 'admin@benetech.org',
password : '123456'
})
.expectStatus(302)
.expectHeaderContains("Location", "/admin")
.toss();
// TODO: Need to ensure that this user already exists
frisby.create("User login")
.post(base_url + '/auth/process', {
username : 'user@benetech.org',
password : '123456'
})
.expectStatus(302)
.expectHeaderContains("Location", "/")
.toss();
frisby.create("Bad login")
.post(base_url + '/auth/process', {
username : 'foo@bar.com',
password : 'abcde'
})
.expectStatus(200)
.expectHeaderContains("Location", "/login")
expectJSON({
message : "login failed"
})
.toss();
});
|
Fix incorrect test for timezone `Pacific/Apia` | var assert = require('power-assert')
var isThisWeek = require('../is_this_week')
describe('isThisWeek', function() {
beforeEach(function() {
this.clock = sinon.useFakeTimers(
new Date(2014, 8 /* Sep */, 25).getTime()
)
})
afterEach(function() {
this.clock.restore()
})
it('returns true if given date and current date have same week', function() {
var date = new Date(2014, 8 /* Sep */, 21)
assert(isThisWeek(date) === true)
})
it('returns false if given date and current date have different weeks', function() {
var date = new Date(2014, 8 /* Sep */, 29)
assert(isThisWeek(date) === false)
})
it('allows to specify when week starts', function() {
var date = new Date(2014, 8 /* Sep */, 28)
assert(isThisWeek(date, 1) === true)
})
it('accepts string', function() {
var date = new Date(2014, 8 /* Sep */, 21).toISOString()
assert(isThisWeek(date) === true)
})
it('accepts timestamp', function() {
var date = new Date(2014, 8 /* Sep */, 21).getTime()
assert(isThisWeek(date) === true)
})
})
| var assert = require('power-assert')
var isThisWeek = require('../is_this_week')
describe('isThisWeek', function() {
beforeEach(function() {
this.clock = sinon.useFakeTimers(
new Date(2014, 8 /* Sep */, 25).getTime()
)
})
afterEach(function() {
this.clock.restore()
})
it('returns true if given date and current date have same week', function() {
var date = new Date(2014, 8 /* Sep */, 21)
assert(isThisWeek(date) === true)
})
it('returns false if given date and current date have different weeks', function() {
var date = new Date(2014, 8 /* Sep */, 28)
assert(isThisWeek(date) === false)
})
it('allows to specify when week starts', function() {
var date = new Date(2014, 8 /* Sep */, 28)
assert(isThisWeek(date, 1) === true)
})
it('accepts string', function() {
var date = new Date(2014, 8 /* Sep */, 21).toISOString()
assert(isThisWeek(date) === true)
})
it('accepts timestamp', function() {
var date = new Date(2014, 8 /* Sep */, 21).getTime()
assert(isThisWeek(date) === true)
})
})
|
Remove superfluous license headers (OKAPI-109) | package org.folio.okapi.bean;
/**
* List of Permissions (and permission sets) belonging to a module. Used as a
* parameter in the system request to initialize the permission module when a
* module is being enabled for a tenant.
*
* @author heikki
*/
public class PermissionList {
String moduleId; // The module that owns these permissions.
Permission[] perms;
public PermissionList() {
}
public PermissionList(String moduleId, Permission[] perms) {
this.moduleId = moduleId;
this.perms = perms.clone();
}
public PermissionList(PermissionList other) {
this.moduleId = other.moduleId;
this.perms = other.perms.clone();
}
public String getModuleId() {
return moduleId;
}
public void setModuleId(String moduleId) {
this.moduleId = moduleId;
}
public Permission[] getPerms() {
return perms;
}
public void setPerms(Permission[] perms) {
this.perms = perms;
}
}
| /*
* Copyright (c) 2015-2017, Index Data
* All rights reserved.
* See the file LICENSE for details.
*/
package org.folio.okapi.bean;
/**
* List of Permissions (and permission sets) belonging to a module. Used as a
* parameter in the system request to initialize the permission module when a a
* module is being enabled for a tenant.
*
* @author heikki
*/
public class PermissionList {
String moduleId; // The module that own these permissions.
Permission[] perms;
public PermissionList() {
}
public PermissionList(String moduleId, Permission[] perms) {
this.moduleId = moduleId;
this.perms = perms.clone();
}
public PermissionList(PermissionList other) {
this.moduleId = other.moduleId;
this.perms = other.perms.clone();
}
public String getModuleId() {
return moduleId;
}
public void setModuleId(String moduleId) {
this.moduleId = moduleId;
}
public Permission[] getPerms() {
return perms;
}
public void setPerms(Permission[] perms) {
this.perms = perms;
}
}
|
Use require for import instead of requirejs | 'use strict';
require.config({
paths: {
jquery: 'bower_components/jquery/jquery.min',
underscore: '../../../node_modules/lodash/dist/lodash.min',
backbone: '../../../node_modules/backbone/backbone-min',
dust: '../../../node_modules/dustjs-linkedin/dist/dust-full.min',
text: '../../../node_modules/text/text',
themes: '../../../gui-themes'
},
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
dust: {
exports: 'dust'
}
}
});
require(['jquery', 'backbone', 'appConfig'], function($, Backbone, appConfig) {
$(function() {
window.liveblog = appConfig.liveblog;
// Router can't be required before liveblog global variable is defined
require(['router'], function(Router){
new Router();
Backbone.history.start({ pushState: true });
});
});
});
| 'use strict';
require.config({
paths: {
jquery: 'bower_components/jquery/jquery.min',
underscore: '../../../node_modules/lodash/dist/lodash.min',
backbone: '../../../node_modules/backbone/backbone-min',
dust: '../../../node_modules/dustjs-linkedin/dist/dust-full.min',
text: '../../../node_modules/text/text',
themes: '../../../gui-themes'
},
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
dust: {
exports: 'dust'
}
}
});
require(['jquery', 'backbone', 'appConfig'], function($, Backbone, appConfig) {
$(function() {
window.liveblog = appConfig.liveblog;
// Router can't be required before liveblog global variable is defined
requirejs(['router'], function(Router){
new Router();
Backbone.history.start({ pushState: true });
});
});
});
|
Stop breaking things Raquel, this is why you need tests | import Cookie from 'js-cookie'
import _ from 'lodash'
import { SAVE_FILE, DELETE_FILE } from '../actions/file_list_actions'
const initialState = Cookie.get('files')
const setState = () => {
const files = Cookie.get('files')
if (files) { return JSON.parse(files) }
return []
}
const saveExistingFile = (state, updatedFile) => {
let newState
if (state.length === 0) {
newState = [updatedFile]
} else {
const removeFile = _.flatten([_.slice(state, 0, updatedFile.id), _.slice(state, updatedFile.id + 1, state.length)])
newState = [...removeFile, updatedFile]
}
Cookie.set('files', newState)
return newState
}
export const fileList = (state = setState(), action) => {
switch (action.type) {
case SAVE_FILE: {
const file = state[action.file.id]
if (file) {
return saveExistingFile(state, action.file)
}
const newState = [...state, action.file]
Cookie.set('files', newState)
return newState
}
case DELETE_FILE: {
const newState = _.flatten([_.slice(state, 0, action.id), _.slice(state, action.id + 1, state.length)])
Cookie.set('files', newState)
return newState
}
default:
return state
}
} | import Cookie from 'js-cookie'
import _ from 'lodash'
import { SAVE_FILE, DELETE_FILE } from '../actions/file_list_actions'
const initialState = Cookie.get('files')
const setState = () => {
const files = Cookie.get('files')
if (files) { return JSON.parse(files) }
return []
}
const saveExistingFile = (state, updatedFile) => {
let newState
if (state.length === 0) {
newState = [updatedFile]
} else {
const removeFile = _.flatten([_.slice(state, 0, updatedFile.id), _.slice(state, updatedFile.id + 1, state.length)])
newState = [...removeFile, updatedFile]
}
Cookie.set('files', newState)
return newState
}
export const fileList = (state = setState(), action) => {
switch (action.type) {
case SAVE_FILE: {
const fileId = state[action.file.id].id
if (fileId) {
return saveExistingFile(state, action.file)
}
const newState = [...state, action.file]
Cookie.set('files', newState)
return newState
}
case DELETE_FILE: {
const newState = _.flatten([_.slice(state, 0, action.id), _.slice(state, action.id + 1, state.length)])
Cookie.set('files', newState)
return newState
}
default:
return state
}
} |
Fix "done is not a function" | /*
* min-webdriver
*
* Copyright (c) 2014-2015 Maximilian Antoni <mail@maxantoni.de>
*
* @license MIT
*/
'use strict';
var path = require('path');
var through = require('through2');
var resolve = require('resolve');
var driver = require('../lib/driver');
var options = require('../lib/options');
function relative(file) {
return './' + path.relative(process.cwd(), file).replace(/\\/g, '/');
}
module.exports = function (b, opts) {
var clientFile = path.join(__dirname, 'client.js');
b.add(relative(clientFile), {
expose : 'min-wd'
});
var done;
var stream = through();
var wrap = b.pipeline.get('wrap');
wrap.push(through(function (chunk, enc, next) {
/*jslint unparam: true*/
stream.push(chunk);
next();
}, function (next) {
done = next;
stream.push(null);
}));
wrap.push(driver(stream, options(opts || {}), function (err) {
if (err) {
b.emit('error', err);
}
if (done) {
done();
}
}));
};
| /*
* min-webdriver
*
* Copyright (c) 2014-2015 Maximilian Antoni <mail@maxantoni.de>
*
* @license MIT
*/
'use strict';
var path = require('path');
var through = require('through2');
var resolve = require('resolve');
var driver = require('../lib/driver');
var options = require('../lib/options');
function relative(file) {
return './' + path.relative(process.cwd(), file).replace(/\\/g, '/');
}
module.exports = function (b, opts) {
var clientFile = path.join(__dirname, 'client.js');
b.add(relative(clientFile), {
expose : 'min-wd'
});
var done;
var stream = through();
var wrap = b.pipeline.get('wrap');
wrap.push(through(function (chunk, enc, next) {
/*jslint unparam: true*/
stream.push(chunk);
next();
}, function (next) {
done = next;
stream.push(null);
}));
wrap.push(driver(stream, options(opts || {}), function (err) {
if (err) {
b.emit('error', err);
}
done();
}));
};
|
Add overlay style to widget overlay | import React, { PropTypes } from 'react'
const overlayStyle = {
position: 'absolute',
top: '0',
right: '0',
bottom: '0',
left: '0',
fontWeight: 'bold',
borderWidth: '6px',
opacity: '.82',
backgroundColor: '#222222',
fontSize: '1.8rem'
}
const WidgetOverlay = ({ children, widget, onClick, onMouseOver, onMouseOut, hasMouseOver }) => (
<div
className='relative overlay'
style={{ cursor: 'pointer' }}
onMouseOver={() => onMouseOver('widget', widget.id)}
onMouseOut={() => onMouseOut('widget')}
onClick={() => onClick()}
>
{children}
{hasMouseOver ? (
<div className='h1 rounded z1 border border-pagenta px2' style={overlayStyle}>
<div className='table full-height col-12 center'>
<div className='white table-cell align-middle'>
{'Clique para editar'}
</div>
</div>
</div>
) : null}
</div>
)
WidgetOverlay.propTypes = {
widget: PropTypes.object,
onClick: PropTypes.func,
// Injected by react-redux
hasMouseOver: PropTypes.bool,
onMouseOver: PropTypes.func,
onMouseOut: PropTypes.func
}
export default WidgetOverlay
| import React, { PropTypes } from 'react'
const WidgetOverlay = ({ children, widget, onClick, onMouseOver, onMouseOut, hasMouseOver }) => (
<div
className='relative'
style={{ cursor: 'pointer' }}
onMouseOver={() => onMouseOver('widget', widget.id)}
onMouseOut={() => onMouseOut('widget')}
onClick={() => onClick()}
>
{children}
{hasMouseOver ? (
<div className='overlay h1 rounded z1 border border-pagenta px2'>
<div className='table full-height col-12 center'>
<div className='white table-cell align-middle'>
{'Clique para editar'}
</div>
</div>
</div>
) : null}
</div>
)
WidgetOverlay.propTypes = {
widget: PropTypes.object,
onClick: PropTypes.func,
// Injected by react-redux
hasMouseOver: PropTypes.bool,
onMouseOver: PropTypes.func,
onMouseOut: PropTypes.func
}
export default WidgetOverlay
|
Make htmlescape function available in templates
For when we explicitly call it. | import aspen_jinja2_renderer as base
from markupsafe import escape as htmlescape
class HTMLRenderer(base.Renderer):
def render_content(self, context):
# Extend to inject an HTML-escaping function. Since autoescape is on,
# template authors shouldn't normally need to use this function, but
# having it in the simplate context makes it easier to implement i18n.
context['state']['escape'] = context['escape'] = htmlescape
return base.Renderer.render_content(self, context)
class Factory(base.Factory):
Renderer = HTMLRenderer
def compile_meta(self, configuration):
# Override to turn on autoescaping.
loader = base.FileSystemLoader(configuration.project_root)
return base.Environment( loader=loader
, autoescape=True
, extensions=['jinja2.ext.autoescape']
)
| import aspen_jinja2_renderer as base
from markupsafe import escape as htmlescape
class HTMLRenderer(base.Renderer):
def render_content(self, context):
# Extend to inject an HTML-escaping function. Since autoescape is on,
# template authors shouldn't normally need to use this function, but
# having it in the simplate context makes it easier to implement i18n.
context['state']['escape'] = htmlescape
return base.Renderer.render_content(self, context)
class Factory(base.Factory):
Renderer = HTMLRenderer
def compile_meta(self, configuration):
# Override to turn on autoescaping.
loader = base.FileSystemLoader(configuration.project_root)
return base.Environment( loader=loader
, autoescape=True
, extensions=['jinja2.ext.autoescape']
)
|
Put readonly on mother tongue instead of disabled | $(document).ready(function() {
// There is no default option for setting readonly a field with django-bootstrap4
$('#id_mother_tongue').prop('readonly', true);
// Set tooltips
$('[data-toggle="tooltip"]').tooltip();
});
$('#id_degree_programme_options').change(function() {
if (this.value === 'extra') {
$('#unknown_degree').show();
$('#unknown_degree input').val('');
} else {
$('#unknown_degree').hide();
$('#unknown_degree input').val(this.value);
}
});
$('input:radio[name="language"]').change(function() {
if ($(this).is(':checked')) {
if ($(this).val() == 'extra') {
$('#id_mother_tongue').prop('readonly', false);
$('#id_mother_tongue').val('');
} else {
$('#id_mother_tongue').prop('readonly', true);
$('#id_mother_tongue').val(this.value);
}
}
});
| $(document).ready(function() {
// There is no default option for disabling a field with django-bootstrap4
$('#id_mother_tongue').prop('disabled', true);
// Set tooltips
$('[data-toggle="tooltip"]').tooltip();
});
$('#id_degree_programme_options').change(function() {
if (this.value === 'extra') {
$('#unknown_degree').show();
$('#unknown_degree input').val('');
} else {
$('#unknown_degree').hide();
$('#unknown_degree input').val(this.value);
}
});
$('input:radio[name="language"]').change(function() {
if ($(this).is(':checked')) {
if ($(this).val() == 'extra') {
$('#id_mother_tongue').prop('disabled', false);
$('#id_mother_tongue').val('');
} else {
$('#id_mother_tongue').prop('disabled', true);
$('#id_mother_tongue').val(this.value);
}
}
});
|
Update to use addUpdater instead of onUpdate on db | 'use babel';
import {Emitter} from 'atom';
import Project from './project';
export default class Projects {
constructor(db=null) {
this.emitter = new Emitter();
this.db = db;
this.db.addUpdater(null, {}, () => this.emitter.emit('projects-updated'));
}
onUpdate(callback) {
this.emitter.on('projects-updated', callback);
}
getAll(callback) {
this.db.find(projectSettings => {
let projects = [];
let setting;
let project;
let key;
for (key in projectSettings) {
setting = projectSettings[key];
if (setting.paths) {
project = new Project(setting, this.db);
projects.push(project);
}
}
callback(projects);
});
}
getCurrent(callback) {
this.getAll(projects => {
projects.forEach(project => {
if (project.isCurrent()) {
callback(project);
}
});
});
}
}
| 'use babel';
import {Emitter} from 'atom';
import Project from './project';
export default class Projects {
constructor(db=null) {
this.emitter = new Emitter();
this.db = db;
this.db.onUpdate(() => this.emitter.emit('projects-updated'));
}
onUpdate(callback) {
this.emitter.on('projects-updated', callback);
}
getAll(callback) {
this.db.find(projectSettings => {
let projects = [];
let setting;
let project;
let key;
for (key in projectSettings) {
setting = projectSettings[key];
if (setting.paths) {
project = new Project(setting, this.db);
projects.push(project);
}
}
callback(projects);
});
}
getCurrent(callback) {
this.getAll(projects => {
projects.forEach(project => {
if (project.isCurrent()) {
callback(project);
}
});
});
}
}
|
Fix bbl up for AWS
- Different calls to AWS return different lists of availability zones
- Short-term fix ignores the az that is not returned by cloudformation
call
[#139857703] | package ec2
import (
"errors"
goaws "github.com/aws/aws-sdk-go/aws"
awsec2 "github.com/aws/aws-sdk-go/service/ec2"
)
type AvailabilityZoneRetriever struct {
ec2ClientProvider ec2ClientProvider
}
func NewAvailabilityZoneRetriever(ec2ClientProvider ec2ClientProvider) AvailabilityZoneRetriever {
return AvailabilityZoneRetriever{
ec2ClientProvider: ec2ClientProvider,
}
}
func (r AvailabilityZoneRetriever) Retrieve(region string) ([]string, error) {
output, err := r.ec2ClientProvider.GetEC2Client().DescribeAvailabilityZones(&awsec2.DescribeAvailabilityZonesInput{
Filters: []*awsec2.Filter{{
Name: goaws.String("region-name"),
Values: []*string{goaws.String(region)},
}},
})
if err != nil {
return []string{}, err
}
azList := []string{}
for _, az := range output.AvailabilityZones {
if az == nil {
return []string{}, errors.New("aws returned nil availability zone")
}
if az.ZoneName == nil {
return []string{}, errors.New("aws returned availability zone with nil zone name")
}
if *az.ZoneName != "us-east-1d" {
azList = append(azList, *az.ZoneName)
}
}
return azList, nil
}
| package ec2
import (
"errors"
goaws "github.com/aws/aws-sdk-go/aws"
awsec2 "github.com/aws/aws-sdk-go/service/ec2"
)
type AvailabilityZoneRetriever struct {
ec2ClientProvider ec2ClientProvider
}
func NewAvailabilityZoneRetriever(ec2ClientProvider ec2ClientProvider) AvailabilityZoneRetriever {
return AvailabilityZoneRetriever{
ec2ClientProvider: ec2ClientProvider,
}
}
func (r AvailabilityZoneRetriever) Retrieve(region string) ([]string, error) {
output, err := r.ec2ClientProvider.GetEC2Client().DescribeAvailabilityZones(&awsec2.DescribeAvailabilityZonesInput{
Filters: []*awsec2.Filter{{
Name: goaws.String("region-name"),
Values: []*string{goaws.String(region)},
}},
})
if err != nil {
return []string{}, err
}
azList := []string{}
for _, az := range output.AvailabilityZones {
if az == nil {
return []string{}, errors.New("aws returned nil availability zone")
}
if az.ZoneName == nil {
return []string{}, errors.New("aws returned availability zone with nil zone name")
}
azList = append(azList, *az.ZoneName)
}
return azList, nil
}
|
Make variable name more consistent | // This file makes all join table relationships
const db = process.env.DB_DATABASE;
const dbHost = process.env.DB_HOST;
const dbUser = process.env.DB_USER;
const dbPassword = process.env.DB_PASS;
const Sequelize = require('sequelize');
const sequelize = new Sequelize(db, dbUser, dbPassword, {
dialect: 'mariadb',
host: dbHost
});
// Any vairable that starts with a capital letter is a model
const User = require('./users.js')(sequelize, Sequelize);
const Bookmark = require('./bookmarks.js')(sequelize, Sequelize);
const BookmarkUsers = require('./bookmarkUsers')(sequelize, Sequelize);
// BookmarkUsers join table:
User.belongsToMany(Bookmark, {
through: 'bookmark_users',
foreignKey: 'user_id'
});
Bookmark.belongsToMany(User, {
through: 'bookmark_users',
foreignKey: 'bookmark_id'
});
//Create missing tables, if any
// sequelize.sync({force: true});
sequelize.sync();
exports.User = User;
exports.Bookmark = Bookmark;
exports.BookmarkUsers = BookmarkUsers; | // This file makes all join table relationships
const database = process.env.DB_DATABASE;
const dbHost = process.env.DB_HOST;
const dbUser = process.env.DB_USER;
const dbPassword = process.env.DB_PASS;
const Sequelize = require('sequelize');
const sequelize = new Sequelize(database, dbUser, dbPassword, {
dialect: 'mariadb',
host: dbHost
});
// Any vairable that starts with a capital letter is a model
const User = require('./users.js')(sequelize, Sequelize);
const Bookmark = require('./bookmarks.js')(sequelize, Sequelize);
const BookmarkUsers = require('./bookmarkUsers')(sequelize, Sequelize);
// BookmarkUsers join table:
User.belongsToMany(Bookmark, {
through: 'bookmark_users',
foreignKey: 'user_id'
});
Bookmark.belongsToMany(User, {
through: 'bookmark_users',
foreignKey: 'bookmark_id'
});
//Create missing tables, if any
// sequelize.sync({force: true});
sequelize.sync();
exports.User = User;
exports.Bookmark = Bookmark;
exports.BookmarkUsers = BookmarkUsers; |
Return from dump instead of echoing | <?php
/**
* Bootstrapping functions, essential and needed for Hana to work together with some common helpers.
*
*/
/**
* Default exception handler.
*
*/
function myExceptionHandler($exception) {
echo "Hana: Uncaught exception: <p>{$exception->getMessage()}</p><pre>" . $exception->getTraceAsString(), "</pre>";
}
set_exception_handler('myExceptionHandler');
/**
* Autoloader for classes.
*
*/
function myAutoloader($class) {
$path = HANA_INSTALL_PATH . "/src/{$class}/{$class}.php";
if(is_file($path)) {
include($path);
}
else {
throw new Exception("Classfile '{$class}' does not exists.");
}
}
spl_autoload_register('myAutoloader');
/**
* Easy dumping of variables for debugging purposes
*
*/
function dump($array) {
return "<pre>" . htmlentities(print_r($array, 1)) . "</pre>";
}
/**
* Current Hana URL
*/
function current_url() {
return explode("?", $_SERVER['REQUEST_URI'])[0];
}
| <?php
/**
* Bootstrapping functions, essential and needed for Hana to work together with some common helpers.
*
*/
/**
* Default exception handler.
*
*/
function myExceptionHandler($exception) {
echo "Hana: Uncaught exception: <p>{$exception->getMessage()}</p><pre>" . $exception->getTraceAsString(), "</pre>";
}
set_exception_handler('myExceptionHandler');
/**
* Autoloader for classes.
*
*/
function myAutoloader($class) {
$path = HANA_INSTALL_PATH . "/src/{$class}/{$class}.php";
if(is_file($path)) {
include($path);
}
else {
throw new Exception("Classfile '{$class}' does not exists.");
}
}
spl_autoload_register('myAutoloader');
/**
* Easy dumping of variables for debugging purposes
*
*/
function dump($array) {
echo "<pre>" . htmlentities(print_r($array, 1)) . "</pre>";
/**
* Current Hana URL
*/
function current_url() {
return explode("?", $_SERVER['REQUEST_URI'])[0];
}
|
Fix TimedEvent sets GUID twice
TBR=nduca@chromium.org
BUG=
Review URL: https://codereview.appspot.com/12746044 | // Copyright (c) 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.
'use strict';
base.require('base.guid');
base.require('tracing.trace_model.event');
/**
* @fileoverview Provides the TimedEvent class.
*/
base.exportTo('tracing.trace_model', function() {
/**
* A TimedEvent is the base type for any piece of data in the trace model with
* a specific start and duration.
*
* @constructor
*/
function TimedEvent(start) {
tracing.trace_model.Event.call(this);
this.start = start;
this.duration = 0;
}
TimedEvent.prototype = {
__proto__: tracing.trace_model.Event.prototype,
get end() {
return this.start + this.duration;
},
addBoundsToRange: function(range) {
range.addValue(this.start);
range.addValue(this.end);
}
};
return {
TimedEvent: TimedEvent
};
});
| // Copyright (c) 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.
'use strict';
base.require('base.guid');
base.require('tracing.trace_model.event');
/**
* @fileoverview Provides the TimedEvent class.
*/
base.exportTo('tracing.trace_model', function() {
/**
* A TimedEvent is the base type for any piece of data in the trace model with
* a specific start and duration.
*
* @constructor
*/
function TimedEvent(start) {
tracing.trace_model.Event.call(this);
this.guid_ = base.GUID.allocate();
this.start = start;
this.duration = 0;
}
TimedEvent.prototype = {
__proto__: tracing.trace_model.Event.prototype,
get end() {
return this.start + this.duration;
},
addBoundsToRange: function(range) {
range.addValue(this.start);
range.addValue(this.end);
}
};
return {
TimedEvent: TimedEvent
};
});
|
Set name of stored file | # sudo apt-get install python-scapy
from scapy.all import *
# sudo pip install scapy_http
from scapy.layers import http
from scapy.layers.http import HTTPResponse
import sys
packets = rdpcap("task07_f1.pcap")
requests = []
answers = []
def has_http_header(packet):
return packet.haslayer(HTTPResponse)
def extract_next_file(packets, file_name):
if ! has_http_header(packets[0]):
return False
first = packets.pop(0)
f = open(file_name, 'w+')
f.write(first['Raw'])
while !has_http_header(packets[0]):
pkt = packets.pop(0)
f.write(pkt['Raw'])
f.close()
return True
for pkt in packets:
tcp = pkt['TCP']
# destination port must be 80
if tcp.dport == 80 and pkt.haslayer('HTTP'):
requests.append(pkt)
for pkt in packets:
tcp = pkt['TCP']
# source port must be 80
if tcp.sport == 80 and pkt.haslayer('HTTP'):
answers.append(pkt)
print '=============== REQUESTS =================='
i = 0
for req in requests:
file_name = "file_" + str(i)
printGET(file_name)
extract_next_file(answer, file_name)
i += 1
| # sudo apt-get install python-scapy
from scapy.all import *
# sudo pip install scapy_http
from scapy.layers import http
from scapy.layers.http import HTTPResponse
import sys
packets = rdpcap("task07_f1.pcap")
requests = []
answers = []
def has_http_header(packet):
return packet.haslayer(HTTPResponse)
def extractNextFile(packets, file_name):
if ! has_http_header(packets[0]):
return False
first = packets.pop(0)
f = open(file_name, 'w+')
f.write(first['Raw'])
while !has_http_header(packets[0]):
pkt = packets.pop(0)
f.write(pkt['Raw'])
f.close()
return True
for pkt in packets:
tcp = pkt['TCP']
# destination port must be 80
if tcp.dport == 80 and pkt.haslayer('HTTP'):
requests.append(pkt)
for pkt in packets:
tcp = pkt['TCP']
# source port must be 80
if tcp.sport == 80 and pkt.haslayer('HTTP'):
answers.append(pkt)
print '=============== REQUESTS =================='
i = 0
for req in requests:
file_name = get_name(req)
printGET(file_name)
extractNextFile(answer, fileName)
|
Annotate clean classes as @Nullsafe:: (7/14) libraries/components/litho-core/src/main/java/com/facebook/litho/
Reviewed By: pasqualeanatriello
Differential Revision: D28505831
fbshipit-source-id: e4831c9e49a9c08a495dacb85c3ed82a5ad1b507 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho;
import com.facebook.infer.annotation.Nullsafe;
/** Data class for params used to log error in LithoView. */
@Nullsafe(Nullsafe.Mode.LOCAL)
public class ComponentLogParams {
public final String logProductId;
public final String logType;
public final int samplingFrequency;
public final boolean failHarder;
public ComponentLogParams(
String logProductId, String logType, int samplingFrequency, boolean failHarder) {
this.logProductId = logProductId;
this.logType = logType;
this.samplingFrequency = samplingFrequency;
this.failHarder = failHarder;
}
public ComponentLogParams(String logProductId, String logType) {
this(logProductId, logType, /* take default*/ 0, false);
}
}
| /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho;
/** Data class for params used to log error in LithoView. */
public class ComponentLogParams {
public final String logProductId;
public final String logType;
public final int samplingFrequency;
public final boolean failHarder;
public ComponentLogParams(
String logProductId, String logType, int samplingFrequency, boolean failHarder) {
this.logProductId = logProductId;
this.logType = logType;
this.samplingFrequency = samplingFrequency;
this.failHarder = failHarder;
}
public ComponentLogParams(String logProductId, String logType) {
this(logProductId, logType, /* take default*/ 0, false);
}
}
|
Move iCheck and jQuery libs to CDN | </div>
<!-- /.login-box -->
<!-- jQuery 2.2.3 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<!-- Bootstrap 3.3.6 -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- iCheck -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/iCheck/1.0.2/icheck.min.js"></script>
<script>
$(function () {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
});
</script>
</body>
</html>
| </div>
<!-- /.login-box -->
<!-- jQuery 2.2.3 -->
<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- Bootstrap 3.3.6 -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- iCheck -->
<script src="plugins/iCheck/icheck.min.js"></script>
<script>
$(function () {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
});
</script>
</body>
</html> |
Increase some intervals to further reduce stress on the jobtracker.
git-svn-id: 4d48d1092ee340c9ada5711cdbe4355b138bc22b@383623 13f79535-47bb-0310-9956-ffa450edef68 | /**
* Copyright 2005 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
/*******************************
* Some handy constants
*
* @author Mike Cafarella
*******************************/
interface MRConstants {
//
// Timeouts, constants
//
public static final long HEARTBEAT_INTERVAL = 10 * 1000;
public static final long TASKTRACKER_EXPIRY_INTERVAL = 10 * 60 * 1000;
//
// Result codes
//
public static int SUCCESS = 0;
public static int FILE_NOT_FOUND = -1;
}
| /**
* Copyright 2005 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
/*******************************
* Some handy constants
*
* @author Mike Cafarella
*******************************/
interface MRConstants {
//
// Timeouts, constants
//
public static final long HEARTBEAT_INTERVAL = 3 * 1000;
public static final long TASKTRACKER_EXPIRY_INTERVAL = 60 * 1000;
//
// Result codes
//
public static int SUCCESS = 0;
public static int FILE_NOT_FOUND = -1;
}
|
Use the loader from the scope | module.exports = function(data){
// If this is not a CanJS project
if(typeof can === "undefined" || !can.view) {
return {};
}
var oldCanImport;
var canImport = function(el, tagData){
var moduleName = el.getAttribute("from");
var templateModule = tagData.options.attr("helpers.module");
var parentName = templateModule ? templateModule.id : undefined;
var isAPage = !!tagData.subtemplate;
var loader = doneSsr.loader;
loader.normalize(moduleName, parentName).then(function(name){
if(isAPage) {
loader.__ssrParentMap[name] = false;
}
var pages = data.pages;
if(!pages) {
pages = data.pages = [];
}
pages.push(name);
});
oldCanImport.apply(this, arguments);
};
return {
beforeTask: function(){
oldCanImport = can.view.callbacks._tags["can-import"];
can.view.callbacks._tags["can-import"] = canImport;
},
afterTask: function(){
can.view.callbacks._tags["can-import"] = oldCanImport;
}
};
};
| module.exports = function(data){
// If this is not a CanJS project
if(typeof can === "undefined" || !can.view) {
return {};
}
var oldCanImport;
var canImport = function(el, tagData){
var moduleName = el.getAttribute("from");
var templateModule = tagData.options.attr("helpers.module");
var parentName = templateModule ? templateModule.id : undefined;
var isAPage = !!tagData.subtemplate;
var loader = doneSsr.loader;
loader.normalize(moduleName, parentName).then(function(name){
if(isAPage) {
doneSsr.loader.__ssrParentMap[name] = false;
}
var pages = data.pages;
if(!pages) {
pages = data.pages = [];
}
pages.push(name);
});
oldCanImport.apply(this, arguments);
};
return {
beforeTask: function(){
oldCanImport = can.view.callbacks._tags["can-import"];
can.view.callbacks._tags["can-import"] = canImport;
},
afterTask: function(){
can.view.callbacks._tags["can-import"] = oldCanImport;
}
};
};
|
Add parts to the page template | <?php
/*
Template Name: Full Width - About Us
*/
get_header(); ?>
<div id="page-full-width" role="main">
<section class="about-us">
<?php get_template_part( 'template-parts/part-main-navigation' ); ?>
<div class="row">
<div class="small-12 columns text-center about-us-header">
<h2 class="page-hook-title ">Unique Layouts, <span class="main-blue">Customize wireframes</span> & User
Interface Kit</h2>
<button type="button" class="button">Take a Tour</button>
</div>
</div>
</section>
<?php get_template_part( 'template-parts/part-quick-view' ); ?>
<?php get_template_part( 'template-parts/part-our-team' ); ?>
<?php get_template_part( 'template-parts/part-our-services' ); ?>
<?php get_template_part( 'template-parts/part-subfooter' ); ?>
</div>
<?php get_footer();
| <?php
/*
Template Name: Full Width - About Us
*/
get_header(); ?>
<div id="page-full-width" role="main">
<section class="about-us">
<?php get_template_part( 'template-parts/part-main-navigation' ); ?>
<div class="row">
<div class="small-12 columns text-center about-us-header">
<h2 class="page-hook-title ">Unique Layouts, <span class="main-blue">Customize wireframes</span> & User
Interface Kit</h2>
<button type="button" class="button">Take a Tour</button>
</div>
</div>
</section>
<?php get_template_part('template-parts/part-quick-view'); ?>
</div>
<?php get_footer();
|
Add default config to module.exports | import fs from 'fs'
import path from 'path'
import _ from 'lodash'
import postcss from 'postcss'
import stylefmt from 'stylefmt'
import defaultConfig from './defaultConfig'
import mergeConfig from './util/mergeConfig'
import substituteResetAtRule from './lib/substituteResetAtRule'
import evaluateTailwindFunctions from './lib/evaluateTailwindFunctions'
import generateUtilities from './lib/generateUtilities'
import substituteHoverableAtRules from './lib/substituteHoverableAtRules'
import substituteFocusableAtRules from './lib/substituteFocusableAtRules'
import substituteResponsiveAtRules from './lib/substituteResponsiveAtRules'
import substituteScreenAtRules from './lib/substituteScreenAtRules'
import substituteClassApplyAtRules from './lib/substituteClassApplyAtRules'
const plugin = postcss.plugin('tailwind', (options = {}) => {
if (_.isString(options)) {
options = require(path.resolve(options))
}
const config = mergeConfig(defaultConfig, options)
return postcss([
substituteResetAtRule(config),
evaluateTailwindFunctions(config),
generateUtilities(config),
substituteHoverableAtRules(config),
substituteFocusableAtRules(config),
substituteResponsiveAtRules(config),
substituteScreenAtRules(config),
substituteClassApplyAtRules(config),
stylefmt,
])
})
plugin.defaultConfig = _.cloneDeep(defaultConfig)
module.exports = plugin
| import fs from 'fs'
import path from 'path'
import _ from 'lodash'
import postcss from 'postcss'
import stylefmt from 'stylefmt'
import defaultConfig from './defaultConfig'
import mergeConfig from './util/mergeConfig'
import substituteResetAtRule from './lib/substituteResetAtRule'
import evaluateTailwindFunctions from './lib/evaluateTailwindFunctions'
import generateUtilities from './lib/generateUtilities'
import substituteHoverableAtRules from './lib/substituteHoverableAtRules'
import substituteFocusableAtRules from './lib/substituteFocusableAtRules'
import substituteResponsiveAtRules from './lib/substituteResponsiveAtRules'
import substituteScreenAtRules from './lib/substituteScreenAtRules'
import substituteClassApplyAtRules from './lib/substituteClassApplyAtRules'
const plugin = postcss.plugin('tailwind', (options = {}) => {
if (_.isString(options)) {
options = require(path.resolve(options))
}
const config = mergeConfig(defaultConfig, options)
return postcss([
substituteResetAtRule(config),
evaluateTailwindFunctions(config),
generateUtilities(config),
substituteHoverableAtRules(config),
substituteFocusableAtRules(config),
substituteResponsiveAtRules(config),
substituteScreenAtRules(config),
substituteClassApplyAtRules(config),
stylefmt,
])
})
module.exports = plugin
|
Print targe and published for all ports of a service | package main
import (
"fmt"
"github.com/docker/engine-api/client"
"github.com/docker/engine-api/types"
"github.com/docker/engine-api/types/filters"
"github.com/fatih/color"
"github.com/urfave/cli"
"golang.org/x/net/context"
)
func output(c *cli.Context) error {
stacks, err := getStacks(c)
if err != nil {
return err
}
swarm, swarmErr := client.NewEnvClient()
if swarmErr != nil {
return cli.NewExitError(swarmErr.Error(), 3)
}
for _, stack := range stacks {
filter := filters.NewArgs()
filter.Add("label", "com.docker.stack.namespace="+stack.Name)
services, servicesErr := swarm.ServiceList(context.Background(), types.ServiceListOptions{Filter: filter})
if servicesErr != nil {
return cli.NewExitError(servicesErr.Error(), 3)
}
current := getSwarmServicesSpecForStack(services)
for _, s := range current {
color.Green("%s\n", s.Spec.Name)
fmt.Println(" - Published Ports")
for _, port := range s.Endpoint.Ports {
fmt.Printf(" %d => %d\n", port.TargetPort, port.PublishedPort)
}
fmt.Println()
}
}
return nil
}
| package main
import (
"fmt"
"github.com/docker/engine-api/client"
"github.com/docker/engine-api/types"
"github.com/docker/engine-api/types/filters"
"github.com/fatih/color"
"github.com/urfave/cli"
"golang.org/x/net/context"
)
func output(c *cli.Context) error {
stacks, err := getStacks(c)
if err != nil {
return err
}
swarm, swarmErr := client.NewEnvClient()
if swarmErr != nil {
return cli.NewExitError(swarmErr.Error(), 3)
}
for _, stack := range stacks {
filter := filters.NewArgs()
filter.Add("label", "com.docker.stack.namespace="+stack.Name)
services, servicesErr := swarm.ServiceList(context.Background(), types.ServiceListOptions{Filter: filter})
if servicesErr != nil {
return cli.NewExitError(servicesErr.Error(), 3)
}
current := getSwarmServicesSpecForStack(services)
for _, s := range current {
color.Green("%s\n", s.Spec.Name)
fmt.Printf(" - Published Port => %d\n", s.Endpoint.Ports[0].PublishedPort)
fmt.Println()
}
}
return nil
}
|
Subtract buffer time from wait time | package departure
import (
"time"
"fmt"
)
func Watch(duration, throttle, bufferTime int, apiKey, origin, destination, transitMode, lineName string) {
ticker := time.NewTicker(time.Second * time.Duration(throttle))
go func() {
for range ticker.C {
desiredDepTime := time.Now().Add(time.Duration(bufferTime) * time.Second)
depTime, err := GetDepartureTime(origin, destination, apiKey, transitMode, lineName, desiredDepTime)
if err != nil {
fmt.Printf("ERROR %s\n", err)
} else {
until := time.Until(depTime)
untilSeconds := int(until.Seconds()) - bufferTime
if untilSeconds < bufferTime {
fmt.Printf("GO %d\n", untilSeconds)
} else {
fmt.Printf("WAIT %d\n", untilSeconds)
}
}
}
}()
time.Sleep(time.Second * time.Duration(duration))
ticker.Stop()
fmt.Println("DONE")
}
| package departure
import (
"time"
"fmt"
)
func Watch(duration, throttle, bufferTime int, apiKey, origin, destination, transitMode, lineName string) {
ticker := time.NewTicker(time.Second * time.Duration(throttle))
go func() {
for range ticker.C {
desiredDepTime := time.Now().Add(time.Duration(bufferTime) * time.Second)
depTime, err := GetDepartureTime(origin, destination, apiKey, transitMode, lineName, desiredDepTime)
if err != nil {
fmt.Printf("ERROR %s\n", err)
} else {
until := time.Until(depTime)
untilSeconds := int(until.Seconds())
if untilSeconds < bufferTime {
fmt.Printf("GO %d\n", untilSeconds)
} else {
fmt.Printf("WAIT %d\n", untilSeconds)
}
}
}
}()
time.Sleep(time.Second * time.Duration(duration))
ticker.Stop()
fmt.Println("DONE")
}
|
Reduce test runtime by decreasing default sleep
Also remove WeakGeneratorWrapper check until gc tests are implemented. | import threading
import time
from ..send_self import WeakGeneratorWrapper
DEFAULT_SLEEP = 0.01
class CustomError(Exception):
pass
def defer(callback, *args, sleep=DEFAULT_SLEEP, expected_return=None, call=True, **kwargs):
def func():
time.sleep(sleep)
if call:
assert expected_return == callback(*args, **kwargs)
else:
print("generator is not re-called")
t = threading.Thread(target=func)
t.start()
def wait_until_finished(wrapper, timeout=1, sleep=DEFAULT_SLEEP, defer_calls=1):
# Can not be called with StrongGeneratorWrapper,
# likely because it will be bound in some frame
# and thus its reference won't get gc'd
# when it would otherwise.
# TOCHECK
# assert type(wrapper) is WeakGeneratorWrapper
if not timeout:
timeout = defer_calls * DEFAULT_SLEEP + 1
ref = wrapper.weak_generator
start_time = time.time()
while time.time() < start_time + timeout:
if wrapper.has_terminated():
return
time.sleep(sleep)
else:
if ref() is None:
return
raise RuntimeError("Has not been collected within %ss" % timeout)
| import threading
import time
from ..send_self import (
WeakGeneratorWrapper,
StrongGeneratorWrapper
)
default_sleep = 0.1
class CustomError(Exception):
pass
def defer(callback, *args, sleep=default_sleep, expected_return=None, call=True,
**kwargs):
def func():
time.sleep(sleep)
if call:
assert expected_return == callback(*args, **kwargs)
else:
print("generator is not re-called")
t = threading.Thread(target=func)
t.start()
def wait_until_finished(wrapper, timeout=None, sleep=default_sleep,
defer_calls=1):
# Can not be called with StrongGeneratorWrapper, likely because it will be
# bound in some frame and thus its reference won't get gc'd when it would
# otherwise. TOCHECK
assert type(wrapper) is WeakGeneratorWrapper
if not timeout:
timeout = defer_calls * default_sleep + 1
ref = wrapper.weak_generator
start_time = time.time()
while time.time() < start_time + timeout:
if wrapper.has_terminated():
return
time.sleep(sleep)
else:
if ref() is None:
return
raise RuntimeError("Has not been collected within %ss" % timeout)
|
Remove auth hook from user | 'use strict';
const globalHooks = require('../../../hooks');
const hooks = require('feathers-hooks');
const auth = require('feathers-authentication').hooks;
exports.before = {
all: [],
find: [
auth.verifyToken(),
auth.populateUser(),
auth.restrictToAuthenticated()
],
get: [
auth.verifyToken(),
auth.populateUser(),
auth.restrictToAuthenticated()
],
create: [
auth.hashPassword()
],
update: [
auth.verifyToken(),
auth.populateUser(),
auth.restrictToAuthenticated(),
auth.restrictToOwner({ ownerField: '_id' })
],
patch: [
auth.verifyToken(),
auth.populateUser(),
auth.restrictToAuthenticated(),
auth.restrictToOwner({ ownerField: '_id' })
],
remove: [
auth.verifyToken(),
auth.populateUser(),
auth.restrictToAuthenticated(),
auth.restrictToOwner({ ownerField: '_id' })
]
};
exports.after = {
all: [hooks.remove('password')],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
};
| 'use strict';
const globalHooks = require('../../../hooks');
const hooks = require('feathers-hooks');
const auth = require('feathers-authentication').hooks;
exports.before = {
all: [
globalHooks.isAdmin()
],
find: [
auth.verifyToken(),
auth.populateUser(),
auth.restrictToAuthenticated()
],
get: [
auth.verifyToken(),
auth.populateUser(),
auth.restrictToAuthenticated()
],
create: [
auth.hashPassword()
],
update: [
auth.verifyToken(),
auth.populateUser(),
auth.restrictToAuthenticated(),
auth.restrictToOwner({ ownerField: '_id' })
],
patch: [
auth.verifyToken(),
auth.populateUser(),
auth.restrictToAuthenticated(),
auth.restrictToOwner({ ownerField: '_id' })
],
remove: [
auth.verifyToken(),
auth.populateUser(),
auth.restrictToAuthenticated(),
auth.restrictToOwner({ ownerField: '_id' })
]
};
exports.after = {
all: [hooks.remove('password')],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
};
|
Add bit of perflogger back | import createLogger from 'redux-logger';
import { enableBatching } from 'redux-batched-actions';
import promiseMiddleware from 'redux-promise-middleware';
import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import perflogger from 'redux-perf-middleware';
import createReducer from '@state/reducers';
import { isProduction } from '@utils';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export default (state = Object.freeze({})) => {
return createStore(
enableBatching(createReducer()),
state,
composeEnhancers(
applyMiddleware(
createLogger(),
promiseMiddleware(),
thunk/*,
!isProduction() && perflogger*/
)
)
);
};
| import createLogger from 'redux-logger';
import { enableBatching } from 'redux-batched-actions';
import promiseMiddleware from 'redux-promise-middleware';
import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
// import perflogger from 'redux-perf-middleware';
import createReducer from '@state/reducers';
// import { isProduction } from '@utils';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export default (state = Object.freeze({})) => {
return createStore(
enableBatching(createReducer()),
state,
composeEnhancers(
applyMiddleware(
createLogger(),
promiseMiddleware(),
thunk/*,
!isProduction() && perflogger*/
)
)
);
};
|
Use interface rather than a class. | <?php
namespace Mulgrew\Model;
use DateTimeInterface;
class Revision
{
/**
* Revision Identifier
* @column(type="string", length="40", )
* @var integer
*/
protected $id;
/**
* The page
* @var Mulgrew\Model\Page
* @ManyToOne(targetEntity="Mulgrew\Model\Page", inversedBy="revisions")
*/
protected $page;
/**
* The user who created the revision
* @var Mulgrew\Model\User
*/
protected $user;
/**
* Opcodes to get to the previous revision
* @var string|null
*/
protected $opcodes;
/**
* Optional comment for this revision
* @var string
*/
protected $comment;
/**
* The date and time the revision was created.
* @var DateTimeInterface
*/
protected $datetime;
} | <?php
namespace Mulgrew\Model;
use DateTime;
class Revision
{
/**
* Revision Identifier
* @column(type="string", length="40", )
* @var integer
*/
protected $id;
/**
* The page
* @var Mulgrew\Model\Page
* @ManyToOne(targetEntity="Mulgrew\Model\Page", inversedBy="revisions")
*/
protected $page;
/**
* The user who created the revision
* @var Mulgrew\Model\User
*/
protected $user;
/**
* Opcodes to get to the previous revision
* @var string|null
*/
protected $opcodes;
/**
* Optional comment for this revision
* @var string
*/
protected $comment;
/**
* The date and time the revision was created.
* @var DateTime
*/
protected $datetime;
} |
Change word from Done to Next | import React from 'react';
class SimpleTourItem extends React.Component {
render() {
const containerStyle = {
background: 'white',
padding: '20px',
color: 'black',
maxWidth: '300px'
};
const buttonStyle = {
cursor: 'pointer',
textDecoration: 'none',
color: '#3498db',
margin: '12px'
};
return (
<div style={containerStyle}>
<p>{this.props.message}</p>
<span
className='simple-tour-item-button'
style={buttonStyle}
onClick={this.props.onSkip}>
Skip
</span>
<span
className='simple-tour-item-button'
style={buttonStyle}
onClick={this.props.onDone}>
Next
</span>
</div>
);
}
}
SimpleTourItem.propTypes = {
message: React.PropTypes.string,
onSkip: React.PropTypes.func,
onDone: React.PropTypes.func
};
export default SimpleTourItem;
| import React from 'react';
class SimpleTourItem extends React.Component {
render() {
const containerStyle = {
background: 'white',
padding: '20px',
color: 'black',
maxWidth: '300px'
};
const buttonStyle = {
cursor: 'pointer',
textDecoration: 'none',
color: '#3498db',
margin: '12px'
};
return (
<div style={containerStyle}>
<p>{this.props.message}</p>
<span
className='simple-tour-item-button'
style={buttonStyle}
onClick={this.props.onSkip}>
Skip
</span>
<span
className='simple-tour-item-button'
style={buttonStyle}
onClick={this.props.onDone}>
Close
</span>
</div>
);
}
}
SimpleTourItem.propTypes = {
message: React.PropTypes.string,
onSkip: React.PropTypes.func,
onDone: React.PropTypes.func
};
export default SimpleTourItem;
|
Support nested key path for result, fix bugs | const jsonServer = require('json-server')
const server = jsonServer.create()
const path = require('path')
const router = jsonServer.router(path.join(__dirname, 'db.json'))
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(jsonServer.bodyParser)
server.use((req, res, next) => {
// non-get requests just send back the same data sent
if (['POST', 'DELETE', 'PUT', 'PATCH'].includes(req.method)) {
res.jsonp(req.body)
} else {
next()
}
})
router.render = (req, res) => {
var result = res.locals.data
var query = req.originalUrl.split('?')[1]
if (query !== undefined) {
var tuple = query.split('=')
var key = tuple[0]
var value = tuple[1]
if (key === 'keyPath') {
var node = {}
var lastNode = null
var lastPath = null
result = node
value.split('.').forEach((path) => {
lastNode = node
lastPath = path
node[path] = {}
node = node[path]
})
lastNode[lastPath] = res.locals.data
}
}
res.jsonp(result)
}
server.use(jsonServer.rewriter({
'/api/': '/'
}))
server.use(router)
server.listen(3000, () => {
console.log('JSON Server is running')
})
| const jsonServer = require('json-server')
const server = jsonServer.create()
const path = require('path')
const router = jsonServer.router(path.join(__dirname, 'db.json'))
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(jsonServer.bodyParser)
server.use((req, res, next) => {
// non-get requests just send back the same data sent
if (['POST', 'DELETE', 'PUT', 'PATCH'].includes(req.method)) {
res.jsonp(req.body)
} else {
next()
}
})
router.render = (req, res) => {
var result = res.locals.data
var keyPath = req.originalUrl.split('=')[1]
if (keyPath === 'keyPath') {
result = {}
result[keyPath] = res.locals.data
}
res.jsonp(result)
}
server.use(jsonServer.rewriter({
'/api/': '/'
}))
server.use(router)
server.listen(3000, () => {
console.log('JSON Server is running')
})
|
Remove dynamic route component importing | import Vue from 'vue';
import VueRouter from 'vue-router';
import * as RouteNames from './constants/route';
import LobbyPage from './vue/LobbyPage.vue';
import NotFound from './vue/NotFound.vue';
import RoomPage from './vue/RoomPage.vue';
Vue.use(VueRouter);
export default new VueRouter({
mode: 'history',
base: __dirname,
routes: [
{
path: '/',
name: RouteNames.Lobby,
component: LobbyPage,
},
{
path: '/404',
name: RouteNames.NotFound,
component: NotFound,
},
{
path: '/:id',
name: RouteNames.Room,
component: RoomPage,
},
],
});
| import Vue from 'vue';
import VueRouter from 'vue-router';
import * as RouteNames from './constants/route';
import Loading from './vue/Loading.vue';
import NotFound from './vue/NotFound.vue';
Vue.use(VueRouter);
export default new VueRouter({
mode: 'history',
base: __dirname,
routes: [
{
path: '/',
name: RouteNames.Lobby,
component: () => ({
component: import('./vue/LobbyPage.vue'),
loading: Loading,
}),
},
{
path: '/404',
name: RouteNames.NotFound,
component: NotFound,
},
{
path: '/:id',
name: RouteNames.Room,
component: () => ({
component: import('./vue/RoomPage.vue'),
loading: Loading,
}),
},
],
});
|
Handle failure to start a program | package main
import (
"os"
"os/exec"
)
func proto_0_0(inFlag, outFlag bool, errFlag, workdir string, args []string) error {
proc := exec.Command(args[0], args[1:]...)
proc.Dir = workdir
logger.Printf("Command path: %v\n", proc.Path)
done := make(chan bool)
done_count := 0
done_count += wrapStdin(proc, os.Stdin, inFlag, done)
if outFlag {
done_count += wrapStdout(proc, os.Stdout, 'o', done)
}
switch errFlag {
case "out":
if outFlag {
done_count += wrapStderr(proc, os.Stdout, 'o', done)
}
case "err":
done_count += wrapStderr(proc, os.Stdout, 'e', done)
case "nil":
// no-op
default:
logger.Panicf("undefined redirect: '%v'\n", errFlag)
}
err := proc.Run()
if e, ok := err.(*exec.Error); ok {
logger.Printf("Run ERROR: %v\n", e)
os.Exit(3)
}
logger.Printf("Run FINISHED: %#v\n", err)
for i := 0; i < done_count; i++ {
<-done
}
return err
}
| package main
import (
"os"
"os/exec"
)
func proto_0_0(inFlag, outFlag bool, errFlag, workdir string, args []string) error {
proc := exec.Command(args[0], args[1:]...)
proc.Dir = workdir
logger.Printf("Command path: %v\n", proc.Path)
done := make(chan bool)
done_count := 0
done_count += wrapStdin(proc, os.Stdin, inFlag, done)
if outFlag {
done_count += wrapStdout(proc, os.Stdout, 'o', done)
}
switch errFlag {
case "out":
if outFlag {
done_count += wrapStderr(proc, os.Stdout, 'o', done)
}
case "err":
done_count += wrapStderr(proc, os.Stdout, 'e', done)
case "nil":
// no-op
default:
logger.Panicf("undefined redirect: '%v'\n", errFlag)
}
err := proc.Run()
for i := 0; i < done_count; i++ {
<-done
}
return err
}
|
Add option to set theme on frontend or backend. | <?php
namespace Yajra\CMS\Themes;
use Illuminate\View\FileViewFinder;
class ThemeViewFinder extends FileViewFinder
{
/**
* Base path to look for blade files.
*
* @var string
*/
protected $basePath;
/**
* Use the given theme as the current theme.
*
* @param string $theme
* @param bool $frontend
*/
public function use($theme, $frontend = true)
{
$key = $frontend ? 'frontend' : 'backend';
$theme = $theme ?: config('themes.' . $key, 'default');
$basePath = config('themes.path.' . $key, base_path('themes/' . $key));
$this->removeBasePath();
$this->setBasePath($basePath . DIRECTORY_SEPARATOR . $theme);
config(['themes.' . $key => $theme]);
}
/**
* Remove base path.
*/
public function removeBasePath()
{
unset($this->paths[0]);
}
/**
* Set file view finder base path.
*
* @param $path
*/
public function setBasePath($path)
{
$this->basePath = $path;
array_unshift($this->paths, $this->basePath);
}
}
| <?php
namespace Yajra\CMS\Themes;
use Illuminate\View\FileViewFinder;
class ThemeViewFinder extends FileViewFinder
{
/**
* Base path to look for blade files.
*
* @var string
*/
protected $basePath;
/**
* Use the given theme as the current theme.
*
* @param string $theme
*/
public function use($theme)
{
$theme = $theme ?: config('themes.frontend', 'default');
$basePath = config('themes.path.frontend', base_path('themes/frontend'));
$this->removeBasePath();
$this->setBasePath($basePath . DIRECTORY_SEPARATOR . $theme);
config(['themes.frontend' => $theme]);
}
/**
* Remove base path.
*/
public function removeBasePath()
{
unset($this->paths[0]);
}
/**
* Set file view finder base path.
*
* @param $path
*/
public function setBasePath($path)
{
$this->basePath = $path;
array_unshift($this->paths, $this->basePath);
}
}
|
Make the jsroot magic a line magic for the C++ kernel | # -*- coding:utf-8 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2016, ROOT Team.
# Authors: Danilo Piparo <Danilo.Piparo@cern.ch> CERN
#-----------------------------------------------------------------------------
from JupyROOT.utils import enableJSVis, disableJSVis, enableJSVisDebug, TBufferJSONErrorMessage, TBufferJSONAvailable
from metakernel import Magic, option
class JSRootMagics(Magic):
def __init__(self, kernel):
super(JSRootMagics, self).__init__(kernel)
@option('arg', default="on", help='Enable or disable JavaScript visualisation. Possible values: on (default), off')
def line_jsroot(self, args):
'''Change the visualisation of plots from images to interactive JavaScript objects.'''
if args == 'on' or args == '':
self.printErrorIfNeeded()
enableJSVis()
elif args == 'off':
disableJSVis()
elif args == 'debug':
self.printErrorIfNeeded()
enableJSVisDebug()
def printErrorIfNeeded(self):
if not TBufferJSONAvailable():
self.kernel.Error(TBufferJSONErrorMessage)
def register_magics(kernel):
kernel.register_magics(JSRootMagics)
| # -*- coding:utf-8 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2016, ROOT Team.
# Authors: Danilo Piparo <Danilo.Piparo@cern.ch> CERN
#-----------------------------------------------------------------------------
from JupyROOT.utils import enableJSVis, disableJSVis, enableJSVisDebug, TBufferJSONErrorMessage, TBufferJSONAvailable
from metakernel import Magic, option
class JSRootMagics(Magic):
def __init__(self, kernel):
super(JSRootMagics, self).__init__(kernel)
@option('arg', default="on", help='Enable or disable JavaScript visualisation. Possible values: on (default), off')
def cell_jsroot(self, args):
'''Change the visualisation of plots from images to interactive JavaScript objects.'''
if args == 'on' or args == '':
self.printErrorIfNeeded()
enableJSVis()
elif args == 'off':
disableJSVis()
elif args == 'debug':
self.printErrorIfNeeded()
enableJSVisDebug()
def printErrorIfNeeded(self):
if not TBufferJSONAvailable():
self.kernel.Error(TBufferJSONErrorMessage)
def register_magics(kernel):
kernel.register_magics(JSRootMagics)
|
Correct issue while trying to connect to backend without credentials
A JavaScript error was dispatched when trying to connect to backend, from login page, without credentials. | (function(app){
"use strict"
app.controller("LoginController", LoginController);
LoginController.$inject = ["$scope", "$location", "authenticationService"];
/**
* Defines the login controller for the login page.
*/
function LoginController($scope, $location, authenticationService){
$scope.verticalAlign = true;
$scope.onError = false;
/**
* Signs in using the login form information (userName and password).
* If user successfully signed in, redirect to the back office
* home page. Otherwise, set the form as on error.
*/
$scope.signIn = function(){
var loginPromise = authenticationService.login($scope.userName, $scope.password);
if(loginPromise){
loginPromise.then(function(result){
authenticationService.setUserInfo(result.data);
$location.path("/admin");
}, function(error){
$scope.onError = true;
$scope.userName = $scope.password = "";
});
}
};
}
})(angular.module("ov")); | (function(app){
"use strict"
app.controller("LoginController", LoginController);
LoginController.$inject = ["$scope", "$location", "authenticationService"];
/**
* Defines the login controller for the login page.
*/
function LoginController($scope, $location, authenticationService){
$scope.verticalAlign = true;
$scope.onError = false;
/**
* Signs in using the login form information (userName and password).
* If user successfully signed in, redirect to the back office
* home page. Otherwise, set the form as on error.
*/
$scope.signIn = function(){
authenticationService.login($scope.userName, $scope.password).then(function(result){
authenticationService.setUserInfo(result.data);
$location.path("/admin");
}, function(error){
$scope.onError = true;
$scope.userName = $scope.password = "";
});
};
}
})(angular.module("ov")); |
Fix signedTx & hardcode a test wallet |
import React from 'react';
import {
StyleSheet,
Text,
View
} from 'react-native';
import WalletService from '../services/WalletService';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
App = () => {
const wallet = WalletService.generateNewWallet();
console.log("wallet info:", wallet);
const toAddress = "0x00c376412f3a8063fc6bceb1d874730ea88eb531";
const amount = 11;
WalletService.send({privateKey: wallet.privateKey, fromAddress: wallet.address}, toAddress, amount);
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to HumanAtm
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
</View>
);
};
export default App;
|
import React from 'react';
import {
StyleSheet,
Text,
View
} from 'react-native';
import WalletService from '../services/WalletService';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
App = () => {
const wallet = WalletService.generateNewWallet();
console.log("wallet info:", wallet);
const toAddress = "0x00c376412f3a8063fc6bceb1d874730ea88eb531";
const amount = 50;
WalletService.send({privateKey: wallet.privateKey, fromAddress: wallet.address}, toAddress, amount);
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to HumanAtm
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
</View>
);
};
export default App;
|
Fix tests when there is an image with int tag | from __future__ import unicode_literals
from __future__ import absolute_import
from fig.packages.docker import Client
from fig.service import Service
from fig.cli.utils import docker_url
from . import unittest
class DockerClientTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.client = Client(docker_url())
cls.client.pull('ubuntu', tag='latest')
def setUp(self):
for c in self.client.containers(all=True):
if c['Names'] and 'figtest' in c['Names'][0]:
self.client.kill(c['Id'])
self.client.remove_container(c['Id'])
for i in self.client.images():
if isinstance(i['Tag'], basestring) and 'figtest' in i['Tag']:
self.client.remove_image(i)
def create_service(self, name, **kwargs):
return Service(
project='figtest',
name=name,
client=self.client,
image="ubuntu",
command=["/bin/sleep", "300"],
**kwargs
)
| from __future__ import unicode_literals
from __future__ import absolute_import
from fig.packages.docker import Client
from fig.service import Service
from fig.cli.utils import docker_url
from . import unittest
class DockerClientTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.client = Client(docker_url())
cls.client.pull('ubuntu', tag='latest')
def setUp(self):
for c in self.client.containers(all=True):
if c['Names'] and 'figtest' in c['Names'][0]:
self.client.kill(c['Id'])
self.client.remove_container(c['Id'])
for i in self.client.images():
if 'figtest' in i['Tag']:
self.client.remove_image(i)
def create_service(self, name, **kwargs):
return Service(
project='figtest',
name=name,
client=self.client,
image="ubuntu",
command=["/bin/sleep", "300"],
**kwargs
)
|
Enhance the SD card list with more info. | import platform
import string
import glob
import os
import stat
def getPossibleSDcardDrives():
drives = []
if platform.system() == "Windows":
from ctypes import windll
import ctypes
bitmask = windll.kernel32.GetLogicalDrives()
for letter in string.uppercase:
if bitmask & 1 and windll.kernel32.GetDriveTypeA(letter + ':/') == 2:
volumeName = ''
nameBuffer = ctypes.create_unicode_buffer(1024)
if windll.kernel32.GetVolumeInformationW(ctypes.c_wchar_p(letter + ':/'), nameBuffer, ctypes.sizeof(nameBuffer), None, None, None, None, 0) == 0:
volumeName = nameBuffer.value
if volumeName == '':
volumeName = 'NO NAME'
drives.append(('%s (%s:)' % (volumeName, letter), letter + ':/', volumeName))
bitmask >>= 1
elif platform.system() == "Darwin":
for volume in glob.glob('/Volumes/*'):
if stat.S_ISLNK(os.lstat(volume).st_mode):
continue
#'Ejectable: Yes' in os.system('diskutil info \'%s\'' % (volume))
drives.append((os.path.basename(volume), os.path.basename(volume), volume))
else:
for volume in glob.glob('/media/*'):
drives.append((os.path.basename(volume), os.path.basename(volume), volume))
return drives
| import platform
import string
import glob
import os
import stat
def getPossibleSDcardDrives():
drives = []
if platform.system() == "Windows":
from ctypes import windll
bitmask = windll.kernel32.GetLogicalDrives()
for letter in string.uppercase:
if bitmask & 1 and windll.kernel32.GetDriveTypeA(letter + ':/') == 2:
drives.append(letter + ':/')
bitmask >>= 1
elif platform.system() == "Darwin":
for volume in glob.glob('/Volumes/*'):
if stat.S_ISLNK(os.lstat(volume).st_mode):
continue
#'Ejectable: Yes' in os.system('diskutil info \'%s\'' % (volume))
drives.append(volume)
else:
for volume in glob.glob('/media/*'):
drives.append(volume)
return drives
|
Remove another class (QSqlDriverPlugin) from test | from __future__ import absolute_import
import pytest
from qtpy import QtSql
def test_qtsvg():
"""Test the qtpy.QtSql namespace"""
assert QtSql.QSqlDatabase is not None
# assert QtSql.QSqlDriverCreator is not None
assert QtSql.QSqlDriverCreatorBase is not None
assert QtSql.QSqlDriver is not None
#assert QtSql.QSqlDriverPlugin is not None
assert QtSql.QSqlError is not None
assert QtSql.QSqlField is not None
assert QtSql.QSqlIndex is not None
assert QtSql.QSqlQuery is not None
assert QtSql.QSqlRecord is not None
assert QtSql.QSqlResult is not None
assert QtSql.QSqlQueryModel is not None
assert QtSql.QSqlRelationalDelegate is not None
assert QtSql.QSqlRelation is not None
assert QtSql.QSqlRelationalTableModel is not None
assert QtSql.QSqlTableModel is not None
| from __future__ import absolute_import
import pytest
from qtpy import QtSql
def test_qtsvg():
"""Test the qtpy.QtSql namespace"""
assert QtSql.QSqlDatabase is not None
# assert QtSql.QSqlDriverCreator is not None
assert QtSql.QSqlDriverCreatorBase is not None
assert QtSql.QSqlDriver is not None
assert QtSql.QSqlDriverPlugin is not None
assert QtSql.QSqlError is not None
assert QtSql.QSqlField is not None
assert QtSql.QSqlIndex is not None
assert QtSql.QSqlQuery is not None
assert QtSql.QSqlRecord is not None
assert QtSql.QSqlResult is not None
assert QtSql.QSqlQueryModel is not None
assert QtSql.QSqlRelationalDelegate is not None
assert QtSql.QSqlRelation is not None
assert QtSql.QSqlRelationalTableModel is not None
assert QtSql.QSqlTableModel is not None
|
Move QGL import inside function
A channel library is not always available | from . import bbn
import auspex.config
from auspex.log import logger
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
from QGL import *
ChannelLibrary()
settings = auspex.config.load_meas_file(auspex.config.find_meas_file())
mkr = settings['markers'][marker_name]
marker = MarkerFactory(marker_name)
APS_name = mkr.split()[0]
APS = bbn.APS2()
APS.connect(settings['instruments'][APS_name]['address'])
APS.set_trigger_source('Software')
seq = [[TRIG(marker,length)]]
APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5'))
APS.run()
APS.trigger()
APS.stop()
APS.disconnect()
logger.info('Switched marker {} ({})'.format(marker_name, mkr))
| from . import bbn
import auspex.config
from auspex.log import logger
from QGL import *
ChannelLibrary()
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
settings = auspex.config.load_meas_file(auspex.config.find_meas_file())
mkr = settings['markers'][marker_name]
marker = MarkerFactory(marker_name)
APS_name = mkr.split()[0]
APS = bbn.APS2()
APS.connect(settings['instruments'][APS_name]['address'])
APS.set_trigger_source('Software')
seq = [[TRIG(marker,length)]]
APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5'))
APS.run()
APS.trigger()
APS.stop()
APS.disconnect()
logger.info('Switched marker {} ({})'.format(marker_name, mkr))
|
Include libraries for transformation with Jest | // https://github.com/thymikee/jest-preset-angular#brief-explanation-of-config
module.exports = {
preset: 'jest-preset-angular',
roots: ['src'],
coverageDirectory: 'reports',
setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'],
moduleNameMapper: {
'@app/(.*)': '<rootDir>/src/app/$1',
'@env': '<rootDir>/src/environments/environment'
},
// Do not ignore librairies such as ionic, ionic-native or bootstrap to transform them during unit testing.
<% const excludedLibrairies = ['jest-test']
if (props.target.includes('cordova')) { excludedLibrairies.push('@ionic-native'); }
if (props.ui === 'ionic') { excludedLibrairies.push('@ionic'); }
if (props.ui === 'bootstrap') { excludedLibrairies.push('@ng-bootstrap'); } -%>
transformIgnorePatterns: ['node_modules/(?!(<%- excludedLibrairies.join('|') %>))']
};
| // https://github.com/thymikee/jest-preset-angular#brief-explanation-of-config
module.exports = {
preset: 'jest-preset-angular',
roots: ['src'],
coverageDirectory: 'reports',
setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'],
moduleNameMapper: {
'@app/(.*)': '<rootDir>/src/app/$1',
'@env': '<rootDir>/src/environments/environment'
},
// Do not ignore librairies such as ionic, ionic-native or bootstrap to transform them during unit testing.
<%
var excludedLibrairies = ['jest-test'];
if (props.target.includes('cordova')) { excludedLibrairies.push('@ionic-native'); }
if (props.ui === 'ionic') { excludedLibrairies.push('@ionic'); }
if (props.ui === 'bootstrap') { excludedLibrairies.push('@ng-bootstrap'); }
-%>
transformIgnorePatterns: ['node_modules/(?!(<%- excludedLibrairies.join('|') %>))']
};
|
Fix scope watch of angular flotchart integration | /**
* Created with IntelliJ IDEA.
* User: issa
* Date: 2/10/14
* Time: 1:18 AM
*/
app.directive('aFloat', function() {
function link(scope, element, attrs){
scope.$watch('afData + afOption', function(){
init(scope.afData,scope.afOption);
});
var totalWidth = element.width(), totalHeight = element.height();
if (totalHeight === 0 || totalWidth === 0) {
throw new Error('Please set height and width for the aFloat element'+'width is '+ele);
}
function init(o,d){
$.plot(element, o , d);
}
}
return {
restrict: 'EA',
template: '<div></div>',
link: link,
replace:true,
scope: {
afOption: '=',
afData: '='
}
};
}); | /**
* Created with IntelliJ IDEA.
* User: issa
* Date: 2/10/14
* Time: 1:18 AM
*/
app.directive('aFloat', function() {
function link(scope, element, attrs){
var data = scope.afData;
var options = scope.afOption;
var totalWidth = element.width(), totalHeight = element.height();
if (totalHeight === 0 || totalWidth === 0) {
throw new Error('Please set height and width for the aFloat element'+'width is '+ele);
}
function init(o,d){
$.plot(element, o , d);
}
scope.$watch('afOption', function (o){
init(o,data);
});
scope.$watch('afData', function (d){
init(d,options);
});
}
return {
restrict: 'EA',
template: '<div></div>',
link: link,
replace:true,
transclude: false,
scope: {
afOption: '=',
afData: '='
}
};
}); |
Add AppSettings dict to app config and inject it | from flask import Flask
from flask_login import LoginManager
from flask_misaka import Misaka
from flask_moment import Moment
from flask_security import Security, SQLAlchemyUserDatastore
from flask_sqlalchemy import SQLAlchemy
from flask_whooshalchemy import whoosh_index
from config import config
db = SQLAlchemy()
lm = LoginManager()
markdown = Misaka()
moment = Moment()
security = Security()
from app.models import Post, User, Role
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
def create_app(config_name):
"""
Initializes a Flask app.
Args:
config_name: The configuration object to use.
Returns:
The Flask app object.
"""
app = Flask(__name__)
app.config.from_object(config[config_name])
db.init_app(app)
lm.init_app(app)
markdown.init_app(app)
moment.init_app(app)
security.init_app(app, user_datastore)
whoosh_index(app, Post)
from app.utils.settings import AppSettings
with app.app_context():
app.config['SETTINGS'] = AppSettings()
@app.context_processor
def inject_settings():
return {'settings': app.config['SETTINGS']}
from app.main.views import main
from app.admin.views import admin
app.register_blueprint(main)
app.register_blueprint(admin, url_prefix='/admin')
return app
| from flask import Flask
from flask_login import LoginManager
from flask_misaka import Misaka
from flask_moment import Moment
from flask_security import Security, SQLAlchemyUserDatastore
from flask_sqlalchemy import SQLAlchemy
from flask_whooshalchemy import whoosh_index
from config import config
db = SQLAlchemy()
lm = LoginManager()
markdown = Misaka()
moment = Moment()
security = Security()
from app.models import Post, User, Role
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
def create_app(config_name):
"""
Initializes a Flask app.
Args:
config_name: The configuration object to use.
Returns:
The Flask app object.
"""
app = Flask(__name__)
app.config.from_object(config[config_name])
db.init_app(app)
lm.init_app(app)
markdown.init_app(app)
moment.init_app(app)
security.init_app(app, user_datastore)
whoosh_index(app, Post)
from app.main.views import main
from app.admin.views import admin
app.register_blueprint(main)
app.register_blueprint(admin, url_prefix='/admin')
return app
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.