text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix wrong order of parameters and change json decode to json encode | <?php
namespace AppBundle\API\Edit;
use AppBundle\API\Webservice;
use AppBundle\AppBundle;
use AppBundle\Entity\FennecUser;
use AppBundle\Entity\WebuserData;
use AppBundle\Service\DBVersion;
use Symfony\Component\HttpFoundation\ParameterBag;
class UpdateProject
{
private $manager;
/**
* UpdateProject constructor.
* @param $dbversion
*/
public function __construct(DBVersion $dbversion)
{
$this->manager = $dbversion->getEntityManager();
}
/**
* @inheritdoc
*/
public function execute($projectId, $biom, FennecUser $user = null)
{
if($biom === null || $projectId === null){
return array('error' => 'Missing parameter "biom" or "projectId"');
}
if($user == null){
return array('error' => 'User not logged in');
}
if($user === null){
return array('error' => 'Could not update project. Not found for user.');
}
$project = $this->manager->getRepository(WebuserData::class)->findOneBy(array('webuser' => $user, 'webuserDataId' => $projectId));
if($project === null){
return array('error' => 'Could not update project. Not found for user.');
}
$project->setProject(json_encode($biom));
$this->manager->persist($project);
$this->manager->flush();
return array('error' => null);
}
} | <?php
namespace AppBundle\API\Edit;
use AppBundle\API\Webservice;
use AppBundle\AppBundle;
use AppBundle\Entity\FennecUser;
use AppBundle\Entity\WebuserData;
use AppBundle\Service\DBVersion;
use Symfony\Component\HttpFoundation\ParameterBag;
class UpdateProject
{
private $manager;
/**
* UpdateProject constructor.
* @param $dbversion
*/
public function __construct(DBVersion $dbversion)
{
$this->manager = $dbversion->getEntityManager();
}
/**
* @inheritdoc
*/
public function execute($projectId, $biom, FennecUser $user = null)
{
if($biom === null || $projectId === null){
return array('error' => 'Missing parameter "biom" or "projectId"');
}
if($user == null){
return array('error' => 'User not logged in');
}
if($user === null){
return array('error' => 'Could not update project. Not found for user.');
}
$project = $this->manager->getRepository(WebuserData::class)->findOneBy(array('webuser' => $user, 'webuserDataId' => $projectId));
if($project === null){
return array('error' => 'Could not update project. Not found for user.');
}
$project->setProject(json_decode($biom, true));
$this->manager->persist($project);
$this->manager->flush();
return array('error' => null);
}
} |
Add window onresize listener to viz | import d3 from 'd3';
export default function openmetadesign_viz(data) {
// The container for the viz
var d3Container = document.getElementById("d3-container");
// Get dimensions of the container on window resize
window.addEventListener("resize", function(d) {
width = d3Container.clientWidth;
height = d3Container.clientHeight;
console.log(width, height);
});
// Add the SVG to the container
var svg = d3.select('#d3-container').append("svg");
svg.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("width", 50)
.attr("height", 100)
.attr("class", "svg-modal-button")
.on("mouseover", function() {
d3.select(this)
.classed("glow", true);
})
.on("mouseout", function() {
d3.select(this)
.classed("glow", false);
})
.attr("data-toggle", "modal");
svg.append("rect")
.attr("x", 40)
.attr("y", 50)
.attr("width", 50)
.attr("height", 100);
// Filters
var defs = svg.append("defs");
var glow = defs.append("filter")
.attr("id", "glow");
glow.append("feGaussianBlur")
.attr("stdDeviation", "3.5")
.attr("result", "coloredBlur");
var feMerge = glow.append("feMerge");
feMerge.append("feMergeNode")
.attr("in", "coloredBlur");
feMerge.append("feMergeNode")
.attr("in", "SourceGraphic");
}
| import d3 from 'd3';
export default function openmetadesign_viz(data) {
var svg = d3.select('#d3-container').append("svg");
svg.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("width", 50)
.attr("height", 100)
.attr("class", "svg-modal-button")
.on("mouseover", function() {
d3.select(this)
.classed("glow", true);
})
.on("mouseout", function() {
d3.select(this)
.classed("glow", false);
})
.attr("data-toggle", "modal");
svg.append("rect")
.attr("x", 40)
.attr("y", 50)
.attr("width", 50)
.attr("height", 100);
// Filters
var defs = svg.append("defs");
var glow = defs.append("filter")
.attr("id", "glow");
glow.append("feGaussianBlur")
.attr("stdDeviation", "3.5")
.attr("result", "coloredBlur");
var feMerge = glow.append("feMerge");
feMerge.append("feMergeNode")
.attr("in", "coloredBlur");
feMerge.append("feMergeNode")
.attr("in", "SourceGraphic");
}
|
Set SRID the new way | # -*- coding: utf-8 -*-
from django.contrib.gis.geos import Polygon
class ResourceLink(object):
def __init__(self, type, href):
self.type = type
self.href = href
class Resource(object):
def __init__(self, id, description, author, links, title,
created_at, updated_at, geom):
self.id = id
self.title = title
self.description = description
self.author = author
self.links = links
self.created_at = created_at
self.updated_at = updated_at
self.geom = geom
class ResourceList(object):
def __init__(self, api_url, catalog, count, results):
self.api_url = api_url
self.catalog = catalog
self.count = count
self.results = results
class BBox(object):
"""
Bounding box from incoming search API request.
"""
def __init__(self, xmin, ymin, xmax, ymax):
self.xmin = xmin
self.xmax = xmax
self.ymin = ymin
self.ymax = ymax
def area(self):
polygon = Polygon.from_bbox((
self.xmin, self.ymin,
self.xmax, self.ymax))
polygon.srid = 4326
return polygon.transform(5070, clone=True).area
| # -*- coding: utf-8 -*-
from django.contrib.gis.geos import Polygon
class ResourceLink(object):
def __init__(self, type, href):
self.type = type
self.href = href
class Resource(object):
def __init__(self, id, description, author, links, title,
created_at, updated_at, geom):
self.id = id
self.title = title
self.description = description
self.author = author
self.links = links
self.created_at = created_at
self.updated_at = updated_at
self.geom = geom
class ResourceList(object):
def __init__(self, api_url, catalog, count, results):
self.api_url = api_url
self.catalog = catalog
self.count = count
self.results = results
class BBox(object):
"""
Bounding box from incoming search API request.
"""
def __init__(self, xmin, ymin, xmax, ymax):
self.xmin = xmin
self.xmax = xmax
self.ymin = ymin
self.ymax = ymax
def area(self):
polygon = Polygon.from_bbox((
self.xmin, self.ymin,
self.xmax, self.ymax))
polygon.set_srid(4326)
return polygon.transform(5070, clone=True).area
|
Make sure that prompt window disappears after entering secret. | var EncryptedLocations = {
decryptAll: function(locations) {
var dfd = $.Deferred()
askForPassword().done(function(password) {
var decryptedLocations = _(locations).map(function(location) {
try {
var decrypted = JSON.parse(decrypt(location.salt, location.iv, password, location.data))
} catch(e) {
return dfd.reject()
}
return _({created: location.created}).extend(decrypted)
})
dfd.resolve(decryptedLocations)
})
return dfd
function decrypt(salt, iv, password, cipherText) {
var key = generateKey(salt, password)
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(cipherText)
})
var decrypted = CryptoJS.AES.decrypt(
cipherParams,
key,
{iv: CryptoJS.enc.Hex.parse(iv)}
)
return decrypted.toString(CryptoJS.enc.Utf8)
}
function generateKey(salt, password) {
return CryptoJS.PBKDF2(
password,
CryptoJS.enc.Hex.parse(salt),
{keySize: 128 / 32, iterations: 10000}
)
}
function askForPassword() {
var dfd = $.Deferred()
alertify.prompt("Find the car", function(ok, password) {
_.defer(function() {
ok ? dfd.resolve(password.trim()) : dfd.reject()
})
}, "enter secret");
return dfd;
}
}
}
| var EncryptedLocations = {
decryptAll: function(locations) {
var dfd = $.Deferred()
askForPassword().done(function(password) {
var decryptedLocations = _(locations).map(function(location) {
try {
var decrypted = JSON.parse(decrypt(location.salt, location.iv, password, location.data))
} catch(e) {
return dfd.reject()
}
return _({created: location.created}).extend(decrypted)
})
dfd.resolve(decryptedLocations)
})
return dfd
function decrypt(salt, iv, password, cipherText) {
var key = generateKey(salt, password)
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(cipherText)
})
var decrypted = CryptoJS.AES.decrypt(
cipherParams,
key,
{iv: CryptoJS.enc.Hex.parse(iv)}
)
return decrypted.toString(CryptoJS.enc.Utf8)
}
function generateKey(salt, password) {
return CryptoJS.PBKDF2(
password,
CryptoJS.enc.Hex.parse(salt),
{keySize: 128 / 32, iterations: 10000}
)
}
function askForPassword() {
var dfd = $.Deferred()
alertify.prompt("Find the car", function(ok, password) {
ok ? dfd.resolve(password.trim()) : dfd.reject()
}, "enter secret");
return dfd;
}
}
}
|
Fix commit_on_http_success when an exception is raised | from django.db.transaction import is_dirty, leave_transaction_management, rollback, commit, enter_transaction_management, managed
from django.db import DEFAULT_DB_ALIAS
from django.http import HttpResponse
def commit_on_http_success(func, using=None):
"""
This decorator activates db commit on HTTP success response. This way, if the
view function return a success reponse, a commit is made; if the viewfunc
produces an exception or return an error response, a rollback is made.
"""
if using is None:
using = DEFAULT_DB_ALIAS
def wrapped_func(*args, **kwargs):
enter_transaction_management(using=using)
managed(True, using=using)
try:
res = func(*args, **kwargs)
except:
if is_dirty(using=using):
rollback(using=using)
raise
else:
if is_dirty(using=using):
if not isinstance(res, HttpResponse) or res.status_code < 200 or res.status_code >= 400:
rollback(using=using)
else:
try:
commit(using=using)
except:
rollback(using=using)
raise
finally:
leave_transaction_management(using=using)
return res
return wrapped_func
| from django.db.transaction import is_dirty, leave_transaction_management, rollback, commit, enter_transaction_management, managed
from django.db import DEFAULT_DB_ALIAS
from django.http import HttpResponse
def commit_on_http_success(func, using=None):
"""
This decorator activates db commit on HTTP success response. This way, if the
view function return a success reponse, a commit is made; if the viewfunc
produces an exception or return an error response, a rollback is made.
"""
if using is None:
using = DEFAULT_DB_ALIAS
def wrapped_func(*args, **kwargs):
enter_transaction_management(using=using)
managed(True, using=using)
try:
res = func(*args, **kwargs)
except:
if is_dirty(using=using):
rollback(using=using)
raise
else:
if is_dirty(using=using):
if not isinstance(res, HttpResponse) or res.status_code < 200 or res.status_code >= 400:
rollback(using=using)
else:
try:
commit(using=using)
except:
rollback(using=using)
raise
leave_transaction_management(using=using)
return res
return wrapped_func
|
Add option to get file size | <?php
namespace Intervention\Image;
class File
{
/**
* Mime type
*
* @var string
*/
public $mime;
/**
* Name of directory path
*
* @var string
*/
public $dirname;
/**
* Basename of current file
*
* @var string
*/
public $basename;
/**
* File extension of current file
*
* @var string
*/
public $extension;
/**
* File name of current file
*
* @var string
*/
public $filename;
/**
* Sets all instance properties from given path
*
* @param string $path
*/
public function setFileInfoFromPath($path)
{
$info = pathinfo($path);
$this->dirname = array_key_exists('dirname', $info) ? $info['dirname'] : null;
$this->basename = array_key_exists('basename', $info) ? $info['basename'] : null;
$this->extension = array_key_exists('extension', $info) ? $info['extension'] : null;
$this->filename = array_key_exists('filename', $info) ? $info['filename'] : null;
if (file_exists($path) && is_file($path)) {
$this->mime = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $path);
}
return $this;
}
/**
* Get file size
*
* @return mixed
*/
public function filesize()
{
$path = $this->basePath();
if (file_exists($path) && is_file($path)) {
return filesize($path);
}
return false;
}
}
| <?php
namespace Intervention\Image;
class File
{
/**
* Mime type
*
* @var string
*/
public $mime;
/**
* Name of directory path
*
* @var string
*/
public $dirname;
/**
* Basename of current file
*
* @var string
*/
public $basename;
/**
* File extension of current file
*
* @var string
*/
public $extension;
/**
* File name of current file
*
* @var string
*/
public $filename;
/**
* Sets all instance properties from given path
*
* @param string $path
*/
public function setFileInfoFromPath($path)
{
$info = pathinfo($path);
$this->dirname = array_key_exists('dirname', $info) ? $info['dirname'] : null;
$this->basename = array_key_exists('basename', $info) ? $info['basename'] : null;
$this->extension = array_key_exists('extension', $info) ? $info['extension'] : null;
$this->filename = array_key_exists('filename', $info) ? $info['filename'] : null;
if (file_exists($path) && is_file($path)) {
$this->mime = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $path);
}
return $this;
}
}
|
Add schema comparator to diff command. | <?php
namespace LazyRecord\Command;
use Exception;
use CLIFramework\Command;
use LazyRecord\Schema;
use LazyRecord\Schema\SchemaFinder;
use LazyRecord\ConfigLoader;
class DiffCommand extends Command
{
public function brief()
{
return 'diff database schema.';
}
public function options($opts)
{
// --data-source
$opts->add('D|data-source:', 'specify data source id');
}
public function execute()
{
$options = $this->options;
$logger = $this->logger;
$loader = ConfigLoader::getInstance();
$loader->load();
$loader->initForBuild();
$connectionManager = \LazyRecord\ConnectionManager::getInstance();
$logger->info("Initialize connection manager...");
// XXX: from config files
$id = $options->{'data-source'} ?: 'default';
$conn = $connectionManager->getConnection($id);
$driver = $connectionManager->getQueryDriver($id);
$finder = new SchemaFinder;
if( $paths = $loader->getSchemaPaths() ) {
$finder->paths = $paths;
}
$finder->loadFiles();
$classes = $finder->getSchemaClasses();
// XXX: currently only mysql support
$parser = \LazyRecord\TableParser::create( $driver, $conn );
$tableSchemas = array();
$tables = $parser->getTables();
foreach( $tables as $table ) {
$tableSchemas[ $table ] = $parser->getTableSchema( $table );
}
$comparator = new \LazyRecord\Schema\Comparator;
foreach( $classes as $class ) {
$b = new $class;
$t = $b->getTable();
if( isset( $tableSchemas[ $t ] ) ) {
$a = $tableSchemas[ $t ];
$diff = $comparator->compare( $a , $b );
$printer = new \LazyRecord\Schema\Comparator\ConsolePrinter($diff);
$printer->output();
}
}
}
}
| <?php
namespace LazyRecord\Command;
use Exception;
use CLIFramework\Command;
use LazyRecord\Schema;
use LazyRecord\Schema\SchemaFinder;
use LazyRecord\ConfigLoader;
class DiffCommand extends Command
{
public function brief()
{
return 'diff database schema.';
}
public function options($opts)
{
// --data-source
$opts->add('D|data-source:', 'specify data source id');
}
public function execute()
{
$options = $this->options;
$logger = $this->logger;
$loader = ConfigLoader::getInstance();
$loader->load();
$loader->initForBuild();
$connectionManager = \LazyRecord\ConnectionManager::getInstance();
$logger->info("Initialize connection manager...");
// XXX: from config files
$id = $options->{'data-source'} ?: 'default';
$conn = $connectionManager->getConnection($id);
$driver = $connectionManager->getQueryDriver($id);
// XXX: currently only mysql support
$parser = \LazyRecord\TableParser::create( $driver, $conn );
$tableSchemas = array();
$tables = $parser->getTables();
foreach( $tables as $table ) {
$tableSchemas[ $table ] = $parser->getTableSchema( $table );
}
}
}
|
Disable contextual menu (not very useful, exposes features we don't want to expose) | YAHOO.xbl.fr.Tinymce.DefaultConfig = {
mode: "exact",
language: "en",
theme: "advanced",
skin: "thebigreason",
plugins: "spellchecker,style,table,save,iespell,preview,media,searchreplace,print,paste,visualchars,nonbreaking,xhtmlxtras,template",
theme_advanced_buttons1: "formatselect,bold,italic,|,bullist,numlist,|,outdent,indent,|,undo,redo",
theme_advanced_buttons2: "",
theme_advanced_buttons3: "",
theme_advanced_buttons4: "",
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_statusbar_location: "bottom",
theme_advanced_resizing: true,
gecko_spellcheck: true,
doctype: '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
encoding: "xml",
entity_encoding: "raw",
forced_root_block: 'div',
remove_redundant_brs: true,
verify_html: true
}; | YAHOO.xbl.fr.Tinymce.DefaultConfig = {
mode: "exact",
language: "en",
theme: "advanced",
skin: "thebigreason",
plugins: "spellchecker,style,table,save,iespell,preview,media,searchreplace,print,contextmenu,paste,visualchars,nonbreaking,xhtmlxtras,template",
theme_advanced_buttons1: "formatselect,bold,italic,|,bullist,numlist,|,outdent,indent,|,undo,redo",
theme_advanced_buttons2: "",
theme_advanced_buttons3: "",
theme_advanced_buttons4: "",
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_statusbar_location: "bottom",
theme_advanced_resizing: true,
gecko_spellcheck: true,
doctype: '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
encoding: "xml",
entity_encoding: "raw",
forced_root_block: 'div',
remove_redundant_brs: true,
verify_html: true
}; |
Adjust path one last time. | <?php
namespace League\StatsD\Laravel5\Provider;
use Illuminate\Support\ServiceProvider;
use League\StatsD\Client as Statsd;
/**
* StatsD Service provider for Laravel
*
* @author Aran Wilkinson <[email protected]>
*/
class StatsdServiceProvider extends ServiceProvider
{
/**
* Boot the service provider.
*
* @return void
*/
public function boot()
{
// Publish config files
$this->publishes([
__DIR__.'/../../../config/config.php' => config_path('statsd.php'),
]);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerStatsD();
}
/**
* Register Statsd
*
* @return void
*/
protected function registerStatsD()
{
$this->app['statsd'] = $this->app->share(
function ($app) {
// Set Default host and port
$options = array();
if (isset($app['config']['statsd.host'])) {
$options['host'] = $app['config']['statsd.host'];
}
if (isset($app['config']['statsd.port'])) {
$options['port'] = $app['config']['statsd.port'];
}
if (isset($app['config']['statsd.namespace'])) {
$options['namespace'] = $app['config']['statsd.namespace'];
}
// Create
$statsd = new Statsd();
$statsd->configure($options);
return $statsd;
}
);
}
}
| <?php
namespace League\StatsD\Laravel5\Provider;
use Illuminate\Support\ServiceProvider;
use League\StatsD\Client as Statsd;
/**
* StatsD Service provider for Laravel
*
* @author Aran Wilkinson <[email protected]>
*/
class StatsdServiceProvider extends ServiceProvider
{
/**
* Boot the service provider.
*
* @return void
*/
public function boot()
{
// Publish config files
$this->publishes([
__DIR__.'/../../../../config/config.php' => config_path('statsd.php'),
]);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerStatsD();
}
/**
* Register Statsd
*
* @return void
*/
protected function registerStatsD()
{
$this->app['statsd'] = $this->app->share(
function ($app) {
// Set Default host and port
$options = array();
if (isset($app['config']['statsd.host'])) {
$options['host'] = $app['config']['statsd.host'];
}
if (isset($app['config']['statsd.port'])) {
$options['port'] = $app['config']['statsd.port'];
}
if (isset($app['config']['statsd.namespace'])) {
$options['namespace'] = $app['config']['statsd.namespace'];
}
// Create
$statsd = new Statsd();
$statsd->configure($options);
return $statsd;
}
);
}
}
|
Allow commands to throw AbortException to fail the build | package org.jenkinsci.plugins.dockerbuildstep.cmd;
import hudson.AbortException;
import hudson.DescriptorExtensionList;
import hudson.ExtensionPoint;
import hudson.model.Describable;
import hudson.model.AbstractBuild;
import hudson.model.Descriptor;
import jenkins.model.Jenkins;
import org.jenkinsci.plugins.dockerbuildstep.DockerBuilder;
import org.jenkinsci.plugins.dockerbuildstep.log.ConsoleLogger;
import com.kpelykh.docker.client.DockerClient;
import com.kpelykh.docker.client.DockerException;
/**
* Parent class of all Docker commands.
*
* @author vjuranek
*
*/
public abstract class DockerCommand implements Describable<DockerCommand>, ExtensionPoint {
public abstract void execute(@SuppressWarnings("rawtypes") AbstractBuild build, ConsoleLogger console)
throws DockerException, AbortException;
protected static DockerClient getClient() {
return ((DockerBuilder.DescriptorImpl) Jenkins.getInstance().getDescriptor(DockerBuilder.class))
.getDockerClient();
}
public DockerCommandDescriptor getDescriptor() {
return (DockerCommandDescriptor) Jenkins.getInstance().getDescriptor(getClass());
}
public static DescriptorExtensionList<DockerCommand, DockerCommandDescriptor> all() {
return Jenkins.getInstance().<DockerCommand, DockerCommandDescriptor> getDescriptorList(DockerCommand.class);
}
public abstract static class DockerCommandDescriptor extends Descriptor<DockerCommand> {
protected DockerCommandDescriptor(Class<? extends DockerCommand> clazz) {
super(clazz);
}
protected DockerCommandDescriptor() {
}
}
}
| package org.jenkinsci.plugins.dockerbuildstep.cmd;
import hudson.DescriptorExtensionList;
import hudson.ExtensionPoint;
import hudson.model.Describable;
import hudson.model.AbstractBuild;
import hudson.model.Descriptor;
import jenkins.model.Jenkins;
import org.jenkinsci.plugins.dockerbuildstep.DockerBuilder;
import org.jenkinsci.plugins.dockerbuildstep.log.ConsoleLogger;
import com.kpelykh.docker.client.DockerClient;
import com.kpelykh.docker.client.DockerException;
/**
* Parent class of all Docker commands.
*
* @author vjuranek
*
*/
public abstract class DockerCommand implements Describable<DockerCommand>, ExtensionPoint {
public abstract void execute(@SuppressWarnings("rawtypes") AbstractBuild build, ConsoleLogger console)
throws DockerException;
protected static DockerClient getClient() {
return ((DockerBuilder.DescriptorImpl) Jenkins.getInstance().getDescriptor(DockerBuilder.class))
.getDockerClient();
}
public DockerCommandDescriptor getDescriptor() {
return (DockerCommandDescriptor) Jenkins.getInstance().getDescriptor(getClass());
}
public static DescriptorExtensionList<DockerCommand, DockerCommandDescriptor> all() {
return Jenkins.getInstance().<DockerCommand, DockerCommandDescriptor> getDescriptorList(DockerCommand.class);
}
public abstract static class DockerCommandDescriptor extends Descriptor<DockerCommand> {
protected DockerCommandDescriptor(Class<? extends DockerCommand> clazz) {
super(clazz);
}
protected DockerCommandDescriptor() {
}
}
}
|
Use context so the test file to get closed after tests | from urllib import request
from bs4 import BeautifulSoup
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
}
class AbstractScraper():
def __init__(self, url, test=False):
if test:
# when testing, we simply load a file
with url:
self.soup = BeautifulSoup(url.read(), "html.parser")
else:
self.soup = BeautifulSoup(request.urlopen(
request.Request(url, headers=HEADERS)).read(), "html.parser")
def host(self):
""" get the host of the url, so we can use the correct scraper (check __init__.py) """
raise NotImplementedError("This should be implemented.")
def publisher_site(self):
""" the original url of the publisher site """
raise NotImplementedError("This should be implemented.")
def title(self):
""" title of the recipe itself """
raise NotImplementedError("This should be implemented.")
def total_time(self):
""" total time it takes to preparate the recipe in minutes """
raise NotImplementedError("This should be implemented.")
def ingredients(self):
""" list of ingredients needed for the recipe """
raise NotImplementedError("This should be implemented.")
def instructions(self):
""" directions provided on the recipe link """
raise NotImplementedError("This should be implemented.")
def social_rating(self):
""" social rating of the recipe in 0 - 100 scale """
raise NotImplementedError("This should be implemented.")
| from urllib import request
from bs4 import BeautifulSoup
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
}
class AbstractScraper():
def __init__(self, url, test=False):
if test:
# when testing, we simply load a file
self.soup = BeautifulSoup(url.read(), "html.parser")
else:
self.soup = BeautifulSoup(request.urlopen(
request.Request(url, headers=HEADERS)).read(), "html.parser")
def host(self):
""" get the host of the url, so we can use the correct scraper (check __init__.py) """
raise NotImplementedError("This should be implemented.")
def publisher_site(self):
""" the original url of the publisher site """
raise NotImplementedError("This should be implemented.")
def title(self):
""" title of the recipe itself """
raise NotImplementedError("This should be implemented.")
def total_time(self):
""" total time it takes to preparate the recipe in minutes """
raise NotImplementedError("This should be implemented.")
def ingredients(self):
""" list of ingredients needed for the recipe """
raise NotImplementedError("This should be implemented.")
def instructions(self):
""" directions provided on the recipe link """
raise NotImplementedError("This should be implemented.")
def social_rating(self):
""" social rating of the recipe in 0 - 100 scale """
raise NotImplementedError("This should be implemented.")
|
Add customer in BOA Application. | <?php
namespace Tisseo\BoaBundle\DataFixtures\ORM;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use CanalTP\SamCoreBundle\DataFixtures\ORM\CustomerTrait;
class FixturesCustomer extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
use CustomerTrait;
/**
* @var ContainerInterface
*/
private $container;
/**
* {@inheritDoc}
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* {@inheritDoc}
*/
public function load(ObjectManager $om)
{
$navitiaToken = $this->container->getParameter('nmm.navitia.token');
$samFixturePerimeters = $this->container->getParameter('sam_fixture_perimeters');
$this->addCustomerToApplication($om, 'app-boa', 'customer-tisseo', $navitiaToken);
foreach($samFixturePerimeters as $key => $value) {
$this->addPerimeterToCustomer($om, $value['coverage'], $value['network'], 'customer-tisseo');
}
$om->flush();
}
/**
* {@inheritDoc}
*/
public function getOrder()
{
return 3;
}
}
| <?php
namespace Tisseo\BoaBundle\DataFixtures\ORM;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use CanalTP\SamCoreBundle\DataFixtures\ORM\CustomerTrait;
class FixturesCustomer extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
use CustomerTrait;
/**
* @var ContainerInterface
*/
private $container;
/**
* {@inheritDoc}
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* {@inheritDoc}
*/
public function load(ObjectManager $om)
{
$navitiaToken = $this->container->getParameter('nmm.navitia.token');
$samFixturePerimeters = $this->container->getParameter('sam_fixture_perimeters');
//$this->addCustomerToApplication($om, 'app-boa', 'customer-tisseo', $navitiaToken);
foreach($samFixturePerimeters as $key => $value) {
$this->addPerimeterToCustomer($om, $value['coverage'], $value['network'], 'customer-tisseo');
}
$om->flush();
}
/**
* {@inheritDoc}
*/
public function getOrder()
{
return 3;
}
}
|
Create static generator from Element | package com.grayben.riskExtractor.htmlScorer.partScorers;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import java.util.ArrayList;
import java.util.List;
public class TagAndAttribute {
private final Tag tag;
private final Attribute attribute;
public Tag getTag() {
return tag;
}
public Attribute getAttribute() {
return attribute;
}
public static List<TagAndAttribute> fromElement(Element element){
List<TagAndAttribute> list = new ArrayList<>();
for (Attribute attribute :
element.attributes()) {
list.add(new TagAndAttribute(element.tag(), attribute));
}
return list;
}
public TagAndAttribute(Tag tag, Attribute attribute) {
super();
if (tag == null) {
throw new NullPointerException(
"Attempted to pass in null tag:Tag"
);
}
if (attribute == null) {
throw new NullPointerException(
"Attempted to pass in null attribute:Attribute"
);
}
this.tag = tag;
this.attribute = attribute;
}
@Override
public boolean equals(Object o) {
assert getTag() != null;
assert getAttribute() != null;
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TagAndAttribute that = (TagAndAttribute) o;
if (!getTag().equals(that.getTag())) return false;
return getAttribute().equals(that.getAttribute());
}
@Override
public int hashCode() {
assert getAttribute() != null;
assert getTag() != null;
int result = getTag().hashCode();
result = 31 * result + getAttribute().hashCode();
return result;
}
}
| package com.grayben.riskExtractor.htmlScorer.partScorers;
import org.jsoup.nodes.Attribute;
import org.jsoup.parser.Tag;
public class TagAndAttribute {
private final Tag tag;
private final Attribute attribute;
public Tag getTag() {
return tag;
}
public Attribute getAttribute() {
return attribute;
}
public TagAndAttribute(Tag tag, Attribute attribute) {
super();
if (tag == null) {
throw new NullPointerException(
"Attempted to pass in null tag:Tag"
);
}
if (attribute == null) {
throw new NullPointerException(
"Attempted to pass in null attribute:Attribute"
);
}
this.tag = tag;
this.attribute = attribute;
}
@Override
public boolean equals(Object o) {
assert getTag() != null;
assert getAttribute() != null;
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TagAndAttribute that = (TagAndAttribute) o;
if (!getTag().equals(that.getTag())) return false;
return getAttribute().equals(that.getAttribute());
}
@Override
public int hashCode() {
assert getAttribute() != null;
assert getTag() != null;
int result = getTag().hashCode();
result = 31 * result + getAttribute().hashCode();
return result;
}
}
|
Align Logger component with new AppiComponent api | import intelLogger from 'intel'
import joi from 'joi'
import { validateObject } from '../../core'
/**
* Returns config data and its schema
* @param {Object} env
* @returns {SchemedData}
*/
function getConfig(env) {
/**
* Log level compatible with intel module
* Valid values: ALL, TRACE, VERBOSE, DEBUG, INFO, WARN, ERROR, CRITICAL, NONE
* @enum {string}
*/
const { LOG_LEVEL = 'INFO' } = env
return {
data: {
logLevel: LOG_LEVEL,
},
schema: {
logLevel: joi.string()
.only([ 'ALL', 'TRACE', 'VERBOSE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL', 'NONE' ])
}
}
}
/**
* Returns logger service
* @param {Object} deps Appi dependencies
* @param {Object} deps.env Env dependency
* @returns {Logger} Configured intel logger
*/
export function logger(deps) {
const config = validateObject(getConfig(deps.env))
intelLogger.setLevel(config.logLevel)
intelLogger.addHandler(new intelLogger.handlers.Console({
formatter: new intelLogger.Formatter({
format: '[%(date)s] %(name)s.%(levelname)s: %(message)s',
datefmt: '%Y-%m-%d %H:%M-%S',
colorize: true,
})
}))
return intelLogger
}
logger.componentName = 'logger'
| import intelLogger from 'intel'
import joi from 'joi'
import { validateObject } from '../../core'
/**
* Returns config data and its schema
* @param {Object} env
* @returns {SchemedData}
*/
function getConfig(env) {
/**
* Log level compatible with intel module
* Valid values: ALL, TRACE, VERBOSE, DEBUG, INFO, WARN, ERROR, CRITICAL, NONE
* @enum {string}
*/
const { LOG_LEVEL = 'INFO' } = env
return {
data: {
logLevel: LOG_LEVEL,
},
schema: {
logLevel: joi.string()
.only([ 'ALL', 'TRACE', 'VERBOSE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL', 'NONE' ])
}
}
}
/**
* Returns logger service
* @param {Object} deps Appi dependencies
* @param {Object} deps.env Env dependency
* @returns {Logger} Configured intel logger
*/
export function logger(deps) {
const config = validateObject(getConfig(deps.env))
intelLogger.setLevel(config.logLevel)
intelLogger.addHandler(new intelLogger.handlers.Console({
formatter: new intelLogger.Formatter({
format: '[%(date)s] %(name)s.%(levelname)s: %(message)s',
datefmt: '%Y-%m-%d %H:%M-%S',
colorize: true,
})
}))
return intelLogger
}
logger.isAppiComponent = true
|
Store values from array to database | <?php
$host = "localhost";
$user_name = "root";
$password = "";
$database_name = "vawhack";
$db = mysql_connect($host, $user_name, $password);
if (mysql_error() > ""){
print_r(mysql_error());
}
mysql_select_db($database_name, $db);
// $directory = "nfsshare/audiofiles/" //directory from where to read file
$directory = "C:/Users/sus/Desktop/voicemail/device/999/INBOX/";
// get all text files with a .txt extension.
$texts = glob($directory . "*.txt");
if(empty($texts)){
echo "File not present";
return;
}
foreach($texts as $filename){
$my_array = array();
$my_array['filename'] = basename($filename, ".txt");
$file = fopen($filename, 'r');
while(!feof($file)){
$current_line = trim(fgets($file));
$each_line = explode("=", $current_line);
if($each_line[0] == "callerid"){
$reg = '/<([0-9]+)>$/';
preg_match($reg, $each_line[1], $matches);
$my_array['caller_id'] = $matches[1];
}
elseif($each_line[0] == "origtime"){
$my_array['origtime'] = $each_line[1];
}
}
fclose($file);
$query = "INSERT INTO vmf(afn, callerid, calltime) values ('".$my_array['filename']."','".$my_array['caller_id']."','".$my_array['origtime']."')";
print_r($query);
$qresult = mysql_query($query);
print_r($my_array);
}
?>
| <?php
// $directory = "nfsshare/audiofiles/" //directory from where to read file
$directory = "C:/Users/sus/Desktop/voicemail/device/999/INBOX/";
// get all text files with a .txt extension.
$texts = glob($directory . "*.txt");
if(empty($texts)){
echo "File not present";
return;
}
foreach($texts as $filename){
$my_array = array();
$my_array['filename'] = basename($filename, ".txt");
$file = fopen($filename, 'r');
while(!feof($file)){
$current_line = trim(fgets($file));
$each_line = explode("=", $current_line);
if($each_line[0] == "callerid"){
$reg = '/<([0-9]+)>$/';
preg_match($reg, $each_line[1], $matches);
$my_array['caller_id'] = $matches[1];
}
elseif($each_line[0] == "origtime"){
$my_array['origtime'] = $each_line[1];
}
}
fclose($file);
print_r($my_array);
}
?>
|
Add getNodes method to fetch the list of nodes from chef. | <?php
namespace DominionEnterprises\Chef;
use Jenssegers\Chef\Chef as ChefApi;
class Chef
{
/**
* @var \Jenssegers\Chef\Chef The chef API
*/
private $_chef;
/**
* Construct the Chef Wrapper
*
* @param \Jenssegers\Chef\Chef $chef The chef API
*/
public function __construct(ChefApi $chef)
{
$this->_chef = $chef;
}
/**
* Updates the data bag item overwriting existing fields with the data provided.
*
* @param string $name The name of the data bag.
* @param string $item The name of the item in the data bag.
* @param array $data Fields to update in the data bag with their data.
*
* @return void
*/
public function patchDatabag($name, $item, array $data)
{
$itemUrl = '/data/' . rawurlencode($name) . '/' . rawurlencode($item);
$data += (array)$this->_chef->get($itemUrl);
$this->_chef->put($itemUrl, $data);
}
/**
* Gets the list of nodes.
*
* @return array The names of the nodes registered in chef.
*/
public function getNodes()
{
return array_keys((array)$this->_chef->get('/nodes'));
}
/**
* Delete the given node.
*
* @param string $node The name of the node to delete.
*
* @return void
*/
public function deleteNode($node)
{
$this->_chef->delete('/nodes/' . rawurlencode($node));
}
}
| <?php
namespace DominionEnterprises\Chef;
use Jenssegers\Chef\Chef as ChefApi;
class Chef
{
/**
* @var \Jenssegers\Chef\Chef The chef API
*/
private $_chef;
/**
* Construct the Chef Wrapper
*
* @param \Jenssegers\Chef\Chef $chef The chef API
*/
public function __construct(ChefApi $chef)
{
$this->_chef = $chef;
}
/**
* Updates the data bag item overwriting existing fields with the data provided.
*
* @param string $name The name of the data bag.
* @param string $item The name of the item in the data bag.
* @param array $data Fields to update in the data bag with their data.
*
* @return void
*/
public function patchDatabag($name, $item, array $data)
{
$itemUrl = '/data/' . rawurlencode($name) . '/' . rawurlencode($item);
$data += (array)$this->_chef->get($itemUrl);
$this->_chef->put($itemUrl, $data);
}
/**
* Delete the given node.
*
* @param string $node The name of the node to delete.
*
* @return void
*/
public function deleteNode($node)
{
$this->_chef->delete('/nodes/' . rawurlencode($node));
}
}
|
Fix import location of environment variables | #-*- coding: utf-8 -*-
import os
if os.path.exists('.env'):
print('Importing environment from .env...')
for line in open('.env'):
var = line.strip().split('=')
if len(var) == 2:
os.environ[var[0]] = var[1]
from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass
from db_create import (
init_db,
drop_db,
init_admin_user,
init_entry,
init_category,
init_tag
)
from flask.ext.migrate import MigrateCommand
from logpot.app import app
manager = Manager(app)
manager.add_command('db', MigrateCommand)
@manager.command
def run():
app.run(threaded=True)
@manager.command
def initialize():
if prompt_bool("Are you sure you want to create DB and initialize?"):
drop_db()
init_db()
if init_admin():
init_category()
init_tag()
init_entry()
print('Success!')
@manager.command
def init_admin():
name = prompt('Resister admin user.\n[?] input username: ')
email = prompt('[?] input email: ')
password = prompt_pass('[?] input password: ')
confirm_password = prompt_pass('[?] input password again: ')
if not password == confirm_password:
print('Password does not match.')
return False
else:
init_admin_user(name, email, password)
return True
if __name__ == "__main__":
manager.run()
| #-*- coding: utf-8 -*-
from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass
from db_create import (
init_db,
drop_db,
init_admin_user,
init_entry,
init_category,
init_tag
)
from flask.ext.migrate import MigrateCommand
from logpot.app import app
import os
if os.path.exists('.env'):
print('Importing environment from .env...')
for line in open('.env'):
var = line.strip().split('=')
if len(var) == 2:
os.environ[var[0]] = var[1]
manager = Manager(app)
manager.add_command('db', MigrateCommand)
@manager.command
def run():
app.run(threaded=True)
@manager.command
def initialize():
if prompt_bool("Are you sure you want to create DB and initialize?"):
drop_db()
init_db()
if init_admin():
init_category()
init_tag()
init_entry()
print('Success!')
@manager.command
def init_admin():
name = prompt('Resister admin user.\n[?] input username: ')
email = prompt('[?] input email: ')
password = prompt_pass('[?] input password: ')
confirm_password = prompt_pass('[?] input password again: ')
if not password == confirm_password:
print('Password does not match.')
return False
else:
init_admin_user(name, email, password)
return True
if __name__ == "__main__":
manager.run()
|
Modify videoloop to allow for audio | #!/usr/bin/env python3
import logging
import re
from gi.repository import Gst
from lib.config import Config
from lib.sources.avsource import AVSource
class VideoLoopSource(AVSource):
timer_resolution = 0.5
def __init__(self, name, has_audio=True, has_video=True,
force_num_streams=None):
super().__init__('VideoLoopSource', name, has_audio, has_video, show_no_signal=True)
self.location = Config.getLocation(name)
self.build_pipeline()
def __str__(self):
return 'VideoLoopSource[{name}] displaying {location}'.format(
name=self.name,
location=self.location
)
def port(self):
m = re.search('.*/([^/]*)', self.location)
return self.location
def num_connections(self):
return 1
def video_channels(self):
return 1
def build_source(self):
return """
multifilesrc
location={location}
loop=true
! decodebin
name=videoloop-{name}
""".format(
name=self.name,
location=self.location
)
def build_videoport(self):
return """
videoloop-{name}.
! videoconvert
! videoscale
""".format(name=self.name)
def build_audioport(self):
return """
videoloop-{name}.
! audioconvert
! audioresample
""".format(name=self.name) | #!/usr/bin/env python3
import logging
import re
from gi.repository import Gst
from lib.config import Config
from lib.sources.avsource import AVSource
class VideoLoopSource(AVSource):
def __init__(self, name):
super().__init__('VideoLoopSource', name, False, True)
self.location = Config.getLocation(name)
self.build_pipeline()
def __str__(self):
return 'VideoLoopSource[{name}] displaying {location}'.format(
name=self.name,
location=self.location
)
def port(self):
m = re.search('.*/([^/]*)', self.location)
return self.location
def num_connections(self):
return 1
def video_channels(self):
return 1
def build_source(self):
return """
multifilesrc
name=videoloop-{name}
location={location}
loop=true
! decodebin
! videoconvert
! videoscale
name=videoloop
""".format(
name=self.name,
location=self.location
)
def build_videoport(self):
return 'videoloop.'
def build_audioport(self, audiostream):
return 'audioloop.'
|
Enable send button when user enters text. | import React from 'react/addons';
export class ChatForm extends React.Component {
static propTypes = {
onSend: React.PropTypes.func.isRequired
}
constructor(props) {
super(props);
this.state = {text: ''};
}
handleSubmit = (e) => {
this.props.onSend(this.state.text);
this.setState({text: ''});
let input = React.findDOMNode(this.refs.message);
input.focus();
e.preventDefault();
}
handleChange = (e) => {
this.setState({text: e.target.value});
}
render() {
return <div className="row">
<div className="col-lg-4">
<form onSubmit={this.handleSubmit}>
<div className="input-group">
<input
type="text"
className="form-control"
ref="message"
onChange={this.handleChange}
value={this.state.text}
autoFocus />
<span className="input-group-btn">
<button className="btn btn-primary" disabled={this.state.text.length === 0}>Send!</button>
</span>
</div>
</form>
</div>
</div>;
}
}
| import React from 'react/addons';
export class ChatForm extends React.Component {
static propTypes = {
onSend: React.PropTypes.func.isRequired
}
constructor(props) {
super(props);
this.state = {text: ''};
}
handleSubmit = (e) => {
this.props.onSend(this.state.text);
this.setState({text: ''});
let input = React.findDOMNode(this.refs.message);
input.focus();
e.preventDefault();
}
handleChange = (e) => {
this.setState({text: e.target.value});
}
render() {
return <div className="row">
<div className="col-lg-4">
<form onSubmit={this.handleSubmit}>
<div className="input-group">
<input
type="text"
className="form-control"
ref="message"
onChange={this.handleChange}
value={this.state.text}
autoFocus />
<span className="input-group-btn">
<button className="btn btn-primary">Send!</button>
</span>
</div>
</form>
</div>
</div>;
}
}
|
Add system status to /status endpoint | <?php
/*
* This file is part of Cachet.
*
* (c) Alt Three Services Limited
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CachetHQ\Cachet\Http\Controllers\Api;
use CachetHQ\Cachet\Integrations\Contracts\Releases;
use CachetHQ\Cachet\Integrations\Contracts\System;
/**
* This is the general api controller.
*
* @author James Brooks <[email protected]>
*/
class GeneralController extends AbstractApiController
{
/**
* Ping endpoint allows API consumers to check the version.
*
* @return \Illuminate\Http\JsonResponse
*/
public function ping()
{
return $this->item('Pong!');
}
/**
* Endpoint to show the Cachet version.
*
* @return \Illuminate\Http\JsonResponse
*/
public function version()
{
$latest = app()->make(Releases::class)->latest();
return $this->setMetaData([
'on_latest' => version_compare(CACHET_VERSION, $latest['tag_name']) === 1,
'latest' => $latest,
])->item(CACHET_VERSION);
}
/**
* Get the system status message.
*
* @return \Illuminate\Http\JsonResponse
*/
public function status()
{
$system = app()->make(System::class)->getStatus();
return $this->item([
'status' => $system['system_status'],
'message' => $system['system_message']
]);
}
}
| <?php
/*
* This file is part of Cachet.
*
* (c) Alt Three Services Limited
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CachetHQ\Cachet\Http\Controllers\Api;
use CachetHQ\Cachet\Integrations\Contracts\Releases;
use CachetHQ\Cachet\Integrations\Contracts\System;
/**
* This is the general api controller.
*
* @author James Brooks <[email protected]>
*/
class GeneralController extends AbstractApiController
{
/**
* Ping endpoint allows API consumers to check the version.
*
* @return \Illuminate\Http\JsonResponse
*/
public function ping()
{
return $this->item('Pong!');
}
/**
* Endpoint to show the Cachet version.
*
* @return \Illuminate\Http\JsonResponse
*/
public function version()
{
$latest = app()->make(Releases::class)->latest();
return $this->setMetaData([
'on_latest' => version_compare(CACHET_VERSION, $latest['tag_name']) === 1,
'latest' => $latest,
])->item(CACHET_VERSION);
}
/**
* Get the system status message.
*
* @return \Illuminate\Http\JsonResponse
*/
public function status()
{
$system = app()->make(System::class)->getStatus();
return $this->item($system['system_message']);
}
}
|
Rename appContextModule variable to appModule. | /*
* Copyright (C) 2017 Yaroslav Mytkalyk
*
* 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.doctoror.fuckoffmusicplayer.di;
import android.content.Context;
import android.support.annotation.NonNull;
/**
* Dagger2 {@link MainComponent} holder
*/
public final class DaggerHolder {
private static volatile DaggerHolder instance;
@NonNull
public static DaggerHolder getInstance(@NonNull final Context context) {
if (instance == null) {
synchronized (DaggerHolder.class) {
if (instance == null) {
instance = new DaggerHolder(context.getApplicationContext());
}
}
}
return instance;
}
@NonNull
private final MainComponent mainComponent;
private DaggerHolder(@NonNull final Context context) {
final AppModule appModule = new AppModule(context);
mainComponent = DaggerMainComponent.builder()
.appModule(appModule)
.build();
}
@NonNull
public MainComponent mainComponent() {
return mainComponent;
}
}
| /*
* Copyright (C) 2017 Yaroslav Mytkalyk
*
* 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.doctoror.fuckoffmusicplayer.di;
import android.content.Context;
import android.support.annotation.NonNull;
/**
* Dagger2 {@link MainComponent} holder
*/
public final class DaggerHolder {
private static volatile DaggerHolder instance;
@NonNull
public static DaggerHolder getInstance(@NonNull final Context context) {
if (instance == null) {
synchronized (DaggerHolder.class) {
if (instance == null) {
instance = new DaggerHolder(context.getApplicationContext());
}
}
}
return instance;
}
@NonNull
private final MainComponent mainComponent;
private DaggerHolder(@NonNull final Context context) {
final AppModule appContextModule = new AppModule(context);
mainComponent = DaggerMainComponent.builder()
.appContextModule(appContextModule)
.build();
}
@NonNull
public MainComponent mainComponent() {
return mainComponent;
}
}
|
Call start() in file:/// test if not file:/// | Batman.ready(function() {
module('Batman.Request');
test('creation', function() {
var request = Batman.Request({url: 'stubs.js'});
ok(request.isRequest, 'request is request');
equal(request.url(), 'stubs.js', 'url is set');
equal(request.method(), 'get', 'default method is get');
request.cancel();
});
test('creation with url passing', function() {
var request = Batman.Request('stubs.js', 'post');
equal(request.url(), 'stubs.js');
equal(request.method(), 'post');
request.cancel();
});
asyncTest('events', function() {
var request = Batman.Request({url: 'stubs/stubs.js'})
.success(function(){
ok(true, 'request was successful');
}).error(function() {
ok(true, 'request failed');
}).complete(function() {
start();
});
expect(1);
});
asyncTest('file:/// to http://', function() {
if (window.location.protocol !== 'file:') {
ok(true, 'not running from file:///');
start();
return;
}
Batman.Request('http://google.com').success(function() {
ok(true, 'request was successful');
start();
});
expect(1);
});
});
| Batman.ready(function() {
module('Batman.Request');
test('creation', function() {
var request = Batman.Request({url: 'stubs.js'});
ok(request.isRequest, 'request is request');
equal(request.url(), 'stubs.js', 'url is set');
equal(request.method(), 'get', 'default method is get');
request.cancel();
});
test('creation with url passing', function() {
var request = Batman.Request('stubs.js', 'post');
equal(request.url(), 'stubs.js');
equal(request.method(), 'post');
request.cancel();
});
asyncTest('events', function() {
var request = Batman.Request({url: 'stubs/stubs.js'})
.success(function(){
ok(true, 'request was successful');
}).error(function() {
ok(true, 'request failed');
}).complete(function() {
start();
});
expect(1);
});
asyncTest('file:/// to http://', function() {
if (window.location.protocol !== 'file:')
return;
Batman.Request('http://google.com').success(function() {
ok(true, 'request was successful');
start();
});
expect(1);
});
});
|
Use new logging facilites in Lambda code updater | "use strict";
const AWS = require('aws-sdk');
const fs = require('fs');
const Promise = require('bluebird');
//
// Step that loops over Lambdas and updates their respective functions' code
//
module.exports = function(context) {
const Lambda = new AWS.Lambda();
return context.logger.task('Updating Lambda code', function(resolve, reject) {
return Promise.mapSeries(context.lambdas, function(lambda) {
return context.logger.task(lambda.name, function(res, rej) {
fs.readFile(lambda.zip, function(err, data) {
if (err) {
return rej(err);
}
Lambda.updateFunctionCode({
FunctionName: lambda.name,
Publish: !!lambda.publish,
ZipFile: data
}, function(innerErr, innerData) {
if (innerErr) {
return rej(innerErr);
}
res(innerData);
});
});
});
}).then(resolve, reject);
}).then(function() {
return context;
});
};
| "use strict";
require('colors');
const AWS = require('aws-sdk');
const fs = require('fs');
const Promise = require('bluebird');
//
// Step that loops over Lambdas and updates their respective functions' code
//
module.exports = function(context) {
const Lambda = new AWS.Lambda();
return new Promise(function(resolve) {
console.log('\nUpdating Lambda code');
resolve(context);
}).then(function() {
return Promise.mapSeries(context.lambdas, function(lambda) {
return new Promise(function(resolve, reject) {
process.stdout.write(`\tUploading code for ${lambda.name}`);
fs.readFile(lambda.zip, function(err, data) {
if (err) {
console.log(' ✖'.red);
return reject(err);
}
Lambda.updateFunctionCode({
FunctionName: lambda.name,
Publish: !!lambda.publish,
ZipFile: data
}, function(innerErr, innerData) {
if (innerErr) {
console.log(' ✖'.red);
return reject(innerErr);
}
console.log(' ✔'.green);
resolve(innerData);
});
});
});
});
}).then(function() {
return context;
});
};
|
Fix Edit Trigger bug flowing from creating a zone | 'use strict';
yeomanApp.controller('EditZoneCtrl'
, ['$scope', '$rootScope', 'UIEvents', 'ZoneFactory', 'ZoneService', 'EditZoneService', 'EditTriggerService', 'TriggerFactory'
, function($scope, $rootScope, UIEvents, ZoneFactory, ZoneService, EditZoneService, EditTriggerService, TriggerFactory) {
$scope.Zone = EditZoneService.Zone;
/**
* Saves the zone to the backend
*/
$scope.Save = function() {
// Detect if this is a new Zone
if ($scope.Zone.id) {
// Existing Zone;
$scope.Zone.Save();
$scope.setRoute('/');
} else {
$scope.Zone.Save(function() {
EditZoneService.Zone = $scope.Zone;
$scope.AddNewTrigger();
});
}
};
/**
* Deletes this zone
*/
$scope.Delete = function() {
$scope.Zone.Delete();
$scope.setRoute('/');
};
/**
* Add a new trigger to the zone
*/
$scope.AddNewTrigger = function() {
var newTrigger = new TriggerFactory({
zone: $scope.Zone,
name: 'My Trigger',
type: 'PIR'
});
EditTriggerService.Trigger = newTrigger;
$scope.setRoute('/configureTrigger');
};
/**
* Edits the specified trigger
* Redirect user to /configureTrigger
* @param {Trigger} trigger Trigger to edit
*/
$scope.EditTrigger = function(trigger) {
EditTriggerService.Trigger = trigger;
$scope.setRoute('/configureTrigger');
};
}]);
| 'use strict';
yeomanApp.controller('EditZoneCtrl'
, ['$scope', '$rootScope', 'UIEvents', 'ZoneFactory', 'ZoneService', 'EditZoneService', 'EditTriggerService', 'TriggerFactory'
, function($scope, $rootScope, UIEvents, ZoneFactory, ZoneService, EditZoneService, EditTriggerService, TriggerFactory) {
$scope.Zone = EditZoneService.Zone;
/**
* Saves the zone to the backend
*/
$scope.Save = function() {
// Detect if this is a new Zone
if ($scope.Zone.id) {
// Existing Zone;
$scope.Zone.Save();
$scope.setRoute('/');
} else {
$scope.Zone.Save();
$scope.AddNewTrigger();
}
};
/**
* Deletes this zone
*/
$scope.Delete = function() {
$scope.Zone.Delete();
$scope.setRoute('/');
};
/**
* Add a new trigger to the zone
*/
$scope.AddNewTrigger = function() {
var newTrigger = new TriggerFactory({
zone: $scope.Zone,
name: 'My Trigger',
type: 'PIR'
});
EditTriggerService.Trigger = newTrigger;
$scope.setRoute('/configureTrigger');
};
/**
* Edits the specified trigger
* Redirect user to /configureTrigger
* @param {Trigger} trigger Trigger to edit
*/
$scope.EditTrigger = function(trigger) {
EditTriggerService.Trigger = trigger;
$scope.setRoute('/configureTrigger');
};
}]);
|
Set name_scope of entire network to the dataset it handles | import tensorflow as tf
import numpy as np
import itertools as it
import importlib
from flowfairy.conf import settings
from flowfairy.utils import take
from flowfairy import data
from flowfairy.feature import FeatureManager
from flowfairy.core.queue import FlowQueue
from flowfairy.core.stage import stage
def load_net():
net = importlib.import_module(settings.NET).Net()
return net
def run(*args, **options):
coord = tf.train.Coordinator()
net = load_net()
queues = []
for data_loader in data.provider:
with tf.variable_scope(data_loader.name) as scope:
fts = FeatureManager(data_loader)
queue = FlowQueue(fts, coord)
queues.append(queue)
X = queue.dequeue()
func = getattr(net, data_loader.name)
func(**dict(zip(fts.fields, X)))
scope.reuse_variables()
with tf.Session() as sess:
stage.before(sess, net)
for queue in queues: queue.start(sess)
sess.run(tf.global_variables_initializer())
try:
step = 1
while not coord.should_stop() and not net.should_stop():
stage.run(sess, step)
step += 1
except KeyboardInterrupt:
pass
coord.request_stop()
queue.stop()
coord.join(stop_grace_period_secs=5)
| import tensorflow as tf
import numpy as np
import itertools as it
import importlib
from flowfairy.conf import settings
from flowfairy.utils import take
from flowfairy import data
from flowfairy.feature import FeatureManager
from flowfairy.core.queue import FlowQueue
from flowfairy.core.stage import stage
def load_net():
net = importlib.import_module(settings.NET).Net()
return net
def run(*args, **options):
coord = tf.train.Coordinator()
net = load_net()
queues = []
with tf.variable_scope('network') as scope:
for data_loader in data.provider:
fts = FeatureManager(data_loader)
queue = FlowQueue(fts, coord)
queues.append(queue)
X = queue.dequeue()
func = getattr(net, data_loader.name)
func(**dict(zip(fts.fields, X)))
scope.reuse_variables()
with tf.Session() as sess:
stage.before(sess, net)
for queue in queues: queue.start(sess)
sess.run(tf.global_variables_initializer())
try:
step = 1
while not coord.should_stop() and not net.should_stop():
stage.run(sess, step)
step += 1
except KeyboardInterrupt:
pass
coord.request_stop()
queue.stop()
coord.join(stop_grace_period_secs=5)
|
Update favorite preset button state automatically | import {
event as d3_event,
select as d3_select
} from 'd3-selection';
import { t } from '../util/locale';
import { svgIcon } from '../svg';
export function uiPresetFavorite(preset, geom, context, klass) {
var presetFavorite = {};
var _button = d3_select(null);
presetFavorite.button = function(selection) {
var canFavorite = geom !== 'relation';
_button = selection.selectAll('.preset-favorite-button')
.data(canFavorite ? [0] : []);
_button.exit().remove();
_button = _button.enter()
.insert('button', '.tag-reference-button')
.attr('class', 'preset-favorite-button ' + klass)
.attr('title', t('icons.favorite'))
.attr('tabindex', -1)
.call(svgIcon('#iD-icon-favorite'))
.merge(_button);
_button
.on('click', function () {
d3_event.stopPropagation();
d3_event.preventDefault();
context.favoritePreset(preset, geom);
update();
});
update();
};
function update() {
_button
.classed('active', context.isFavoritePreset(preset, geom));
}
context.on('favoritePreset.button-' + preset.id.replace(/[^a-zA-Z\d:]/g, '-') + '-' + geom, update);
return presetFavorite;
}
| import {
event as d3_event,
select as d3_select
} from 'd3-selection';
import { t } from '../util/locale';
import { svgIcon } from '../svg';
export function uiPresetFavorite(preset, geom, context, klass) {
var presetFavorite = {};
var _button = d3_select(null);
presetFavorite.button = function(selection) {
var canFavorite = geom !== 'relation';
_button = selection.selectAll('.preset-favorite-button')
.data(canFavorite ? [0] : []);
_button.exit().remove();
_button = _button.enter()
.insert('button', '.tag-reference-button')
.attr('class', 'preset-favorite-button ' + klass)
.attr('title', t('icons.favorite'))
.attr('tabindex', -1)
.call(svgIcon('#iD-icon-favorite'))
.merge(_button);
_button
.classed('active', function() {
return context.isFavoritePreset(preset, geom);
})
.on('click', function () {
d3_event.stopPropagation();
d3_event.preventDefault();
//update state of favorite icon
d3_select(this)
.classed('active', function() {
return !d3_select(this).classed('active');
});
context.favoritePreset(preset, geom);
});
};
return presetFavorite;
}
|
Fix menu close btn position | import * as React from 'react'
import { Link } from 'gatsby'
import { Container } from './Container'
import { CloseIcon } from './icons/Close'
export const Menu = ({ showMenu, onClick }) => {
return (
<div
className={`${
showMenu ? 'fixed' : 'hidden'
} inset-0 z-40 h-full bg-black w-full bg-opacity-25`}
>
<div className="h-full px-5 mx-auto mr-32 antialiased bg-white sm:px-8 md:px-12 lg:px-0">
<Container className="flex flex-col space-y-4">
<Link
to="/articles"
className="font-bold text-gray-500 text-normal hover:underline"
>
Articles
</Link>
<Link
to="/projects"
className="font-bold text-gray-500 text-normal hover:underline"
>
Projects
</Link>
</Container>
</div>
<div className="absolute bottom-0 right-0 p-4 m-6 text-white bg-black rounded-full">
<CloseIcon
className="w-6 h-6"
onClick={() => onClick((prevState) => !prevState)}
/>
</div>
</div>
)
}
| import * as React from 'react'
import { Link } from 'gatsby'
import { Container } from './Container'
import { CloseIcon } from './icons/Close'
export const Menu = ({ showMenu, onClick }) => {
return (
<div
className={`${
showMenu ? 'fixed' : 'hidden'
} inset-0 z-40 h-screen bg-black w-full bg-opacity-25`}
>
<div className="h-full px-5 mx-auto mr-32 antialiased bg-white sm:px-8 md:px-12 lg:px-0">
<Container className="flex flex-col space-y-4">
<Link
to="/articles"
className="font-bold text-gray-500 text-normal hover:underline"
>
Articles
</Link>
<Link
to="/projects"
className="font-bold text-gray-500 text-normal hover:underline"
>
Projects
</Link>
</Container>
</div>
<div className="absolute bottom-0 right-0 p-4 m-6 text-white bg-black rounded-full">
<CloseIcon
className="w-6 h-6"
onClick={() => onClick((prevState) => !prevState)}
/>
</div>
</div>
)
}
|
Delete ZnZendFlashMessages view helper - ZF2 has own helper now | <?php
return array(
'controller_plugins' => array(
'invokables' => array(
'znZendDataTables' => 'ZnZend\Mvc\Controller\Plugin\ZnZendDataTables',
'znZendMvcParams' => 'ZnZend\Mvc\Controller\Plugin\ZnZendMvcParams',
'znZendPageStore' => 'ZnZend\Mvc\Controller\Plugin\ZnZendPageStore',
'znZendTimestamp' => 'ZnZend\Mvc\Controller\Plugin\ZnZendTimestamp',
),
),
'view_helpers' => array(
'invokables' => array(
'znZendColumnizeEntities' => 'ZnZend\View\Helper\ZnZendColumnizeEntities',
'znZendExcerpt' => 'ZnZend\View\Helper\ZnZendExcerpt',
'znZendFormatBytes' => 'ZnZend\View\Helper\ZnZendFormatBytes',
'znZendFormatDateRange' => 'ZnZend\View\Helper\ZnZendFormatDateRange',
'znZendFormatTimeRange' => 'ZnZend\View\Helper\ZnZendFormatTimeRange',
'znZendResizeImage' => 'ZnZend\View\Helper\ZnZendResizeImage',
// Form view helpers
'znZendFormElementValue' => 'ZnZend\Form\View\Helper\ZnZendFormElementValue',
'znZendFormCaptchaQuestion' => 'ZnZend\Form\View\Helper\Captcha\Question',
),
),
'view_manager' => array(
'strategies' => array(
'ViewJsonStrategy', // required for returning of JsonModel to work
),
),
);
| <?php
return array(
'controller_plugins' => array(
'invokables' => array(
'znZendDataTables' => 'ZnZend\Mvc\Controller\Plugin\ZnZendDataTables',
'znZendMvcParams' => 'ZnZend\Mvc\Controller\Plugin\ZnZendMvcParams',
'znZendPageStore' => 'ZnZend\Mvc\Controller\Plugin\ZnZendPageStore',
'znZendTimestamp' => 'ZnZend\Mvc\Controller\Plugin\ZnZendTimestamp',
),
),
'view_helpers' => array(
'invokables' => array(
'znZendColumnizeEntities' => 'ZnZend\View\Helper\ZnZendColumnizeEntities',
'znZendExcerpt' => 'ZnZend\View\Helper\ZnZendExcerpt',
'znZendFlashMessages' => 'ZnZend\View\Helper\ZnZendFlashMessages',
'znZendFormatBytes' => 'ZnZend\View\Helper\ZnZendFormatBytes',
'znZendFormatDateRange' => 'ZnZend\View\Helper\ZnZendFormatDateRange',
'znZendFormatTimeRange' => 'ZnZend\View\Helper\ZnZendFormatTimeRange',
'znZendResizeImage' => 'ZnZend\View\Helper\ZnZendResizeImage',
// Form view helpers
'znZendFormElementValue' => 'ZnZend\Form\View\Helper\ZnZendFormElementValue',
'znZendFormCaptchaQuestion' => 'ZnZend\Form\View\Helper\Captcha\Question',
),
),
'view_manager' => array(
'strategies' => array(
'ViewJsonStrategy', // required for returning of JsonModel to work
),
),
);
|
Add notifications to retsult of api /login method | <?php
class AuthController extends BaseController {
public function login()
{
$remember = Input::get('remember') == 'true' ? true : false;
if (Auth::attempt(['shadow_name' => Str::lower(Input::get('username')),
'password' => Input::get('password'), 'is_activated' => true], $remember))
{
if (Auth::user()->removed_at || Auth::user()->blocked_at)
{
Auth::logout();
return Response::json(['error' => 'Account blocked or removed'], 400);
}
$folders = Auth::user()->folders->toArray();
foreach ($folders as &$folder)
{
$folder['groups'] = Group::whereIn('_id', $folder['groups'])->get()->toArray();
}
$notifications = Notification::with(['sourceUser' => function($q) { $q->select('avatar')->remember(3); }])
->target(['user_id' => Auth::id()])
->orderBy('created_at', 'desc')
->take(15)->get();
$data['user'] = array_merge(Auth::user()->toArray(), [
'subscribed_groups' => Group::whereIn('_id', Auth::user()->subscribedGroups())->get()->toArray(),
'blocked_groups' => Group::whereIn('_id', Auth::user()->blockedGroups())->get()->toArray(),
'moderated_groups' => Group::whereIn('_id', Auth::user()->moderatedGroups())->get()->toArray(),
'folders' => $folders,
'notifications' => $notifications,
]);
return Response::json($data);
}
return Response::json(['error' => 'Invalid login or password'], 400);
}
public function logout()
{
Auth::logout();
}
}
| <?php
class AuthController extends BaseController {
public function login()
{
$remember = Input::get('remember') == 'true' ? true : false;
if (Auth::attempt(['shadow_name' => Str::lower(Input::get('username')),
'password' => Input::get('password'), 'is_activated' => true], $remember))
{
if (Auth::user()->removed_at || Auth::user()->blocked_at)
{
Auth::logout();
return Response::json(['error' => 'Account blocked or removed'], 400);
}
$folders = Auth::user()->folders->toArray();
foreach ($folders as &$folder)
{
$folder['groups'] = Group::whereIn('_id', $folder['groups'])->get()->toArray();
}
$data['user'] = array_merge(Auth::user()->toArray(), [
'subscribed_groups' => Group::whereIn('_id', Auth::user()->subscribedGroups())->get()->toArray(),
'blocked_groups' => Group::whereIn('_id', Auth::user()->blockedGroups())->get()->toArray(),
'moderated_groups' => Group::whereIn('_id', Auth::user()->moderatedGroups())->get()->toArray(),
'folders' => $folders,
]);
return Response::json($data);
}
return Response::json(['error' => 'Invalid login or password'], 400);
}
public function logout()
{
Auth::logout();
}
}
|
Use the error returned from the response type | <?php
namespace League\OAuth2\Server\Middleware;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Server;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class ResourceServerMiddleware
{
/**
* @var \League\OAuth2\Server\Server
*/
private $server;
/**
* ResourceServerMiddleware constructor.
*
* @param \League\OAuth2\Server\Server $server
*/
public function __construct(Server $server)
{
$this->server = $server;
}
/**
* @param \Psr\Http\Message\ServerRequestInterface $request
* @param \Psr\Http\Message\ResponseInterface $response
* @param callable $next
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
{
if ($request->hasHeader('authorization') === false) {
$exception = OAuthServerException::accessDenied('Missing authorization header');
return $exception->generateHttpResponse($response);
}
$request = $this->server->getResponseType()->determineAccessTokenInHeader($request);
if ($request->getAttribute('oauth_access_token') === null) {
$exception = OAuthServerException::accessDenied($request->getAttribute('oauth_access_token_error'));
return $exception->generateHttpResponse($response);
}
// Pass the request and response on to the next responder in the chain
return $next($request, $response);
}
}
| <?php
namespace League\OAuth2\Server\Middleware;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Server;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class ResourceServerMiddleware
{
/**
* @var \League\OAuth2\Server\Server
*/
private $server;
/**
* ResourceServerMiddleware constructor.
*
* @param \League\OAuth2\Server\Server $server
*/
public function __construct(Server $server)
{
$this->server = $server;
}
/**
* @param \Psr\Http\Message\ServerRequestInterface $request
* @param \Psr\Http\Message\ResponseInterface $response
* @param callable $next
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
{
if ($request->hasHeader('authorization') === false) {
$exception = OAuthServerException::accessDenied('Missing authorization header');
return $exception->generateHttpResponse($response);
}
$request = $this->server->getResponseType()->determineAccessTokenInHeader($request);
if ($request->getAttribute('oauth_access_token') === null) {
$exception = OAuthServerException::accessDenied('Access token was invalid');
return $exception->generateHttpResponse($response);
}
// Pass the request and response on to the next responder in the chain
return $next($request, $response);
}
}
|
Remove listeners object from broadcaster if topic is empty | package com.clinicpatientqueueexample.messaging;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
public abstract class AbstractBroadcaster {
private final ConcurrentMap<String, ConcurrentLinkedQueue<Consumer<String>>> listeners = new ConcurrentHashMap<>();
private final ExecutorService executorService = Executors.newSingleThreadExecutor();
public void register(String topic, Consumer<String> listener) {
ConcurrentLinkedQueue<Consumer<String>> topicListeners = listeners.putIfAbsent(topic, new ConcurrentLinkedQueue<>());
if (topicListeners == null) {
topicListeners = listeners.get(topic);
}
topicListeners.add(listener);
}
public void unregister(String topic, Consumer<String> listener) {
final ConcurrentLinkedQueue<Consumer<String>> topicListeners = listeners.get(topic);
if (topicListeners == null) {
return;
}
topicListeners.remove(listener);
if (topicListeners.isEmpty()) {
listeners.remove(topic);
}
}
public void broadcast(String topic, String message) {
final ConcurrentLinkedQueue<Consumer<String>> topicListeners = listeners.get(topic);
if (topicListeners != null) {
for (final Consumer<String> listener : topicListeners) {
executorService.execute(() -> listener.accept(message));
}
}
}
}
| package com.clinicpatientqueueexample.messaging;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
public abstract class AbstractBroadcaster {
private final ConcurrentMap<String, ConcurrentLinkedQueue<Consumer<String>>> listeners = new ConcurrentHashMap<>();
private final ExecutorService executorService = Executors.newSingleThreadExecutor();
public void register(String topic, Consumer<String> listener) {
ConcurrentLinkedQueue<Consumer<String>> topicListeners = listeners.putIfAbsent(topic, new ConcurrentLinkedQueue<>());
if (topicListeners == null) {
topicListeners = listeners.get(topic);
}
topicListeners.add(listener);
}
public void unregister(String topic, Consumer<String> listener) {
final ConcurrentLinkedQueue<Consumer<String>> topicListeners = listeners.get(topic);
if (topicListeners != null) {
topicListeners.remove(listener);
}
}
public void broadcast(String topic, String message) {
final ConcurrentLinkedQueue<Consumer<String>> topicListeners = listeners.get(topic);
if (topicListeners != null) {
for (final Consumer<String> listener : topicListeners) {
executorService.execute(() -> listener.accept(message));
}
}
}
}
|
Add option 'response' to render | <?php
namespace Spark\Controller;
use Silex\Application;
use Symfony\Component\HttpFoundation\Response;
use Spark\Core\ApplicationAware;
abstract class Base implements ApplicationAware
{
use ActionHelper\Filters;
use ActionHelper\Redirect;
use ActionHelper\Layout;
protected $application;
protected $response;
protected $flash;
function __construct()
{
$this->response = new Response;
$this->setup();
}
function setup()
{}
function render($options = [])
{
$attributes = $this->request()->attributes;
if (!$options) {
$options['script'] = $attributes->get('controller') . '/' . $attributes->get('action');
}
if (isset($options['status'])) {
$this->response()->setStatusCode($options['status']);
unset($options['status']);
}
if (isset($options['response'])) {
$response = $options['response'];
unset($options['response']);
} else {
$response = $this->response();
}
return $this->application['spark.render_pipeline']->render($options, $response);
}
function request()
{
return $this->application['request'];
}
function response()
{
return $this->response;
}
function flash()
{
return $this->flash ?: $this->flash = $this->application['session']->getFlashBag();
}
function session()
{
return $this->application['session'];
}
function application()
{
return $this->application;
}
function setApplication(Application $application)
{
$this->application = $application;
}
}
| <?php
namespace Spark\Controller;
use Silex\Application;
use Symfony\Component\HttpFoundation\Response;
use Spark\Core\ApplicationAware;
abstract class Base implements ApplicationAware
{
use ActionHelper\Filters;
use ActionHelper\Redirect;
use ActionHelper\Layout;
protected $application;
protected $response;
protected $flash;
function __construct()
{
$this->response = new Response;
$this->setup();
}
function setup()
{}
function render($options = [])
{
$attributes = $this->request()->attributes;
if (!$options) {
$options['script'] = $attributes->get('controller') . '/' . $attributes->get('action');
}
if (isset($options['status'])) {
$this->response()->setStatusCode($options['status']);
unset($options['status']);
}
return $this->application['spark.render_pipeline']->render($options, $this->response());
}
function request()
{
return $this->application['request'];
}
function response()
{
return $this->response;
}
function flash()
{
return $this->flash ?: $this->flash = $this->application['session']->getFlashBag();
}
function session()
{
return $this->application['session'];
}
function application()
{
return $this->application;
}
function setApplication(Application $application)
{
$this->application = $application;
}
}
|
Fix case where path is None in sanitize_path | # -*- coding: utf-8 -*-
import os
import os.path
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
from nimp.utilities.system import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, folder) = os.path.split(path)
if folder != "":
splitted_path.insert(0, folder)
else:
if path != "":
splitted_path.insert(0, path)
break
return splitted_path
def sanitize_path(path):
if path is None:
return None
if is_windows() and not is_msys():
if path[0:1] == '/' and path[1:2].isalpha() and path[2:3] == '/':
return '%s:\\%s' % (path[1], path[3:].replace('/', '\\'))
if os.sep is '\\':
return path.replace('/', '\\')
# elif os.sep is '/':
return path.replace('\\', '/')
#-------------------------------------------------------------------------------
# This function is necessary because Python’s makedirs cannot create a
# directory such as "d:\data\foo/bar" because it’ll split it as "d:\data"
# and "foo/bar" then try to create a directory named "foo/bar".
def safe_makedirs(path):
path = sanitize_path(path)
try:
os.makedirs(path)
except FileExistsError:
# Maybe someone else created the directory for us; if so, ignore error
if os.path.exists(path):
return
raise
| # -*- coding: utf-8 -*-
import os
import os.path
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
from nimp.utilities.system import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, folder) = os.path.split(path)
if folder != "":
splitted_path.insert(0, folder)
else:
if path != "":
splitted_path.insert(0, path)
break
return splitted_path
def sanitize_path(path):
if is_windows() and not is_msys():
if path[0:1] == '/' and path[1:2].isalpha() and path[2:3] == '/':
return '%s:\\%s' % (path[1], path[3:].replace('/', '\\'))
if os.sep is '\\':
return path.replace('/', '\\')
# elif os.sep is '/':
return path.replace('\\', '/')
#-------------------------------------------------------------------------------
# This function is necessary because Python’s makedirs cannot create a
# directory such as "d:\data\foo/bar" because it’ll split it as "d:\data"
# and "foo/bar" then try to create a directory named "foo/bar".
def safe_makedirs(path):
path = sanitize_path(path)
try:
os.makedirs(path)
except FileExistsError:
# Maybe someone else created the directory for us; if so, ignore error
if os.path.exists(path):
return
raise
|
Remove a relative import that escaped test.test_importlib. | import os
import sys
from test import support
import unittest
def test_suite(package=__package__, directory=os.path.dirname(__file__)):
suite = unittest.TestSuite()
for name in os.listdir(directory):
if name.startswith(('.', '__')):
continue
path = os.path.join(directory, name)
if (os.path.isfile(path) and name.startswith('test_') and
name.endswith('.py')):
submodule_name = os.path.splitext(name)[0]
module_name = "{0}.{1}".format(package, submodule_name)
__import__(module_name, level=0)
module_tests = unittest.findTestCases(sys.modules[module_name])
suite.addTest(module_tests)
elif os.path.isdir(path):
package_name = "{0}.{1}".format(package, name)
__import__(package_name, level=0)
package_tests = getattr(sys.modules[package_name], 'test_suite')()
suite.addTest(package_tests)
else:
continue
return suite
def test_main():
start_dir = os.path.dirname(__file__)
top_dir = os.path.dirname(os.path.dirname(start_dir))
test_loader = unittest.TestLoader()
support.run_unittest(test_loader.discover(start_dir, top_level_dir=top_dir))
| import os
import sys
from .. import support
import unittest
def test_suite(package=__package__, directory=os.path.dirname(__file__)):
suite = unittest.TestSuite()
for name in os.listdir(directory):
if name.startswith(('.', '__')):
continue
path = os.path.join(directory, name)
if (os.path.isfile(path) and name.startswith('test_') and
name.endswith('.py')):
submodule_name = os.path.splitext(name)[0]
module_name = "{0}.{1}".format(package, submodule_name)
__import__(module_name, level=0)
module_tests = unittest.findTestCases(sys.modules[module_name])
suite.addTest(module_tests)
elif os.path.isdir(path):
package_name = "{0}.{1}".format(package, name)
__import__(package_name, level=0)
package_tests = getattr(sys.modules[package_name], 'test_suite')()
suite.addTest(package_tests)
else:
continue
return suite
def test_main():
start_dir = os.path.dirname(__file__)
top_dir = os.path.dirname(os.path.dirname(start_dir))
test_loader = unittest.TestLoader()
support.run_unittest(test_loader.discover(start_dir, top_level_dir=top_dir))
|
Make code comply to PEP8 | #
# -*- encoding: utf-8 -*-
#
import re
import config
import surllib
import semail
import datetime
import urllib
URL_PREFIX = 'http://%s/Infoweb/Fi/' % config.HOSTNAME
URL_MAIN = URL_PREFIX + 'Ugeplaner.asp'
def docFindWeekplans(bs):
trs = bs.findAll('tr')
for line in trs:
if not line.has_key('class'):
continue
if not [c for c in line['class'].split() if c.startswith('linje')]:
continue
links = line.findAll('a')
assert(len(links) >= 1)
# find week date
title = links[0].text
# find url
url = links[0]['href']
url = url.encode('iso-8859-1')
url = URL_PREFIX + urllib.quote(url, safe=':/?=&%')
bs = surllib.skoleGetURL(url, True)
msg = semail.Message('weekplans', bs)
msg.setTitle(u'%s' % title)
msg.updatePersonDate()
msg.maybeSend()
def skoleWeekplans():
global bs
# surllib.skoleLogin()
config.log(u'Kigger efter nye ugeplaner')
# read the initial page
bs = surllib.skoleGetURL(URL_MAIN, True, True)
docFindWeekplans(bs)
if __name__ == '__main__':
# test
skoleWeekplans()
| #
# -*- encoding: utf-8 -*-
#
import re
import config
import surllib
import semail
import datetime
import urllib
URL_PREFIX = 'http://%s/Infoweb/Fi/' % config.HOSTNAME
URL_MAIN = URL_PREFIX + 'Ugeplaner.asp'
def docFindWeekplans(bs):
trs = bs.findAll('tr')
for line in trs:
if not line.has_key('class'):
continue
if not [c for c in line['class'].split() if c.startswith('linje')]:
continue
links = line.findAll('a')
assert(len(links) >= 1)
# find week date
title = links[0].text
# find url
url = links[0]['href']
url = URL_PREFIX + urllib.quote(url.encode('iso-8859-1'), safe=':/?=&%')
bs = surllib.skoleGetURL(url, True)
msg = semail.Message('weekplans', bs)
msg.setTitle(u'%s' % title)
msg.updatePersonDate()
msg.maybeSend()
def skoleWeekplans():
global bs
# surllib.skoleLogin()
config.log(u'Kigger efter nye ugeplaner')
# read the initial page
bs = surllib.skoleGetURL(URL_MAIN, True, True)
docFindWeekplans(bs)
if __name__ == '__main__':
# test
skoleWeekplans()
|
Add try and catch and log errors | <?php
namespace BrockReece\ElasticAnalytics;
class ElasticAnalytics {
protected $client;
public function __construct() {
$this->client = $this->buildClient();
}
public static function buildClient() {
return \Elasticsearch\ClientBuilder::create()
->setHosts(config('elasticquent.config.hosts'))
->setRetries(config('elasticquent.config.retries'))
->build();
}
public static function buildClientByIP($ip) {
return \Elasticsearch\ClientBuilder::create()
->setHosts($ip)
->setRetries(config('elasticquent.config.retries'))
->build();
}
public static function log(array $params) {
if (!config('elasticquent.active')) {
return;
}
self::buildClient()->index($params);
}
public static function magicReplicator($function) {
if (!config('elasticquent.active')) {
return;
}
foreach (config('elasticquent.clusters') as $ip) {
try {
$client = self::buildClientByIP($ip);
$function($client);
}
catch(\Elasticsearch\Common\Exceptions\NoNodesAvailableException $e) {
\Log::error($e->getMessage() . ' - Nodes - ' . implode($ip));
}
}
}
}
| <?php
namespace BrockReece\ElasticAnalytics;
class ElasticAnalytics {
protected $client;
public function __construct() {
$this->client = $this->buildClient();
}
public static function buildClient() {
return \Elasticsearch\ClientBuilder::create()
->setHosts(config('elasticquent.config.hosts'))
->setRetries(config('elasticquent.config.retries'))
->build();
}
public static function buildClientByIP($ip) {
return \Elasticsearch\ClientBuilder::create()
->setHosts([$ip])
->setRetries(config('elasticquent.config.retries'))
->build();
}
public static function log(array $params) {
if (!config('elasticquent.active')) {
return;
}
self::buildClient()->index($params);
}
public static function magicReplicator($function) {
if (!config('elasticquent.active')) {
return;
}
foreach (config('elasticquent.clusters') as $ip) {
$client = self::buildClientByIP($ip);
$function($client);
}
}
}
|
Set frames to be not resizable | package alotoc.graphics.view;
import java.awt.Point;
import javax.swing.JFrame;
/**
* This is an abstract class for all the frames in the program.
*
* @author Kazeheki
*
*/
@SuppressWarnings("serial")
public abstract class AbstractAlotocFrame extends JFrame {
/**
* Ctor.
*
* @param x
* X position of frame.
* @param y
* Y position of frame.
* @param w
* Width of frame.
* @param h
* Height of frame.
* @param title
* Title of frame.
*/
public AbstractAlotocFrame(final int x, final int y, final int w, final int h, final String title) {
this.setTitle(title);
this.setAlwaysOnTop(true);
this.setBounds(x, y, w, h);
this.setUndecorated(true);
this.setLayout(null);
this.setResizable(false);
}
/**
* Ctor.
*
* @param p
* Postion Point of frame.
* @param w
* Width of frame.
* @param h
* Height of frame.
* @param title
* Title of frame.
*/
public AbstractAlotocFrame(final Point p, final int w, final int h, final String title) {
this(p.x, p.y, w, h, title);
}
}
| package alotoc.graphics.view;
import java.awt.Point;
import javax.swing.JFrame;
/**
* This is an abstract class for all the frames in the program.
*
* @author Kazeheki
*
*/
@SuppressWarnings("serial")
public abstract class AbstractAlotocFrame extends JFrame {
/**
* Ctor.
*
* @param x
* X position of frame.
* @param y
* Y position of frame.
* @param w
* Width of frame.
* @param h
* Height of frame.
* @param title
* Title of frame.
*/
public AbstractAlotocFrame(final int x, final int y, final int w, final int h, final String title) {
this.setTitle(title);
this.setAlwaysOnTop(true);
this.setBounds(x, y, w, h);
this.setUndecorated(true);
this.setLayout(null);
}
/**
* Ctor.
*
* @param p
* Postion Point of frame.
* @param w
* Width of frame.
* @param h
* Height of frame.
* @param title
* Title of frame.
*/
public AbstractAlotocFrame(final Point p, final int w, final int h, final String title) {
this(p.x, p.y, w, h, title);
}
}
|
Add message in log with plotting process id. | import datetime
import multiprocessing
from lobster.cmssw.plotting import Plotter
logger = multiprocessing.get_logger()
class DummyPlotter(object):
def make_plots(*args, **kwargs):
pass
class Actions(object):
def __init__(self, config):
if 'plotdir' in config:
logger.info('plots in {0} will be updated automatically'.format(config['plotdir']))
if 'foremen logs' in config:
logger.info('foremen logs will be included from: {0}'.format(', '.join(config['foremen logs'])))
plotter = Plotter(config['filename'], config['plotdir'])
else:
plotter = DummyPlotter()
def plotf(q):
while q.get() not in ('stop', None):
plotter.make_plots(foremen=config.get('foremen logs'))
self.plotq = multiprocessing.Queue()
self.plotp = multiprocessing.Process(target=plotf, args=(self.plotq,))
self.plotp.start()
logger.info('spawning process for automatic plotting with pid {0}'.format(self.plotp.pid))
self.__last = datetime.datetime.now()
def __del__(self):
self.plotq.put('stop')
def take(self):
now = datetime.datetime.now()
if (now - self.__last).seconds > 15 * 60:
self.plotq.put('plot')
self.__last = now
| import datetime
import multiprocessing
from lobster.cmssw.plotting import Plotter
logger = multiprocessing.get_logger()
class DummyPlotter(object):
def make_plots(*args, **kwargs):
pass
class Actions(object):
def __init__(self, config):
if 'plotdir' in config:
logger.info('plots in {0} will be updated automatically'.format(config['plotdir']))
if 'foremen logs' in config:
logger.info('foremen logs will be included from: {0}'.format(', '.join(config['foremen logs'])))
plotter = Plotter(config['filename'], config['plotdir'])
else:
plotter = DummyPlotter()
def plotf(q):
while q.get() not in ('stop', None):
plotter.make_plots(foremen=config.get('foremen logs'))
self.plotq = multiprocessing.Queue()
self.plotp = multiprocessing.Process(target=plotf, args=(self.plotq,))
self.plotp.start()
self.__last = datetime.datetime.now()
def __del__(self):
self.plotq.put('stop')
def take(self):
now = datetime.datetime.now()
if (now - self.__last).seconds > 15 * 60:
self.plotq.put('plot')
self.__last = now
|
Add equality methods to SpatialReference | """Spatial reference systems"""
__all__ = ['SpatialReference']
from osgeo import osr
class BaseSpatialReference(osr.SpatialReference):
"""Base class for extending osr.SpatialReference."""
def __repr__(self):
return self.wkt
def __eq__(self, another):
return bool(self.IsSame(another))
def __ne__(self, another):
return not self.__eq__(another)
@property
def srid(self):
"""Returns the EPSG ID as int if it exists."""
epsg_id = (self.GetAuthorityCode('PROJCS') or
self.GetAuthorityCode('GEOGCS'))
try:
return int(epsg_id)
except TypeError:
return
@property
def wkt(self):
"""Returns this projection in WKT format."""
return self.ExportToWkt()
@property
def proj4(self):
"""Returns this projection as a proj4 string."""
return self.ExportToProj4()
class SpatialReference(object):
"""A spatial reference."""
def __new__(cls, sref):
"""Returns a new BaseSpatialReference instance
This allows for customized construction of osr.SpatialReference which
has no init method which precludes the use of super().
"""
sr = BaseSpatialReference()
if isinstance(sref, int):
sr.ImportFromEPSG(sref)
elif isinstance(sref, str):
if sref.strip().startswith('+proj='):
sr.ImportFromProj4(sref)
else:
sr.ImportFromWkt(sref)
# Add EPSG authority if applicable
sr.AutoIdentifyEPSG()
else:
raise TypeError('Cannot create SpatialReference '
'from {}'.format(str(sref)))
return sr
| """Spatial reference systems"""
from osgeo import osr
class BaseSpatialReference(osr.SpatialReference):
"""Base class for extending osr.SpatialReference."""
def __repr__(self):
return self.wkt
@property
def srid(self):
"""Returns the EPSG ID as int if it exists."""
epsg_id = (self.GetAuthorityCode('PROJCS') or
self.GetAuthorityCode('GEOGCS'))
try:
return int(epsg_id)
except TypeError:
return
@property
def wkt(self):
"""Returns this projection in WKT format."""
return self.ExportToWkt()
@property
def proj4(self):
"""Returns this projection as a proj4 string."""
return self.ExportToProj4()
class SpatialReference(object):
"""A spatial reference."""
def __new__(cls, sref):
"""Returns a new BaseSpatialReference instance
This allows for customized construction of osr.SpatialReference which
has no init method which precludes the use of super().
"""
sr = BaseSpatialReference()
if isinstance(sref, int):
sr.ImportFromEPSG(sref)
elif isinstance(sref, str):
if sref.strip().startswith('+proj='):
sr.ImportFromProj4(sref)
else:
sr.ImportFromWkt(sref)
# Add EPSG authority if applicable
sr.AutoIdentifyEPSG()
else:
raise TypeError('Cannot create SpatialReference '
'from {}'.format(str(sref)))
return sr
|
Add test for Mysql sc | import unittest
from tests.common import load_check
import time
class TestMySql(unittest.TestCase):
def setUp(self):
# This should run on pre-2.7 python so no skiptest
self.skip = False
try:
import pymysql
except ImportError:
self.skip = True
def testChecks(self):
if not self.skip:
agentConfig = {
'version': '0.1',
'api_key': 'toto' }
conf = {'init_config': {}, 'instances': [{
'server': 'localhost',
'user': 'dog',
'pass': 'dog',
'options': {'replication': True},
}]}
# Initialize the check from checks.d
self.check = load_check('mysql', conf, agentConfig)
self.check.run()
metrics = self.check.get_metrics()
self.assertTrue(len(metrics) >= 8, metrics)
# Service checks
service_checks = self.check.get_service_checks()
service_checks_count = len(service_checks)
self.assertTrue(type(service_checks) == type([]))
self.assertTrue(service_checks_count > 0)
self.assertEquals(len([sc for sc in service_checks if sc['check'] == "mysql.can_connect"]), 1, service_checks)
# Assert that all service checks have the proper tags: host and port
self.assertEquals(len([sc for sc in service_checks if "host:localhost" in sc['tags']]), service_checks_count, service_checks)
self.assertEquals(len([sc for sc in service_checks if "port:0" in sc['tags']]), service_checks_count, service_checks)
time.sleep(1)
self.check.run()
metrics = self.check.get_metrics()
self.assertTrue(len(metrics) >= 16, metrics)
if __name__ == '__main__':
unittest.main()
| import unittest
from tests.common import load_check
import time
class TestMySql(unittest.TestCase):
def setUp(self):
# This should run on pre-2.7 python so no skiptest
self.skip = False
try:
import pymysql
except ImportError:
self.skip = True
def testChecks(self):
if not self.skip:
agentConfig = {
'version': '0.1',
'api_key': 'toto' }
conf = {'init_config': {}, 'instances': [{
'server': 'localhost',
'user': 'dog',
'pass': 'dog',
'options': {'replication': True},
}]}
# Initialize the check from checks.d
self.check = load_check('mysql', conf, agentConfig)
self.check.run()
metrics = self.check.get_metrics()
self.assertTrue(len(metrics) >= 8, metrics)
time.sleep(1)
self.check.run()
metrics = self.check.get_metrics()
self.assertTrue(len(metrics) >= 16, metrics)
if __name__ == '__main__':
unittest.main()
|
Add static method to extract post from post id | <?php
namespace WPCore;
use WPCore\admin\WPpostSaveable;
class WPcustomPost implements WPpostSaveable
{
protected $postId;
protected $post;
protected $meta = array();
protected $metakey = 'wpcmeta';
public static function getInstance($id)
{
$post = new self($id);
$post->setPost(\WP_Post::get_instance($id));
$post->fetch();
return $post;
}
static public function create($postId)
{
return new self($postId);
}
public function __construct($postId)
{
$this->postId = $postId;
}
public function setPost(\WP_Post $post)
{
$this->post = $post;
return $this;
}
public function getPost()
{
return $this->post;
}
public function get($key)
{
if (isset($this->meta[$key])) {
return $this->meta[$key];
}
return null;
}
public function set($key, $value)
{
$this->meta[$key] = $value;
return $this;
}
public function fetch()
{
$this->meta = get_post_meta($this->postId, $this->metakey, true);
if (empty($this->meta)) {
$this->meta = array();
} else {
$this->meta = unserialize($this->meta);
}
return true;
}
public function save()
{
return update_post_meta($this->postId, $this->metakey, serialize($this->meta));
}
} | <?php
namespace WPCore;
use WPCore\admin\WPpostSaveable;
class WPcustomPost implements WPpostSaveable
{
protected $postId;
protected $post;
protected $meta = array();
protected $metakey = 'wpcmeta';
static public function create($postId)
{
return new self($postId);
}
public function __construct($postId)
{
$this->postId = $postId;
}
public function setPost(\WP_Post $post)
{
$this->post = $post;
return $this;
}
public function getPost()
{
return $this->post;
}
public function get($key)
{
if (isset($this->meta[$key])) {
return $this->meta[$key];
}
return null;
}
public function set($key, $value)
{
$this->meta[$key] = $value;
return $this;
}
public function fetch()
{
$this->meta = get_post_meta($this->postId, $this->metakey, true);
if (empty($this->meta)) {
$this->meta = array();
} else {
$this->meta = unserialize($this->meta);
}
return true;
}
public function save()
{
return update_post_meta($this->postId, $this->metakey, serialize($this->meta));
}
} |
Add more information to exception | <?php
namespace Laravel\Dusk;
use Exception;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
class DuskServiceProvider extends ServiceProvider
{
/**
* Bootstrap any package services.
*
* @return void
*/
public function boot()
{
Route::get('/_dusk/login/{userId}/{guard?}', [
'middleware' => 'web',
'uses' => 'Laravel\Dusk\Http\Controllers\UserController@login',
]);
Route::get('/_dusk/logout/{guard?}', [
'middleware' => 'web',
'uses' => 'Laravel\Dusk\Http\Controllers\UserController@logout',
]);
Route::get('/_dusk/user/{guard?}', [
'middleware' => 'web',
'uses' => 'Laravel\Dusk\Http\Controllers\UserController@user',
]);
}
/**
* Register any package services.
*
* @return void
* @throws Exception
*/
public function register()
{
if ($this->app->environment('production')) {
throw new Exception('Do not register Dusk in production! Read more on https://github.com/laravel/dusk/issues/57');
}
if ($this->app->runningInConsole()) {
$this->commands([
Console\InstallCommand::class,
Console\DuskCommand::class,
Console\MakeCommand::class,
Console\PageCommand::class,
]);
}
}
}
| <?php
namespace Laravel\Dusk;
use Exception;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
class DuskServiceProvider extends ServiceProvider
{
/**
* Bootstrap any package services.
*
* @return void
*/
public function boot()
{
Route::get('/_dusk/login/{userId}/{guard?}', [
'middleware' => 'web',
'uses' => 'Laravel\Dusk\Http\Controllers\UserController@login',
]);
Route::get('/_dusk/logout/{guard?}', [
'middleware' => 'web',
'uses' => 'Laravel\Dusk\Http\Controllers\UserController@logout',
]);
Route::get('/_dusk/user/{guard?}', [
'middleware' => 'web',
'uses' => 'Laravel\Dusk\Http\Controllers\UserController@user',
]);
}
/**
* Register any package services.
*
* @return void
* @throws Exception
*/
public function register()
{
if ($this->app->environment('production')) {
throw new Exception('Do not register Dusk in production!');
}
if ($this->app->runningInConsole()) {
$this->commands([
Console\InstallCommand::class,
Console\DuskCommand::class,
Console\MakeCommand::class,
Console\PageCommand::class,
]);
}
}
}
|
Stop relying on array [] shorthand
We want to support PHP 5.3 for now | <?php
namespace Lstr\Silex\Database;
use PHPUnit_Framework_TestCase;
use Silex\Application;
class DatabaseServiceTest extends PHPUnit_Framework_TestCase
{
public function testPdoConnectionCanBeRetrieved()
{
$app = new Application();
$db = new DatabaseService($app, $this->getConfig());
$pdo = $db->getPdo();
$this->assertInstanceOf('PDO', $pdo);
$this->assertSame($pdo, $db->getPdo());
}
/**
* @dataProvider dbProvider
*/
public function testASimpleQueryCanBeRan($db)
{
$sql = <<<SQL
SELECT :param_a AS col UNION
SELECT :param_b AS col UNION
SELECT :last_param AS col
ORDER BY col
SQL;
$result = $db->query($sql, array(
'param_a' => 1,
'param_b' => 2,
'last_param' => 3,
));
$count = 1;
while ($row = $result->fetch()) {
$this->assertEquals($count, $row['col']);
++$count;
}
}
public function dbProvider()
{
$app = new Application();
$db = new DatabaseService($app, $this->getConfig());
return array(
array($db),
);
}
private function getConfig()
{
$config = require __DIR__ . '/../../../../config/config.php';
return $config['database'];
}
}
| <?php
namespace Lstr\Silex\Database;
use PHPUnit_Framework_TestCase;
use Silex\Application;
class DatabaseServiceTest extends PHPUnit_Framework_TestCase
{
public function testPdoConnectionCanBeRetrieved()
{
$app = new Application();
$db = new DatabaseService($app, $this->getConfig());
$pdo = $db->getPdo();
$this->assertInstanceOf('PDO', $pdo);
$this->assertSame($pdo, $db->getPdo());
}
/**
* @dataProvider dbProvider
*/
public function testASimpleQueryCanBeRan($db)
{
$sql = <<<SQL
SELECT :param_a AS col UNION
SELECT :param_b AS col UNION
SELECT :last_param AS col
ORDER BY col
SQL;
$result = $db->query($sql, [
'param_a' => 1,
'param_b' => 2,
'last_param' => 3,
]);
$count = 1;
while ($row = $result->fetch()) {
$this->assertEquals($count, $row['col']);
++$count;
}
}
public function dbProvider()
{
$app = new Application();
$db = new DatabaseService($app, $this->getConfig());
return [
[$db],
];
}
private function getConfig()
{
$config = require __DIR__ . '/../../../../config/config.php';
return $config['database'];
}
}
|
Add underscore prefix for routes | <?php
namespace BW\SecurityCheckerBundle\Controller;
use BW\SecurityCheckerBundle\Entity\VulnerabilityReport;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Class SecurityController
* @package BW\SecurityCheckerBundle\Controller
* @Route("/_bw")
*/
class SecurityController extends Controller
{
/**
* @Route("/security/check", name="bw_security_check")
*/
public function checkAction(Request $request)
{
$kernel = $this->get('kernel');
$fs = $this->get('filesystem');
$checker = $this->get('sensio_distribution.security_checker');
$lockFilePath = $kernel->getRootDir() . '/../' . VulnerabilityReport::LOCK_FILENAME;
if (! $fs->exists($lockFilePath)) {
throw new \RuntimeException('Composer lock file not exist. Maybe run "composer update" first?');
}
$result = $checker->check($lockFilePath);
$cachedFilePath = $kernel->getCacheDir() . '/' . VulnerabilityReport::FILENAME;
if (is_array($result)) {
$fs->dumpFile($cachedFilePath, serialize(new VulnerabilityReport($result)));
} else {
if ($fs->exists($cachedFilePath)) {
$fs->remove($cachedFilePath);
}
}
return new RedirectResponse($request->server->get('HTTP_REFERER'));
}
}
| <?php
namespace BW\SecurityCheckerBundle\Controller;
use BW\SecurityCheckerBundle\Entity\VulnerabilityReport;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Class SecurityController
* @package BW\SecurityCheckerBundle\Controller
* @Route("/bw")
*/
class SecurityController extends Controller
{
/**
* @Route("/security/check", name="bw_security_check")
*/
public function checkAction(Request $request)
{
$kernel = $this->get('kernel');
$fs = $this->get('filesystem');
$checker = $this->get('sensio_distribution.security_checker');
$lockFilePath = $kernel->getRootDir() . '/../' . VulnerabilityReport::LOCK_FILENAME;
if (! $fs->exists($lockFilePath)) {
throw new \RuntimeException('Composer lock file not exist. Maybe run "composer update" first?');
}
$result = $checker->check($lockFilePath);
$cachedFilePath = $kernel->getCacheDir() . '/' . VulnerabilityReport::FILENAME;
if (is_array($result)) {
$fs->dumpFile($cachedFilePath, serialize(new VulnerabilityReport($result)));
} else {
if ($fs->exists($cachedFilePath)) {
$fs->remove($cachedFilePath);
}
}
return new RedirectResponse($request->server->get('HTTP_REFERER'));
}
}
|
Handle events' odd button click:
- pass values to parent using props function; | import React from 'react'
import styles from './event-bets.module.styl'
export default ({ betTypes, optionClickHandler = () => {} }) => (
<table className={styles.betsTable}>
<tbody>
{betTypes.map((betType, idx) => (
<tr key={idx}>
<th>{betType.name}</th>
<td>
{betType.options.map((option, idx) => (
<table key={idx}>
<tbody>
<tr>
{option.map((nameValue, idx) => (
<td key={idx}>
<button
type='button'
title={nameValue.name}
onClick={optionClickHandler({
betTypeName: betType.name,
oddName: nameValue.name,
oddValue: nameValue.value
})}
>
{nameValue.value}
</button>
</td>
))}
</tr>
</tbody>
</table>
))}
</td>
</tr>
))}
</tbody>
</table>
)
| import React from 'react'
import styles from './event-bets.module.styl'
export default ({ betTypes }) => (
<table className={styles.betsTable}>
<tbody>
{betTypes.map((betType, idx) => (
<tr key={idx}>
<th>{betType.name}</th>
<td>
{betType.options.map((option, idx) => (
<table key={idx}>
<tbody>
<tr>
{option.map((nameValue, idx) => (
<td key={idx}>
<button type='button' title={nameValue.name}>
{nameValue.value}
</button>
</td>
))}
</tr>
</tbody>
</table>
))}
</td>
</tr>
))}
</tbody>
</table>
)
|
Fix test: Missing Guice dependency | package guice;
import play.Application;
import services.AuthenticationService;
import services.StubConfigurationImplTest;
import services.ConfigurationService;
import services.ESConstantImpl;
import services.ESConstantService;
import services.ESSearchImpl;
import services.ESSearchService;
import stub.StubAuthenticationImplTest;
import utils.EncodeUtils;
import utils.FileUtils;
import utils.IEncodeUtils;
import utils.IFileUtils;
import utils.eslasticsearch.ESServerEmbedded;
import utils.eslasticsearch.IESServerEmbedded;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import configuration.GlobalConfiguration;
import controllers.AuthenticationController;
public class GlobalTest extends GlobalConfiguration {
@Override
protected AbstractModule buildAbstractModule() {
return new AbstractModule() {
@Override
protected void configure() {
bind(IESServerEmbedded.class).to(ESServerEmbedded.class);
bind(IEncodeUtils.class).to(EncodeUtils.class);
bind(IFileUtils.class).to(FileUtils.class);
bind(ESSearchService.class).to(ESSearchImpl.class);
bind(ESConstantService.class).to(ESConstantImpl.class);
bind(ConfigurationService.class).to(StubConfigurationImplTest.class);
bind(AuthenticationService.class).to(StubAuthenticationImplTest.class);
bind(AuthenticationController.class).asEagerSingleton();
}
};
}
@Override
public void onStart(Application application) {
this.injector = Guice.createInjector(buildAbstractModule());
}
@Override
public void onStop(Application arg0) {
// do nothing
}
}
| package guice;
import play.Application;
import services.AuthenticationService;
import services.StubConfigurationImplTest;
import services.ConfigurationService;
import services.ESConstantImpl;
import services.ESConstantService;
import services.ESSearchImpl;
import services.ESSearchService;
import stub.StubAuthenticationImplTest;
import utils.EncodeUtils;
import utils.IEncodeUtils;
import utils.eslasticsearch.ESServerEmbedded;
import utils.eslasticsearch.IESServerEmbedded;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import configuration.GlobalConfiguration;
import controllers.AuthenticationController;
public class GlobalTest extends GlobalConfiguration {
@Override
protected AbstractModule buildAbstractModule() {
return new AbstractModule() {
@Override
protected void configure() {
bind(IESServerEmbedded.class).to(ESServerEmbedded.class);
bind(IEncodeUtils.class).to(EncodeUtils.class);
bind(ESSearchService.class).to(ESSearchImpl.class);
bind(ESConstantService.class).to(ESConstantImpl.class);
bind(ConfigurationService.class).to(StubConfigurationImplTest.class);
bind(AuthenticationService.class).to(StubAuthenticationImplTest.class);
bind(AuthenticationController.class).asEagerSingleton();
}
};
}
@Override
public void onStart(Application application) {
this.injector = Guice.createInjector(buildAbstractModule());
}
@Override
public void onStop(Application arg0) {
// do nothing
}
}
|
admin_screenshow: Add form for irc messages. | # -*- coding: utf-8 -*-
from django import forms
from django.core.exceptions import ValidationError
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder
from Instanssi.screenshow.models import Sponsor,Message,IRCMessage
import os
class IRCMessageForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(IRCMessageForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
u'IRC-Viesti',
'nick',
'date',
'message',
ButtonHolder (
Submit('submit', u'Tallenna')
)
)
)
class Meta:
model = IRCMessage
fields = ('nick','message','date')
class MessageForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MessageForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
u'Viesti',
'show_start',
'show_end',
'text',
ButtonHolder (
Submit('submit', u'Tallenna')
)
)
)
class Meta:
model = Message
fields = ('show_start','show_end','text')
class SponsorForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(SponsorForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
u'Sponsori',
'name',
'logo',
ButtonHolder (
Submit('submit', u'Tallenna')
)
)
)
class Meta:
model = Sponsor
fields = ('name','logo') | # -*- coding: utf-8 -*-
from django import forms
from django.core.exceptions import ValidationError
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder
from Instanssi.screenshow.models import Sponsor,Message,IRCMessage
import os
class MessageForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MessageForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
u'Viesti',
'show_start',
'show_end',
'text',
ButtonHolder (
Submit('submit', u'Tallenna')
)
)
)
class Meta:
model = Message
fields = ('show_start','show_end','text')
class SponsorForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(SponsorForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
u'Sponsori',
'name',
'logo',
ButtonHolder (
Submit('submit', u'Tallenna')
)
)
)
class Meta:
model = Sponsor
fields = ('name','logo') |
Use ~200MB chunk to simulate memory problem | <?php
/**
* Created by PhpStorm.
* User: miroslavcillik
* Date: 24/02/16
* Time: 14:02
*/
namespace Keboola\Syrup\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ErrorCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('syrup:test:error')
->setDescription('Create an error')
->addArgument('error', InputArgument::REQUIRED, 'One of notice, warning, fatal, memory')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$error = $input->getArgument('error');
switch ($error) {
case 'notice':
trigger_error('This is NOTICE!', E_USER_NOTICE);
break;
case 'warning':
trigger_error('This is WARNING!', E_USER_WARNING);
break;
case 'fatal':
$foo = new Bar();
break;
case 'memory':
$str = "something";
while (true) {
$str .= str_repeat("abcdeABCDE", 1000*1000*20);
}
break;
default:
echo "You must specify one of 'notice | warning | fatal | memory'";
}
}
}
| <?php
/**
* Created by PhpStorm.
* User: miroslavcillik
* Date: 24/02/16
* Time: 14:02
*/
namespace Keboola\Syrup\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ErrorCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('syrup:test:error')
->setDescription('Create an error')
->addArgument('error', InputArgument::REQUIRED, 'One of notice, warning, fatal, memory')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$error = $input->getArgument('error');
switch ($error) {
case 'notice':
trigger_error('This is NOTICE!', E_USER_NOTICE);
break;
case 'warning':
trigger_error('This is WARNING!', E_USER_WARNING);
break;
case 'fatal':
$foo = new Bar();
break;
case 'memory':
$str = "something";
while (true) {
$str .= "something else";
}
break;
default:
echo "You must specify one of 'notice | warning | fatal | memory'";
}
}
}
|
Update the config for the prompts for inquirer. | /*
* <%= appNameSlug %>
* https://github.com/<%= userName %>/<%= appNameSlug %>
*
* Copyright (c) <%= year %>, <%= authorName %>
* Licensed under the <%= license %> license.
*/
'use strict';
var gulp = require('gulp'),
install = require('gulp-install'),
conflict = require('gulp-conflict'),
template = require('gulp-template'),
rename = require('gulp-rename'),
_ = require('underscore.string'),
inquirer = require('inquirer');
gulp.task('default', function (done) {
var prompts = [{
type: 'input',
name: 'appName',
message: 'What is the name of your generator?',
default: gulp.args.join(' ')
}, {
type: 'input',
name: 'appDescription',
message: 'What is the description for your generator?'
}, {
type: 'confirm',
name: 'moveon',
message: 'Continue?'
}];
//Ask
inquirer.prompt(prompts,
function (answers) {
if (!answers.moveon) {
return done();
}
answers.appNameSlug = _.slugify(answers.appName);
gulp.src(__dirname + '/templates/**')
.pipe(template(answers))
.pipe(rename(function (file) {
if (file.basename[0] === '_') {
file.basename = '.' + file.basename.slice(1);
}
}))
.pipe(conflict('./'))
.pipe(gulp.dest('./'))
.pipe(install())
.on('end', function () {
done();
});
});
});
| /*
* <%= appNameSlug %>
* https://github.com/<%= userName %>/<%= appNameSlug %>
*
* Copyright (c) <%= year %>, <%= authorName %>
* Licensed under the <%= license %> license.
*/
'use strict';
var gulp = require('gulp'),
install = require('gulp-install'),
conflict = require('gulp-conflict'),
template = require('gulp-template'),
rename = require('gulp-rename'),
_ = require('underscore.string'),
inquirer = require('inquirer');
gulp.task('default', function(done) {
var prompts = [{
name: 'appName',
message: 'What is the name of example?'
}, {
name: 'appDescription',
message: 'What is the description?'
}];
//Ask
inquirer.prompt(prompts,
function(answers) {
if (!answers.appName) {
return done();
}
answers.appNameSlug = _.slugify(answers.appName)
gulp.src(__dirname + '/templates/**')
.pipe(template(answers))
.pipe(rename(function(file) {
if (file.basename[0] === '_') {
file.basename = '.' + file.basename.slice(1);
}
}))
.pipe(conflict('./'))
.pipe(gulp.dest('./'))
.pipe(install())
.on('end', function() {
done();
});
});
});
|
Add CSS class changes to the asset partial. | <div class="col-md-3 asset" data-asset-id="{{ $asset->getId() }}">
<a href="#">
<div class="list-content-card animated pulse-hover">
<span class="label label-danger m-r-5">
{{ $asset->getCriticalSeverityVulnerabilities()->count() }}
</span>
<span class="label label-high m-r-5">
{{ $asset->getHighSeverityVulnerabilities()->count() }}
</span>
<span class="label label-warning m-r-5">
{{ $asset->getMediumSeverityVulnerabilities()->count() }}
</span>
<span class="label label-success m-r-5">
{{ $asset->getLowSeverityVulnerabilities()->count() }}
</span>
<span class="label label-info m-r-5">
{{ $asset->getInformationalVulnerabilities()->count() }}
</span>
<h4 class="h-4-1">{{ $asset->getHostname() ?? $asset->getName() }}</h4>
<p>IP Address: {{ $asset->getIpAddressV4() }}</p>
</div>
</a>
</div> | <div class="col-md-3 asset" data-asset-id="{{ $asset->getId() }}">
<a href="#">
<div class="list-content-card animated pulse-hover">
<span class="label label-danger">
{{ $asset->getCriticalSeverityVulnerabilities()->count() }}
</span>
<span class="label label-high">
{{ $asset->getHighSeverityVulnerabilities()->count() }}
</span>
<span class="label label-warning">
{{ $asset->getMediumSeverityVulnerabilities()->count() }}
</span>
<span class="label label-success">
{{ $asset->getLowSeverityVulnerabilities()->count() }}
</span>
<span class="label label-info">
{{ $asset->getInformationalVulnerabilities()->count() }}
</span>
<h4 class="h-4-1">{{ $asset->getHostname() ?? $asset->getName() }}</h4>
<p>IP Address: {{ $asset->getIpAddressV4() }}</p>
</div>
</a>
</div> |
Add problem admin URL to problem report email | from django.core.mail import mail_managers
from django.conf import settings
from django.urls import reverse
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
def inform_managers(report):
admin_url = settings.SITE_URL + reverse(
'admin:problem_problemreport_change', args=(report.id,))
mail_managers(
_('New problem: {label} [#{reqid}]').format(
label=report.get_kind_display(),
reqid=report.message.request_id
),
'{}\n\n---\n\n{}\n{}'.format(
report.description,
report.get_absolute_domain_url(),
admin_url
)
)
def inform_user_problem_resolved(report):
if report.auto_submitted or not report.user:
return False
foirequest = report.message.request
subject = _('Problem resolved on your request')
body = render_to_string("problem/email_problem_resolved.txt", {
"user": report.user,
"title": foirequest.title,
"report": report,
"url": report.user.get_autologin_url(
report.message.get_absolute_short_url()
),
"site_name": settings.SITE_NAME
})
report.user.send_mail(subject, body)
return True
| from django.core.mail import mail_managers
from django.conf import settings
from django.urls import reverse
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
def inform_managers(report):
admin_url = settings.SITE_URL + reverse(
'admin:problem_problemreport_change', args=(report.id,))
mail_managers(
_('New problem: {label} [#{reqid}]').format(
label=report.get_kind_display(),
reqid=report.message.request_id
),
'{}\n\n---\n\n{}\n'.format(
report.description,
report.get_absolute_domain_url(),
admin_url
)
)
def inform_user_problem_resolved(report):
if report.auto_submitted or not report.user:
return False
foirequest = report.message.request
subject = _('Problem resolved on your request')
body = render_to_string("problem/email_problem_resolved.txt", {
"user": report.user,
"title": foirequest.title,
"report": report,
"url": report.user.get_autologin_url(
report.message.get_absolute_short_url()
),
"site_name": settings.SITE_NAME
})
report.user.send_mail(subject, body)
return True
|
Fix error on comment screen. | <?php
namespace WPametu\UI\Admin;
use WPametu\UI\MetaBox;
abstract class EditMetaBox extends MetaBox
{
/**
* Meta box context
*
* @var string 'normal', 'side', and 'advanced'
*/
protected $context = 'advanced';
/**
* Meta box priority
*
* @var string 'high', 'low', and 'default'
*/
protected $priority = 'default';
/**
* Register UI hook
*/
protected function register_ui(){
add_action('add_meta_boxes', [$this, 'add_meta_boxes'], 10, 2);
}
/**
* Register meta box
*
* @param string $post_type
* @param \WP_Post $post
*/
public function add_meta_boxes($post_type, $post){
if( $this->is_valid_post_type($post_type) && $this->has_cap() ){
if( empty($this->name) || empty($this->label) ){
$message = sprintf($this->__('<code>%s</code> has invalid name or label.'), get_called_class());
add_action('admin_notices', function() use ($message) {
printf('<div class="error"><p>%s</p></div>', $message);
});
}else{
add_meta_box($this->name, $this->label, [$this, 'render'], $post_type, $this->context, $this->priority);
}
}
}
}
| <?php
namespace WPametu\UI\Admin;
use WPametu\UI\MetaBox;
abstract class EditMetaBox extends MetaBox
{
/**
* Meta box context
*
* @var string 'normal', 'side', and 'advanced'
*/
protected $context = 'advanced';
/**
* Meta box priority
*
* @var string 'high', 'low', and 'default'
*/
protected $priority = 'default';
/**
* Register UI hook
*/
protected function register_ui(){
add_action('add_meta_boxes', [$this, 'add_meta_boxes'], 10, 2);
}
/**
* Register meta box
*
* @param string $post_type
* @param \WP_Post $post
*/
public function add_meta_boxes($post_type, \WP_Post $post){
if( $this->is_valid_post_type($post_type) && $this->has_cap() ){
if( empty($this->name) || empty($this->label) ){
$message = sprintf($this->__('<code>%s</code> has invalid name or label.'), get_called_class());
add_action('admin_notices', function() use ($message) {
printf('<div class="error"><p>%s</p></div>', $message);
});
}else{
add_meta_box($this->name, $this->label, [$this, 'render'], $post_type, $this->context, $this->priority);
}
}
}
}
|
Add url to contact form | // Here be the site javascript!
$(document).ready(function () {
$(".button-collapse").sideNav();
$('.scrollspy').scrollSpy();
$("form").submit(function (event) {
event.preventDefault();
$("#send-msg").attr("disabled", true);
$("#fa-send").toggleClass("fa-envelope-o").toggleClass("fa-spinner").toggleClass("fa-spin");
var msg = $("#message").val();
var mail = $("#email").val();
var subject = $("#subject").val();
payload = {subject: subject, email: mail, message: msg};
// Send mail to the local python mail server
$.ajax({
type: "POST",
url: "http://mattij.com:5000/sendmail",
crossDomain: true,
data: payload,
complete: function (data, status, req) {
$("#fa-send").toggleClass("fa-envelope-o").toggleClass("fa-spinner").toggleClass("fa-spin");
$("#message").val("");
$("#email").val("");
$("#subject").val("");
$("#send-msg").attr("disabled", false);
$('#modal1').openModal();
}
});
});
}); | // Here be the site javascript!
$(document).ready(function () {
$(".button-collapse").sideNav();
$('.scrollspy').scrollSpy();
$("form").submit(function (event) {
event.preventDefault();
$("#send-msg").attr("disabled", true);
$("#fa-send").toggleClass("fa-envelope-o").toggleClass("fa-spinner").toggleClass("fa-spin");
var msg = $("#message").val();
var mail = $("#email").val();
var subject = $("#subject").val();
payload = {subject: subject, email: mail, message: msg};
// Send mail to the local python mail server
$.ajax({
type: "POST",
url: "http://46.101.248.58:5000/sendmail",
crossDomain: true,
data: payload,
complete: function (data, status, req) {
$("#fa-send").toggleClass("fa-envelope-o").toggleClass("fa-spinner").toggleClass("fa-spin");
$("#message").val("");
$("#email").val("");
$("#subject").val("");
$("#send-msg").attr("disabled", false);
$('#modal1').openModal();
}
});
});
}); |
Fix comment in aliases php script | <?php
// Grab the datastore settings from drupdates
$result = json_decode(exec('python ~/.drush/settings.py'), true);
$path = $result['workingDir']['value'];
$driver = $result['datastoreDriver']['value'];
$user = $result['datastoreSuperUser']['value'];
$pass = $result['datastoreSuperPword']['value'];
$port = $result['datastorePort']['value'];
$host = $result['datastoreHost']['value'];
$webroot = $result['webrootDir']['value'];
// I'm not sure why but if you keep $result populated you get ghost aliases who
// values are the same as the $result array elelment names
$result = array();
$aliases = array();
$dir_handle = new DirectoryIterator($path);
while($dir_handle->valid()) {
if($dir_handle->isDir() && !$dir_handle->isDot()) {
$basename = $dir_handle->getBasename();
$root = $dir_handle->getPathname();
$root = $webroot != "" ? $root : $root . $webroot;
$aliases[$basename] = array(
'uri' => 'http://localhost/' . $basename,
'root' => $root,
'databases' => array(
'default' => array(
'default' => array(
'driver' => $driver,
'username' => $basename . '_user',
'password' => $basename . '_pass',
'port' => $port,
'host' => $host,
'database' => $basename,
),
),
),
);
}
$dir_handle->next();
}
| <?php
// Grab the "Global" settings from drupdates
$result = json_decode(exec('python ~/.drush/settings.py'), true);
$path = $result['workingDir']['value'];
$driver = $result['datastoreDriver']['value'];
$user = $result['datastoreSuperUser']['value'];
$pass = $result['datastoreSuperPword']['value'];
$port = $result['datastorePort']['value'];
$host = $result['datastoreHost']['value'];
$webroot = $result['webrootDir']['value'];
// I'm not sure why but if you keep $result populated you get ghost aliases who
// values are the same as the $result array elelment names
$result = array();
$aliases = array();
$dir_handle = new DirectoryIterator($path);
while($dir_handle->valid()) {
if($dir_handle->isDir() && !$dir_handle->isDot()) {
$basename = $dir_handle->getBasename();
$root = $dir_handle->getPathname();
$root = $webroot != "" ? $root : $root . $webroot;
$aliases[$basename] = array(
'uri' => 'http://localhost/' . $basename,
'root' => $root,
'databases' => array(
'default' => array(
'default' => array(
'driver' => $driver,
'username' => $basename . '_user',
'password' => $basename . '_pass',
'port' => $port,
'host' => $host,
'database' => $basename,
),
),
),
);
}
$dir_handle->next();
}
|
Clone the parameters too since they are an object
We need to clone the parameters for this query or the parameters could change if the original query's parameters are changed.
This is how doctrine does it.
https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Tools/Pagination/Paginator.php#L212
To bad that method isn't static. | <?php
namespace Knp\Component\Pager\Event\Subscriber\Paginate\Doctrine\ORM\Query;
use Doctrine\ORM\Query;
/**
* ORM Query helper for cloning
* and hint processing
*/
class Helper
{
/**
* Clones the given $query and copies all used
* parameters and hints
*
* @param Query $query
* @return Query
*/
public static function cloneQuery(Query $query)
{
$clonedQuery = clone $query;
$clonedQuery->setParameters(clone $query->getParameters());
// attach hints
foreach ($query->getHints() as $name => $hint) {
$clonedQuery->setHint($name, $hint);
}
return $clonedQuery;
}
/**
* Add a custom TreeWalker $walker class name to
* be included in the CustomTreeWalker hint list
* of the given $query
*
* @param Query $query
* @param string $walker
* @return void
*/
public static function addCustomTreeWalker(Query $query, $walker)
{
$customTreeWalkers = $query->getHint(Query::HINT_CUSTOM_TREE_WALKERS);
if ($customTreeWalkers !== false && is_array($customTreeWalkers)) {
$customTreeWalkers = array_merge($customTreeWalkers, array($walker));
} else {
$customTreeWalkers = array($walker);
}
$query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, $customTreeWalkers);
}
}
| <?php
namespace Knp\Component\Pager\Event\Subscriber\Paginate\Doctrine\ORM\Query;
use Doctrine\ORM\Query;
/**
* ORM Query helper for cloning
* and hint processing
*/
class Helper
{
/**
* Clones the given $query and copies all used
* parameters and hints
*
* @param Query $query
* @return Query
*/
public static function cloneQuery(Query $query)
{
$clonedQuery = clone $query;
$clonedQuery->setParameters($query->getParameters());
// attach hints
foreach ($query->getHints() as $name => $hint) {
$clonedQuery->setHint($name, $hint);
}
return $clonedQuery;
}
/**
* Add a custom TreeWalker $walker class name to
* be included in the CustomTreeWalker hint list
* of the given $query
*
* @param Query $query
* @param string $walker
* @return void
*/
public static function addCustomTreeWalker(Query $query, $walker)
{
$customTreeWalkers = $query->getHint(Query::HINT_CUSTOM_TREE_WALKERS);
if ($customTreeWalkers !== false && is_array($customTreeWalkers)) {
$customTreeWalkers = array_merge($customTreeWalkers, array($walker));
} else {
$customTreeWalkers = array($walker);
}
$query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, $customTreeWalkers);
}
}
|
Use correct m2m join table name in LatestCommentsFeed
git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@9089 bcc190cf-cafb-0310-a4f2-bffc1f526a37 | from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"%s comments" % self._site.name
def link(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return "http://%s/" % (self._site.domain)
def description(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"Latest comments on %s" % self._site.name
def items(self):
qs = comments.get_model().objects.filter(
site__pk = settings.SITE_ID,
is_public = True,
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs.order_by('-submit_date')[:40]
def item_pubdate(self, item):
return item.submit_date
| from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"%s comments" % self._site.name
def link(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return "http://%s/" % (self._site.domain)
def description(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"Latest comments on %s" % self._site.name
def items(self):
qs = comments.get_model().objects.filter(
site__pk = settings.SITE_ID,
is_public = True,
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_users_group WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs.order_by('-submit_date')[:40]
def item_pubdate(self, item):
return item.submit_date
|
Fix links in the cherry-pick demo | import './base.css';
import './application.css';
import 'suitcss-base';
import 'suitcss-utils-text';
import 'suitcss-components-arrange';
import React from 'react';
module.exports = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
link: function () {
var router = this.context.router;
return router.generate.apply(router, arguments);
},
getInitialState() {
var time = new Date().getTime();
// setInterval(this.updateTime, 1000);
return { time };
},
updateTime() {
var time = new Date().getTime();
this.setState({time});
},
render: function () {
return (
<div className='Application'>
<div className='Navbar'>
<div className='Navbar-header'>
<a className='Navbar-brand' href={this.link('index')}></a>
</div>
</div>
<div className='Application-content'>
{this.props.children}
</div>
<footer className='Footer'>
<p className='u-textCenter'>Cherrytree Demo. ·
<a href='https://github.com/QubitProducts/cherrytree'>Cherrytree Repo</a> ·
<a href='https://github.com/QubitProducts/cherrytree/tree/master/examples/cherry-pick'>Demo Source Code</a>
</p>
</footer>
</div>
);
}
}); | import './base.css';
import './application.css';
import 'suitcss-base';
import 'suitcss-utils-text';
import 'suitcss-components-arrange';
import React from 'react';
module.exports = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
link: function () {
var router = this.context.router;
return router.generate.apply(router, arguments);
},
getInitialState() {
var time = new Date().getTime();
// setInterval(this.updateTime, 1000);
return { time };
},
updateTime() {
var time = new Date().getTime();
this.setState({time});
},
render: function () {
return (
<div className='Application'>
<div className='Navbar'>
<div className='Navbar-header'>
<a className='Navbar-brand' href={this.link('index')}></a>
</div>
</div>
<div className='Application-content'>
{this.props.children}
</div>
<footer className='Footer'>
<p className='u-textCenter'>Cherrytree Demo. ·
<a href='github.com/QubitProducts/cherrytree'>Cherrytree Repo</a> ·
<a href='github.com/KidkArolis/cherrypick'>Demo Source Code</a>
</p>
</footer>
</div>
);
}
}); |
Add addition method to Terrain | """This module is for the Terrain class, used for storing randomly generated terrain."""
class Terrain(object):
"""Container for a randomly generated area of terrain.
Attributes:
width (int): Width of generated terrain.
length (int): Length of generated terrain.
height_map (list): Map of heights of terrain. Values range from 0 to 1.
"""
def __init__(self, width, length):
"""Initializer for Terrain.
Args:
width (int): Width of terrain.
length (int): Height of terrain.
"""
self.width = width
self.length = length
self.height_map = [[0 for _ in self.width]] * self.length
def __getitem__(self, item):
"""Get an item at x-y coordinates.
Args:
item (tuple): 2-tuple of x and y coordinates.
Returns:
float: Height of terrain at coordinates, between 0 and 1.
"""
return self.height_map[item[1]][item[0]]
def __setitem__(self, key, value):
"""Set the height of an item.
Args:
key (tuple): 2-tuple of x and y coordinates.
value (float): New height of map at x and y coordinates, between 0 and 1.
"""
self.height_map[key[1]][key[0]] = value
def __add__(self, other):
"""Add two terrains, height by height.
Args:
other (Terrain): Other terrain to add self to. Must have same dimensions as self.
Returns:
Terrain: Terrain of self and other added together.
"""
result = Terrain(self.width, self.length)
for i in range(self.width):
for j in range(self.length):
result[i, j] = self[i, j] + other[i, j]
return result
| """This module is for the Terrain class, used for storing randomly generated terrain."""
class Terrain(object):
"""Container for a randomly generated area of terrain.
Attributes:
width (int): Width of generated terrain.
length (int): Length of generated terrain.
height_map (list): Map of heights of terrain. Values range from 0 to 1.
"""
def __init__(self, width, length):
"""Initializer for Terrain.
Args:
width (int): Width of terrain.
length (int): Height of terrain.
"""
self.width = width
self.length = length
self.height_map = [[0 for _ in self.width]] * self.length
def __getitem__(self, item):
"""Get an item at x-y coordinates.
Args:
item (tuple): 2-tuple of x and y coordinates.
Returns:
float: Height of terrain at coordinates, between 0 and 1.
"""
return self.height_map[item[1]][item[0]]
def __setitem__(self, key, value):
"""Set the height of an item.
Args:
key (tuple): 2-tuple of x and y coordinates.
value (float): New height of map at x and y coordinates, between 0 and 1.
"""
self.height_map[key[1]][key[0]] = value
|
Include command: All arguments lowercase. Require file, default to empty
macros | '''
Created on Mar 8,2015
@author: qiuyx
'''
from scan.commands.command import Command
import xml.etree.ElementTree as ET
class Include(Command):
'''
classdocs
'''
def __init__(self, scan, macros=None, errhandler=None):
'''
@param scan: Name of included scan file, must be on the server's list of script_paths
@param macros: "name=value, other=42"
Usage::
>>>icl=Include(scanFile='PrepMotor.scn', macros='macro=value')
'''
self.__scanFile = scan
self.__macros = macros
self.__errHandler = errhandler
def genXML(self):
xml = ET.Element('include')
ET.SubElement(xml, 'scan_file').text = self.__scanFile
if self.__macros:
ET.SubElement(xml, 'macros').text = self.__macros
if self.__errHandler:
ET.SubElement(xml,'error_handler').text = self.__errHandler
return xml
def __repr__(self):
return self.toCmdString()
def toCmdString(self):
result = "Include('%s'" % self.__scanFile
if self.__macros:
result += ", macros='%s'" % self.__macros
if self.__errHandler:
result += ", errHandler='%s'" % self.__errHandler
result += ")"
return result
| '''
Created on Mar 8,2015
@author: qiuyx
'''
from scan.commands.command import Command
import xml.etree.ElementTree as ET
class Include(Command):
'''
classdocs
'''
def __init__(self, scanFile=None, macros=None,errHandler=None):
'''
@param scanFile: The included scan file path located at /scan/example
Defaults as None.
@param macros:
Usage::
>>>icl=Include(scanFile='PrepMotor.scn',macros='macro=value')
'''
self.__scanFile=scanFile
self.__macros=macros
self.__errHandler=errHandler
def genXML(self):
xml = ET.Element('include')
ET.SubElement(xml, 'scan_file').text = self.__scanFile
if self.__macros:
ET.SubElement(xml, 'macros').text = self.__macros
if self.__errHandler:
ET.SubElement(xml,'error_handler').text = self.__errHandler
return xml
def __repr__(self):
return self.toCmdString()
def toCmdString(self):
result = "Include('%s'" % self.__scanFile
if self.__macros:
result += ", macros='%s'" % self.__macros
if self.__errHandler:
result += ", errHandler='%s'" % self.__errHandler
result += ")"
return result
|
Work with new and *older* kombu versions | from Queue import Empty
from anyjson import serialize, deserialize
from kombu.transport import virtual
from django.conf import settings
from django.core import exceptions as errors
from djkombu.models import Queue
POLLING_INTERVAL = getattr(settings, "DJKOMBU_POLLING_INTERVAL", 5.0)
class Channel(virtual.Channel):
def _new_queue(self, queue, **kwargs):
Queue.objects.get_or_create(name=queue)
def _put(self, queue, message, **kwargs):
Queue.objects.publish(queue, serialize(message))
def basic_consume(self, queue, *args, **kwargs):
qinfo = self.state.bindings[queue]
exchange = qinfo[0]
if self.typeof(exchange).type == "fanout":
return
super(Channel, self).basic_consume(queue, *args, **kwargs)
def _get(self, queue):
#self.refresh_connection()
m = Queue.objects.fetch(queue)
if m:
return deserialize(m)
raise Empty()
def _size(self, queue):
return Queue.objects.size(queue)
def _purge(self, queue):
return Queue.objects.purge(queue)
def refresh_connection(self):
from django import db
db.close_connection()
class DatabaseTransport(virtual.Transport):
Channel = Channel
default_port = 0
polling_interval = POLLING_INTERVAL
connection_errors = ()
channel_errors = (errors.ObjectDoesNotExist,
errors.MultipleObjectsReturned)
| from Queue import Empty
from anyjson import serialize, deserialize
from kombu.transport import virtual
from django.conf import settings
from django.core import exceptions as errors
from djkombu.models import Queue
POLLING_INTERVAL = getattr(settings, "DJKOMBU_POLLING_INTERVAL", 5.0)
class Channel(virtual.Channel):
def _new_queue(self, queue, **kwargs):
Queue.objects.get_or_create(name=queue)
def _put(self, queue, message, **kwargs):
Queue.objects.publish(queue, serialize(message))
def basic_consume(self, queue, *args, **kwargs):
exchange, _ , _ = self.state.bindings[queue]
if self.typeof(exchange).type == "fanout":
return
super(Channel, self).basic_consume(queue, *args, **kwargs)
def _get(self, queue):
#self.refresh_connection()
m = Queue.objects.fetch(queue)
if m:
return deserialize(m)
raise Empty()
def _size(self, queue):
return Queue.objects.size(queue)
def _purge(self, queue):
return Queue.objects.purge(queue)
def refresh_connection(self):
from django import db
db.close_connection()
class DatabaseTransport(virtual.Transport):
Channel = Channel
default_port = 0
polling_interval = POLLING_INTERVAL
connection_errors = ()
channel_errors = (errors.ObjectDoesNotExist,
errors.MultipleObjectsReturned)
|
Include testing workflow in default task. | 'use strict';
module.exports = function(grunt) {
// Configuration.
grunt.initConfig({
jscs: {
options: {
config: '.jscsrc'
},
grunt: 'Gruntfile.js',
tasks: 'tasks/**/*.js'
},
jshint: {
options: {
jshintrc: true
},
grunt: 'Gruntfile.js',
tasks: 'tasks/**/*.js'
},
jsonlint: {
jshint: ['.jshintrc'],
npm: ['package.json']
},
nodeunit: {
all: 'test/**/*.js'
}
});
// Load tasks.
grunt.loadTasks('./tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-jscs-checker');
grunt.loadNpmTasks('grunt-jsonlint');
grunt.loadNpmTasks('grunt-release');
// Register tasks.
grunt.renameTask('release', 'bump');
grunt.registerTask('lint', ['jsonlint', 'jshint', 'jscs']);
grunt.registerTask('release', function() {
grunt.task.run('lint', Array.prototype.concat.apply('bump', arguments).join(':'));
});
grunt.registerTask('test', ['nodeunit']);
grunt.registerTask('travis', ['lint', 'validate']);
grunt.registerTask('validate', ['npm-validate']);
grunt.registerTask('default', ['lint', 'test', 'validate']);
};
| 'use strict';
module.exports = function(grunt) {
// Configuration.
grunt.initConfig({
jscs: {
options: {
config: '.jscsrc'
},
grunt: 'Gruntfile.js',
tasks: 'tasks/**/*.js'
},
jshint: {
options: {
jshintrc: true
},
grunt: 'Gruntfile.js',
tasks: 'tasks/**/*.js'
},
jsonlint: {
jshint: ['.jshintrc'],
npm: ['package.json']
},
nodeunit: {
all: 'test/**/*.js'
}
});
// Load tasks.
grunt.loadTasks('./tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-jscs-checker');
grunt.loadNpmTasks('grunt-jsonlint');
grunt.loadNpmTasks('grunt-release');
// Register tasks.
grunt.renameTask('release', 'bump');
grunt.registerTask('lint', ['jsonlint', 'jshint', 'jscs']);
grunt.registerTask('release', function() {
grunt.task.run('lint', Array.prototype.concat.apply('bump', arguments).join(':'));
});
grunt.registerTask('test', ['nodeunit']);
grunt.registerTask('travis', ['lint', 'validate']);
grunt.registerTask('validate', ['npm-validate']);
grunt.registerTask('default', ['lint', 'validate']);
};
|
Remove PHP 7.1 feature usage for 7.0 compat | <?php
namespace Amp;
final class CombinedCancellationToken implements CancellationToken
{
private $tokens = [];
private $nextId = "a";
private $callbacks = [];
private $exception;
public function __construct(CancellationToken ...$tokens)
{
foreach ($tokens as $token) {
$id = $token->subscribe(function ($exception) {
$this->exception = $exception;
$callbacks = $this->callbacks;
$this->callbacks = [];
foreach ($callbacks as $callback) {
asyncCall($callback, $this->exception);
}
});
$this->tokens[] = [$token, $id];
}
}
public function __destruct()
{
foreach ($this->tokens as list($token, $id)) {
/** @var CancellationToken $token */
$token->unsubscribe($id);
}
}
/** @inheritdoc */
public function subscribe(callable $callback): string
{
$id = $this->nextId++;
if ($this->exception) {
asyncCall($callback, $this->exception);
} else {
$this->callbacks[$id] = $callback;
}
return $id;
}
/** @inheritdoc */
public function unsubscribe(string $id)
{
unset($this->callbacks[$id]);
}
/** @inheritdoc */
public function isRequested(): bool
{
foreach ($this->tokens as list($token)) {
if ($token->isRequested()) {
return true;
}
}
return false;
}
/** @inheritdoc */
public function throwIfRequested()
{
foreach ($this->tokens as list($token)) {
$token->throwIfRequested();
}
}
}
| <?php
namespace Amp;
final class CombinedCancellationToken implements CancellationToken
{
private $tokens = [];
private $nextId = "a";
private $callbacks = [];
private $exception;
public function __construct(CancellationToken ...$tokens)
{
foreach ($tokens as $token) {
$id = $token->subscribe(function ($exception) {
$this->exception = $exception;
$callbacks = $this->callbacks;
$this->callbacks = [];
foreach ($callbacks as $callback) {
asyncCall($callback, $this->exception);
}
});
$this->tokens[] = [$token, $id];
}
}
public function __destruct()
{
foreach ($this->tokens as [$token, $id]) {
/** @var CancellationToken $token */
$token->unsubscribe($id);
}
}
/** @inheritdoc */
public function subscribe(callable $callback): string
{
$id = $this->nextId++;
if ($this->exception) {
asyncCall($callback, $this->exception);
} else {
$this->callbacks[$id] = $callback;
}
return $id;
}
/** @inheritdoc */
public function unsubscribe(string $id)
{
unset($this->callbacks[$id]);
}
/** @inheritdoc */
public function isRequested(): bool
{
foreach ($this->tokens as [$token]) {
if ($token->isRequested()) {
return true;
}
}
return false;
}
/** @inheritdoc */
public function throwIfRequested()
{
foreach ($this->tokens as [$token]) {
$token->throwIfRequested();
}
}
}
|
Update vigenereDicitonaryHacker: simplified comparison with None | # Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenereDictionary(ciphertext)
if not hackedMessage:
print('Copying hacked message to clipboard:')
print(hackedMessage)
pyperclip.copy(hackedMessage)
else:
print('Failed to hack encryption.')
def hackVigenereDictionary(ciphertext):
fo = open('dictionary.txt')
words = fo.readlines()
fo.close()
for word in words:
word = word.strip() # Remove the newline at the end.
decryptedText = vigenereCipher.decryptMessage(word, ciphertext)
if detectEnglish.isEnglish(decryptedText, wordPercentage=40):
# Check with user to see if the decrypted key has been found:
print()
print('Possible encryption break:')
print('Key ' + str(word) + ': ' + decryptedText[:100])
print()
print('Enter D for done, or just press Enter to continue breaking:')
response = input('> ')
if response.upper().startswith('D'):
return decryptedText
if __name__ == '__main__':
main()
| # Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenereDictionary(ciphertext)
if hackedMessage != None:
print('Copying hacked message to clipboard:')
print(hackedMessage)
pyperclip.copy(hackedMessage)
else:
print('Failed to hack encryption.')
def hackVigenereDictionary(ciphertext):
fo = open('dictionary.txt')
words = fo.readlines()
fo.close()
for word in words:
word = word.strip() # Remove the newline at the end.
decryptedText = vigenereCipher.decryptMessage(word, ciphertext)
if detectEnglish.isEnglish(decryptedText, wordPercentage=40):
# Check with user to see if the decrypted key has been found:
print()
print('Possible encryption break:')
print('Key ' + str(word) + ': ' + decryptedText[:100])
print()
print('Enter D for done, or just press Enter to continue breaking:')
response = input('> ')
if response.upper().startswith('D'):
return decryptedText
if __name__ == '__main__':
main()
|
Update image path for Windows builder test | <?php
use BryanCrowe\Growl\Builder\GrowlNotifyWindowsBuilder;
class GrowlNotifyWindowsBuilderTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
parent::setUp();
$this->GrowlNotifyWindowsBuilder = new GrowlNotifyWindowsBuilder();
}
public function tearDown()
{
unset($this->GrowlNotifyWindowsBuilder);
parent::tearDown();
}
public function testBuild()
{
$options = [
'title' => 'Hello',
'image' => 'C:\okay.jpg',
'url' => 'http://www.example.com',
'message' => 'World',
'sticky' => true
];
$expected = 'growlnotify /t:Hello /i:C:\okay.jpg /cu:' .
'http://www.example.com /s:true World';
$result = $this->GrowlNotifyWindowsBuilder->build($options);
$this->assertSame($expected, $result);
$options = [
'title' => 'Hello',
'message' => 'World',
'sticky' => false
];
$expected = 'growlnotify /t:Hello World';
$result = $this->GrowlNotifyWindowsBuilder->build($options);
$this->assertSame($expected, $result);
}
}
| <?php
use BryanCrowe\Growl\Builder\GrowlNotifyWindowsBuilder;
class GrowlNotifyWindowsBuilderTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
parent::setUp();
$this->GrowlNotifyWindowsBuilder = new GrowlNotifyWindowsBuilder();
}
public function tearDown()
{
unset($this->GrowlNotifyWindowsBuilder);
parent::tearDown();
}
public function testBuild()
{
$options = [
'title' => 'Hello',
'image' => 'Mail',
'url' => 'http://www.example.com',
'message' => 'World',
'sticky' => true
];
$expected = 'growlnotify /t:Hello /i:Mail /cu:' .
'http://www.example.com /s:true World';
$result = $this->GrowlNotifyWindowsBuilder->build($options);
$this->assertSame($expected, $result);
$options = [
'title' => 'Hello',
'message' => 'World',
'sticky' => false
];
$expected = 'growlnotify /t:Hello World';
$result = $this->GrowlNotifyWindowsBuilder->build($options);
$this->assertSame($expected, $result);
}
}
|
Save game_id when joining game | class MainController {
constructor(_, $scope, $state, $log, SocketService) {
'ngInject';
this._ = _;
this.$log = $log;
this.$state = $state;
this.$scope = $scope;
this.SocketService = SocketService;
this.name = '';
this.password = '';
this.errorMessage = '';
this.processing = false;
if(this.SocketService.playerName !== '') {
this.name = this.SocketService.playerName;
}
}
canPlay() {
const _ = this._;
return !_.isEmpty(this.name) && this.password.length === 6;
}
play() {
this.processing = true;
this.SocketService.connect().then((result) => {
this.$log.log('success');
this.SocketService.extendedHandler = (message) => {
if (message.type === 'join_room') {
this.$log.log('join room message');
if (message.result === true) {
this.SocketService.game_id = message.game_id;
this.$state.go('lobby', {roomName: this.password});
} else {
this.$log.log('result is false');
this.errorMessage = message.reason;
this.processing = false;
this.$scope.$apply(() => {
this.$scope.errorMessage = this.errorMessage;
this.$scope.processing = this.processing;
})
}
}
};
this.SocketService.joinRoom(this.password, this.name);
});
}
}
export default MainController;
| class MainController {
constructor(_, $scope, $state, $log, SocketService) {
'ngInject';
this._ = _;
this.$log = $log;
this.$state = $state;
this.$scope = $scope;
this.SocketService = SocketService;
this.name = '';
this.password = '';
this.errorMessage = '';
this.processing = false;
if(this.SocketService.playerName !== '') {
this.name = this.SocketService.playerName;
}
}
canPlay() {
const _ = this._;
return !_.isEmpty(this.name) && this.password.length === 6;
}
play() {
this.processing = true;
this.SocketService.connect().then((result) => {
this.$log.log('success');
this.SocketService.extendedHandler = (message) => {
if (message.type === 'join_room') {
this.$log.log('join room message');
if (message.result === true) {
this.$state.go('lobby', {roomName: this.password});
} else {
this.$log.log('result is false');
this.errorMessage = message.reason;
this.processing = false;
this.$scope.$apply(() => {
this.$scope.errorMessage = this.errorMessage;
this.$scope.processing = this.processing;
})
}
}
};
this.SocketService.joinRoom(this.password, this.name);
});
}
}
export default MainController;
|
Remove references to NdbManipulatorBase, which never really happened. | from helpers.manipulator_base import ManipulatorBase
class TeamManipulator(ManipulatorBase):
"""
Handle Team database writes.
"""
@classmethod
def updateMerge(self, new_team, old_team):
"""
Given an "old" and a "new" Team object, replace the fields in the
"old" team that are present in the "new" team, but keep fields from
the "old" team that are null in the "new" team.
"""
attrs = [
"address",
"name",
"nickname",
"website",
]
for attr in attrs:
if getattr(new_team, attr) is not None:
if getattr(new_team, attr) != getattr(old_team, attr):
setattr(old_team, attr, getattr(new_team, attr))
old_team.dirty = True
# Take the new tpid and tpid_year iff the year is newer than the old one
if (new_team.first_tpid_year > old_team.first_tpid_year):
old_team.first_tpid_year = new_team.first_tpid_year
old_team.first_tpid = new_team.first_tpid
old_team.dirty = True
return old_team
| from helpers.ndb_manipulator_base import NdbManipulatorBase
class TeamManipulator(NdbManipulatorBase):
"""
Handle Team database writes.
"""
@classmethod
def updateMerge(self, new_team, old_team):
"""
Given an "old" and a "new" Team object, replace the fields in the
"old" team that are present in the "new" team, but keep fields from
the "old" team that are null in the "new" team.
"""
attrs = [
"address",
"name",
"nickname",
"website",
]
for attr in attrs:
if getattr(new_team, attr) is not None:
if getattr(new_team, attr) != getattr(old_team, attr):
setattr(old_team, attr, getattr(new_team, attr))
old_team.dirty = True
# Take the new tpid and tpid_year iff the year is newer than the old one
if (new_team.first_tpid_year > old_team.first_tpid_year):
old_team.first_tpid_year = new_team.first_tpid_year
old_team.first_tpid = new_team.first_tpid
old_team.dirty = True
return old_team
|
Add logs for listener callbacks | package com.davidferrand.subappbarpanelsample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import com.davidferrand.subappbarpanel.SubAppBarPanel;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private SubAppBarPanel panel;
private ImageView expandIndicator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
panel = (SubAppBarPanel) findViewById(R.id.main_panel);
expandIndicator = (ImageView) findViewById(R.id.main_toolbar_indicator);
setSupportActionBar(toolbar);
toolbar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
panel.toggle();
}
});
panel.setOnPanelMovementListener(new SubAppBarPanel.OnPanelMovementListener() {
@Override
public void onPanelMovementStarted(boolean expanding) {
Log.v("Panel movement", "The panel is " +
(expanding ? "expanding" : "collapsing"));
expandIndicator.setImageResource(expanding ?
R.drawable.ic_expand_less_white_24dp :
R.drawable.ic_expand_more_white_24dp);
}
@Override
public void onPanelMovementEnded(boolean expanded) {
Log.v("Panel movement", "The panel is completely " +
(expanded ? "expanded" : "collapsed"));
}
});
}
}
| package com.davidferrand.subappbarpanelsample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import com.davidferrand.subappbarpanel.SubAppBarPanel;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private SubAppBarPanel panel;
private ImageView expandIndicator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
panel = (SubAppBarPanel) findViewById(R.id.main_panel);
expandIndicator = (ImageView) findViewById(R.id.main_toolbar_indicator);
setSupportActionBar(toolbar);
toolbar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
panel.toggle();
}
});
panel.setOnPanelMovementListener(new SubAppBarPanel.OnPanelMovementListener() {
@Override
public void onPanelMovementStarted(boolean expanding) {
expandIndicator.setImageResource(expanding ?
R.drawable.ic_expand_less_white_24dp :
R.drawable.ic_expand_more_white_24dp);
}
@Override
public void onPanelMovementEnded(boolean expanded) {
}
});
}
}
|
Fix : delete command call badly formatted in handler | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Handler(object):
def __init__(self, db):
# Each handlers is formatted following
# the pattern : [ command,
# default return value,
# raised error ]
self.handles = {
'GET': (db.Get, "", KeyError),
'PUT': (db.Put, "True", TypeError),
'DELETE': (db.Delete, ""),
}
def command(self, message):
op_code = message.op_code
args = message.data
if op_code in self.handles:
if len(self.handles[op_code]) == 2:
value = self.handles[op_code][0](*args)
else:
# FIXME
# global except catching is a total
# performance killer. Should enhance
# the handles attributes to link possible
# exceptions with leveldb methods.
try:
value = self.handles[op_code][0](*args)
except self.handles[op_code][2]:
return ""
else:
raise KeyError("op_code not handle")
return value if value else self.handles[op_code][1]
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Handler(object):
def __init__(self, db):
# Each handlers is formatted following
# the pattern : [ command,
# default return value,
# raised error ]
self.handles = {
'GET': (db.Get, "", KeyError),
'PUT': (db.Put, "True", TypeError),
'DELETE': (db.Delete, ""),
}
def command(self, message):
op_code = message.op_code
args = message.data
if op_code in self.handles:
if len(self.handles[op_code]) == 2:
return self.handles[op_code](*args)
else:
# FIXME
# global except catching is a total
# performance killer. Should enhance
# the handles attributes to link possible
# exceptions with leveldb methods.
try:
value = self.handles[op_code][0](*args)
except self.handles[op_code][2]:
return ""
else:
raise KeyError("op_code not handle")
return value if value else self.handles[op_code][1]
|
Fix for the date of birth label | const _ = require('lodash');
const countries = require('../../../config/countries');
module.exports = {
'expiry-year': {
labelClassName: 'form-label',
formatter: 'removehyphens',
validate: [
'numeric',
'required'
]
},
'expiry-month': {
labelClassName: 'form-label',
formatter: 'removehyphens',
validate: [
'numeric',
'required'
]
},
'age-day': {
labelClassName: 'form-label',
formatter: 'removehyphens',
validate: [
'numeric',
'required'
]
},
'age-year': {
labelClassName: 'form-label',
formatter: 'removehyphens',
validate: [
'numeric',
'required'
]
},
'age-month': {
labelClassName: 'form-label',
formatter: 'removehyphens',
validate: [
'numeric',
'required'
]
},
'issuing-authority': {
legend: {
value: 'Which is your passport issuing authority?',
className: 'visuallyhidden'
},
options: [
{value: 'UKPA', label: 'UKPA'},
{value: 'UKPS', label: 'UKPS'},
{value: 'IPS', label: 'IPS'},
{value: 'Other', label: 'Other'}
],
validate: [
'required'
]
}
};
| const _ = require('lodash');
const countries = require('../../../config/countries');
module.exports = {
'expiry-year': {
labelClassName: 'form-label',
formatter: 'removehyphens',
validate: [
'numeric',
'required'
]
},
'expiry-month': {
labelClassName: 'form-label',
formatter: 'removehyphens',
validate: [
'numeric',
'required'
]
},
'age-year': {
labelClassName: 'form-label',
formatter: 'removehyphens',
validate: [
'numeric',
'required'
]
},
'age-month': {
labelClassName: 'form-label',
formatter: 'removehyphens',
validate: [
'numeric',
'required'
]
},
'issuing-authority': {
legend: {
value: 'Which is your passport issuing authority?',
className: 'visuallyhidden'
},
options: [
{value: 'UKPA', label: 'UKPA'},
{value: 'UKPS', label: 'UKPS'},
{value: 'IPS', label: 'IPS'},
{value: 'Other', label: 'Other'}
],
validate: [
'required'
]
}
};
|
Adjust for new IATI Updates API; don't have to page through results |
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3.0
import json
import urllib2
from iatidq import db
import models
def add_test_status(package_id, status_id):
with db.session.begin():
pstatus = models.PackageStatus()
pstatus.package_id = package_id
pstatus.status = status_id
db.session.add(pstatus)
def clear_revisions():
with db.session.begin():
for pkg in models.Package.query.filter(
models.Package.package_revision_id!=None,
models.Package.active == True
).all():
pkg.package_revision_id = None
db.session.add(pkg)
def packages_from_registry(registry_url):
#offset = 0
#while True:
#data = urllib2.urlopen(registry_url % (offset), timeout=60).read()
#print (registry_url % (offset))
data = urllib2.urlopen(registry_url, timeout=60).read()
print registry_url
data = json.loads(data)
#if len(data["results"]) < 1:
# break
for pkg in data["data"]:
yield pkg
#offset += 1000
|
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3.0
import json
import urllib2
from iatidq import db
import models
def add_test_status(package_id, status_id):
with db.session.begin():
pstatus = models.PackageStatus()
pstatus.package_id = package_id
pstatus.status = status_id
db.session.add(pstatus)
def clear_revisions():
with db.session.begin():
for pkg in models.Package.query.filter(
models.Package.package_revision_id!=None,
models.Package.active == True
).all():
pkg.package_revision_id = None
db.session.add(pkg)
def packages_from_registry(registry_url):
offset = 0
while True:
data = urllib2.urlopen(registry_url % (offset), timeout=60).read()
print (registry_url % (offset))
data = json.loads(data)
if len(data["results"]) < 1:
break
for pkg in data["results"]:
yield pkg
offset += 1000
|
Fix a minor bootstrap UI issue | var getThat = {};
getThat.controller = function() {
};
getThat.header = function() {
return m('.row', [
m('.col-md-10', [
m('.jumbotron', [
m('h1', [
m('a[href="//getthat.email"]', 'Get That Email')
])
])
])
]);
};
getThat.emailSelectBtn = function() {
return m('button.btn.btn-default.dropdown-toggle[type="button"][data-toggle="dropdown"][style="border-bottom-right-radius: 0px;border-top-right-radius: 0px"]', [
'Select a Domain ',
m('span.caret'),
]);
};
getThat.emailSelectDropdown = function() {
return m('ul.dropdown-menu[role="menu"]', [
m('li', [
m('a[href="#"]', 'Test')
])
]);
};
getThat.input = function() {
return m('.row', [
m('.col-md-10', [
m('.input-group', [
m('input.form-control[type="text"'),
m('.input-group-btn', [
this.emailSelectBtn(),
this.emailSelectDropdown(),
m('button.btn.btn-success[type="button"]', [
m('span.glyphicon.glyphicon-credit-card'),
' Get It!'
])
])
])
])
]);
};
getThat.view = function() {
return m('.container', [
this.header(),
this.input()
]);
};
//initialize
m.module(document.body, getThat);
| var getThat = {};
getThat.controller = function() {
};
getThat.header = function() {
return m('.row', [
m('.col-md-10', [
m('.jumbotron', [
m('h1', [
m('a[href="//getthat.email"]', 'Get That Email')
])
])
])
]);
};
getThat.emailSelectBtn = function() {
return m('button.btn.btn-default.dropdown-toggle[type="button"][data-toggle="dropdown"]', [
'Select a Domain ',
m('span.caret'),
]);
};
getThat.emailSelectDropdown = function() {
return m('ul.dropdown-menu[role="menu"]', [
m('li', [
m('a[href="#"]', 'Test')
])
]);
};
getThat.input = function() {
return m('.row', [
m('.col-md-10', [
m('.input-group', [
m('input.form-control[type="text"'),
m('.input-group-btn', [
this.emailSelectBtn(),
this.emailSelectDropdown(),
m('button.btn.btn-success[type="button"]', [
m('span.glyphicon.glyphicon-credit-card'),
' Get It!'
])
])
])
])
]);
};
getThat.view = function() {
return m('.container', [
this.header(),
this.input()
]);
};
//initialize
m.module(document.body, getThat);
|
Add getInstance method for symfony kernel
this allows us using symfony services everywhere. | <?php
use Symfony\Component\HttpKernel\Kernel;
use Doctrine\Common\Annotations\AnnotationRegistry;
abstract class Kwf_SymfonyKernel extends Kernel
{
private static $_instance;
public function __construct()
{
$env = Kwf_Config::getValue('symfony.environment');
if (in_array($env, array('test', 'dev'))) {
$environment = $env;
$debug = true;
//Debug::enable();
} else {
$environment = 'prod';
$debug = false;
}
parent::__construct($environment, $debug);
AnnotationRegistry::registerLoader(array('Kwf_Loader', 'loadClass'));
}
public function locateResource($name, $dir = null, $first = true)
{
if (substr($name, 0, 4) == '@Kwc') {
if (!$first) throw new \Kwf_Exception_NotYetImplemented();
$componentClass = substr($name, 4, strpos($name, '/')-4);
$name = substr($name, strpos($name, '/')+1);
$paths = \Kwc_Abstract::getSetting($componentClass, 'parentFilePaths');
foreach ($paths as $path=>$cls) {
if (file_exists($path.'/'.$name)) {
return $path.'/'.$name;
}
}
throw new \Kwf_Exception();
} else {
return parent::locateResource($name, $dir, $first);
}
}
/**
* Don't use this method in Symfony context
*/
public static function getInstance()
{
if (!isset(self::$_instance)) {
$cls = Kwf_Config::getValue('symfony.kernelClass');
self::$_instance = new $cls();
self::$_instance->boot(); //make sure it is booted (won't do it twice)
}
return self::$_instance;
}
}
| <?php
use Symfony\Component\HttpKernel\Kernel;
use Doctrine\Common\Annotations\AnnotationRegistry;
abstract class Kwf_SymfonyKernel extends Kernel
{
public function __construct()
{
$env = Kwf_Config::getValue('symfony.environment');
if (in_array($env, array('test', 'dev'))) {
$environment = $env;
$debug = true;
//Debug::enable();
} else {
$environment = 'prod';
$debug = false;
}
parent::__construct($environment, $debug);
AnnotationRegistry::registerLoader(array('Kwf_Loader', 'loadClass'));
}
public function locateResource($name, $dir = null, $first = true)
{
if (substr($name, 0, 4) == '@Kwc') {
if (!$first) throw new \Kwf_Exception_NotYetImplemented();
$componentClass = substr($name, 4, strpos($name, '/')-4);
$name = substr($name, strpos($name, '/')+1);
$paths = \Kwc_Abstract::getSetting($componentClass, 'parentFilePaths');
foreach ($paths as $path=>$cls) {
if (file_exists($path.'/'.$name)) {
return $path.'/'.$name;
}
}
throw new \Kwf_Exception();
} else {
return parent::locateResource($name, $dir, $first);
}
}
}
|
Use importlib.import_module instead of __import__ | """
:py:mod:`pymco.utils`
---------------------
python-mcollective utils.
"""
import importlib
def import_class(import_path):
"""Import a class based on given dotted import path string.
It just splits the import path in order to geth the module and class names,
then it just calls to :py:func:`__import__` with the module name and
:py:func:`getattr` with the module and the class name.
Params:
``import_path``: A dotted import path string.
Returns:
``class``: The class once imported.
Raises:
:py:exc:`ImportError`
"""
parts = import_path.split('.')
mod_str, klass_str = '.'.join(parts[:-1]), parts[-1]
try:
mod = importlib.import_module(mod_str)
return getattr(mod, klass_str)
except (AttributeError, ValueError):
raise ImportError('Unable to import {klass} from module {mod}'.format(
klass=klass_str,
mod=mod_str,
))
def import_object(import_path, *args, **kwargs):
"""Import a class and instantiate it.
Uses :py:func:`import_class` in order to import the given class by its
import path and instantiate it using given positional and keyword
arguments.
Params:
``import_path``: Same argument as :py:func:`import_class`.
``args``: Positional arguments for object instantiation.
``kwargs``: Keyword arguments for object instantiation.
"""
return import_class(import_path)(*args, **kwargs)
| """
:py:mod:`pymco.utils`
---------------------
python-mcollective utils.
"""
def import_class(import_path):
"""Import a class based on given dotted import path string.
It just splits the import path in order to geth the module and class names,
then it just calls to :py:func:`__import__` with the module name and
:py:func:`getattr` with the module and the class name.
Params:
``import_path``: A dotted import path string.
Returns:
``class``: The class once imported.
Raises:
:py:exc:`ImportError`
"""
parts = import_path.split('.')
mod_str, klass_str = '.'.join(parts[:-1]), parts[-1]
try:
mod = __import__(mod_str)
return getattr(mod, klass_str)
except (AttributeError, ValueError):
raise ImportError('Unable to import {klass} from module {mod}'.format(
klass=klass_str,
mod=mod_str,
))
def import_object(import_path, *args, **kwargs):
"""Import a class and instantiate it.
Uses :py:func:`import_class` in order to import the given class by its
import path and instantiate it using given positional and keyword
arguments.
Params:
``import_path``: Same argument as :py:func:`import_class`.
``args``: Positional arguments for object instantiation.
``kwargs``: Keyword arguments for object instantiation.
"""
return import_class(import_path)(*args, **kwargs)
|
Set AtsMode to 'disabled', if no apply link is found. | <?php
/**
* @filesource
* @copyright (c) 2013 - 2017 Cross Solution (http://cross-solution.de)
* @license MIT
* @author Miroslav Fedeleš <[email protected]>
* @since 0.30
*/
namespace SimpleImport\Hydrator;
use Zend\Hydrator\HydrationInterface;
use Jobs\Entity\AtsMode;
class JobHydrator implements HydrationInterface
{
/**
* {@inheritDoc}
* @see \Zend\Hydrator\HydrationInterface::hydrate()
*/
public function hydrate(array $data, $job)
{
/** @var \Jobs\Entity\Job $job */
$job->setTitle($data['title'])
->setLocation($data['location'])
->setCompany($data['company'])
->setReference($data['reference'])
->setContactEmail($data['contactEmail'])
->setLanguage($data['language'])
->setLink($data['link'])
->setDatePublishStart($data['datePublishStart'])
->setLogoRef($data['logoRef']);
if ($data['datePublishEnd']) {
$job->setDatePublishEnd($data['datePublishEnd']);
}
if ($data['linkApply']) {
$job->setAtsMode(new AtsMode(AtsMode::MODE_URI, $data['linkApply']));
} else {
$job->setAtsMode(new AtsMode(AtsMode::MODE_NONE));
}
// TODO: implement classifications
}
}
| <?php
/**
* @filesource
* @copyright (c) 2013 - 2017 Cross Solution (http://cross-solution.de)
* @license MIT
* @author Miroslav Fedeleš <[email protected]>
* @since 0.30
*/
namespace SimpleImport\Hydrator;
use Zend\Hydrator\HydrationInterface;
use Jobs\Entity\AtsMode;
class JobHydrator implements HydrationInterface
{
/**
* {@inheritDoc}
* @see \Zend\Hydrator\HydrationInterface::hydrate()
*/
public function hydrate(array $data, $job)
{
/** @var \Jobs\Entity\Job $job */
$job->setTitle($data['title'])
->setLocation($data['location'])
->setCompany($data['company'])
->setReference($data['reference'])
->setContactEmail($data['contactEmail'])
->setLanguage($data['language'])
->setLink($data['link'])
->setDatePublishStart($data['datePublishStart'])
->setLogoRef($data['logoRef']);
if ($data['datePublishEnd']) {
$job->setDatePublishEnd($data['datePublishEnd']);
}
if ($data['linkApply']) {
$job->setAtsMode(new AtsMode(AtsMode::MODE_URI, $data['linkApply']));
}
// TODO: implement classifications
}
} |
Refactor to use promises for social media service responses. | module.exports = (function(){
// GET /users/:id/media?lat=<LAT>&lng=<LNG>&time=<TIME>
return function* collection(id) {
var Q = require('q');
var TwitterManager = require('../media/twitter');
var InstagramManager = require('../media/instagram');
// Twitter Requests
var twitterDef = Q.defer();
var twitterGranuals = twitterDef.promise
.then(TwitterManager.search);
// Instagram Requests
var instagramDef = Q.defer();
var instagramGranuals = instagramDef.promise
.then(InstagramManager.search);
// Flickr Requests
// var FlickrManager = require('../media/flickr');
// var flickrGranuals = yield FlickrManager.search(this.request.url);
// Creating a universal capsul object
var capsul = {
"user_id": id,
"latitude": require('../../helpers').paramsForUrl(this.request.url).lat,
"longitude": require('../../helpers').paramsForUrl(this.request.url).lng,
"timestamp": require('../../helpers').paramsForUrl(this.request.url).time,
"data": []
}
twitterDef.resolve(this.request.url)
instagramDef.resolve(this.request.url)
capsul.data.push(twitterGranuals);
capsul.data.push(instagramGranuals);
this.body = yield capsul;
}
})(); | module.exports = (function(){
// GET /users/:id/media?lat=<LAT>&lng=<LNG>&time=<TIME>
return function* collection(id) {
// Twitter Requests
var twitterDef = require('q').defer()
var TwitterManager = require('../media/twitter');
var twitterGranuals = twitterDef.promise.then(TwitterManager.search);
// var twitterDef = require('q').defer()
// var instagramDef = require('q').defer()
var InstagramManager = require('../media/instagram');
// var instagramGranuals = instagramDef.promise.then(InstagramManager.search);
var instagramGranuals = InstagramManager.search(this.request.url);
// Flickr Requests
// var FlickrManager = require('../media/flickr');
// var flickrGranuals = yield FlickrManager.search(this.request.url);
// Creating a universal capsul object
var capsul = {
"user_id": id,
"latitude": require('../../helpers').paramsForUrl(this.request.url).lat,
"longitude": require('../../helpers').paramsForUrl(this.request.url).lng,
"timestamp": require('../../helpers').paramsForUrl(this.request.url).time,
"data": []
}
// def.resolve(this.request.url)
// var instaGranuals = def.promise.then(InstagramManager.search);
// capsul.data.push(instagramGranuals)
twitterDef.resolve(this.request.url)
// instagramDef.resolve(this.request.url)
capsul.data.push(twitterGranuals);
capsul.data.push(instagramGranuals)
this.body = yield capsul;
}
})(); |
Fix layer model serialize method to use new organization | cinema.models.LayerModel = Backbone.Model.extend({
constructor: function (defaults, options) {
Backbone.Model.call(this, {}, options);
if (typeof defaults === 'string') {
this.setFromString(defaults);
} else if (defaults) {
this.set('state', defaults);
}
},
/**
* Convert an object that maps layer identifiers to color-by values into
* a single string that is consumable by other parts of the application.
*/
serialize: function () {
var query = '';
_.each(this.get('state'), function (v, k) {
query += k + v;
});
return query;
},
/**
* Convert a query string to an object that maps layer identifiers to
* their color-by value. The query string is a sequence of two-character
* pairs, where the first character identifies the layer ID and the second
* character identifies which field it should be colored by.
*
* The query string is then saved to the model.
*/
unserialize: function (query) {
var obj = {};
if (query.length % 2) {
return console.error('Query string "' + query + '" has odd length.');
}
for (var i = 0; i < query.length; i += 2) {
obj[query[i]] = query[i + 1];
}
return obj;
},
/**
* Set the layers by a "query string".
*/
setFromString: function (query) {
var obj = this.unserialize(query);
this.set('state', obj);
}
});
| cinema.models.LayerModel = Backbone.Model.extend({
constructor: function (defaults, options) {
Backbone.Model.call(this, {}, options);
if (typeof defaults === 'string') {
this.setFromString(defaults);
} else if (defaults) {
this.set('state', defaults);
}
},
/**
* Convert an object that maps layer identifiers to color-by values into
* a single string that is consumable by other parts of the application.
*/
serialize: function () {
var query = '';
_.each(this.attributes, function (v, k) {
query += k + v;
});
return query;
},
/**
* Convert a query string to an object that maps layer identifiers to
* their color-by value. The query string is a sequence of two-character
* pairs, where the first character identifies the layer ID and the second
* character identifies which field it should be colored by.
*
* The query string is then saved to the model.
*/
unserialize: function (query) {
var obj = {};
if (query.length % 2) {
return console.error('Query string "' + query + '" has odd length.');
}
for (var i = 0; i < query.length; i += 2) {
obj[query[i]] = query[i + 1];
}
return obj;
},
/**
* Set the layers by a "query string".
*/
setFromString: function (query) {
var obj = this.unserialize(query);
this.set('state', obj);
}
});
|
Add missing api key in product picker.
Fixes #6185 | $.fn.productAutocomplete = function (options) {
'use strict';
// Default options
options = options || {};
var multiple = typeof(options.multiple) !== 'undefined' ? options.multiple : true;
this.select2({
minimumInputLength: 3,
multiple: multiple,
initSelection: function (element, callback) {
$.get(Spree.routes.product_search, {
ids: element.val().split(','),
token: Spree.api_key
}, function (data) {
callback(multiple ? data.products : data.products[0]);
});
},
ajax: {
url: Spree.routes.product_search,
datatype: 'json',
data: function (term, page) {
return {
q: {
name_cont: term,
sku_cont: term
},
m: 'OR',
token: Spree.api_key
};
},
results: function (data, page) {
var products = data.products ? data.products : [];
return {
results: products
};
}
},
formatResult: function (product) {
return product.name;
},
formatSelection: function (product) {
return product.name;
}
});
};
$(document).ready(function () {
$('.product_picker').productAutocomplete();
});
| $.fn.productAutocomplete = function (options) {
'use strict';
// Default options
options = options || {};
var multiple = typeof(options.multiple) !== 'undefined' ? options.multiple : true;
this.select2({
minimumInputLength: 3,
multiple: multiple,
initSelection: function (element, callback) {
$.get(Spree.routes.product_search, {
ids: element.val().split(',')
}, function (data) {
callback(multiple ? data.products : data.products[0]);
});
},
ajax: {
url: Spree.routes.product_search,
datatype: 'json',
data: function (term, page) {
return {
q: {
name_cont: term,
sku_cont: term
},
m: 'OR',
token: Spree.api_key
};
},
results: function (data, page) {
var products = data.products ? data.products : [];
return {
results: products
};
}
},
formatResult: function (product) {
return product.name;
},
formatSelection: function (product) {
return product.name;
}
});
};
$(document).ready(function () {
$('.product_picker').productAutocomplete();
});
|
Make sure content app works when there are no variants | (function () {
'use strict';
function RelatedLinksAppController($scope) {
var vm = this;
vm.relations = $scope.model.viewModel;
var currentVariant = _.find($scope.content.variants, function (v) { return v.active });
if (currentVariant.language) {
vm.culture = currentVariant.language.culture;
vm.cultureRelations = _.filter(vm.relations,
function(r) { return r.Culture.toLowerCase() === vm.culture.toLowerCase() });
} else {
vm.cultureRelations = vm.relations;
}
vm.ungrouped = [];
for (var i = 0; i < vm.cultureRelations.length; i++) {
var relation = vm.cultureRelations[i];
for (var j = 0; j < relation.Properties.length; j++) {
vm.ungrouped.push({
id: relation.Id,
name: relation.Name,
propertyname: relation.Properties[j].PropertyName,
tabname: relation.Properties[j].TabName
});
}
}
}
angular.module('umbraco').controller('Our.Umbraco.Nexu.Controllers.RelatedLinksAppController',
[
'$scope',
'editorState',
'localizationService',
RelatedLinksAppController
]);
})(); | (function () {
'use strict';
function RelatedLinksAppController($scope) {
var vm = this;
vm.relations = $scope.model.viewModel;
var currentVariant = _.find($scope.content.variants, function(v) { return v.active });
vm.culture = currentVariant.language.culture;
vm.cultureRelations = _.filter(vm.relations, function (r) { return r.Culture.toLowerCase() === vm.culture.toLowerCase() });
vm.ungrouped = [];
for (var i = 0; i < vm.cultureRelations.length; i++) {
var relation = vm.cultureRelations[i];
for (var j = 0; j < relation.Properties.length; j++) {
vm.ungrouped.push({
id: relation.Id,
name: relation.Name,
propertyname: relation.Properties[j].PropertyName,
tabname: relation.Properties[j].TabName
});
}
}
}
angular.module('umbraco').controller('Our.Umbraco.Nexu.Controllers.RelatedLinksAppController',
[
'$scope',
'editorState',
'localizationService',
RelatedLinksAppController
]);
})(); |
Add `route_strategy` to Demo conf | <?php
$debug = true;
return [
'debug' => $debug,
'kernel' => [
'root' => realpath(__DIR__),
],
'databases' => [
'write' => [
'driver' => 'mysql',
'host' => '127.0.0.1',
'name' => 'simple_x',
'user' => 'root',
'password' => null,
],
],
'twig' => [
'paths' => [
'Base' => '/View',
'Welcome' => '/../src/View',
],
'options' => [
'debug' => false,
'cache' => realpath(__DIR__.'/../var/Cache/Twig'),
'strict_variables' => $debug,
'auto_reload' => true,
'autoescape' => true,
],
],
'routes' => [
'DemoBundle' => require realpath(__DIR__ . '/../src/Routing/Routing.php'),
],
'route_strategy' => \Colonel\UriRequestStrategy::class,
'services' => [
'di' => require realpath(__DIR__ . '/Service.php'),
],
'service_providers' => [
\Demo\Application\DemoServiceProvider::class => new \Demo\Application\DemoServiceProvider(),
]
]; | <?php
$debug = true;
return [
'debug' => $debug,
'kernel' => [
'root' => realpath(__DIR__),
],
'databases' => [
'write' => [
'driver' => 'mysql',
'host' => '127.0.0.1',
'name' => 'simple_x',
'user' => 'root',
'password' => null,
],
],
'twig' => [
'paths' => [
'Base' => '/View',
'Welcome' => '/../src/View',
],
'options' => [
'debug' => false,
'cache' => realpath(__DIR__.'/../var/Cache/Twig'),
'strict_variables' => $debug,
'auto_reload' => true,
'autoescape' => true,
],
],
'routes' => [
'DemoBundle' => require realpath(__DIR__ . '/../src/Routing/Routing.php'),
],
'services' => [
'di' => require realpath(__DIR__ . '/Service.php'),
],
'service_providers' => [
\Demo\Application\DemoServiceProvider::class => new \Demo\Application\DemoServiceProvider(),
]
]; |
Update grunt configuration for the embedded web server | module.exports = function (grunt) {
'use strict';
grunt.loadNpmTasks('grunt-php');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.initConfig({
php: {
dist: {
options: {
keepalive: true,
open: true,
port: 8085,
router: "index.php"
}
}
},
less: {
development: {
options: {
cleancss: true,
report: 'min'
},
files: {
"resources/themes/daux-blue/css/theme.min.css": "resources/themes/daux-blue/less/theme.less",
"resources/themes/daux-green/css/theme.min.css": "resources/themes/daux-green/less/theme.less",
"resources/themes/daux-navy/css/theme.min.css": "resources/themes/daux-navy/less/theme.less",
"resources/themes/daux-red/css/theme.min.css": "resources/themes/daux-red/less/theme.less"
}
}
},
watch: {
scripts: {
files: ['templates/default/theme/**/*.less'],
tasks: ['less'],
options: {
nospawn: true
},
},
},
});
//grunt.registerTask('default', ['less', 'watch']);
grunt.registerTask('default', ['php']);
};
| module.exports = function (grunt) {
'use strict';
grunt.loadNpmTasks('grunt-php');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.initConfig({
php: {
dist: {
options: {
keepalive: true,
open: true,
port: 8085
}
}
},
less: {
development: {
options: {
cleancss: true,
report: 'min'
},
files: {
"resources/themes/daux-blue/css/theme.min.css": "resources/themes/daux-blue/less/theme.less",
"resources/themes/daux-green/css/theme.min.css": "resources/themes/daux-green/less/theme.less",
"resources/themes/daux-navy/css/theme.min.css": "resources/themes/daux-navy/less/theme.less",
"resources/themes/daux-red/css/theme.min.css": "resources/themes/daux-red/less/theme.less"
}
}
},
watch: {
scripts: {
files: ['templates/default/theme/**/*.less'],
tasks: ['less'],
options: {
nospawn: true
},
},
},
});
//grunt.registerTask('default', ['less', 'watch']);
grunt.registerTask('default', ['php']);
};
|
Use proper npm ui-bootstrap dependency | var webpack = require('webpack');
var ejs = require('ejs');
var MIN = process.argv.indexOf('-p') > -1;
function getBanner() {
var pkg = require('./bower.json');
var banner = ['/**',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @link <%= pkg.homepage %>',
' * @license <%= pkg.license %>',
' */',
''].join('\n');
return ejs.render(banner, {pkg: pkg});
}
module.exports = {
entry: __dirname + '/src/angular-bootstrap-confirm.js',
output: {
path: __dirname + '/dist',
filename: MIN ? 'angular-bootstrap-confirm.min.js' : 'angular-bootstrap-confirm.js',
libraryTarget: 'umd'
},
externals: {
angular: 'angular',
'angular-sanitize': 'angular-sanitize',
'./ui-bootstrap-position': 'angular-ui-bootstrap'
},
devtool: MIN ? 'source-map' : null,
module: {
preLoaders: [{
test: /.*\.js$/,
loaders: ['eslint'],
exclude: /node_modules/
}],
loaders: [{
test: /.*\.js$/,
loaders: ['ng-annotate'],
exclude: /node_modules/
}]
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.BannerPlugin(getBanner(), {
raw: true,
entryOnly: true
})
]
};
| var webpack = require('webpack');
var ejs = require('ejs');
var MIN = process.argv.indexOf('-p') > -1;
function getBanner() {
var pkg = require('./bower.json');
var banner = ['/**',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @link <%= pkg.homepage %>',
' * @license <%= pkg.license %>',
' */',
''].join('\n');
return ejs.render(banner, {pkg: pkg});
}
module.exports = {
entry: __dirname + '/src/angular-bootstrap-confirm.js',
output: {
path: __dirname + '/dist',
filename: MIN ? 'angular-bootstrap-confirm.min.js' : 'angular-bootstrap-confirm.js',
libraryTarget: 'umd'
},
externals: {
angular: 'angular',
'angular-sanitize': 'angular-sanitize',
'./ui-bootstrap-position': 'angular-bootstrap'
},
devtool: MIN ? 'source-map' : null,
module: {
preLoaders: [{
test: /.*\.js$/,
loaders: ['eslint'],
exclude: /node_modules/
}],
loaders: [{
test: /.*\.js$/,
loaders: ['ng-annotate'],
exclude: /node_modules/
}]
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.BannerPlugin(getBanner(), {
raw: true,
entryOnly: true
})
]
};
|
newuser: Add some explanation as to what to do with the output. | import logging
import getpass
from wikked.bcryptfallback import generate_password_hash
from wikked.commands.base import WikkedCommand, register_command
logger = logging.getLogger(__name__)
@register_command
class UsersCommand(WikkedCommand):
def __init__(self):
super(UsersCommand, self).__init__()
self.name = 'users'
self.description = "Lists users of this wiki."
def setupParser(self, parser):
pass
def run(self, ctx):
logger.info("Users:")
for user in ctx.wiki.auth.getUsers():
logger.info(" - " + user.username)
@register_command
class NewUserCommand(WikkedCommand):
def __init__(self):
super(NewUserCommand, self).__init__()
self.name = 'newuser'
self.description = (
"Generates the entry for a new user so you can "
"copy/paste it in your `.wikirc`.")
def setupParser(self, parser):
parser.add_argument('username', nargs=1)
parser.add_argument('password', nargs='?')
def run(self, ctx):
username = ctx.args.username
password = ctx.args.password or getpass.getpass('Password: ')
password = generate_password_hash(password)
logger.info("%s = %s" % (username[0], password))
logger.info("")
logger.info("(copy this into your .wikirc file)")
| import logging
import getpass
from wikked.bcryptfallback import generate_password_hash
from wikked.commands.base import WikkedCommand, register_command
logger = logging.getLogger(__name__)
@register_command
class UsersCommand(WikkedCommand):
def __init__(self):
super(UsersCommand, self).__init__()
self.name = 'users'
self.description = "Lists users of this wiki."
def setupParser(self, parser):
pass
def run(self, ctx):
logger.info("Users:")
for user in ctx.wiki.auth.getUsers():
logger.info(" - " + user.username)
@register_command
class NewUserCommand(WikkedCommand):
def __init__(self):
super(NewUserCommand, self).__init__()
self.name = 'newuser'
self.description = (
"Generates the entry for a new user so you can "
"copy/paste it in your `.wikirc`.")
def setupParser(self, parser):
parser.add_argument('username', nargs=1)
parser.add_argument('password', nargs='?')
def run(self, ctx):
username = ctx.args.username
password = ctx.args.password or getpass.getpass('Password: ')
password = generate_password_hash(password)
logger.info("%s = %s" % (username[0], password))
|
Check if an anetry already exists before adding it | """
Module for adding new entries
"""
import re
import api
import conf
import json
def add(target_url, title=None, star=False, read=False):
conf.load()
valid_url = False
if not re.compile("(?i)https?:\\/\\/.+").match(target_url):
for protocol in "https://", "http://":
if api.is_valid_url("{0}{1}".format(protocol, target_url)):
target_url = "{0}{1}".format(protocol, target_url)
valid_url = True
break
else:
valid_url = api.is_valid_url(target_url)
if not valid_url:
print("Error: Invalid url to add.")
print()
exit(-1)
try:
request = api.api_entry_exists(target_url)
if(request.hasError()):
print("Error: {0} - {1}".format(request.error_text,
request.error_description))
exit(-1)
response = json.loads(request.response)
print(response['exists'])
if response['exists'] == True:
print("The url was already saved.")
exit(0)
except api.OAuthException as e:
print("Error: {0}".format(e.text))
print()
exit(-1)
try:
request = api.api_add_entry(target_url, title, star, read)
if(request.hasError()):
print("Error: {0} - {1}".format(request.error_text,
request.error_description))
exit(-1)
else:
print("Entry successfully added")
exit(0)
except api.OAuthException as e:
print("Error: {0}".format(e.text))
print()
exit(-1)
| """
Module for adding new entries
"""
import re
import api
import conf
def add(target_url, title=None, star=False, read=False):
conf.load()
valid_url = False
if not re.compile("(?i)https?:\\/\\/.+").match(target_url):
for protocol in "https://", "http://":
if api.is_valid_url("{0}{1}".format(protocol, target_url)):
target_url = "{0}{1}".format(protocol, target_url)
valid_url = True
break
else:
valid_url = api.is_valid_url(target_url)
if not valid_url:
print("Error: Invalid url to add.")
print()
exit(-1)
try:
request = api.api_add_entry(target_url, title, star, read)
if(request.hasError()):
print("Error: {0} - {1}".format(request.error_text,
request.error_description))
exit(-1)
else:
print("Entry successfully added")
exit(0)
except api.OAuthException as e:
print("Error: {0}".format(e.text))
print()
exit(-1)
|
Change production build for input/output files | module.exports = function(grunt) {
'use strict';
grunt.initConfig({
less: {
development: {
options: {
paths: ['velvet']
},
files: {
'build/style.css': 'velvet/velvet.less'
}
},
production: {
options: {
paths: ['less'],
yuicompress: true
},
files: {
'build/style.css': 'velvet/velvet.less'
}
}
},
copy: {
options: {
processContentExcluded: ['**/*.{png,gif}']
},
main: {
files: [
{ expand: true
, cwd: 'velvet/'
, src: ['*.{png,gif}']
, dest: 'build/'
}
]
}
},
watch: {
files: 'velvet/*.less',
tasks: ['less:development']
}
});
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['less:development', 'copy']);
grunt.registerTask('release', ['less:production', 'copy']);
};
| module.exports = function(grunt) {
'use strict';
grunt.initConfig({
less: {
development: {
options: {
paths: ['velvet']
},
files: {
'build/style.css': 'velvet/velvet.less'
}
},
production: {
options: {
paths: ['less'],
yuicompress: true
},
files: {
'css/style.css': 'less/main.less'
}
}
},
copy: {
options: {
processContentExcluded: ['**/*.{png,gif}']
},
main: {
files: [
{ expand: true
, cwd: 'velvet/'
, src: ['*.{png,gif}']
, dest: 'build/'
}
]
}
},
watch: {
files: 'velvet/*.less',
tasks: ['less:development']
}
});
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['less:development', 'copy']);
grunt.registerTask('release', ['less:production', 'copy']);
};
|
Return a list for objects on pb widget | import json
from django import forms
from .models import PublicBody
class PublicBodySelect(forms.Widget):
input_type = "text"
template_name = 'publicbody/_chooser.html'
initial_search = None
class Media:
extend = False
js = ('js/publicbody.js',)
def set_initial_search(self, search):
self.initial_search = search
def get_context(self, name, value=None, attrs=None):
pb, pb_desc = None, None
if value is not None:
try:
pb = PublicBody.objects.get(pk=int(value))
pb_desc = pb.get_label()
except (ValueError, PublicBody.DoesNotExist):
pass
context = super(PublicBodySelect, self).get_context(name, value, attrs)
context['widget'].update({
'value_label': pb_desc,
'search': self.initial_search,
'publicbody': pb,
'json': json.dumps({
'fields': {
name: {
'value': value,
'objects': [pb.as_data()] if pb is not None else None
}
}
})
})
return context
| import json
from django import forms
from .models import PublicBody
class PublicBodySelect(forms.Widget):
input_type = "text"
template_name = 'publicbody/_chooser.html'
initial_search = None
class Media:
extend = False
js = ('js/publicbody.js',)
def set_initial_search(self, search):
self.initial_search = search
def get_context(self, name, value=None, attrs=None):
pb, pb_desc = None, None
if value is not None:
try:
pb = PublicBody.objects.get(pk=int(value))
pb_desc = pb.get_label()
except (ValueError, PublicBody.DoesNotExist):
pass
context = super(PublicBodySelect, self).get_context(name, value, attrs)
context['widget'].update({
'value_label': pb_desc,
'search': self.initial_search,
'publicbody': pb,
'json': json.dumps({
'fields': {
name: {
'value': value,
'objects': pb.as_data() if pb is not None else None
}
}
})
})
return context
|
FIX: Make watermark robust if __version__ attribute is missing. | from __future__ import (absolute_import, division, print_function,
unicode_literals)
from collections import OrderedDict
import importlib
import sys
import six
def watermark():
"""
Give the version of each of the dependencies -- useful for bug reports.
Returns
-------
result : dict
mapping the name of each package to its version string or, if an
optional dependency is not installed, None
"""
packages = ['six', 'numpy', 'scipy', 'matplotlib', 'pandas', 'pims',
'pyyaml', 'metadatastore', 'filestore',
'channelarchiver', 'bubblegum']
result = OrderedDict()
for package_name in packages:
try:
package = importlib.import_module(package_name)
except ImportError:
result[package_name] = None
else:
try:
version = package.__version__
except AttributeError as err:
version = "FAILED TO DETECT: {0}".format(err)
result[package_name] = version
# enaml provides its version differently
try:
import enaml
except ImportError:
result['enaml'] = None
else:
from enaml.version import version_info
result['enaml'] = _make_version_string(version_info)
# ...as does Python
version_info = sys.version_info
result['python'] = _make_version_string(version_info)
return result
def _make_version_string(version_info):
version_string = '.'.join(map(str, [version_info[0], version_info[1],
version_info[2]]))
return version_string
| from __future__ import (absolute_import, division, print_function,
unicode_literals)
from collections import OrderedDict
import importlib
import six
def watermark():
"""
Give the version of each of the dependencies -- useful for bug reports.
Returns
-------
result : dict
mapping the name of each package to its version string or, if an
optional dependency is not installed, None
"""
packages = ['six', 'numpy', 'scipy', 'matplotlib', 'pandas', 'pims',
'pyyaml', 'metadatastore', 'filestore',
'channelarchiver', 'bubblegum']
result = OrderedDict()
for package_name in packages:
try:
package = importlib.import_module(package_name)
except ImportError:
result[package_name] = None
else:
version = package.__version__
# enaml provides its version differently
try:
import enaml
except ImportError:
result['enaml'] = None
else:
from enaml.version import version_info
result['enaml'] = _make_version_string(version_info)
# ...as does Python
version_info = sys.version_info
result['python'] = _make_version_string(version_info)
return result
def _make_version_string(version_info):
version_string = '.'.join(map(str, [version_info[0], version_info[1],
version_info[2]]))
return version_string
|
Remove json and an unused alias | const paths = require('./paths');
const utils = require('../build/utils');
const vueLoaderConfig = require('../build/vue-loader.conf');
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');
module.exports = {
resolve: {
extensions: ['.js', '.vue', '.scss'],
alias: {
'@': paths.src,
},
},
externals: {
firebase: 'firebase',
vue: 'Vue',
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig,
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]'),
},
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]'),
},
},
],
},
plugins: [
new FriendlyErrorsPlugin(),
],
};
| const paths = require('./paths');
const utils = require('../build/utils');
const vueLoaderConfig = require('../build/vue-loader.conf');
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');
module.exports = {
resolve: {
extensions: ['.js', '.vue', '.json', '.scss'],
alias: {
vue$: 'vue/dist/vue.esm.js',
'@': paths.src,
},
},
externals: {
firebase: 'firebase',
vue: 'Vue',
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig,
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]'),
},
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]'),
},
},
],
},
plugins: [
new FriendlyErrorsPlugin(),
],
};
|
Tweak to bam file name calling | #!/usr/bin/env python
# Standard packages
import sys
import argparse
# Third-party packages
from toil.job import Job
# Package methods
from ddb import configuration
from ddb_ngsflow import gatk
from ddb_ngsflow import pipeline
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--samples_file', help="Input configuration file for samples")
parser.add_argument('-c', '--configuration', help="Configuration file for various settings")
Job.Runner.addToilOptions(parser)
args = parser.parse_args()
# args.logLevel = "INFO"
sys.stdout.write("Parsing configuration data\n")
config = configuration.configure_runtime(args.configuration)
sys.stdout.write("Parsing sample data\n")
samples = configuration.configure_samples(args.samples_file, config)
root_job = Job.wrapJobFn(pipeline.spawn_batch_jobs)
for sample in samples:
diagnose_targets_job = Job.wrapJobFn(gatk.diagnosetargets, config, sample, samples,
"{}.recalibrated.sorted.bam".format(sample),
cores=int(config['gatk']['num_cores']),
memory="{}G".format(config['gatk']['max_mem']))
root_job.addChild(diagnose_targets_job)
# Start workflow execution
Job.Runner.startToil(root_job, args)
| #!/usr/bin/env python
# Standard packages
import sys
import argparse
# Third-party packages
from toil.job import Job
# Package methods
from ddb import configuration
from ddb_ngsflow import gatk
from ddb_ngsflow import pipeline
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--samples_file', help="Input configuration file for samples")
parser.add_argument('-c', '--configuration', help="Configuration file for various settings")
Job.Runner.addToilOptions(parser)
args = parser.parse_args()
# args.logLevel = "INFO"
sys.stdout.write("Parsing configuration data\n")
config = configuration.configure_runtime(args.configuration)
sys.stdout.write("Parsing sample data\n")
samples = configuration.configure_samples(args.samples_file, config)
root_job = Job.wrapJobFn(pipeline.spawn_batch_jobs)
for sample in samples:
diagnose_targets_job = Job.wrapJobFn(gatk.diagnosetargets, config, sample, samples, samples[sample]['bam'],
cores=int(config['gatk']['num_cores']),
memory="{}G".format(config['gatk']['max_mem']))
root_job.addChild(diagnose_targets_job)
# Start workflow execution
Job.Runner.startToil(root_job, args)
|
Check for deleted machine when showing pending surveys.
Hopefully a work around for #382 | <h2><span class="label label-default">Pending surveys</span></h2>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Survey ID</th>
<th>Description</th>
<th>Date Scheduled</th>
<th>Test type</th>
<th>Accession</th>
<th>Survey Note</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach ($pendingSurveys as $pending)
if (is_null($pending->machine)) {
break;
}
else {
<tr>
<td><a href="{{ route('surveys.edit', $pending->id)}}">{{ $pending->id }}</a></td>
<td><a href="{{ route('machines.show', $pending->machine->id) }}">{{ $pending->machine->description }}</a></td>
<td>{{ $pending->test_date}}</td>
<td>{{ $pending->type->test_type}}</td>
<td>{{ $pending->accession }}</td>
<td>{{ $pending->notes }}</td>
<td><a href="{{ route('surveys.edit', $pending->id) }}" class="btn btn-default btn-xs" role="button" data-toggle="tooltip" title="Modify this machine">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a>
</td>
</tr>
}
@endforeach
</tbody>
</table>
| <h2><span class="label label-default">Pending surveys</span></h2>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Survey ID</th>
<th>Description</th>
<th>Date Scheduled</th>
<th>Test type</th>
<th>Accession</th>
<th>Survey Note</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach ($pendingSurveys as $pending)
<tr>
<td><a href="{{ route('surveys.edit', $pending->id)}}">{{ $pending->id }}</a></td>
<td><a href="{{ route('machines.show', $pending->machine->id) }}">{{ $pending->machine->description }}</a></td>
<td>{{ $pending->test_date}}</td>
<td>{{ $pending->type->test_type}}</td>
<td>{{ $pending->accession }}</td>
<td>{{ $pending->notes }}</td>
<td><a href="{{ route('surveys.edit', $pending->id) }}" class="btn btn-default btn-xs" role="button" data-toggle="tooltip" title="Modify this machine">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a>
</td>
</tr>
@endforeach
</tbody>
</table>
|
Add an action for server disconnects | from twisted.internet.protocol import ClientFactory, ReconnectingClientFactory
from heufybot.connection import HeufyBotConnection
class HeufyBotFactory(ReconnectingClientFactory):
protocol = HeufyBotConnection
def __init__(self, bot):
self.bot = bot
self.currentlyDisconnecting = []
def buildProtocol(self, addr):
self.resetDelay()
return self.protocol(self.bot)
def clientConnectionFailed(self, connector, reason):
self.bot.log.info("Client connection to {connector.host} failed (Reason: {reason.value}).",
connector=connector, reason=reason)
ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
def clientConnectionLost(self, connector, reason):
# Disable modules
if connector.host in self.bot.moduleHandler.enabledModules:
for module in self.bot.moduleHandler.enabledModules[connector.host]:
self.bot.moduleHandler.disableModule(module, connector.host, True)
self.bot.moduleHandler.runGenericAction("disconnect", connector.host)
del self.bot.servers[connector.host]
# Check whether or not we should reconnect
if connector.host in self.currentlyDisconnecting:
self.bot.log.info("Connection to {connector.host} was closed cleanly.", connector=connector)
ClientFactory.clientConnectionLost(self, connector, reason)
self.currentlyDisconnecting.remove(connector.host)
self.bot.countConnections()
else:
ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
| from twisted.internet.protocol import ClientFactory, ReconnectingClientFactory
from heufybot.connection import HeufyBotConnection
class HeufyBotFactory(ReconnectingClientFactory):
protocol = HeufyBotConnection
def __init__(self, bot):
self.bot = bot
self.currentlyDisconnecting = []
def buildProtocol(self, addr):
self.resetDelay()
return self.protocol(self.bot)
def clientConnectionFailed(self, connector, reason):
self.bot.log.info("Client connection to {connector.host} failed (Reason: {reason.value}).",
connector=connector, reason=reason)
ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
def clientConnectionLost(self, connector, reason):
# Disable modules
if connector.host in self.bot.moduleHandler.enabledModules:
for module in self.bot.moduleHandler.enabledModules[connector.host]:
self.bot.moduleHandler.disableModule(module, connector.host, True)
del self.bot.servers[connector.host]
# Check whether or not we should reconnect
if connector.host in self.currentlyDisconnecting:
self.bot.log.info("Connection to {connector.host} was closed cleanly.", connector=connector)
ClientFactory.clientConnectionLost(self, connector, reason)
self.currentlyDisconnecting.remove(connector.host)
self.bot.countConnections()
else:
ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
|
Add py solution for 329. Longest Increasing Path in a Matrix
329. Longest Increasing Path in a Matrix: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
Approach 2:
Top down search | from collections import Counter
class Solution(object):
def dfs(self, dp, matrix, x, y, w, h):
v = matrix[x][y]
if dp[x, y] == 0:
dp[x, y] = 1 + max(
0 if x == 0 or matrix[x - 1][y] <= v else self.dfs(dp, matrix, x - 1, y, w, h),
0 if y == 0 or matrix[x][y - 1] <= v else self.dfs(dp, matrix, x, y - 1, w, h),
0 if x == h - 1 or matrix[x + 1][y] <= v else self.dfs(dp, matrix, x + 1, y, w, h),
0 if y == w - 1 or matrix[x][y + 1] <= v else self.dfs(dp, matrix, x, y + 1, w, h)
)
return dp[x, y]
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix:
return 0
h = len(matrix)
w = len(matrix[0])
ans = 1
starts = set(xrange(h * w))
dp = Counter()
for x, row in enumerate(matrix):
for y, v in enumerate(row):
ans = max(ans, self.dfs(dp, matrix, x, y, w, h))
return ans
| from collections import defaultdict, Counter
class Solution(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix:
return 0
h = len(matrix)
w = len(matrix[0])
neighbors = defaultdict(list)
in_deg = Counter()
longest_length = Counter()
ds = [(0, -1), (0, 1), (1, 0), (-1, 0)]
starts = set(xrange(h * w))
for x, row in enumerate(matrix):
for y, v in enumerate(row):
for dx, dy in ds:
nx, ny = x + dx, y + dy
if 0 <= nx < h and 0 <= ny < w:
if matrix[nx][ny] > v:
neighbors[x * w + y].append(nx * w + ny)
in_deg[nx * w + ny] += 1
starts.discard(nx * w + ny)
for start in starts:
longest_length[start] = 1
q = list(starts)
ans = 1
for v in q:
for neighbor in neighbors[v]:
longest_length[neighbor] = max(longest_length[neighbor], longest_length[v] + 1)
ans = max(longest_length[neighbor], ans)
in_deg[neighbor] -= 1
if in_deg[neighbor] == 0:
q.append(neighbor)
return ans
|
Add classname to permissions data cell for testing | import React, { PropTypes } from 'react';
import Immutable from 'immutable';
import { Table } from 'react-bootstrap';
import { AUTHENTICATED_USER } from '../../../utils/Consts/UserRoleConsts';
import styles from '../styles.module.css';
export default class RolePermissionsTable extends React.Component {
static propTypes = {
rolePermissions: PropTypes.instanceOf(Immutable.Map).isRequired,
headers: PropTypes.array.isRequired
}
getRows = () => {
const { rolePermissions } = this.props;
const rows = [];
if (rolePermissions) {
rolePermissions.keySeq().forEach((role) => {
const permissionsStr = rolePermissions.get(role).join(', ');
let roleStr = role;
if (role === AUTHENTICATED_USER) {
roleStr = 'Default for all users';
}
rows.push(<tr className={styles.mainRow} key={role}><td>{roleStr}</td><td className={`permissions-${role}`}>{permissionsStr}</td></tr>);
});
}
return rows;
}
render() {
const headers = [];
this.props.headers.forEach((header) => {
headers.push(<th key={header}>{header}</th>);
});
return (
<Table bordered responsive className={styles.table}>
<thead>
<tr>
{headers}
</tr>
</thead>
<tbody>
{this.getRows()}
</tbody>
</Table>
);
}
}
| import React, { PropTypes } from 'react';
import Immutable from 'immutable';
import { Table } from 'react-bootstrap';
import { AUTHENTICATED_USER } from '../../../utils/Consts/UserRoleConsts';
import styles from '../styles.module.css';
export default class RolePermissionsTable extends React.Component {
static propTypes = {
rolePermissions: PropTypes.instanceOf(Immutable.Map).isRequired,
headers: PropTypes.array.isRequired
}
getRows = () => {
const { rolePermissions } = this.props;
const rows = [];
if (rolePermissions) {
rolePermissions.keySeq().forEach((role) => {
const permissionsStr = rolePermissions.get(role).join(', ');
let roleStr = role;
if (role === AUTHENTICATED_USER) {
roleStr = 'Default for all users';
}
rows.push(<tr className={styles.mainRow} key={role}><td>{roleStr}</td><td>{permissionsStr}</td></tr>);
});
}
return rows;
}
render() {
const headers = [];
this.props.headers.forEach((header) => {
headers.push(<th key={header}>{header}</th>);
});
return (
<Table bordered responsive className={styles.table}>
<thead>
<tr>
{headers}
</tr>
</thead>
<tbody>
{this.getRows()}
</tbody>
</Table>
);
}
}
|
Switch off the output file generation. | #!/usr/bin/env python3
# coding: utf-8
"""
================================================
Optimization Benchmark: Plot the Sphere Function
================================================
This example show how to plot the *Sphere function*.
"""
###############################################################################
# Import required packages
import numpy as np
import matplotlib.pyplot as plt
from ailib.utils.plot import plot_2d_contour_solution_space, plot_2d_solution_space
from ailib.optimize.functions.unconstrained import sphere
###############################################################################
# Plot the sphere function
plot_2d_solution_space(sphere,
xmin=-2*np.ones(2),
xmax=2*np.ones(2),
xstar=np.zeros(2),
angle_view=(55, 83),
title="Sphere function")
plt.tight_layout()
plt.show()
###############################################################################
# Plot the contours
plot_2d_contour_solution_space(sphere,
xmin=-10*np.ones(2),
xmax=10*np.ones(2),
xstar=np.zeros(2),
title="Sphere function")
plt.tight_layout()
plt.show()
| #!/usr/bin/env python3
# coding: utf-8
"""
================================================
Optimization Benchmark: Plot the Sphere Function
================================================
This example show how to plot the *Sphere function*.
"""
###############################################################################
# Import required packages
import numpy as np
import matplotlib.pyplot as plt
from ailib.utils.plot import plot_2d_contour_solution_space, plot_2d_solution_space
from ailib.optimize.functions.unconstrained import sphere
###############################################################################
# Plot the sphere function
plot_2d_solution_space(sphere,
xmin=-2*np.ones(2),
xmax=2*np.ones(2),
xstar=np.zeros(2),
angle_view=(55, 83),
title="Sphere function",
output_file_name="sphere_3d.png")
plt.tight_layout()
plt.show()
###############################################################################
# Plot the contours
plot_2d_contour_solution_space(sphere,
xmin=-10*np.ones(2),
xmax=10*np.ones(2),
xstar=np.zeros(2),
title="Sphere function",
output_file_name="sphere.png")
plt.tight_layout()
plt.show()
|
[IMP] Use constraint decorator on account_constraints+ | # -*- coding: utf-8 -*-
##############################################################################
#
# Author Joel Grand-Guillaume. Copyright 2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, api, exceptions, _
class AccountMove(models.Model):
_inherit = "account.move"
@api.constrains('journal_id', 'period_id', 'date')
def _check_fiscal_year(self):
for move in self:
if move.journal_id.allow_date_fy:
date_start = move.period_id.fiscalyear_id.date_start
date_stop = move.period_id.fiscalyear_id.date_stop
if not date_start <= move.date <= date_stop:
raise exceptions.Warning(
_('You cannot create entries with date not in the '
'fiscal year of the chosen period'))
return True
| # -*- coding: utf-8 -*-
##############################################################################
#
# Author Joel Grand-Guillaume. Copyright 2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, api
class AccountMove(models.Model):
_inherit = "account.move"
@api.multi
def _check_fiscal_year(self):
for move in self:
if move.journal_id.allow_date_fy:
date_start = move.period_id.fiscalyear_id.date_start
date_stop = move.period_id.fiscalyear_id.date_stop
if not date_start <= move.date <= date_stop:
return False
return True
_constraints = [
(_check_fiscal_year,
'You cannot create entries with date not in the '
'fiscal year of the chosen period',
['line_id']),
]
|
Fix statistics not showing in navbar during the first iteration of textillate | var navbar = function($interval, $q, User) {
return {
restrict: 'E', // only activate on element attribute
templateUrl: 'navbar.html',
link: function(scope, element) {
var formats = [formatPercentResolvedBugs, formatNumberProjects];
var currentFormat;
var $statisticLabel = $('.label-statistic', element);
function getStatistics() {
var deferred = $q.defer();
User.statistics(function(successData) {
deferred.resolve(successData);
}, function(errorData) {
deferred.reject(errorData);
});
return deferred.promise;
}
function formatPercentResolvedBugs(data) {
var percent = Math.round((data.number_resolved_bugs / data.number_bugs) * 100);
if (_.isNaN(percent)) {
percent = 100;
}
return percent + "% of the bugs across all your projects are resolved.";
}
function formatNumberProjects(data) {
return "You are currently working on " + data.number_projects + " projects.";
}
getStatistics().then(function(data) {
scope.statistics = [
formatPercentResolvedBugs(data),
formatNumberProjects(data)
];
$statisticLabel.textillate({
minDisplayTime: 15000,
initialDelay: 0,
loop: true,
autoStart: true,
in: {
effect: 'fadeInUp',
sync: true
},
out: {
effect: 'fadeOutUp',
sync: true
}
});
});
}
};
};
bugtracker.directive('navbar', ['$interval', '$q', 'User', navbar]); | var navbar = function($interval, $q, User) {
return {
restrict: 'E', // only activate on element attribute
templateUrl: 'navbar.html',
link: function(scope, element) {
var formats = [formatPercentResolvedBugs, formatNumberProjects];
var currentFormat;
var $statisticLabel = $('.label-statistic', element);
function getStatistics() {
var deferred = $q.defer();
User.statistics(function(successData) {
deferred.resolve(successData);
}, function(errorData) {
deferred.reject(errorData);
});
return deferred.promise;
}
function formatPercentResolvedBugs(data) {
var percent = Math.round((data.number_resolved_bugs / data.number_bugs) * 100);
if (_.isNaN(percent)) {
percent = 100;
}
return percent + "% of the bugs across all your projects are resolved.";
}
function formatNumberProjects(data) {
return "You are currently working on " + data.number_projects + " projects.";
}
getStatistics().then(function(data) {
scope.statistics = [
formatPercentResolvedBugs(data),
formatNumberProjects(data)
];
});
$statisticLabel.textillate({
minDisplayTime: 15000,
initialDelay: 0,
loop: true,
autoStart: true,
in: {
effect: 'fadeInUp',
sync: true
},
out: {
effect: 'fadeOutUp',
sync: true
}
});
}
};
};
bugtracker.directive('navbar', ['$interval', '$q', 'User', navbar]); |
Update event namings based on edX standard formats | function OfficeMixBlock(runtime, element) {
var iframe = $('iframe', element);
var player = new playerjs.Player(iframe.get(0));
var mixUrl = iframe.attr('src');
var eventUrl = runtime.handlerUrl(element, 'publish_event');
player.on('ready', function () {
player.getDuration(function (duration) {
var data = {
'event_type': 'microsoft.office.mix.loaded',
url: mixUrl,
duration: duration
};
$.post(eventUrl, JSON.stringify(data));
});
player.on('play', function () {
player.getCurrentTime(function (value) {
var data = {
'event_type': 'microsoft.office.mix.played',
url: mixUrl,
time: value
};
$.post(eventUrl, JSON.stringify(data));
});
});
player.on('pause', function () {
player.getCurrentTime(function (value) {
var data = {
'event_type': 'microsoft.office.mix.paused',
url: mixUrl,
time: value
};
$.post(eventUrl, JSON.stringify(data));
});
});
player.on('ended', function () {
var data = {
'event_type': 'microsoft.office.mix.stopped',
url: mixUrl
};
$.post(eventUrl, JSON.stringify(data));
});
});
}
| function OfficeMixBlock(runtime, element) {
var iframe = $('iframe', element);
var player = new playerjs.Player(iframe.get(0));
var mixUrl = iframe.attr('src');
var eventUrl = runtime.handlerUrl(element, 'publish_event');
player.on('ready', function () {
player.getDuration(function (duration) {
var data = {
'event_type': 'xblock.officemix.loaded',
url: mixUrl,
duration: duration
};
$.post(eventUrl, JSON.stringify(data));
});
player.on('play', function () {
player.getCurrentTime(function (value) {
var data = {
'event_type': 'xblock.officemix.played',
url: mixUrl,
time: value
};
$.post(eventUrl, JSON.stringify(data));
});
});
player.on('pause', function () {
player.getCurrentTime(function (value) {
var data = {
'event_type': 'xblock.officemix.paused',
url: mixUrl,
time: value
};
$.post(eventUrl, JSON.stringify(data));
});
});
player.on('ended', function () {
var data = {
'event_type': 'xblock.officemix.stopped',
url: mixUrl
};
$.post(eventUrl, JSON.stringify(data));
});
});
}
|
Define Link ID as UUID | """Module with all classes related to links.
Links are low level abstractions representing connections between two
interfaces.
"""
import json
from uuid import uuid4
from kytos.core.common import GenericEntity
class Link(GenericEntity):
"""Define a link between two Endpoints."""
def __init__(self, endpoint_a, endpoint_b):
"""Create a Link instance and set its attributes."""
self.endpoint_a = endpoint_a
self.endpoint_b = endpoint_b
self._uuid = uuid4()
super().__init__()
def __eq__(self, other):
"""Check if two instances of Link are equal."""
return ((self.endpoint_a == other.endpoint_a and
self.endpoint_b == other.endpoint_b) or
(self.endpoint_a == other.endpoint_b and
self.endpoint_b == other.endpoint_a))
@property
def id(self): # pylint: disable=invalid-name
"""Return id from Link intance.
Returns:
string: link id.
"""
return "{}".format(self._uuid)
def as_dict(self):
"""Return the Link as a dictionary."""
return {'id': self.id,
'endpoint_a': self.endpoint_a.as_dict(),
'endpoint_b': self.endpoint_b.as_dict(),
'metadata': self.metadata,
'active': self.active,
'enabled': self.enabled}
def as_json(self):
"""Return the Link as a JSON string."""
return json.dumps(self.as_dict())
| """Module with all classes related to links.
Links are low level abstractions representing connections between two
interfaces.
"""
import json
from kytos.core.common import GenericEntity
class Link(GenericEntity):
"""Define a link between two Endpoints."""
def __init__(self, endpoint_a, endpoint_b):
"""Create a Link instance and set its attributes."""
self.endpoint_a = endpoint_a
self.endpoint_b = endpoint_b
super().__init__()
def __eq__(self, other):
"""Check if two instances of Link are equal."""
return ((self.endpoint_a == other.endpoint_a and
self.endpoint_b == other.endpoint_b) or
(self.endpoint_a == other.endpoint_b and
self.endpoint_b == other.endpoint_a))
@property
def id(self): # pylint: disable=invalid-name
"""Return id from Link intance.
Returns:
string: link id.
"""
return "{}:{}".format(self.endpoint_a.id, self.endpoint_b.id)
def as_dict(self):
"""Return the Link as a dictionary."""
return {'id': self.id,
'endpoint_a': self.endpoint_a.as_dict(),
'endpoint_b': self.endpoint_b.as_dict(),
'metadata': self.metadata,
'active': self.active,
'enabled': self.enabled}
def as_json(self):
"""Return the Link as a JSON string."""
return json.dumps(self.as_dict())
|
Remove "A" from start of title for RT search | import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self.format_title()
movie_page = requests.get(search_url)
contents = movie_page.text
soup = BeautifulSoup(contents, 'lxml')
ratings = self.get_ratings(soup)
ratings.link = search_url
return ratings
def format_title(self):
formatted_title = self.title
if formatted_title.startswith('The '):
formatted_title = formatted_title.replace('The ', '', 1)
if formatted_title.startswith('A '):
formatted_title = formatted_title.replace('A ', '', 1)
if "'s" in formatted_title:
formatted_title = formatted_title.replace("'s", 's')
formatted_title = formatted_title.replace(' ', self.__SEPERATOR)
formatted_title = formatted_title.replace('-', '')
formatted_title = formatted_title.replace(':', '')
formatted_title = formatted_title.replace(',', '')
return formatted_title
def get_ratings(self, soup):
items = []
for item in soup.findAll(attrs={'itemprop': 'ratingValue'}):
items.append(item.get_text().strip('%'))
return RTRating(items)
| import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self.format_title()
movie_page = requests.get(search_url)
contents = movie_page.text
soup = BeautifulSoup(contents, 'lxml')
ratings = self.get_ratings(soup)
ratings.link = search_url
return ratings
def format_title(self):
formatted_title = self.title
if formatted_title.startswith('The '):
formatted_title = formatted_title.replace('The ', '', 1)
if "'s" in formatted_title:
formatted_title = formatted_title.replace("'s", 's')
formatted_title = formatted_title.replace(' ', self.__SEPERATOR)
formatted_title = formatted_title.replace('-', '')
formatted_title = formatted_title.replace(':', '')
formatted_title = formatted_title.replace(',', '')
return formatted_title
def get_ratings(self, soup):
items = []
for item in soup.findAll(attrs={'itemprop': 'ratingValue'}):
items.append(item.get_text().strip('%'))
return RTRating(items)
|
Fix e2e tests for ShowView | /*global describe,it,expect,$$,element,browser,by*/
describe('ShowView', function () {
'use strict';
var hasToLoad = true;
beforeEach(function() {
if (hasToLoad) {
browser.get(browser.baseUrl + '#/posts/show/1');
hasToLoad = false;
}
});
describe('ChoiceField', function() {
it('should render as a label when choices is an array', function () {
$$('.ng-admin-field-category').then(function (fields) {
expect(fields[0].getText()).toBe('Tech');
});
});
it('should render as a label when choices is a function', function () {
$$('.ng-admin-field-subcategory').then(function (fields) {
expect(fields[0].getText()).toBe('Computers');
});
});
});
describe('ReferencedListField', function() {
it('should render as a datagrid', function () {
$$('.ng-admin-field-comments th').then(function (inputs) {
expect(inputs.length).toBe(2);
expect(inputs[0].getAttribute('class')).toBe('ng-scope ng-admin-column-created_at');
expect(inputs[1].getAttribute('class')).toBe('ng-scope ng-admin-column-body');
});
});
});
});
| /*global describe,it,expect,$$,element,browser,by*/
describe('ShowView', function () {
'use strict';
var hasToLoad = true;
beforeEach(function() {
if (hasToLoad) {
browser.get(browser.baseUrl + '#/posts/show/1');
hasToLoad = false;
}
});
describe('ChoiceField', function() {
it('should render as a label when choices is an array', function () {
$$('.ng-admin-field-category').then(function (fields) {
expect(fields[0].getText()).toBe('Tech');
});
});
it('should render as a label when choices is a function', function () {
$$('.ng-admin-field-subcategory').then(function (fields) {
expect(fields[0].getText()).toBe('Computers');
});
});
});
describe('ReferencedListField', function() {
it('should render as a datagrid', function () {
$$('.ng-admin-field-comments th').then(function (inputs) {
expect(inputs.length).toBe(2);
expect(inputs[0].getAttribute('class')).toBe('ng-scope ng-admin-column-id');
expect(inputs[1].getAttribute('class')).toBe('ng-scope ng-admin-column-body');
});
});
});
});
|
Rework external link style in catalogues | <table class="catalogue_table">
<thead>
<tr>
<th></th>
<th><?php echo __('Link');?></th>
<th><?php echo __('Comment');?></th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach($links as $link):?>
<tr>
<td>
<?php echo link_to(image_tag('edit.png'),'extlinks/extLinks?table='.$table.'&cid='.$link->getId().'&id='.$eid,array('class' => 'link_catalogue','title' => __('Edit Url') )) ; ?>
</td>
<td>
<a href="<?php echo $link->getUrl();?>" target="_pop" class='complete_widget'>
<?php echo $link->getUrl();?>
</a>
</td>
<td>
<?php echo $link->getComment();?>
</td>
<td class="widget_row_delete">
<a class="widget_row_delete" href="<?php echo url_for('catalogue/deleteRelated?table=ext_links&id='.$link->getId());?>" title="<?php echo __('Delete Link') ?>"><?php echo image_tag('remove.png'); ?>
</a>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<br />
<?php echo image_tag('add_green.png');?><a title="<?php echo __('Add Link');?>" class="link_catalogue" href="<?php echo url_for('extlinks/extLinks?table='.$table.'&id='.$eid);?>"><?php echo __('Add');?></a>
| <table class="catalogue_table">
<thead>
<tr>
<th><?php echo __('Link');?></th>
<th><?php echo __('Comment');?></th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach($links as $link):?>
<tr>
<td>
<?php echo link_to($link->getUrl(),'extlinks/extLinks?table='.$table.'&cid='.$link->getId().'&id='.$eid,array('class' => 'link_catalogue','title' => __('Edit Url') )) ; ?>
<a href="<?php echo $link->getUrl();?>" target="_pop" class='complete_widget'>
<?php echo image_tag('next.png',array('title'=>__('Go to this link'))) ; ?>
</a>
</td>
<td>
<?php echo $link->getComment();?>
</td>
<td class="widget_row_delete">
<a class="widget_row_delete" href="<?php echo url_for('catalogue/deleteRelated?table=ext_links&id='.$link->getId());?>" title="<?php echo __('Delete Link') ?>"><?php echo image_tag('remove.png'); ?>
</a>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<br />
<?php echo image_tag('add_green.png');?><a title="<?php echo __('Add Link');?>" class="link_catalogue" href="<?php echo url_for('extlinks/extLinks?table='.$table.'&id='.$eid);?>"><?php echo __('Add');?></a>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.