text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Store hyperparameters with the other settings
Instead of storing them in their own 'parameters' directory.
|
from __future__ import print_function, absolute_import, division
import csv
import json
from six.moves import cStringIO
from .config import Config
from .trials import Trial
def execute(args, parser):
config = Config(args.config, verbose=False)
session = config.trials()
columns = Trial.__mapper__.columns
if args.output == 'json':
items = [curr.to_dict() for curr in session.query(Trial).all()]
new_items = []
# Instead of saving the parameters on their own nested dict,
# save them along the rest of elements
for item in items:
parameters = item.pop('parameters') # remove dict
item.update(parameters) # update original dict with the parameters
new_items.append(item)
value = json.dumps(new_items)
elif args.output == 'csv':
buf = cStringIO()
outcsv = csv.writer(buf)
outcsv.writerow([column.name for column in columns])
for curr in session.query(Trial).all():
row = [getattr(curr, column.name) for column in columns]
outcsv.writerow(row)
value = buf.getvalue()
print(value)
return value
|
from __future__ import print_function, absolute_import, division
import csv
import json
from six.moves import cStringIO
from .config import Config
from .trials import Trial
def execute(args, parser):
config = Config(args.config, verbose=False)
session = config.trials()
columns = Trial.__mapper__.columns
if args.output == 'json':
items = [curr.to_dict() for curr in session.query(Trial).all()]
value = json.dumps(items)
elif args.output == 'csv':
buf = cStringIO()
outcsv = csv.writer(buf)
outcsv.writerow([column.name for column in columns])
for curr in session.query(Trial).all():
row = [getattr(curr, column.name) for column in columns]
outcsv.writerow(row)
value = buf.getvalue()
print(value)
return value
|
Make unit test vars overridable.
|
package org.typemeta.funcj.codec.mpack;
import org.junit.Assert;
import org.typemeta.funcj.codec.TestBase;
import javax.xml.bind.DatatypeConverter;
import java.io.*;
public class MpackCodecTest extends TestBase {
@Override
protected <T> void roundTrip(T val, Class<T> clazz) {
final MpackCodecCore codec = prepareCodecCore(MpackCodecs.mpackCodec());
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
codec.encode(clazz, val, baos);
final byte[] ba = baos.toByteArray();
if (printData()) {
System.out.println(DatatypeConverter.printHexBinary(ba));
}
if (printSizes()) {
System.out.println("Encoded MessagePack " + clazz.getSimpleName() + " data size = " + ba.length + " bytes");
}
final ByteArrayInputStream bais = new ByteArrayInputStream(ba);
final T val2 = codec.decode(clazz, bais);
if (!printData() && !val.equals(val2)) {
System.out.println(DatatypeConverter.printHexBinary(ba));
}
Assert.assertEquals(val, val2);
}
}
|
package org.typemeta.funcj.codec.mpack;
import org.junit.Assert;
import org.typemeta.funcj.codec.TestBase;
import javax.xml.bind.DatatypeConverter;
import java.io.*;
public class MpackCodecTest extends TestBase {
@Override
protected <T> void roundTrip(T val, Class<T> clazz) {
final MpackCodecCore codec = prepareCodecCore(MpackCodecs.mpackCodec());
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
codec.encode(clazz, val, baos);
final byte[] ba = baos.toByteArray();
if (printData) {
System.out.println(DatatypeConverter.printHexBinary(ba));
}
if (printSizes) {
System.out.println("Encoded MessagePack " + clazz.getSimpleName() + " data size = " + ba.length + " bytes");
}
final ByteArrayInputStream bais = new ByteArrayInputStream(ba);
final T val2 = codec.decode(clazz, bais);
if (!printData && !val.equals(val2)) {
System.out.println(DatatypeConverter.printHexBinary(ba));
}
Assert.assertEquals(val, val2);
}
}
|
Fix record function returning this
|
let path = require('path');
let Manifest = require('./Manifest');
let objectValues = require('lodash').values;
class Versioning {
/**
* Create a new Versioning instance.
*
* @param {object} manifest
*/
constructor(manifest) {
this.manifest = manifest;
this.files = [];
}
/**
* Record versioned files.
*/
record() {
if (! this.manifest.exists()) return this;
this.reset();
this.files = objectValues(this.manifest.read());
return this;
}
/**
* Reset all recorded files.
*/
reset() {
this.files = [];
return this;
}
/**
* Replace all old hashed files with the new versions.
*
* @param {string} baseDir
*/
prune(baseDir) {
let updated = new Versioning(this.manifest).record();
if (! updated) return;
this.files.filter(file => ! updated.files.includes(file))
.forEach(file => this.manifest.remove(path.join(baseDir, file)));
this.files = updated.files;
return this;
}
}
module.exports = Versioning;
|
let path = require('path');
let Manifest = require('./Manifest');
let objectValues = require('lodash').values;
class Versioning {
/**
* Create a new Versioning instance.
*
* @param {object} manifest
*/
constructor(manifest) {
this.manifest = manifest;
this.files = [];
}
/**
* Record versioned files.
*/
record() {
if (! this.manifest.exists()) return;
this.reset();
this.files = objectValues(this.manifest.read());
return this;
}
/**
* Reset all recorded files.
*/
reset() {
this.files = [];
return this;
}
/**
* Replace all old hashed files with the new versions.
*
* @param {string} baseDir
*/
prune(baseDir) {
let updated = new Versioning(this.manifest).record();
if (! updated) return;
this.files.filter(file => ! updated.files.includes(file))
.forEach(file => this.manifest.remove(path.join(baseDir, file)));
this.files = updated.files;
return this;
}
}
module.exports = Versioning;
|
Fix error in query parameter.
|
/**
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
package com.codeup.hibernate.repositories;
import com.codeup.movies.Movie;
import com.codeup.movies.Movies;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
public class MoviesRepository implements Movies {
private final Session session;
public MoviesRepository(Session session) {
this.session = session;
}
public void add(Movie movie) {
session.beginTransaction();
session.save(movie);
session.getTransaction().commit();
}
public Movie with(int id) {
Query query = session.createQuery("FROM Movie WHERE id = ?");
query.setParameter(0, id);
return (Movie) query.uniqueResult();
}
@Override
public List<Movie> withTitleSimilarTo(String title) {
Query query = session.createQuery("FROM Movie WHERE title LIKE ?");
query.setParameter(0, "%" + title + "%");
@SuppressWarnings("unchecked")
List movies = query.getResultList();
return movies;
}
}
|
/**
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
package com.codeup.hibernate.repositories;
import com.codeup.movies.Movie;
import com.codeup.movies.Movies;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
public class MoviesRepository implements Movies {
private final Session session;
public MoviesRepository(Session session) {
this.session = session;
}
public void add(Movie movie) {
session.beginTransaction();
session.save(movie);
session.getTransaction().commit();
}
public Movie with(int id) {
Query query = session.createQuery("FROM Movie WHERE id = ?");
query.setParameter(0, id);
return (Movie) query.uniqueResult();
}
@Override
public List<Movie> withTitleSimilarTo(String title) {
Query query = session.createQuery("FROM Movie WHERE title LIKE ?");
query.setParameter(0, title);
@SuppressWarnings("unchecked")
List movies = query.getResultList();
return movies;
}
}
|
Convert to using requests to resolve ssl errors
|
"""Rachiopy setup script."""
from setuptools import find_packages, setup
VERSION = "0.2.0"
GITHUB_USERNAME = "rfverbruggen"
GITHUB_REPOSITORY = "rachiopy"
GITHUB_PATH = f"{GITHUB_USERNAME}/{GITHUB_REPOSITORY}"
GITHUB_URL = f"https://github.com/{GITHUB_PATH}"
DOWNLOAD_URL = f"{GITHUB_URL}/archive/{VERSION}.tar.gz"
PROJECT_URLS = {"Bug Reports": f"{GITHUB_URL}/issues"}
PACKAGES = find_packages(exclude=["tests", "tests.*"])
setup(
name="RachioPy",
version=VERSION,
author="Robbert Verbruggen",
author_email="rfverbruggen@icloud.com",
packages=PACKAGES,
install_requires=["requests"],
url=GITHUB_URL,
download_url=DOWNLOAD_URL,
project_urls=PROJECT_URLS,
license="MIT",
description="A Python module for the Rachio API.",
platforms="Cross Platform",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Topic :: Software Development",
],
)
|
"""Rachiopy setup script."""
from setuptools import find_packages, setup
version = "0.2.0"
GITHUB_USERNAME = "rfverbruggen"
GITHUB_REPOSITORY = "rachiopy"
GITHUB_PATH = f"{GITHUB_USERNAME}/{GITHUB_REPOSITORY}"
GITHUB_URL = f"https://github.com/{GITHUB_PATH}"
DOWNLOAD_URL = f"{GITHUB_URL}/archive/{VERSION}.tar.gz"
PROJECT_URLS = {"Bug Reports": f"{GITHUB_URL}/issues"}
PACKAGES = find_packages(exclude=["tests", "tests.*"])
setup(
name="RachioPy",
version=VERSION,
author="Robbert Verbruggen",
author_email="rfverbruggen@icloud.com",
packages=PACKAGES,
install_requires=["requests"],
url=GITHUB_URL,
download_url=DOWNLOAD_URL,
project_urls=PROJECT_URLS,
license="MIT",
description="A Python module for the Rachio API.",
platforms="Cross Platform",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Topic :: Software Development",
],
)
|
Set API version to v2.0.M1.
|
/*
* Copyright 2014 Open mHealth
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openmhealth.dsu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.lang.annotation.*;
/**
* A specialisation of the {@link Controller} annotation that controls the version number of the DSU API.
*
* @author Emerson Farrugia
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@RequestMapping("/v2.0.M1")
public @interface ApiController {
}
|
/*
* Copyright 2014 Open mHealth
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openmhealth.dsu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.lang.annotation.*;
/**
* A specialisation of the {@link Controller} annotation that controls the version number of the DSU API.
*
* @author Emerson Farrugia
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@RequestMapping("/v2")
public @interface ApiController {
}
|
Fix bootstrapped `test:unit:watch` npm script 🐛
|
import path from 'path'
import json from '../../util/json'
const saguiScripts = {
'build': 'sagui build',
'develop': 'sagui develop --port 3000',
'dist': 'NODE_ENV=production sagui build --optimize',
'start': 'npm run develop',
'test': 'npm run test:lint && npm run test:unit',
'test:coverage': 'npm run test:unit -- --coverage',
'test:lint': 'sagui lint',
'test:unit': 'NODE_ENV=test sagui test',
'test:unit:watch': 'npm run test:unit -- --watch'
}
export default function (projectPath) {
const packagePath = path.join(projectPath, 'package.json')
const packageJSON = json.read(packagePath)
json.write(packagePath, {
...packageJSON,
scripts: {
...saguiScripts,
...withoutDefaults(packageJSON.scripts)
}
})
}
/**
* Remove default configurations generated by NPM that can be overwriten
* We don't want to overwrite any user configured scripts
*/
function withoutDefaults (scripts = {}) {
const defaultScripts = {
'test': 'echo "Error: no test specified" && exit 1'
}
return Object.keys(scripts)
.filter((key) => !scripts[key] !== '' && scripts[key] !== defaultScripts[key])
.reduce((filtered, key) => {
return {
...filtered,
[key]: scripts[key]
}
}, {})
}
|
import path from 'path'
import json from '../../util/json'
const saguiScripts = {
'build': 'sagui build',
'develop': 'sagui develop --port 3000',
'dist': 'NODE_ENV=production sagui build --optimize',
'start': 'npm run develop',
'test': 'npm run test:lint && npm run test:unit',
'test:lint': 'sagui lint',
'test:unit': 'NODE_ENV=test sagui test',
'test:coverage': 'npm run test:unit -- --coverage',
'test:unit:watch': 'npm run test -- --watch'
}
export default function (projectPath) {
const packagePath = path.join(projectPath, 'package.json')
const packageJSON = json.read(packagePath)
json.write(packagePath, {
...packageJSON,
scripts: {
...saguiScripts,
...withoutDefaults(packageJSON.scripts)
}
})
}
/**
* Remove default configurations generated by NPM that can be overwriten
* We don't want to overwrite any user configured scripts
*/
function withoutDefaults (scripts = {}) {
const defaultScripts = {
'test': 'echo "Error: no test specified" && exit 1'
}
return Object.keys(scripts)
.filter((key) => !scripts[key] !== '' && scripts[key] !== defaultScripts[key])
.reduce((filtered, key) => {
return {
...filtered,
[key]: scripts[key]
}
}, {})
}
|
Remove autoreplies from db template
|
package models
type Config struct {
Id string `rethink:"id,omitempty"`
Guild string `rethink:"guild"`
Prefix string `rethink:"prefix"`
CleanupEnabled bool `rethink:"cleanup_enabled"`
AnnouncementsEnabled bool `rethink:"announcements_enabled"`
AnnouncementsChannel string `rethink:"announcements_channel"`
WelcomeNewUsersEnabled bool `rethink:"welcome_new_users_enabled"`
WelcomeNewUsersText string `rethink:"welcome_new_users_text"`
}
func (c Config) Default(guild string) Config {
return Config{
Guild: guild,
Prefix: "%",
CleanupEnabled: false,
AnnouncementsEnabled: false,
AnnouncementsChannel: "",
WelcomeNewUsersEnabled: false,
WelcomeNewUsersText: "",
}
}
|
package models
type Config struct {
Id string `rethink:"id,omitempty"`
Guild string `rethink:"guild"`
Prefix string `rethink:"prefix"`
CleanupEnabled bool `rethink:"cleanup_enabled"`
AutoRepliesEnabled bool `rethink:"auto_replies_enabled"`
AutoReplies map[string]string `rethink:"auto_replies"`
AnnouncementsEnabled bool `rethink:"announcements_enabled"`
AnnouncementsChannel string `rethink:"announcements_channel"`
WelcomeNewUsersEnabled bool `rethink:"welcome_new_users_enabled"`
WelcomeNewUsersText string `rethink:"welcome_new_users_text"`
}
func (c Config) Default(guild string) Config {
return Config{
Guild: guild,
Prefix: "%",
CleanupEnabled: false,
AutoRepliesEnabled: false,
AutoReplies: make(map[string]string),
AnnouncementsEnabled: false,
AnnouncementsChannel: "",
WelcomeNewUsersEnabled: false,
WelcomeNewUsersText: "",
}
}
|
Update comment after trying pq.Array w/ pgx
|
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/lib/pq"
// To use the pgx driver, import this instead of pq. You'll also have to
// change the driverName param of sql.Open from "postgres" to "pgx".
// There's no need to update db.go, since pq.Array will work just fine with
// pgx (but it does incur importing pgx).
// See https://github.com/jackc/pgx/issues/72 for details on array usage
//_ "github.com/jackc/pgx/v4/stdlib"
)
func Check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
dbpath := "postgresql://testuser:testpassword@localhost/testmooc"
db, err := sql.Open("postgres", dbpath)
Check(err)
defer db.Close()
users, err := dbAllUsersForCourse(db, 2)
Check(err)
fmt.Println(users)
courses, err := dbAllCoursesForUser(db, 5)
Check(err)
fmt.Println(courses)
projects, err := dbAllProjectsForUser(db, 5)
Check(err)
fmt.Println(projects)
}
|
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/lib/pq"
// To use the pgx driver, import this instead of pq. You'll also have to
// change the driverName param of sql.Open from "postgres" to "pgx".
//_ "github.com/jackc/pgx/v4/stdlib"
)
func Check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
dbpath := "postgresql://testuser:testpassword@localhost/testmooc"
db, err := sql.Open("postgres", dbpath)
Check(err)
defer db.Close()
users, err := dbAllUsersForCourse(db, 2)
Check(err)
fmt.Println(users)
courses, err := dbAllCoursesForUser(db, 5)
Check(err)
fmt.Println(courses)
projects, err := dbAllProjectsForUser(db, 5)
Check(err)
fmt.Println(projects)
}
|
Revert back to first hack attempt, maybe need to implement a better event subscription model
git-svn-id: cd28ba526fba5b39766c0a4e72305690b33c2c6e@702414 13f79535-47bb-0310-9956-ffa450edef68
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.gshell.event;
/**
* Adapter for typed {@link Event} processing.
*
* @version $Rev$ $Date$
*/
public abstract class EventAdapter<T extends Event>
implements EventListener
{
@SuppressWarnings({"unchecked"})
public void onEvent(final Event event) throws Exception {
assert event != null;
// HACK: Can't check the type from T, so just handle the CCE, might not be very efficent though :-(
try {
handleEvent((T)event);
}
catch (ClassCastException ignore) {}
}
protected abstract void handleEvent(T event) throws Exception;
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.gshell.event;
/**
* Adapter for typed {@link Event} processing.
*
* @version $Rev$ $Date$
*/
public abstract class EventAdapter<T extends Event>
implements EventListener
{
@SuppressWarnings({"unchecked"})
public void onEvent(final Event event) throws Exception {
T targetEvent = null;
// HACK: Can't check the type from T, so just handle the CCE, might not be very efficent though :-(
try {
targetEvent = (T)event;
}
catch (ClassCastException ignore) {}
if (targetEvent != null) {
handleEvent(targetEvent);
}
}
protected abstract void handleEvent(T event) throws Exception;
}
|
Allow to dismiss the code integrity warning
Signed-off-by: Joas Schilling <ab43a7c9cb5b2380afc4ddf8b3e2583169b39a02@schilljs.com>
|
/**
* @author Lukas Reschke
*
* @copyright Copyright (c) 2015, ownCloud, Inc.
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
/**
* This gets only loaded if the integrity check has failed and then shows a notification
*/
$(document).ready(function(){
var text = t(
'core',
'<a href="{docUrl}">There were problems with the code integrity check. More information…</a>',
{
docUrl: OC.generateUrl('/settings/admin#security-warning')
}
);
OC.Notification.showHtml(
text,
{
type: 'error',
isHTML: true
}
);
});
|
/**
* @author Lukas Reschke
*
* @copyright Copyright (c) 2015, ownCloud, Inc.
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
/**
* This gets only loaded if the integrity check has failed and then shows a notification
*/
$(document).ready(function(){
var text = t(
'core',
'<a href="{docUrl}">There were problems with the code integrity check. More information…</a>',
{
docUrl: OC.generateUrl('/settings/admin#security-warning')
}
);
OC.Notification.showHtml(
text,
{
isHTML: true
}
);
});
|
Add status column to Screen table migration
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateScreensTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('screens',function(Blueprint $table) {
$table->increments('id');
$table->integer('vn_id')->unsigned();
$table->string('original_filename');
$table->string('local_filename');
$table->string('alternative_image_url')->nullable();
$table->smallInteger('screen_category')->nullable()->comment('1:title, 2:gameplay, 3:config, 4:save/load, 5:omake');
$table->string('description', 600)->nullable();
$table->integer('status')->default(1)->comment('1:active, 2:archived, 3:deleted');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('screens');
}
}
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateScreensTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('screens',function(Blueprint $table) {
$table->increments('id');
$table->integer('vn_id')->unsigned();
$table->string('original_filename');
$table->string('local_filename');
$table->string('alternative_image_url')->nullable();
$table->smallInteger('screen_category')->nullable()->comment('1:title, 2:gameplay, 3:config, 4:save/load, 5:omake');
$table->string('description', 600)->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('screens');
}
}
|
Set disqus page title and hardcode url to nusmods.com
|
define(['backbone.marionette', 'hbs!../templates/module'],
function (Marionette, template) {
'use strict';
return Marionette.ItemView.extend({
template: template,
initialize: function (data) {
},
events: {
'click .show-full-desc': 'showFullDescription'
},
onShow: function () {
var module = this.model.get('module');
DISQUS.reset({
reload: true,
config: function () {
var code = module.ModuleCode;
this.page.identifier = code;
this.page.title = code + ' ' + module.ModuleTitle + ' · Reviews';
this.page.url = 'http://nusmods.com/#!/modules/' + code + '/reviews';
}
});
},
showFullDescription: function ($ev) {
$('.module-desc').addClass('module-desc-more');
return false;
}
});
});
|
define(['backbone.marionette', 'hbs!../templates/module'],
function (Marionette, template) {
'use strict';
return Marionette.ItemView.extend({
template: template,
initialize: function (data) {
},
events: {
'click .show-full-desc': 'showFullDescription'
},
onShow: function () {
var code = this.model.get('module').ModuleCode;
DISQUS.reset({
reload: true,
config: function () {
this.page.identifier = code;
this.page.url = window.location.href;
}
});
},
showFullDescription: function ($ev) {
$('.module-desc').addClass('module-desc-more');
return false;
}
});
});
|
Clone `defaults` object to avoid member assignment
Fixes urbica/galton#183
|
const defaults = require('./defaults.js');
const parseBoolean = boolean => boolean === 'true';
const parseIntervals = (intervals) => {
if (Array.isArray(intervals)) {
return intervals
.filter(i => !isNaN(i))
.map(parseFloat)
.sort((a, b) => a - b);
}
const interval = parseFloat(intervals);
return interval ? [interval] : defaults.intervals;
};
const parseUnits = (units) => {
if (units === 'kilometers' || units === 'miles') {
return units;
}
return defaults.units;
};
const parsers = {
lng: parseFloat,
lat: parseFloat,
radius: parseFloat,
cellSize: parseFloat,
concavity: parseFloat,
lengthThreshold: parseFloat,
deintersect: parseBoolean,
intervals: parseIntervals,
units: parseUnits
};
const parseQuery = query =>
Object.keys(parsers).reduce((acc, paramKey) => {
if (query[paramKey]) {
const parser = parsers[paramKey];
acc[paramKey] = parser(query[paramKey]);
}
return acc;
}, Object.assign({}, defaults));
module.exports = parseQuery;
|
const defaults = require('./defaults.js');
const parseBoolean = boolean => boolean === 'true';
const parseIntervals = (intervals) => {
if (Array.isArray(intervals)) {
return intervals
.filter(i => !isNaN(i))
.map(parseFloat)
.sort((a, b) => a - b);
}
const interval = parseFloat(intervals);
return interval ? [interval] : defaults.intervals;
};
const parseUnits = (units) => {
if (units === 'kilometers' || units === 'miles') {
return units;
}
return defaults.units;
};
const parsers = {
lng: parseFloat,
lat: parseFloat,
radius: parseFloat,
cellSize: parseFloat,
concavity: parseFloat,
lengthThreshold: parseFloat,
deintersect: parseBoolean,
intervals: parseIntervals,
units: parseUnits
};
const parseQuery = query =>
Object.keys(parsers).reduce((acc, paramKey) => {
if (query[paramKey]) {
const parser = parsers[paramKey];
acc[paramKey] = parser(query[paramKey]);
}
return acc;
}, defaults);
module.exports = parseQuery;
|
Introduce a new way to `require` plugins when using RequireJS (dev mode).
This is to fix an issue with timing that existed previously.
|
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the organization nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
window.process = {};
window.process._RJS_baseUrl = function(n)
{
return "..";
};
window.process._RJS_rootDir = function(n)
{
if (n == 2) return ".";
if (n == 1) return "readium-shared-js";
if (n == 0) return "readium-shared-js/readium-cfi-js";
};
// Used in readium-build-tools/pluginsConfigMaker
// and readium_shared_js/globalsSetup.
// Flag as not optimized by r.js
window._RJS_isBrowser = true;
require.config({
/* http://requirejs.org/docs/api.html#config-waitSeconds */
waitSeconds: 1,
paths:
{
"version":
process._RJS_rootDir(2) + '/dev/version'
}
});
|
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the organization nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
window.process = {};
window.process._RJS_baseUrl = function(n)
{
return "..";
};
window.process._RJS_rootDir = function(n)
{
if (n == 2) return ".";
if (n == 1) return "readium-shared-js";
if (n == 0) return "readium-shared-js/readium-cfi-js";
};
window.process._RJS_isBrowser = true;
require.config({
/* http://requirejs.org/docs/api.html#config-waitSeconds */
waitSeconds: 1,
paths:
{
"version":
process._RJS_rootDir(2) + '/dev/version'
}
});
|
Add TODO comment in loadRepos method to remind me to improve error handling
|
import * as types from './actionTypes';
import GithubAPI from '../api/githubAPI';
export function reposLoaded(repos){
return {type: types.REPOS_LOADED, repos};
}
export function branchesLoadedForRepo(branches, repo){
return {type: types.BRANCHES_LOADED_FOR_REPO, branches, repo};
}
export function loadRepos(){
return function(dispatch, getState) {
const currentState = getState();
return GithubAPI.getUserOwnedRepos(currentState.oauths.authenticatedUser.login).then(repos => {
dispatch(reposLoaded(repos));
}).catch(error => {
//TODO: Improve error handling instead of re-throwing error
throw(error);
});
};
}
export function loadBranchesForRepo(repoName){
return function(dispatch, getState) {
const currentState = getState();
let repo = currentState.repos.find(repo => repo.name == repoName);
return GithubAPI.getBranchesInRepo(repo.owner.login, repo.name).then(branches => {
dispatch(branchesLoadedForRepo(branches, repo));
}).catch(error => {
//TODO: Improve error handling instead of re-throwing error
throw(error);
});
};
}
|
import * as types from './actionTypes';
import GithubAPI from '../api/githubAPI';
export function reposLoaded(repos){
return {type: types.REPOS_LOADED, repos};
}
export function branchesLoadedForRepo(branches, repo){
return {type: types.BRANCHES_LOADED_FOR_REPO, branches, repo};
}
export function loadRepos(){
return function(dispatch, getState) {
const currentState = getState();
return GithubAPI.getUserOwnedRepos(currentState.oauths.authenticatedUser.login).then(repos => {
dispatch(reposLoaded(repos));
}).catch(error => {
throw(error);
});
};
}
export function loadBranchesForRepo(repoName){
return function(dispatch, getState) {
const currentState = getState();
let repo = currentState.repos.find(repo => repo.name == repoName);
return GithubAPI.getBranchesInRepo(repo.owner.login, repo.name).then(branches => {
dispatch(branchesLoadedForRepo(branches, repo));
}).catch(error => {
//TODO: Improve error handling instead of re-throwing error
throw(error);
});
};
}
|
Make stringprep exception extend IOException
|
/**
*
* Copyright © 2014-2015 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jxmpp.stringprep;
import java.io.IOException;
public class XmppStringprepException extends IOException {
/**
*
*/
private static final long serialVersionUID = -8491853210107124624L;
private final String causingString;
public XmppStringprepException(String causingString, Exception exception) {
super("XmppStringprepException caused by '" + causingString + "': " + exception);
initCause(exception);
this.causingString = causingString;
}
public XmppStringprepException(String causingString, String message) {
super(message);
this.causingString = causingString;
}
public String getCausingString() {
return causingString;
}
}
|
/**
*
* Copyright © 2014-2015 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jxmpp.stringprep;
public class XmppStringprepException extends Exception {
/**
*
*/
private static final long serialVersionUID = -8491853210107124624L;
private final String causingString;
public XmppStringprepException(String causingString, Exception exception) {
super("XmppStringprepException caused by '" + causingString + "': " + exception, exception);
this.causingString = causingString;
}
public XmppStringprepException(String causingString, String message) {
super(message);
this.causingString = causingString;
}
public String getCausingString() {
return causingString;
}
}
|
Expand environment variables when resolving parameters in selector
Signed-off-by: Miguel González <967cccf84fe94e619b35e1dff246b8b33dcf8eed@unity3d.com>
|
package com.codicesoftware.plugins.hudson.util;
import hudson.EnvVars;
import hudson.Util;
import hudson.model.ParameterValue;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SelectorParametersResolver {
private SelectorParametersResolver() { }
public static String resolve(String text, List<ParameterValue> parameters, EnvVars environment) {
if (parameters == null) {
return text;
}
Map<String, String> parametersMap = new HashMap<>();
for (ParameterValue parameter : parameters) {
if ((parameter != null) && (parameter.getName() != null) && (parameter.getValue() != null)) {
parametersMap.put(parameter.getName(), parameter.getValue().toString());
}
}
return environment.expand(Util.replaceMacro(
resolveLegacyFormat(text, parametersMap), parametersMap));
}
static String resolveLegacyFormat(String text, Map<String, String> parametersMap) {
String result = text;
for (Map.Entry<String, String> entry : parametersMap.entrySet()) {
result = result.replaceAll("%" + entry.getKey() + "%", entry.getValue());
}
return result;
}
}
|
package com.codicesoftware.plugins.hudson.util;
import hudson.Util;
import hudson.model.ParameterValue;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SelectorParametersResolver {
private SelectorParametersResolver() { }
public static String resolve(String text, List<ParameterValue> parameters) {
if (parameters == null) {
return text;
}
Map<String, String> parametersMap = new HashMap<>();
for (ParameterValue parameter : parameters) {
if ((parameter != null) && (parameter.getName() != null) && (parameter.getValue() != null)) {
parametersMap.put(parameter.getName(), parameter.getValue().toString());
}
}
return Util.replaceMacro(
resolveLegacyFormat(text, parametersMap), parametersMap);
}
static String resolveLegacyFormat(String text, Map<String, String> parametersMap) {
String result = text;
for (Map.Entry<String, String> entry : parametersMap.entrySet()) {
result = result.replaceAll("%" + entry.getKey() + "%", entry.getValue());
}
return result;
}
}
|
Make unserialization error message more friendly
|
protected function parsePayload($payload, $force = false)
{
if ($force || !isset($this->_payload_array))
{
$format = $this->getFormat();
$serializer = $this->getSerializer();
if ($serializer)
{
$payload_array = $serializer->unserialize($payload);
}
if (!isset($payload_array) || $payload_array === false)
{
throw new sfException(sprintf('Could not parse payload, not valid %s data', $format));
}
$filter_params = <?php var_export(array_flip(array_merge(
$this->configuration->getValue('get.global_additional_fields', array()),
$this->configuration->getValue('get.object_additional_fields', array())
))) ?>;
$this->_payload_array = array_diff_key($payload_array, $filter_params);
}
return $this->_payload_array;
}
|
protected function parsePayload($payload, $force = false)
{
if ($force || !isset($this->_payload_array))
{
$format = $this->getFormat();
$serializer = $this->getSerializer();
if ($serializer)
{
$payload_array = $serializer->unserialize($payload);
}
if (!isset($payload_array) || $payload_array === false)
{
throw new sfException(sprintf('Could not parse payload, obviously not a valid %s data!', $format));
}
$filter_params = <?php var_export(array_flip(array_merge(
$this->configuration->getValue('get.global_additional_fields', array()),
$this->configuration->getValue('get.object_additional_fields', array())
))) ?>;
$this->_payload_array = array_diff_key($payload_array, $filter_params);
}
return $this->_payload_array;
}
|
Use a clean instance of Footer component at each test
|
'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import Footer from './../Footer';
import { assert } from 'chai';
describe('Test Footer Component', () => {
var component;
beforeEach(function() {
component = TestUtils.renderIntoDocument(
<Footer />
);
});
it('verify the text content are correctly', () => {
let footerNode = ReactDOM.findDOMNode(component);
assert.equal(footerNode.textContent, 'Made with by @afonsopacifer');
});
it('link of github author should be https://github.com/afonsopacifer', () => {
let linkElement = TestUtils.scryRenderedDOMComponentsWithTag(component, 'a');
assert.equal(linkElement.length, 1);
assert.equal(linkElement[0].getAttribute('href'), 'https://github.com/afonsopacifer', 'the link is incorrect');
});
});
|
'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import Footer from './../Footer';
import { assert } from 'chai';
describe('Footer', () => {
const footer = TestUtils.renderIntoDocument(
<Footer />
);
it('verify the text content are correctly', () => {
let footerNode = ReactDOM.findDOMNode(footer);
assert.equal(footerNode.textContent, 'Made with by @afonsopacifer');
});
it('link of github author should be https://github.com/afonsopacifer', () => {
let linkElement = TestUtils.scryRenderedDOMComponentsWithTag(footer, 'a');
assert.equal(linkElement.length, 1);
assert.equal(linkElement[0].getAttribute('href'), 'https://github.com/afonsopacifer', 'the link is incorrect');
});
});
|
Add granuals to the capsul.data object individually.
|
module.exports = (function(){
// GET /users/:id/media?lat=<LAT>&lng=<LNG>&time=<TIME>
return function* collection(id) {
// // Twitter Requests
// var TwitterManager = require('../media/twitter');
// var twitterGranuals = yield TwitterManager.search(this.request.url)
// // Flickr Requests
// var FlickrManager = require('../media/flickr');
// var flickrGranuals = yield FlickrManager.search(this.request.url);
// Instagram Requests
var InstagramManager = require('../media/instagram');
var instagramGranuals = yield InstagramManager.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": []
}
function addGranuals(granualCollection) {
granualCollection.forEach(function(granual) {
capsul.data.push(granual);
});
}
// Joining all source granuals
addGranuals(instagramGranuals);
// addGranuals(twitterGranuals);
// addGranuals(flickrGranuals);
this.body = yield capsul;
}
})();
|
module.exports = (function(){
// GET /users/:id/media?lat=<LAT>&lng=<LNG>&time=<TIME>
return function* collection(id) {
// // Twitter Requests
// var TwitterManager = require('../media/twitter');
// var twitterGranuals = yield TwitterManager.search(this.request.url)
// // Flickr Requests
// var FlickrManager = require('../media/flickr');
// var flickrGranuals = yield FlickrManager.search(this.request.url);
// Instagram Requests
var InstagramManager = require('../media/instagram');
var instagramGranuals = yield InstagramManager.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": []
}
// Joining all source granuals
capsul.data.push(instagramGranuals);
// capsul.data.push(twitterGranuals);
// capsul.data.push(flickrGranuals);
this.body = yield capsul;
}
})();
|
Make subsequent runs only update resources
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
from collector.acled_africa import generate_urls
from collector.parser import parse
from collector.register import create_datasets, create_resources, create_gallery_items
def main():
'''
Wrapper.
'''
firstrun = False
server = 'http://test-data.hdx.rwlabs.org'
objects = generate_urls()
parsed_data = parse(objects)
if firstrun:
create_datasets(datasets=parsed_data['datasets'],
hdx_site=server, apikey=os.getenv('HDX_KEY'))
create_gallery_items(gallery_items=parsed_data['gallery_items'],
hdx_site=server, apikey=os.getenv('HDX_KEY'))
create_resources(resources=parsed_data['resources'],
hdx_site=server, apikey=os.getenv('HDX_KEY'))
if __name__ == '__main__':
main()
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
from collector.acled_africa import generate_urls
from collector.parser import parse
from collector.register import create_datasets, create_resources, create_gallery_items
def main():
'''
Wrapper.
'''
server = 'http://test-data.hdx.rwlabs.org'
objects = generate_urls()
parsed_data = parse(objects)
create_datasets(datasets=parsed_data['datasets'],
hdx_site=server, apikey=os.getenv('HDX_KEY'))
create_resources(resources=parsed_data['resources'],
hdx_site=server, apikey=os.getenv('HDX_KEY'))
create_gallery_items(gallery_items=parsed_data['gallery_items'],
hdx_site=server, apikey=os.getenv('HDX_KEY'))
if __name__ == '__main__':
main()
|
Add a banner to prepend to builds.
|
module.exports = function(grunt) {
grunt.initConfig({
pkg: '<json:package.json>',
meta: {
banner:
'// rivets.js\n' +
'// version: <%= pkg.version %>\n' +
'// author: <%= pkg.author %>\n' +
'// license: <%= pkg.licenses[0].type %>'
},
lint: {
files: ['grunt.js', 'lib/**/*.js', 'spec/**/*.js']
},
min: {
dist: {
src: ['<banner:meta.banner>', 'lib/rivets.js'],
dest: 'lib/rivets.min.js'
}
},
watch: {
files: 'src/rivets.coffee',
tasks: 'build'
},
});
grunt.registerTask('default', 'watch');
grunt.registerTask('compile', 'Compiles CoffeeScript source into JavaScript.', function(){
var coffee = require('coffee-script');
var js = coffee.compile(grunt.file.read('src/rivets.coffee'));
var banner = grunt.task.directive('<banner:meta.banner>', function() { return null; });
if (js) grunt.file.write('lib/rivets.js', banner + js);
});
grunt.registerTask('build', 'compile min');
};
|
module.exports = function(grunt) {
grunt.initConfig({
lint: {
files: ['grunt.js', 'lib/**/*.js', 'spec/**/*.js']
},
min: {
dist: {
src: 'lib/rivets.js',
dest: 'lib/rivets.min.js'
}
},
watch: {
files: 'src/rivets.coffee',
tasks: 'build'
},
});
grunt.registerTask('default', 'watch');
grunt.registerTask('compile', 'Compiles CoffeeScript source into JavaScript.', function(){
var coffee = require('coffee-script');
var js = coffee.compile(grunt.file.read('src/rivets.coffee'));
if (js) grunt.file.write('lib/rivets.js', js);
});
grunt.registerTask('build', 'compile min');
};
|
Add timeout and fix logic
|
let counter = (function(value = 0) {
const getValue = function() {
return value;
}
const changeBy = function (n) {
if (isNaN(n)) {
throw `${n} is not a number`;
}
value += n;
return value;
}
const add = function(n) {
return changeBy(n);
}
const subtract = function(n) {
return changeBy(-n);
}
return {
getValue : getValue,
add : add,
increment : () => { return add(1); },
subtract : subtract,
decrement : () => { return subtract(1); },
}
})();
function traceCounterMethods(counter, total) {
const handlers = {
get: function(target, propKey, receiver) {
const method = target[propKey];
return function (...args) {
let result = method.apply(this, args);
let progress = (1 - (result + 1) / (total + 1)) * 100;
let progressString = `${Math.floor(progress)}%`;
console.log(progressString);
$("#progress").animate({width : progressString}, 300);
if (result < 0) {
$('body').removeClass('loading');
setTimeout(() => $('#progress-bar').animate({width : 0}, 300), 1000);
}
return result;
};
}
};
return new Proxy(counter, handlers);
}
|
let counter = (function(value = 0) {
const getValue = function() {
return value;
}
const changeBy = function (n) {
if (isNaN(n)) {
throw `${n} is not a number`;
}
value += n;
return value;
}
const add = function(n) {
return changeBy(n);
}
const subtract = function(n) {
return changeBy(-n);
}
return {
getValue : getValue,
add : add,
increment : () => { return add(1); },
subtract : subtract,
decrement : () => { return subtract(1); },
}
})();
function traceCounterMethods(counter, total) {
const handlers = {
get: function(target, propKey, receiver) {
const method = target[propKey];
return function (...args) {
let result = method.apply(this, args);
if (result < 0) {
$('body').removeClass('loading');
}
let progress = (1 - (result + 1) / (total + 1)) * 100;
let progressString = `${Math.floor(progress)}%`;
console.log(progressString);
$("#loading-bar::after").animate({width : progressString});
return result;
};
}
};
return new Proxy(counter, handlers);
}
|
Set eslint config as root
|
module.exports = {
"root": true,
"extends": "airbnb-base/legacy",
"parserOptions": {
"ecmaVersion": 5
},
"env": {
"browser": true,
"node": true
},
"rules": {
"indent": ["error", 2],
"brace-style": ["error", "1tbs"],
"curly": ["error", "all"],
"func-call-spacing": ["error", "never"],
"linebreak-style": "off",
"quotes": ["error", "single"],
"semi": ["error", "always"],
"space-before-function-paren": ["error", "never"],
"func-names": ["error", "never"],
"no-unused-vars": "off",
"no-underscore-dangle": "off"
},
"globals": {
"chai": true,
"rewire": true,
"describe": true,
"expect": true,
"assert": true,
"it": true,
"$": true
}
};
|
module.exports = {
"extends": "airbnb-base/legacy",
"parserOptions": {
"ecmaVersion": 5
},
"env": {
"browser": true,
"node": true
},
"rules": {
"indent": ["error", 2],
"brace-style": ["error", "1tbs"],
"curly": ["error", "all"],
"func-call-spacing": ["error", "never"],
"linebreak-style": "off",
"quotes": ["error", "single"],
"semi": ["error", "always"],
"space-before-function-paren": ["error", "never"],
"func-names": ["error", "never"],
"no-unused-vars": "off",
"no-underscore-dangle": "off"
},
"globals": {
"chai": true,
"rewire": true,
"describe": true,
"expect": true,
"assert": true,
"it": true,
"$": true
}
};
|
Fix expected failure decorator in test.
|
import pytest
import chatexchange
from chatexchange.events import MessageEdited
import live_testing
if live_testing:
@pytest.mark.xfail(reason="not implemented yet")
def test_room_iterators():
client = chatexchange.Client(
'stackexchange.com', live_testing.email, live_testing.password)
me = client.get_me()
sandbox = client.get_room(11540)
my_message = None
with sandbox.messages() as messages:
sandbox.send_message("hello worl")
for message in messages:
if message.owner is me:
my_message = message
assert my_message.content == "hello worl"
break
with sandbox.events(MessageEdited) as edits:
my_message.edit("hello world")
for edit in edits:
assert isinstance(edit, MessageEdited)
if edit.message is my_message:
assert my_message.content == "hello world"
break
|
import pytest
import chatexchange
from chatexchange.events import MessageEdited
import live_testing
if live_testing:
@pytest.mark.xfail("not implemented yet")
def test_room_iterators():
client = chatexchange.Client(
'stackexchange.com', live_testing.email, live_testing.password)
me = client.get_me()
sandbox = client.get_room(11540)
my_message = None
with sandbox.messages() as messages:
sandbox.send_message("hello worl")
for message in messages:
if message.owner is me:
my_message = message
assert my_message.content == "hello worl"
break
with sandbox.events(MessageEdited) as edits:
my_message.edit("hello world")
for edit in edits:
assert isinstance(edit, MessageEdited)
if edit.message is my_message:
assert my_message.content == "hello world"
break
|
Fix the unnecessary list comprehension
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import re
import requests
from zhihudaily.cache import cache
@cache.memoize(timeout=1200)
def make_request(url):
session = requests.Session()
session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux \
x86_64; rv:28.0) Gecko/20100101 Firefox/28.0'})
r = session.get(url)
return r
def get_news_info(response):
display_date = response.json()['display_date']
date = response.json()['date']
news_list = response.json()['news']
return display_date, date, news_list
def handle_image(news_list):
"""Point all the images to my server, because use zhihudaily's
images directly may get 403 error.
"""
for news in news_list:
items = re.search(r'(?<=http://)(.*?)\.zhimg.com/(.*)$',
news['image']).groups()
news['image'] = (
'http://zhihudaily.lord63.com/img/{0}/{1}'.format(
items[0], items[1]))
return news_list
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import re
import requests
from zhihudaily.cache import cache
@cache.memoize(timeout=1200)
def make_request(url):
session = requests.Session()
session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux \
x86_64; rv:28.0) Gecko/20100101 Firefox/28.0'})
r = session.get(url)
return r
def get_news_info(response):
display_date = response.json()['display_date']
date = response.json()['date']
news_list = [item for item in response.json()['news']]
return display_date, date, news_list
def handle_image(news_list):
"""Point all the images to my server, because use zhihudaily's
images directly may get 403 error.
"""
for news in news_list:
items = re.search(r'(?<=http://)(.*?)\.zhimg.com/(.*)$',
news['image']).groups()
news['image'] = (
'http://zhihudaily.lord63.com/img/{0}/{1}'.format(
items[0], items[1]))
return news_list
|
Add warning about prod needing full file paths
|
/* remember that file paths need to be full, or it will only work in dev, not in prod */
module.exports = {
uri: 'http://localhost:3000/',
sessionSecret: 'sessionSecretString',
trust_proxy: false,
auth: {
google: {
clientId: 'googleClientId',
clientSecret: 'googleCLientSecret',
callbackURL: 'http://localhost:3000/auth/google/callback'
}
},
redis: {
host: '127.0.0.1',
port: 6379
},
mongo: {
servers: ['mongodb://localhost/boilerplate'],
replset: null
},
locales: ['en', 'nb'],
defaultLocale: 'en'
};
/* secret gen: cat /dev/urandom| base64 | fold -w 64 */
|
module.exports = {
uri: 'http://localhost:3000/',
sessionSecret: 'sessionSecretString',
trust_proxy: false,
auth: {
google: {
clientId: 'googleClientId',
clientSecret: 'googleCLientSecret',
callbackURL: 'http://localhost:3000/auth/google/callback'
}
},
redis: {
host: '127.0.0.1',
port: 6379
},
mongo: {
servers: ['mongodb://localhost/boilerplate'],
replset: null
},
locales: ['en', 'nb'],
defaultLocale: 'en'
};
/* secret gen: cat /dev/urandom| base64 | fold -w 64 */
|
Fix coverage validation for phpunit 7 (backguards compatibility.
|
<?php
namespace PhpGitHooks\Module\PhpUnit\Infrastructure\Tool;
use PhpGitHooks\Infrastructure\Tool\ToolPathFinder;
use PhpGitHooks\Module\PhpUnit\Model\StrictCoverageProcessorInterface;
use Symfony\Component\Process\Process;
class StrictCoverageProcessor implements StrictCoverageProcessorInterface
{
/**
* @var ToolPathFinder
*/
private $toolPathFinder;
/**
* StrictCoverageProcessor constructor.
*
* @param ToolPathFinder $toolPathFinder
*/
public function __construct(ToolPathFinder $toolPathFinder)
{
$this->toolPathFinder = $toolPathFinder;
}
/**
* @return float
*/
public function process()
{
$tool = $this->toolPathFinder->find('phpunit');
$command = 'php '.$tool.' --coverage-text|grep Classes| tr -s \' \' |cut -d " " -f 3|cut -d "%" -f 1';
$process = new Process($command);
$process->run();
return (float) $process->getOutput();
}
}
|
<?php
namespace PhpGitHooks\Module\PhpUnit\Infrastructure\Tool;
use PhpGitHooks\Infrastructure\Tool\ToolPathFinder;
use PhpGitHooks\Module\PhpUnit\Model\StrictCoverageProcessorInterface;
use Symfony\Component\Process\Process;
class StrictCoverageProcessor implements StrictCoverageProcessorInterface
{
/**
* @var ToolPathFinder
*/
private $toolPathFinder;
/**
* StrictCoverageProcessor constructor.
*
* @param ToolPathFinder $toolPathFinder
*/
public function __construct(ToolPathFinder $toolPathFinder)
{
$this->toolPathFinder = $toolPathFinder;
}
/**
* @return float
*/
public function process()
{
$tool = $this->toolPathFinder->find('phpunit');
$command = 'php '.$tool.' --coverage-text|grep Classes|cut -d " " -f 5|cut -d "%" -f 1';
$process = new Process($command);
$process->run();
return (float) $process->getOutput();
}
}
|
Handle empty values on person better (force to NULL)
|
<?
include '../scat.php';
include '../lib/person.php';
$person_id= (int)$_REQUEST['id'];
$person= person_load($db, $person_id);
if (!$person)
die_jsonp('No such person.');
if (isset($_REQUEST['phone'])) {
$_REQUEST['loyalty_number']= preg_replace('/[^\d]/', '', $_REQUEST['phone']);
}
// TODO: reset sms_ok and email_ok when email or phone changed
foreach (array('name', 'role', 'company', 'email', 'notes',
'phone', 'loyalty_number', 'tax_id', 'address') as $key) {
if (isset($_REQUEST[$key])) {
$value= trim($_REQUEST[$key]);
/* Turn empty strings into NULL, escape others and wrap in quotes */
$value= ($value != '') ? "'" . $db->escape($value) . "'" : 'NULL';
$q= "UPDATE person SET $key = $value WHERE id = $person_id";
$r= $db->query($q)
or die_query($db, $q);
}
}
if (isset($_REQUEST['active'])) {
$active= (int)$_REQUEST['active'];
$q= "UPDATE person
SET active = $active
WHERE id = $person_id";
$r= $db->query($q)
or die_query($db, $q);
}
$person= person_load($db, $person_id);
echo jsonp(array('person' => $person));
|
<?
include '../scat.php';
include '../lib/person.php';
$person_id= (int)$_REQUEST['id'];
$person= person_load($db, $person_id);
if (!$person)
die_jsonp('No such person.');
if ($_REQUEST['phone']) {
$_REQUEST['loyalty_number']= preg_replace('/[^\d]/', '', $_REQUEST['phone']);
}
foreach (array('name', 'role', 'company', 'email', 'notes',
'phone', 'loyalty_number', 'tax_id', 'address') as $key) {
if (isset($_REQUEST[$key])) {
$value= $db->real_escape_string($_REQUEST[$key]);
$q= "UPDATE person SET $key = '$value' WHERE id = $person_id";
$r= $db->query($q)
or die_query($db, $q);
}
}
if (isset($_REQUEST['active'])) {
$active= (int)$_REQUEST['active'];
$q= "UPDATE person
SET active = $active
WHERE id = $person_id";
$r= $db->query($q)
or die_query($db, $q);
}
$person= person_load($db, $person_id);
echo jsonp(array('person' => $person));
|
Add todo item for shard stats collector
|
<?php
namespace Maghead\Sharding;
use Maghead\Sharding\Shard;
use Maghead\Schema\BaseSchema;
class ShardStatsCollector
{
protected $shards;
public function __construct(ShardCollection $shards)
{
$this->shards = $shards;
}
public function collect(BaseSchema $schema)
{
$stats = [];
$repoClass = $schema->getRepoClass();
foreach ($this->shards as $shard) {
$repo = $shard->repo($repoClass);
$startTime = microtime(true);
$stats[$shard->id]['rows'] = count($repo);
$stats[$shard->id]['queryTime'] = microtime(true) - $startTime;
// TODO: query table/index stats
}
return $stats;
}
}
|
<?php
namespace Maghead\Sharding;
use Maghead\Sharding\Shard;
use Maghead\Schema\BaseSchema;
class ShardStatsCollector
{
protected $shards;
public function __construct(ShardCollection $shards)
{
$this->shards = $shards;
}
public function collect(BaseSchema $schema)
{
$stats = [];
$repoClass = $schema->getRepoClass();
foreach ($this->shards as $shard) {
$repo = $shard->repo($repoClass);
$startTime = microtime(true);
$stats[$shard->id]['rows'] = count($repo);
$stats[$shard->id]['queryTime'] = microtime(true) - $startTime;
}
return $stats;
}
}
|
Fix the bug that causes "set frame range" error on a scene that has no rigid body world.
|
# -*- coding: utf-8 -*-
import bpy
def setupFrameRanges():
s, e = 1, 1
for i in bpy.data.actions:
ts, te = i.frame_range
s = min(s, ts)
e = max(e, te)
bpy.context.scene.frame_start = s
bpy.context.scene.frame_end = e
if bpy.context.scene.rigidbody_world is not None:
bpy.context.scene.rigidbody_world.point_cache.frame_start = s
bpy.context.scene.rigidbody_world.point_cache.frame_end = e
def setupLighting():
bpy.context.scene.world.light_settings.use_ambient_occlusion = True
bpy.context.scene.world.light_settings.use_environment_light = True
bpy.context.scene.world.light_settings.use_indirect_light = True
def setupFps():
bpy.context.scene.render.fps = 30
bpy.context.scene.render.fps_base = 1
|
# -*- coding: utf-8 -*-
import bpy
def setupFrameRanges():
s, e = 1, 1
for i in bpy.data.actions:
ts, te = i.frame_range
s = min(s, ts)
e = max(e, te)
bpy.context.scene.frame_start = s
bpy.context.scene.frame_end = e
bpy.context.scene.rigidbody_world.point_cache.frame_start = s
bpy.context.scene.rigidbody_world.point_cache.frame_end = e
def setupLighting():
bpy.context.scene.world.light_settings.use_ambient_occlusion = True
bpy.context.scene.world.light_settings.use_environment_light = True
bpy.context.scene.world.light_settings.use_indirect_light = True
def setupFps():
bpy.context.scene.render.fps = 30
bpy.context.scene.render.fps_base = 1
|
Interpolate parameters in baseURL as well
|
import _merge from 'lodash/merge'
import _template from 'lodash/template'
/**
* Send a request using axios. Designed to be used by Model and their instance
*
* @param {Object} caller Object that call this function
* @param {Object} config Axios config
* @param {Object} [options]
* @param {string} [options.on] Which route ('collection' or 'member')
* @return {Promise} Axios promise
*/
export function request (caller, config, options = {}) {
const interpolate = caller.getOption('urlParamPattern')
const params = caller.toParam()
const route = caller.getRoute(options.on)
// set variables pre request
caller._pending = true
caller._routeParams = {}
// merge default config (api) with config
config = _merge({}, caller.axios(), config)
// prepend route to url and interpolate url and baseURL
config.url = _template([route, config.url].join(''), { interpolate })(params)
config.baseURL = _template(config.baseURL, { interpolate })(params)
// send request and handle responses
return caller.getGlobal('axios')(config)
.then((response) => {
caller._pending = false
return response
})
.catch((error) => {
caller._pending = false
throw error
})
}
|
import _merge from 'lodash/merge'
import _template from 'lodash/template'
/**
* Send a request using axios. Designed to be used by Model and their instance
*
* @param {Object} caller Object that call this function
* @param {Object} config Axios config
* @param {Object} [options]
* @param {string} [options.on] Which route ('collection' or 'member')
* @return {Promise} Axios promise
*/
export function request (caller, config, options = {}) {
const interpolate = caller.getOption('urlParamPattern')
const params = caller.toParam()
const route = caller.getRoute(options.on)
// set variables pre request
caller._pending = true
caller._routeParams = {}
// merge default config (api) with config
config = _merge({}, caller.axios(), config)
// prepend route to url and replace variables
config.url = _template([route, config.url].join(''), { interpolate })(params)
// send request and handle responses
return caller.getGlobal('axios')(config)
.then((response) => {
caller._pending = false
return response
})
.catch((error) => {
caller._pending = false
throw error
})
}
|
Switch to more robust remaining semantic.
|
var ByteBuffer = require('bytebuffer');
var ProtoBuf = require('protobufjs');
var path = require('path');
var ChunkData =
ProtoBuf
.loadProtoFile(path.join(__dirname, 'ChunkData.proto'))
.build('ChunkData');
var DataRedirectRequestType = {
isBinary: true,
getRequestURL: function(props) {
return props.url;
},
parseResponseBody: function(rsp) {
var buf = ByteBuffer.wrap(rsp);
var chunks = [];
while (buf.remaining() > 0) {
var size = buf.readUint32();
var slice = buf.slice(buf.offset, buf.offset + size);
buf.skip(size);
chunks.push(ChunkData.decode(slice.toBuffer()));
}
return chunks;
}
};
module.exports = DataRedirectRequestType;
|
var ByteBuffer = require('bytebuffer');
var ProtoBuf = require('protobufjs');
var path = require('path');
var ChunkData =
ProtoBuf
.loadProtoFile(path.join(__dirname, 'ChunkData.proto'))
.build('ChunkData');
var DataRedirectRequestType = {
isBinary: true,
getRequestURL: function(props) {
return props.url;
},
parseResponseBody: function(rsp) {
var buf = ByteBuffer.wrap(rsp);
var chunks = [];
while(buf.remaining()) {
var size = buf.readUint32();
var slice = buf.slice(buf.offset, buf.offset + size);
buf.skip(size);
chunks.push(ChunkData.decode(slice.toBuffer()));
}
return chunks;
}
};
module.exports = DataRedirectRequestType;
|
Remove copy & paste issues
|
import { reaction, runInAction } from 'mobx';
import { SettingsWSStore } from './store';
import state, { resetState } from './state';
const debug = require('debug')('Franz:feature:settingsWS');
let store = null;
export default function initSettingsWebSocket(stores, actions) {
const { features } = stores;
// Toggle SettingsWebSocket feature
reaction(
() => (
features.features.isSettingsWSEnabled
),
(isEnabled) => {
if (isEnabled) {
debug('Initializing `settingsWS` feature');
store = new SettingsWSStore(stores, null, actions, state);
store.initialize();
runInAction(() => { state.isFeatureActive = true; });
} else if (store) {
debug('Disabling `settingsWS` feature');
runInAction(() => { state.isFeatureActive = false; });
store.teardown();
store = null;
resetState(); // Reset state to default
}
},
{
fireImmediately: true,
},
);
}
|
import { reaction, runInAction } from 'mobx';
import { SettingsWSStore } from './store';
import state, { resetState } from './state';
const debug = require('debug')('Franz:feature:settingsWS');
let store = null;
export default function initAnnouncements(stores, actions) {
const { features } = stores;
// Toggle workspace feature
reaction(
() => (
features.features.isSettingsWSEnabled
),
(isEnabled) => {
if (isEnabled) {
debug('Initializing `settingsWS` feature');
store = new SettingsWSStore(stores, null, actions, state);
store.initialize();
runInAction(() => { state.isFeatureActive = true; });
} else if (store) {
debug('Disabling `settingsWS` feature');
runInAction(() => { state.isFeatureActive = false; });
store.teardown();
store = null;
resetState(); // Reset state to default
}
},
{
fireImmediately: true,
},
);
}
|
Remove notification from news article model.
|
angular.module( 'gj.Game.NewsArticle' ).factory( 'Game_NewsArticle', function( Model, User, Game, KeyGroup )
{
function Game_NewsArticle( data )
{
if ( data ) {
angular.extend( this, data );
if ( data.game ) {
this.game = new Game( data.game );
}
if ( data.key_groups ) {
this.key_groups = KeyGroup.populate( data.key_groups );
}
}
}
Game_NewsArticle.prototype.$save = function()
{
var options = {
allowComplexData: [ 'keyGroups' ],
};
if ( this.id ) {
return this.$_save( '/web/dash/developer/games/news/save/' + this.game_id + '/' + this.id, 'newsArticle', options );
}
else {
return this.$_save( '/web/dash/developer/games/news/save/' + this.game_id, 'newsArticle', options );
}
};
Game_NewsArticle.prototype.$remove = function()
{
return this.$_remove( '/web/dash/developer/games/news/remove/' + this.game_id + '/' + this.id );
};
return Model.create( Game_NewsArticle );
} );
|
angular.module( 'gj.Game.NewsArticle' ).factory( 'Game_NewsArticle', function( Model, User, Game, Notification, KeyGroup )
{
function Game_NewsArticle( data )
{
if ( data ) {
angular.extend( this, data );
if ( data.game ) {
this.game = new Game( data.game );
}
if ( data.notification ) {
this.notification = new Notification( data.notification );
}
if ( data.key_groups ) {
this.key_groups = KeyGroup.populate( data.key_groups );
}
}
}
Game_NewsArticle.prototype.$save = function()
{
var options = {
allowComplexData: [ 'keyGroups' ],
};
if ( this.id ) {
return this.$_save( '/web/dash/developer/games/news/save/' + this.game_id + '/' + this.id, 'newsArticle', options );
}
else {
return this.$_save( '/web/dash/developer/games/news/save/' + this.game_id, 'newsArticle', options );
}
};
Game_NewsArticle.prototype.$remove = function()
{
return this.$_remove( '/web/dash/developer/games/news/remove/' + this.game_id + '/' + this.id );
};
return Model.create( Game_NewsArticle );
} );
|
Fix calcLineNo for undefined offset
- now returns -1
|
/**
* copyObject(object, [recurse]) -- for all JS Objects
*
* Copies all properties and the prototype to a new object
* Optionally set recurse to array containing the properties, on wich this function should be called recursively
*/
function copyObject(object, recurse) {
var new_obj = Object.create(Object.getPrototypeOf(object));
recurse = (recurse) ? recurse : [];
for(var prop in object) {
new_obj[prop] = object[prop];
if(recurse.indexOf(prop) !== -1) new_obj[prop] = copyObject(object[prop]);
}
return new_obj;
}
function repeatString(str, times) {
for(var padding = "", i=0; i < times; i++) {
padding += str;
}
return padding;
}
function isInt(n) {
return String(parseInt(n)) === String(n) && parseInt(n) >= 0 && isFinite(n);
}
function calcLineNo(source, offset) {
return offset ? source.substr( 0, offset ).split("\n").length : -1;
};
function getLineExcerpt(source, offset) {
return source.substr( 0, offset ).split("\n").pop() + source.substr( offset, 250 ).split("\n")[0];
};
function getLineCol(source, offset) {
return source.substr( 0, offset ).split("\n").pop().length+1
};
|
/**
* copyObject(object, [recurse]) -- for all JS Objects
*
* Copies all properties and the prototype to a new object
* Optionally set recurse to array containing the properties, on wich this function should be called recursively
*/
function copyObject(object, recurse) {
var new_obj = Object.create(Object.getPrototypeOf(object));
recurse = (recurse) ? recurse : [];
for(var prop in object) {
new_obj[prop] = object[prop];
if(recurse.indexOf(prop) !== -1) new_obj[prop] = copyObject(object[prop]);
}
return new_obj;
}
function repeatString(str, times) {
for(var padding = "", i=0; i < times; i++) {
padding += str;
}
return padding;
}
function isInt(n) {
return String(parseInt(n)) === String(n) && parseInt(n) >= 0 && isFinite(n);
}
function calcLineNo(source, offset) {
return source.substr( 0, offset ).split("\n").length;
};
function getLineExcerpt(source, offset) {
return source.substr( 0, offset ).split("\n").pop() + source.substr( offset, 250 ).split("\n")[0];
};
function getLineCol(source, offset) {
return source.substr( 0, offset ).split("\n").pop().length+1
};
|
Refactor the taxonomy pages plugin to use site.config data.
|
var fs = require('fs')
var natural = require('natural')
var inflector = new natural.NounInflector()
var _ = require('lodash-node/modern')
module.exports = function() {
var Page = this.Page
var Taxonomy = this.Taxonomy
var config = this.config
function layoutExists(layout) {
return fs.existsSync(config.layoutsDirectory + '/' + layout + '.html')
}
this.events.on('beforeBuild', function() {
Taxonomy.each(function(taxonomy) {
if (layoutExists(taxonomy.type.toLowerCase())) {
var obj = {
content: '',
title: taxonomy.value,
permalink: (taxonomy.typePlural + '/' + taxonomy.value).toLowerCase(),
layout: taxonomy.type.toLowerCase()
}
// add the taxonomy type and value to the page data
obj[taxonomy.type] = taxonomy.value
// add the taxonomy to the query params
obj.query = {}
obj.query[taxonomy.type] = taxonomy.value
taxonomy.page = new Page(obj)
}
})
})
}
|
var fs = require('fs')
var natural = require('natural')
var inflector = new natural.NounInflector()
var _ = require('lodash-node/modern')
var config = require('../lib/config')
var Page = require('../lib/page')
var Taxonomy = require('../lib/taxonomy')
var layoutExists = function(layout) {
return fs.existsSync(config.layoutsDirectory + '/' + layout + '.html')
}
module.exports = function() {
this.events.on('beforeBuild', function() {
Taxonomy.each(function(taxonomy) {
if (layoutExists(taxonomy.type.toLowerCase())) {
var obj = {
content: '',
title: taxonomy.value,
permalink: (taxonomy.typePlural + '/' + taxonomy.value).toLowerCase(),
layout: taxonomy.type.toLowerCase()
}
// add the taxonomy type and value to the page data
obj[taxonomy.type] = taxonomy.value
// add the taxonomy to the query params
obj.query = {}
obj.query[taxonomy.type] = taxonomy.value
taxonomy.page = new Page(obj)
}
})
})
}
|
Update import in response to deprecation warning
|
import { expect } from 'chai';
import { launchNewNotebook } from '../../build/main/launch';
import {ipcMain as ipc} from 'electron';
describe('launch', () => {
describe('launchNewNotebook', () => {
it('launches a window', function() {
// The render window may take a while to display on slow machines.
// Set the timeout to 5s
this.timeout(5000);
return launchNewNotebook().then(win => {
expect(win).to.not.be.undefined;
return new Promise(resolve => {
// Query selector all and make sure the length for .cells is
// greater than 0. Use IPC to return the results from the
// render window.
ipc.on('queryLength', function (event, value) {
expect(value).to.be.greaterThan(0);
resolve();
});
win.webContents.executeJavaScript(`
var ipc = require('ipc');
ipc.send('queryLength', document.querySelectorAll('div.cell').length);
`);
});
});
});
});
});
|
import { expect } from 'chai';
import { launchNewNotebook } from '../../build/main/launch';
var ipc = require('ipc');
describe('launch', () => {
describe('launchNewNotebook', () => {
it('launches a window', function() {
// The render window may take a while to display on slow machines.
// Set the timeout to 5s
this.timeout(5000);
return launchNewNotebook().then(win => {
expect(win).to.not.be.undefined;
return new Promise(resolve => {
// Query selector all and make sure the length for .cells is
// greater than 0. Use IPC to return the results from the
// render window.
ipc.on('queryLength', function (event, value) {
expect(value).to.be.greaterThan(0);
resolve();
});
win.webContents.executeJavaScript(`
var ipc = require('ipc');
ipc.send('queryLength', document.querySelectorAll('div.cell').length);
`);
});
});
});
});
});
|
Make sure the target of Say isn't in Unicode, otherwise Twisted complains
|
from CommandTemplate import CommandTemplate
from IrcMessage import IrcMessage
class Command(CommandTemplate):
triggers = ['say', 'do', 'notice']
helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')"
adminOnly = True
showInCommandList = False
def execute(self, message):
"""
:type message: IrcMessage
"""
if message.messagePartsLength < 2:
message.bot.say(message.source, u"Please provide both a channel or user name to say something to, and the text to say")
#Check if we're in the channel we have to say something to
elif not message.isPrivateMessage and message.messageParts[0] not in message.bot.channelsUserList:
message.bot.say(message.source, u"I'm not in that channel, so I can't say anything in there, sorry.")
#Nothing's stopping us now! Say it!
else:
messageToSay = u" ".join(message.messageParts[1:])
messageType = u'say'
if message.trigger == u'do':
messageType = u'action'
elif message.trigger == u'notice':
messageType = u'notice'
target = message.messageParts[0]
#Make absolutely sure the target isn't unicode, because Twisted doesn't like that
try:
target = target.encode('utf-8')
except (UnicodeEncodeError, UnicodeDecodeError):
print "[Say module] Unable to convert '{}' to a string".format(target)
message.bot.sendMessage(target, messageToSay, messageType)
|
from CommandTemplate import CommandTemplate
from IrcMessage import IrcMessage
class Command(CommandTemplate):
triggers = ['say', 'do', 'notice']
helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')"
adminOnly = True
showInCommandList = False
def execute(self, message):
"""
:type message: IrcMessage
"""
if message.messagePartsLength < 2:
message.bot.say(message.source, u"Please provide both a channel or user name to say something to, and the text to say")
#Check if we're in the channel we have to say something to
elif not message.isPrivateMessage and message.messageParts[0] not in message.bot.channelsUserList:
message.bot.say(message.source, u"I'm not in that channel, so I can't say anything in there, sorry.")
#Nothing's stopping us now! Say it!
else:
messageToSay = u" ".join(message.messageParts[1:])
messageType = u'say'
if message.trigger == u'do':
messageType = u'action'
elif message.trigger == u'notice':
messageType = u'notice'
message.bot.sendMessage(message.messageParts[0], messageToSay, messageType)
|
Add some things from tutorial
|
var HomeView = function(store) {
this.initialize = function() {
// Define a div wrapper for the view. The div wrapper is used to attach events.
this.el = $('<div/>');
this.el.on('keyup', '.search-key', this.findByName);
};
this.render = function() {
this.el.html(HomeView.template());
return this;
};
this.findByName = function() {
console.log('findByName');
store.findByName($('.search-key').val(), function(employees) {
$('.employee-list').html(HomeView.liTemplate(employees));
});
};
this.initialize();
}
HomeView.template = Handlebars.compile($("#home-tpl").html());
HomeView.liTemplate = Handlebars.compile($("#employee-li-tpl").html());
|
var HomeView = function(store) {
this.initialize = function() {
// Define a div wrapper for the view. The div wrapper is used to attach events.
this.el = $('<div/>');
this.el.on('keyup', '.search-key', this.findByName);
};
this.render: function() {
this.el.html(HomeView.template());
return this;
},
findByName: function() {
console.log('findByName');
store.findByName($('.search-key').val(), function(employees) {
$('.employee-list').html(HomeView.liTemplate(employees));
});
},
this.initialize();
}
HomeView.template = Handlebars.compile($("#home-tpl").html());
HomeView.liTemplate = Handlebars.compile($("#employee-li-tpl").html());
|
Add dividers to radiolist demo.
svn commit r16811
|
<?php
/* vim: set noexpandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
require_once 'Demo.php';
/**
* A demo using a radiolist
*
* @package SwatDemo
* @copyright 2005-2007 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
class RadioListDemo extends Demo
{
// {{{ public function buildDemoUI()
public function buildDemoUI(SwatUI $ui)
{
$radiolist = $ui->getWidget('radiolist');
$radiolist->addOptionsByArray(array(
0 => 'Apple',
1 => 'Orange',
2 => 'Banana',
3 => 'Pear',
4 => 'Pineapple',
5 => 'Kiwi',
6 => 'Tangerine',
7 => 'Grapefruit',
8 => 'Strawberry'));
$radiolist->addDivider();
$radiolist->addOption(new SwatOption(9, 'I don\'t like fruit'));
$radiotable = $ui->getWidget('radiotable');
$radiotable->addOptionsByArray(array(
0 => 'Apple',
1 => 'Orange',
2 => 'Banana',
3 => 'Pear',
4 => 'Pineapple',
5 => 'Kiwi',
6 => 'Tangerine',
7 => 'Grapefruit',
8 => 'Strawberry'));
$radiotable->addDivider();
$radiotable->addOption(new SwatOption(9, 'I don\'t like fruit'));
}
// }}}
}
?>
|
<?php
/* vim: set noexpandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
require_once 'Demo.php';
/**
* A demo using a radiolist
*
* @package SwatDemo
* @copyright 2005-2007 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
class RadioListDemo extends Demo
{
// {{{ public function buildDemoUI()
public function buildDemoUI(SwatUI $ui)
{
$radiolist = $ui->getWidget('radiolist');
$radiolist->addOptionsByArray(array(
0 => 'Apple',
1 => 'Orange',
2 => 'Banana',
3 => 'Pear',
4 => 'Pineapple',
5 => 'Kiwi',
6 => 'Tangerine',
7 => 'Grapefruit',
8 => 'Strawberry'));
$radiotable = $ui->getWidget('radiotable');
$radiotable->addOptionsByArray(array(
0 => 'Apple',
1 => 'Orange',
2 => 'Banana',
3 => 'Pear',
4 => 'Pineapple',
5 => 'Kiwi',
6 => 'Tangerine',
7 => 'Grapefruit',
8 => 'Strawberry'));
}
// }}}
}
?>
|
Add "Python 2" classifier since it works (according to Travis CI).
|
#!/usr/bin/env python
from setuptools import setup
setup(
name='rinse',
version='0.1.2',
description='Python3 SOAP client built with lxml and requests.',
long_description=open('README.rst').read(),
author='Tyson Clugg',
author_email='tyson@clugg.net',
url='http://github.com/tysonclugg/rinse',
license='MIT',
packages=['rinse'],
test_suite='rinse.tests',
install_requires=[
'defusedxml',
'lxml',
'requests',
],
classifiers=[
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
],
)
|
#!/usr/bin/env python
from setuptools import setup
setup(
name='rinse',
version='0.1.2',
description='Python3 SOAP client built with lxml and requests.',
long_description=open('README.rst').read(),
author='Tyson Clugg',
author_email='tyson@clugg.net',
url='http://github.com/tysonclugg/rinse',
license='MIT',
packages=['rinse'],
test_suite='rinse.tests',
install_requires=[
'defusedxml',
'lxml',
'requests',
],
classifiers=[
"Programming Language :: Python :: 3",
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
],
)
|
mpd: Add TODO for handling unknown outpitid
|
from __future__ import unicode_literals
from mopidy.frontends.mpd.protocol import handle_request
@handle_request(r'^disableoutput "(?P<outputid>\d+)"$')
def disableoutput(context, outputid):
"""
*musicpd.org, audio output section:*
``disableoutput``
Turns an output off.
"""
if int(outputid) == 0:
context.core.playback.set_mute(True)
# TODO Return proper error on unknown outputid
@handle_request(r'^enableoutput "(?P<outputid>\d+)"$')
def enableoutput(context, outputid):
"""
*musicpd.org, audio output section:*
``enableoutput``
Turns an output on.
"""
if int(outputid) == 0:
context.core.playback.set_mute(False)
# TODO Return proper error on unknown outputid
@handle_request(r'^outputs$')
def outputs(context):
"""
*musicpd.org, audio output section:*
``outputs``
Shows information about all outputs.
"""
enabled = 0 if context.core.playback.get_mute().get() else 1
return [
('outputid', 0),
('outputname', 'Default'),
('outputenabled', enabled),
]
|
from __future__ import unicode_literals
from mopidy.frontends.mpd.protocol import handle_request
@handle_request(r'^disableoutput "(?P<outputid>\d+)"$')
def disableoutput(context, outputid):
"""
*musicpd.org, audio output section:*
``disableoutput``
Turns an output off.
"""
if int(outputid) == 0:
context.core.playback.set_mute(True)
@handle_request(r'^enableoutput "(?P<outputid>\d+)"$')
def enableoutput(context, outputid):
"""
*musicpd.org, audio output section:*
``enableoutput``
Turns an output on.
"""
if int(outputid) == 0:
context.core.playback.set_mute(False)
@handle_request(r'^outputs$')
def outputs(context):
"""
*musicpd.org, audio output section:*
``outputs``
Shows information about all outputs.
"""
enabled = 0 if context.core.playback.get_mute().get() else 1
return [
('outputid', 0),
('outputname', 'Default'),
('outputenabled', enabled),
]
|
Adjust version number to match other deliveries
Set version from 2.7 to 2012.1 to match the other OpenStack
Keystone deliveries (python-keystoneclient will be released
as part of Keystone 2012.1~e3). Also adjusted the location
of the git repository to match new location. Fixes bug 917656.
Change-Id: I4d8d071e3cdc5665e29a89067958f5f1e8964221
|
import os
import sys
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
requirements = ['httplib2', 'argparse', 'prettytable']
if sys.version_info < (2, 6):
requirements.append('simplejson')
setup(
name = "python-keystoneclient",
version = "2012.1",
description = "Client library for OpenStack Keystone API",
long_description = read('README.rst'),
url = 'https://github.com/openstack/python-keystoneclient',
license = 'Apache',
author = 'Nebula Inc, based on work by Rackspace and Jacob Kaplan-Moss',
author_email = 'gabriel.hurley@nebula.com',
packages = find_packages(exclude=['tests', 'tests.*']),
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
install_requires = requirements,
tests_require = ["nose", "mock", "mox"],
test_suite = "nose.collector",
entry_points = {
'console_scripts': ['keystone = keystoneclient.shell:main']
}
)
|
import os
import sys
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
requirements = ['httplib2', 'argparse', 'prettytable']
if sys.version_info < (2, 6):
requirements.append('simplejson')
setup(
name = "python-keystoneclient",
version = "2.7",
description = "Client library for OpenStack Keystone API",
long_description = read('README.rst'),
url = 'https://github.com/4P/python-keystoneclient',
license = 'Apache',
author = 'Nebula Inc, based on work by Rackspace and Jacob Kaplan-Moss',
author_email = 'gabriel.hurley@nebula.com',
packages = find_packages(exclude=['tests', 'tests.*']),
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
install_requires = requirements,
tests_require = ["nose", "mock", "mox"],
test_suite = "nose.collector",
entry_points = {
'console_scripts': ['keystone = keystoneclient.shell:main']
}
)
|
Add a random <Route> to a generated <Client>
Issue #214
|
# coding=utf-8
import factory
import datetime
import random
from django.contrib.auth.models import User
from member.models import Member, Address, Contact, Client, PAYMENT_TYPE, Route
from member.models import DELIVERY_TYPE, GENDER_CHOICES
class AddressFactory (factory.DjangoModelFactory):
class Meta:
model = Address
street = factory.Faker('street_address')
city = 'Montreal'
postal_code = factory.Faker('postalcode')
class ContactFactory (factory.DjangoModelFactory):
class Meta:
model = Contact
type = 'Home phone'
value = factory.Faker('phone_number')
class MemberFactory (factory.DjangoModelFactory):
class Meta:
model = Member
firstname = factory.Faker('first_name')
lastname = factory.Faker('last_name')
address = factory.SubFactory(AddressFactory)
class ClientFactory (factory.DjangoModelFactory):
class Meta:
model = Client
member = factory.SubFactory(MemberFactory)
billing_member = member
billing_payment_type = random.choice(PAYMENT_TYPE)[0]
rate_type = "default"
member = member
emergency_contact = factory.SubFactory(MemberFactory)
status = random.choice(Client.CLIENT_STATUS)[0]
language = "en"
alert = factory.Faker('sentence')
delivery_type = random.choice(DELIVERY_TYPE)[0]
gender = random.choice(GENDER_CHOICES)[0]
birthdate = factory.Faker('date')
route = random.choice(Route.objects.all())
|
# coding=utf-8
import factory
import datetime
import random
from django.contrib.auth.models import User
from member.models import Member, Address, Contact, Client, PAYMENT_TYPE
from member.models import DELIVERY_TYPE, GENDER_CHOICES
class AddressFactory (factory.DjangoModelFactory):
class Meta:
model = Address
street = factory.Faker('street_address')
city = 'Montreal'
postal_code = factory.Faker('postalcode')
class ContactFactory (factory.DjangoModelFactory):
class Meta:
model = Contact
type = 'Home phone'
value = factory.Faker('phone_number')
class MemberFactory (factory.DjangoModelFactory):
class Meta:
model = Member
firstname = factory.Faker('first_name')
lastname = factory.Faker('last_name')
address = factory.SubFactory(AddressFactory)
class ClientFactory (factory.DjangoModelFactory):
class Meta:
model = Client
member = factory.SubFactory(MemberFactory)
billing_member = member
billing_payment_type = random.choice(PAYMENT_TYPE)[0]
rate_type = "default"
member = member
emergency_contact = factory.SubFactory(MemberFactory)
status = random.choice(Client.CLIENT_STATUS)[0]
language = "en"
alert = factory.Faker('sentence')
delivery_type = random.choice(DELIVERY_TYPE)[0]
gender = random.choice(GENDER_CHOICES)[0]
birthdate = factory.Faker('date')
|
Add try again button to error screen
|
/**
* Error Screen
*
<Error text={'Server is down'} />
*
* React Native Starter App
* https://github.com/mcnamee/react-native-starter-app
*/
import React, { PropTypes } from 'react';
import { View } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
// Consts and Libs
import { AppStyles } from '@theme/';
// Components
import { Spacer, Text, Button } from '@ui/';
/* Component ==================================================================== */
const Error = ({ text, tryAgain }) => (
<View style={[AppStyles.container, AppStyles.containerCentered]}>
<Icon name={'ios-alert-outline'} size={50} color={'#CCC'} />
<Spacer size={10} />
<Text>{text}</Text>
<Spacer size={20} />
{!!tryAgain &&
<Button
small
outlined
title={'Try again'}
onPress={() => tryAgain()}
/>
}
</View>
);
Error.propTypes = { text: PropTypes.string, tryAgain: PropTypes.func };
Error.defaultProps = { text: 'Woops, Something went wrong.' };
Error.componentName = 'Error';
/* Export Component ==================================================================== */
export default Error;
|
/**
* Error Screen
*
<Error text={'Server is down'} />
*
* React Native Starter App
* https://github.com/mcnamee/react-native-starter-app
*/
import React, { PropTypes } from 'react';
import { View } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
// Consts and Libs
import { AppStyles } from '@theme/';
// Components
import { Spacer, Text } from '@ui/';
/* Component ==================================================================== */
const Error = ({ text }) => (
<View style={[AppStyles.container, AppStyles.containerCentered]}>
<Icon name={'ios-alert-outline'} size={50} color={'#CCC'} />
<Spacer size={10} />
<Text>{text}</Text>
</View>
);
Error.propTypes = { text: PropTypes.string };
Error.defaultProps = { text: 'Woops, Something went wrong.' };
Error.componentName = 'Error';
/* Export Component ==================================================================== */
export default Error;
|
Change to handling of links to allow for no link
|
<?php
class CarouselSlide extends DataObject {
private static $db = array(
'Title' => 'Varchar(100)',
'UseLink' => 'Boolean',
'ExternalLink' => 'Varchar(200)',
'SlideSort' => 'Int'
);
private static $has_one = array(
'SlideImage' => 'Image',
'HolderPage' => 'Page',
'IntenalLink' => 'SiteTree'
);
private static $default_sort = 'SlideSort';
public function getCMSFields() {
$fields = new FieldList();
$fields->push(new TextField('Title', 'Title'));
$fields->push($image = new UploadField('SlideImage', 'SlideImage'));
$image->setAllowedFileCategories('image');
$image->setAllowedMaxFileNumber(1);
$image->setCanAttachExisting(true);
$image->setFolderName('Carousel');
$fields->push(new CheckboxField('UseLink', 'Slide links to page'));
$fields->push($tree = new TreeDropdownField("IntenalLinkID", "Choose a page to link to", "SiteTree"));
$fields->push(new TextField('ExternalLink', 'Or use this URL'));
$tree->setChildrenMethod('Children');
return $fields;
}
public function onBeforeWrite() {
parent::onBeforeWrite();
$this->ExternalLink = trim($this->ExternalLink);
if($this->ExternalLink != '' && !preg_match('!://!', $this->ExternalLink)) $this->ExternalLink = 'http://' . $this->ExternalLink;
if($this->SlideImage()) {
$this->SlideImage()->Title = $this->Title;
$this->SlideImage()->write();
}
}
}
|
<?php
class CarouselSlide extends DataObject {
private static $db = array(
'Title' => 'Varchar(100)',
'External' => 'Boolean',
'ExternalLink' => 'Varchar(200)',
'SlideSort' => 'Int'
);
private static $has_one = array(
'SlideImage' => 'Image',
'HolderPage' => 'Page',
'IntenalLink' => 'SiteTree'
);
private static $default_sort = 'SlideSort';
public function getCMSFields() {
$fields = new FieldList();
$fields->push(new TextField('Title', 'Title'));
$fields->push($image = new UploadField('SlideImage', 'SlideImage'));
$image->setAllowedFileCategories('image');
$image->setAllowedMaxFileNumber(1);
$image->setCanAttachExisting(true);
$image->setFolderName('Carousel');
$fields->push(new TreeDropdownField("IntenalLinkID", "Choose a page to link to", "SiteTree"));
$fields->push(new CheckboxField('External', 'Using external link'));
$fields->push(new TextField('ExternalLink', 'External Link URL'));
return $fields;
}
}
|
Add failing (on Py 2) test for passwd_check with unicode arguments
|
# coding: utf-8
from IPython.lib import passwd
from IPython.lib.security import passwd_check, salt_len
import nose.tools as nt
def test_passwd_structure():
p = passwd('passphrase')
algorithm, salt, hashed = p.split(':')
nt.assert_equal(algorithm, 'sha1')
nt.assert_equal(len(salt), salt_len)
nt.assert_equal(len(hashed), 40)
def test_roundtrip():
p = passwd('passphrase')
nt.assert_equal(passwd_check(p, 'passphrase'), True)
def test_bad():
p = passwd('passphrase')
nt.assert_equal(passwd_check(p, p), False)
nt.assert_equal(passwd_check(p, 'a:b:c:d'), False)
nt.assert_equal(passwd_check(p, 'a:b'), False)
def test_passwd_check_unicode():
# GH issue #4524
phash = u'sha1:9dc18846ca26:6bb62badc41fde529c258a8a7fbe259a91313df8'
assert passwd_check(phash, u'mypassword³')
|
from IPython.lib import passwd
from IPython.lib.security import passwd_check, salt_len
import nose.tools as nt
def test_passwd_structure():
p = passwd('passphrase')
algorithm, salt, hashed = p.split(':')
nt.assert_equal(algorithm, 'sha1')
nt.assert_equal(len(salt), salt_len)
nt.assert_equal(len(hashed), 40)
def test_roundtrip():
p = passwd('passphrase')
nt.assert_equal(passwd_check(p, 'passphrase'), True)
def test_bad():
p = passwd('passphrase')
nt.assert_equal(passwd_check(p, p), False)
nt.assert_equal(passwd_check(p, 'a:b:c:d'), False)
nt.assert_equal(passwd_check(p, 'a:b'), False)
|
Update log output when handling pairing requests
|
package pair
import(
"io"
"fmt"
)
type PairingHandler interface {
Handle(Container) (Container, error)
}
func HandleReaderForHandler(r io.Reader, h PairingHandler) (r_out io.Reader, err error) {
cont_in, err := NewTLV8ContainerFromReader(r)
if err != nil {
return nil, err
}
fmt.Println("-> Seq:", cont_in.GetByte(TLVType_SequenceNumber))
cont_out, err := h.Handle(cont_in)
if err != nil {
fmt.Println("[ERROR]", err)
} else {
if cont_out != nil {
fmt.Println("<- Seq:", cont_out.GetByte(TLVType_SequenceNumber))
r_out = cont_out.BytesBuffer()
}
}
fmt.Println("--------------------------")
return r_out, err
}
|
package pair
import(
"io"
"fmt"
)
type PairingHandler interface {
Handle(Container) (Container, error)
}
func HandleReaderForHandler(r io.Reader, h PairingHandler) (io.Reader, error) {
cont_in, err := NewTLV8ContainerFromReader(r)
if err != nil {
return nil, err
}
fmt.Println("-> Seq:", cont_in.GetByte(TLVType_SequenceNumber))
cont_out, err := h.Handle(cont_in)
if err != nil {
fmt.Println("[ERROR]", err)
return nil, err
} else {
if cont_out != nil {
fmt.Println("<- Seq:", cont_out.GetByte(TLVType_SequenceNumber))
fmt.Println("-------------")
return cont_out.BytesBuffer(), nil
}
}
return nil, err
}
|
Use the proper namespace for config
|
<?php
namespace ProjectRena\Model\Database\Site;
use ProjectRena\RenaApp;
/**
* Class Config.
*/
class Config
{
private $app;
private $db;
function __construct(RenaApp $app)
{
$this->app = $app;
$this->db = $app->Db;
}
/**
* @param $key
*
* @return string
*/
public function get($key)
{
$dbResult = $this->db->queryField('SELECT value FROM configuration WHERE `key` = :key', 'value', array(':key' => $key));
return $dbResult;
}
/**
* @param $key
* @param $value
*
* @return mixed
*/
public function set($key, $value)
{
return $this->db->execute('INSERT INTO configuration (`key`, value) VALUES (:key, :value)', array(':key' => $key,
':value' => $value,
));
}
}
|
<?php
namespace ProjectRena\Model;
use ProjectRena\RenaApp;
/**
* Class Config.
*/
class Config
{
private $app;
private $db;
function __construct(RenaApp $app)
{
$this->app = $app;
$this->db = $app->Db;
}
/**
* @param $key
*
* @return string
*/
public function get($key)
{
$dbResult = $this->db->queryField('SELECT value FROM configuration WHERE `key` = :key', 'value', array(':key' => $key));
return $dbResult;
}
/**
* @param $key
* @param $value
*
* @return mixed
*/
public function set($key, $value)
{
return $this->db->execute('INSERT INTO configuration (`key`, value) VALUES (:key, :value)', array(':key' => $key,
':value' => $value,
));
}
}
|
Add config tag for config publish
|
<?php
namespace Sztyup\Authsch;
use Illuminate\Support\ServiceProvider;
class AuthschServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->make('Sztyup\Authsch\LoginController');
$this->loadRoutesFrom(__DIR__ . "/../routes/routes.php");
$this->mergeConfigFrom(
__DIR__.'/../config/config.php', 'authsch'
);
}
public function boot()
{
$this->publishes([
__DIR__ . '/../config/config.php' => config_path('authsch.php')
], 'config');
$socialite = $this->app->make('Laravel\Socialite\Contracts\Factory');
$socialite->extend(
'authsch',
function ($app) use ($socialite) {
$config = $app['config']['authsch.driver'];
return $socialite->buildProvider(SchProvider::class, $config);
}
);
}
}
|
<?php
namespace Sztyup\Authsch;
use Illuminate\Support\ServiceProvider;
class AuthschServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->make('Sztyup\Authsch\LoginController');
$this->loadRoutesFrom(__DIR__ . "/../routes/routes.php");
$this->mergeConfigFrom(
__DIR__.'/../config/config.php', 'authsch'
);
}
public function boot()
{
$this->publishes([
__DIR__ . '/../config/config.php' => config_path('authsch.php')
]);
$socialite = $this->app->make('Laravel\Socialite\Contracts\Factory');
$socialite->extend(
'authsch',
function ($app) use ($socialite) {
$config = $app['config']['authsch.driver'];
return $socialite->buildProvider(SchProvider::class, $config);
}
);
}
}
|
Clear out existing models on load to avoid conflicts when reloading data
|
import {createReducer} from "common/utils/reducerUtils";
import {DATA_LOADED} from "features/tools/toolConstants";
import schema from "app/schema"
const initialState = schema.getDefaultState();
export function loadData(state, payload) {
// Create a Redux-ORM session from our entities "tables"
const session = schema.from(state);
// Get a reference to the correct version of model classes for this Session
const {Pilot, MechDesign, Mech} = session;
const {pilots, designs, mechs} = payload;
// Clear out any existing models from state so that we can avoid
// conflicts from the new data coming in if data is reloaded
[Pilot, Mech, MechDesign].forEach(modelType => {
modelType.all().withModels.forEach(model => model.delete());
session.state = session.reduce();
});
// Queue up creation commands for each entry
pilots.forEach(pilot => Pilot.parse(pilot));
designs.forEach(design => MechDesign.parse(design));
mechs.forEach(mech => Mech.parse(mech));
// Apply the queued updates and return the updated "tables"
return session.reduce();
}
export default createReducer(initialState, {
[DATA_LOADED] : loadData,
});
|
import {createReducer} from "common/utils/reducerUtils";
import {DATA_LOADED} from "features/tools/toolConstants";
import schema from "app/schema"
const initialState = schema.getDefaultState();
export function loadData(state, payload) {
// Create a Redux-ORM session from our entities "tables"
const session = schema.from(state);
// Get a reference to the correct version of model classes for this Session
const {Pilot, MechDesign, Mech} = session;
const {pilots, designs, mechs} = payload;
// Queue up creation commands for each entry
pilots.forEach(pilot => Pilot.parse(pilot));
designs.forEach(design => MechDesign.parse(design));
mechs.forEach(mech => Mech.parse(mech));
// Apply the queued updates and return the updated "tables"
return session.reduce();
}
export default createReducer(initialState, {
[DATA_LOADED] : loadData,
});
|
Set the version to 0.0 to let people know that this is ever changing
|
from setuptools import setup, find_packages
import sys, os
version = '0.0'
setup(name='arbeiter',
version=version,
description="An unassuming work queue system",
long_description="""\
A work queue system built using Kestrel""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='Eric Moritz',
author_email='eric@themoritzfamily.com',
url='',
license='BSD',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
# -*- Extra requirements: -*-
"pykestrel",
],
entry_points="""
# -*- Entry points: -*-
""",
)
|
from setuptools import setup, find_packages
import sys, os
version = '0.1'
setup(name='arbeiter',
version=version,
description="An unassuming work queue system",
long_description="""\
A work queue system built using Kestrel""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='Eric Moritz',
author_email='eric@themoritzfamily.com',
url='',
license='BSD',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
# -*- Extra requirements: -*-
"pykestrel",
],
entry_points="""
# -*- Entry points: -*-
""",
)
|
Simplify inline styles for inheritance
|
const DEFAULT_IN = 'fadeIn'
const DEFAULT_OUT = 'fadeOut'
class Slide extends BaseElement {
static get observedAttributes () {
return ['active', 'in', 'out']
}
get active () {
return this.hasAttribute('active')
}
set active (value) {
value ? this.setAttribute('active', '')
: this.removeAttribute('active')
}
get in () {
return this.getAttribute('in') || DEFAULT_IN
}
get out () {
return this.getAttribute('out') || DEFAULT_OUT
}
onConnect() {
this.classList.add('animated')
Object.assign(this.style, this.inlineCSS())
}
renderCallback () {
if (this.active) {
this.classList.add(this.in)
this.classList.remove(this.out)
} else {
this.classList.add(this.out)
this.classList.remove(this.in)
}
}
inlineCSS() {
return {
position: 'fixed',
top: 0,
left: 0,
display: 'flex',
width: '100%',
height: '100%',
background: 'black',
fontFamily: 'BlinkMacSystemFont, sans-serif',
borderWidth: '30px',
borderStyle: 'solid',
padding: '100px'
}
}
}
customElements.define('x-slide', Slide)
|
const DEFAULT_IN = 'fadeIn'
const DEFAULT_OUT = 'fadeOut'
class Slide extends BaseElement {
static get observedAttributes () {
return ['active', 'in', 'out']
}
get active () {
return this.hasAttribute('active')
}
set active (value) {
value ? this.setAttribute('active', '')
: this.removeAttribute('active')
}
get in () {
return this.getAttribute('in') || DEFAULT_IN
}
get out () {
return this.getAttribute('out') || DEFAULT_OUT
}
onConnect() {
this.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
`
this.classList.add('animated')
}
renderCallback () {
if (this.active) {
this.classList.add(this.in)
this.classList.remove(this.out)
} else {
this.classList.add(this.out)
this.classList.remove(this.in)
}
}
}
customElements.define('x-slide', Slide)
|
Simplify some of the console boot code
|
<?php
namespace Spark\Core;
class Cli
{
function run()
{
if (!isset($_SERVER['SPARK_ENV'])) $_SERVER['SPARK_ENV'] = 'development';
if ($bootstrap = $this->findApplicationBootstrap()) {
$app = require($bootstrap);
} else {
$app = new \Spark\Application;
}
return $app['console']->run();
}
protected function findApplicationBootstrap()
{
$path = "config/bootstrap.php";
$cwd = getcwd();
while (!$rp = realpath("$cwd/$path")) {
$cwd .= '/..';
if (realpath($cwd) === false) {
break;
}
}
return $rp;
}
}
|
<?php
namespace Spark\Core;
class Cli
{
protected $console;
protected $application;
function __construct()
{
if ($bootstrap = $this->findApplicationBootstrap()) {
if (!isset($_SERVER['SPARK_ENV'])) $_SERVER['SPARK_ENV'] = 'development';
$this->application = require($bootstrap);
} else {
$this->application = new \Spark\Application;
}
$this->console = $this->application['console'];
}
function run()
{
$this->console->run();
}
protected function findApplicationBootstrap()
{
$path = "config/bootstrap.php";
$cwd = getcwd();
while (!$rp = realpath("$cwd/$path")) {
$cwd .= '/..';
if (realpath($cwd) === false) {
break;
}
}
return $rp;
}
}
|
Move sessionmaker outside of loop
|
#!/usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
# Copyright 2021 The HERA Collaboration
# Licensed under the 2-clause BSD License
"""
Check that input files are safely in the librarian.
This script takes a list of input files and returns the list of those
found in the HERA_MC.lib_files table.
NOTE: Assumes that lib_files is a faithful list of files uploaded to the Librarian
"""
import os
from hera_mc import mc
ap = mc.get_mc_argument_parser()
ap.description = """Check that listed files are safely in librarian."""
ap.add_argument("files", type=str, default=None, nargs="*", help="list of files")
args = ap.parse_args()
db = mc.connect_to_mc_db(args)
found_files = []
with db.sessionmaker() as session:
for pathname in args.files:
filename = os.path.basename(pathname)
out = session.get_lib_files(filename)
if len(out) > 0:
print(pathname) # if we have a file, say so
|
#!/usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
# Copyright 2021 The HERA Collaboration
# Licensed under the 2-clause BSD License
"""
Check that input files are safely in the librarian.
This script takes a list of input files and returns the list of those
found in the HERA_MC.lib_files table.
NOTE: Assumes that lib_files is a faithful list of files uploaded to the Librarian
"""
import os
from hera_mc import mc
ap = mc.get_mc_argument_parser()
ap.description = """Check that listed files are safely in librarian."""
ap.add_argument("files", type=str, default=None, nargs="*", help="list of files")
args = ap.parse_args()
db = mc.connect_to_mc_db(args)
found_files = []
for pathname in args.files:
filename = os.path.basename(pathname)
with db.sessionmaker() as session:
out = session.get_lib_files(filename)
if len(out) > 0:
print(pathname) # if we have a file, say so
|
Remove unused argument and increase patch size limit
|
export const MAX_PATCH_CHARS = 10 * 1024 * 1024;
export function filter(original) {
let accumulating = false;
let accumulated = '';
let includedChars = 0;
let index = 0;
while (index !== -1) {
let include = true;
const result = original.indexOf('\ndiff --git ', index);
const nextIndex = result !== -1 ? result + 1 : -1;
const patchEnd = nextIndex !== -1 ? nextIndex : original.length;
// Exclude this patch if its inclusion would cause the patch to become too large.
const patchChars = patchEnd - index + 1;
if (includedChars + patchChars > MAX_PATCH_CHARS) {
include = false;
}
if (include) {
// Avoid copying large buffers of text around if we're including everything anyway.
if (accumulating) {
accumulated += original.slice(index, patchEnd);
}
includedChars += patchChars;
} else {
// If this is the first excluded patch, start by copying everything before this into "accumulated."
if (!accumulating) {
accumulating = true;
accumulated = original.slice(0, index);
}
}
index = nextIndex;
}
return accumulating ? accumulated : original;
}
|
export const MAX_PATCH_CHARS = 10240;
export function filter(original, fileSet) {
let accumulating = false;
let accumulated = '';
let includedChars = 0;
let index = 0;
while (index !== -1) {
let include = true;
const result = original.indexOf('\ndiff --git ', index);
const nextIndex = result !== -1 ? result + 1 : -1;
const patchEnd = nextIndex !== -1 ? nextIndex : original.length;
// Exclude this patch if its inclusion would cause the patch to become too large.
const patchChars = patchEnd - index + 1;
if (includedChars + patchChars > MAX_PATCH_CHARS) {
include = false;
}
if (include) {
// Avoid copying large buffers of text around if we're including everything anyway.
if (accumulating) {
accumulated += original.slice(index, patchEnd);
}
includedChars += patchChars;
} else {
// If this is the first excluded patch, start by copying everything before this into "accumulated."
if (!accumulating) {
accumulating = true;
accumulated = original.slice(0, index);
}
}
index = nextIndex;
}
return accumulating ? accumulated : original;
}
|
[PhpUnitBridge] Enforce @-silencing of deprecation notices according to new policy
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Yaml\Tests;
use Symfony\Component\Yaml\Yaml;
class YamlTest extends \PHPUnit_Framework_TestCase
{
public function testParseAndDump()
{
$data = array('lorem' => 'ipsum', 'dolor' => 'sit');
$yml = Yaml::dump($data);
$parsed = Yaml::parse($yml);
$this->assertEquals($data, $parsed);
}
/**
* @group legacy
*/
public function testLegacyParseFromFile()
{
$filename = __DIR__.'/Fixtures/index.yml';
$contents = file_get_contents($filename);
$parsedByFilename = Yaml::parse($filename);
$parsedByContents = Yaml::parse($contents);
$this->assertEquals($parsedByFilename, $parsedByContents);
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Yaml\Tests;
use Symfony\Component\Yaml\Yaml;
class YamlTest extends \PHPUnit_Framework_TestCase
{
public function testParseAndDump()
{
$data = array('lorem' => 'ipsum', 'dolor' => 'sit');
$yml = Yaml::dump($data);
$parsed = Yaml::parse($yml);
$this->assertEquals($data, $parsed);
}
/**
* @group legacy
*/
public function testLegacyParseFromFile()
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
$filename = __DIR__.'/Fixtures/index.yml';
$contents = file_get_contents($filename);
$parsedByFilename = Yaml::parse($filename);
$parsedByContents = Yaml::parse($contents);
$this->assertEquals($parsedByFilename, $parsedByContents);
}
}
|
Fix running SET command in sqlite
|
var fixtures = require('node-require-directory')(__dirname);
exports.load = function(specificFixtures) {
return exports.unload().then(function() {
if (typeof specificFixtures === 'string') {
specificFixtures = [specificFixtures];
}
var promises = [];
Object.keys(fixtures).filter(function(key) {
if (key === 'index') {
return false;
}
if (specificFixtures && specificFixtures.indexOf(key) === -1) {
return false;
}
return true;
}).forEach(function(key) {
var promise = fixtures[key].load().then(function(instances) {
exports[key] = instances;
});
promises.push(promise);
});
return Promise.all(promises);
}).catch(function(err) {
console.error(err.stack);
});
};
exports.unload = function() {
if (sequelize.options.dialect === 'mysql') {
return sequelize.query('SET FOREIGN_KEY_CHECKS = 0').then(function() {
return sequelize.sync({ force: true });
}).then(function() {
return sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
});
} else {
return sequelize.sync({ force: true });
}
};
|
var fixtures = require('node-require-directory')(__dirname);
exports.load = function(specificFixtures) {
return exports.unload().then(function() {
if (typeof specificFixtures === 'string') {
specificFixtures = [specificFixtures];
}
var promises = [];
Object.keys(fixtures).filter(function(key) {
if (key === 'index') {
return false;
}
if (specificFixtures && specificFixtures.indexOf(key) === -1) {
return false;
}
return true;
}).forEach(function(key) {
var promise = fixtures[key].load().then(function(instances) {
exports[key] = instances;
});
promises.push(promise);
});
return Promise.all(promises);
}).catch(function(err) {
console.error(err.stack);
});
};
exports.unload = function() {
return sequelize.query('SET FOREIGN_KEY_CHECKS = 0').then(function() {
return sequelize.sync({ force: true });
}).then(function() {
return sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
});
};
|
Use ::class for class name resolution
Change-Id: I9e7d92d92901ecf1195bce652e77741e1c592d59
|
<?php
// Keep in sync with same script in Flow.
require_once getenv( 'MW_INSTALL_PATH' ) !== false
? getenv( 'MW_INSTALL_PATH' ) . '/maintenance/Maintenance.php'
: __DIR__ . '/../../../maintenance/Maintenance.php';
/**
* Generates Echo autoload info
*/
class GenerateEchoAutoload extends Maintenance {
public function __construct() {
parent::__construct();
$this->addDescription( 'Generates Echo autoload data' );
}
public function execute() {
$base = dirname( __DIR__ );
$generator = new AutoloadGenerator( $base );
$dirs = [
'includes',
'tests',
'maintenance',
];
foreach ( $dirs as $dir ) {
$generator->readDir( $base . '/' . $dir );
}
foreach ( glob( $base . '/*.php' ) as $file ) {
$generator->readFile( $file );
}
$target = $generator->getTargetFileInfo();
file_put_contents(
$target['filename'],
$generator->getAutoload( basename( __DIR__ ) . '/' . basename( __FILE__ ) )
);
echo "Done.\n\n";
}
}
$maintClass = GenerateEchoAutoload::class;
require_once RUN_MAINTENANCE_IF_MAIN;
|
<?php
// Keep in sync with same script in Flow.
require_once getenv( 'MW_INSTALL_PATH' ) !== false
? getenv( 'MW_INSTALL_PATH' ) . '/maintenance/Maintenance.php'
: __DIR__ . '/../../../maintenance/Maintenance.php';
/**
* Generates Echo autoload info
*/
class GenerateEchoAutoload extends Maintenance {
public function __construct() {
parent::__construct();
$this->addDescription( 'Generates Echo autoload data' );
}
public function execute() {
$base = dirname( __DIR__ );
$generator = new AutoloadGenerator( $base );
$dirs = [
'includes',
'tests',
'maintenance',
];
foreach ( $dirs as $dir ) {
$generator->readDir( $base . '/' . $dir );
}
foreach ( glob( $base . '/*.php' ) as $file ) {
$generator->readFile( $file );
}
$target = $generator->getTargetFileInfo();
file_put_contents(
$target['filename'],
$generator->getAutoload( basename( __DIR__ ) . '/' . basename( __FILE__ ) )
);
echo "Done.\n\n";
}
}
$maintClass = "GenerateEchoAutoload";
require_once RUN_MAINTENANCE_IF_MAIN;
|
Add callback script to ubuntu installation workflow
|
// Copyright 2015, EMC, Inc.
'use strict';
module.exports = {
friendlyName: 'Install Ubuntu',
injectableName: 'Task.Os.Install.Ubuntu',
implementsTask: 'Task.Base.Os.Install',
schemaRef: 'install-ubuntu.json',
options: {
osType: 'linux', //readonly options, should avoid change it
profile: 'install-ubuntu.ipxe',
installScript: 'ubuntu-preseed',
installScriptUri: '{{api.templates}}/{{options.installScript}}',
rackhdCallbackScript: 'ubuntu.rackhdcallback',
hostname: 'localhost',
comport: 'ttyS0',
version: 'trusty',
repo: '{{file.server}}/ubuntu',
baseUrl: 'dists/trusty/main/installer-amd64/current/images/netboot/ubuntu-installer/amd64',
rootPassword: "RackHDRocks!",
interface: "auto",
installDisk: "/dev/sda",
kvm: false,
kargs:{}
},
properties: {
os: {
linux: {
distribution: 'ubuntu'
}
}
}
};
|
// Copyright 2015, EMC, Inc.
'use strict';
module.exports = {
friendlyName: 'Install Ubuntu',
injectableName: 'Task.Os.Install.Ubuntu',
implementsTask: 'Task.Base.Os.Install',
schemaRef: 'install-ubuntu.json',
options: {
osType: 'linux', //readonly options, should avoid change it
profile: 'install-ubuntu.ipxe',
installScript: 'ubuntu-preseed',
installScriptUri: '{{api.templates}}/{{options.installScript}}',
hostname: 'localhost',
comport: 'ttyS0',
version: 'trusty',
repo: '{{file.server}}/ubuntu',
baseUrl: 'dists/trusty/main/installer-amd64/current/images/netboot/ubuntu-installer/amd64',
rootPassword: "RackHDRocks!",
interface: "auto",
installDisk: "/dev/sda",
kvm: false,
kargs:{}
},
properties: {
os: {
linux: {
distribution: 'ubuntu'
}
}
}
};
|
Fix bugs and increment version number
|
#!/usr/bin/python3
"""Command line runtime for Tea."""
import runtime.lib
from runtime import tokenizer, parser, env
TEA_VERSION = "0.0.4-dev"
TEA_TITLE = "Tea @" + TEA_VERSION
CLI_SYMBOL = "#> "
CLI_SPACE = " " * 3
CLI_RESULT = "<- "
def interpret(expression, context):
"""Interpret an expression by tokenizing, parsing and evaluating."""
if expression == "exit":
context.flags.append("exit")
return
tokens = tokenizer.apply(expression)
tree = parser.generate(tokens)
return tree.eval(context)
def main():
"""Run the CLI."""
# print application title
print(TEA_TITLE)
# run REPL
context = env.empty_context()
context.load(runtime.lib)
while "done" not in context.flags:
output = interpret(input(CLI_SYMBOL), context)
while "continue" in context.flags:
output = interpret(input(CLI_SPACE), context)
if "exit" in context.flags:
return
print(output)
if __name__ == "__main__":
main()
|
#!/usr/bin/python3
"""Command line runtime for Tea."""
from runtime import tokenizer, parser, ast, std
TEA_VERSION = "0.0.3-dev"
TEA_TITLE = "Tea @" + TEA_VERSION
CLI_SYMBOL = "#> "
CLI_SPACE = " " * 3
CLI_RESULT = "<- "
def interpret(expression, context):
"""Interpret an expression by tokenizing, parsing and evaluating."""
if expression == "exit":
context.flags.append("exit")
return
tokens = tokenizer.apply(expression)
tree = parser.generate(tokens)
return tree.tree_to_string()
def main():
"""Run the CLI."""
# print application title
print(TEA_TITLE)
# run REPL
context = std.default_context()
while "done" not in context.flags:
output = interpret(input(CLI_SYMBOL), context)
while "continue" in context.flags:
output = interpret(input(CLI_SPACE), context)
if "exit" in context.flags: return
print(output)
if __name__ == "__main__":
main()
|
Update the enemy bounds in the enemy class
|
'use strict';
/**
* @description Enemy class => objects the player should avoid
* @constructor
* @param {number} x position of the enemy on the 'x' axis
* @param {number} y position of the enemy on the 'y' axis
* @param {number} speed speed factor of the enemy
*/
var Enemy = function (x, y, speed) {
this.x = x;
this.y = y; // TODO: update y = (y * rowHeight) + (0.5 * rowHeight) + 73
this.speed = speed; // TODO: update speed = * speedRatio
this.sprite = 'images/goomba.png'; //TODO: remove hard coded sprite
};
/**
* @description Move the enemy accross the gameBord
* @param {number} dt Time delta between the previous and actual frame
* @param {object} bounds Gameboard bounds
*/
Enemy.prototype.update = function (dt, bounds) {
// Restrict the enemy back and forth mouvement to the bound of the screen
this.speed = this.x < bounds.right - 10 && this.x > bounds.left + 10 ? this.speed : -this.speed;
// Move the enemy accross the screen back and forth
this.x += this.speed * dt;
};
/**
* @descritpion Render the enemy object
*/
Enemy.prototype.render = function (context) {
context.drawImage(Resources.get(this.sprite), this.x, this.y);
};
|
'use strict';
/**
* @description Enemy class => objects the player should avoid
* @constructor
* @param {number} x position of the enemy on the 'x' axis
* @param {number} y position of the enemy on the 'y' axis
* @param {number} speed speed factor of the enemy
*/
var Enemy = function (x, y, speed) {
this.x = x;
this.y = y; // TODO: update y = (y * rowHeight) + (0.5 * rowHeight) + 73
this.speed = speed; // TODO: update speed = * speedRatio
this.sprite = 'images/goomba.png'; //TODO: remove hard coded sprite
};
/**
* @description Move the enemy accross the gameBord
* @param {number} dt Time delta between the previous and actual frame
* @param {object} bounds Gameboard bounds
*/
Enemy.prototype.update = function (dt, bounds) {
// Restrict the enemy back and forth mouvement to the bound of the screen
this.speed = this.x < bounds.right && this.x > bounds.left ? this.speed : -this.speed;
// Move the enemy accross the screen back and forth
this.x += this.speed * dt;
};
/**
* @descritpion Render the enemy object
*/
Enemy.prototype.render = function (context) {
context.drawImage(Resources.get(this.sprite), this.x, this.y);
};
|
Make stats reading and writing somewhat atomic.
|
package foodtruck.monitoring;
import com.google.inject.Inject;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.joda.time.DateTime;
import foodtruck.dao.SystemStatDAO;
import foodtruck.model.SystemStats;
import foodtruck.util.Clock;
/**
* @author aviolette@gmail.com
* @since 7/5/12
*/
public class MonitorInterceptor implements MethodInterceptor {
private SystemStatDAO systemStatDAO;
private Clock clock;
@Inject
public MonitorInterceptor() {
}
@Inject
public void initialize(SystemStatDAO dao, Clock clock) {
this.systemStatDAO = dao;
this.clock = clock;
}
@Override public Object invoke(MethodInvocation invocation) throws Throwable {
String methodName = invocation.getMethod().getName();
String className = invocation.getMethod().getDeclaringClass().getName();
// TODO: This is not thread-safe!
String prefix = className + "_" + methodName;
DateTime now = clock.now();
try {
return invocation.proceed();
} catch (Exception e) {
SystemStats stats = systemStatDAO.findByTimestamp(now);
stats.incrementCount(prefix + "_failed");
systemStatDAO.save(stats);
throw e;
} finally {
SystemStats stats = systemStatDAO.findByTimestamp(now);
stats.incrementCount(prefix + "_total");
systemStatDAO.save(stats);
}
}
}
|
package foodtruck.monitoring;
import com.google.inject.Inject;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import foodtruck.dao.SystemStatDAO;
import foodtruck.model.SystemStats;
import foodtruck.util.Clock;
/**
* @author aviolette@gmail.com
* @since 7/5/12
*/
public class MonitorInterceptor implements MethodInterceptor {
private SystemStatDAO systemStatDAO;
private Clock clock;
@Inject
public MonitorInterceptor() {
}
@Inject
public void initialize(SystemStatDAO dao, Clock clock) {
this.systemStatDAO = dao;
this.clock = clock;
}
@Override public Object invoke(MethodInvocation invocation) throws Throwable {
String methodName = invocation.getMethod().getName();
String className = invocation.getMethod().getDeclaringClass().getName();
// TODO: This is not thread-safe!
SystemStats stats = systemStatDAO.findByTimestamp(clock.now());
String prefix = className + "_" + methodName;
stats.incrementCount(prefix + "_total");
try {
return invocation.proceed();
} catch (Exception e) {
stats.incrementCount(prefix + "_failed");
throw e;
} finally {
systemStatDAO.save(stats);
}
}
}
|
Fix error of blob function not found in whatwg-fetch with Network Inspect enabled
|
/*
* See https://github.com/jhen0409/react-native-debugger/issues/209
*
* Patch whatwg-fetch code to get `support` var,
* so we could use it to fix the issue.
*/
const isFetch = /"node_modules\/@?[a-zA-Z-_/]*whatwg-fetch\/fetch.js"/;
const fetchSupportFlag = /(if \(self.fetch\) {\n\s+return;\n\s+}\n\s+var support )(=)( {)/g;
const fetchSupportReplaceStr = '$1= self.__FETCH_SUPPORT__ =$3';
const toggleFlag = 'self.fetch.polyfill = true';
// Toggle Network Inspect after define `support` var.
// We have been set up `__NETWORK_INSPECT__` in Worker before import application script.
const toggleReplaceStr = `self.__NETWORK_INSPECT__ && self.__NETWORK_INSPECT__(true);${toggleFlag}`;
export const checkFetchExists = code => isFetch.test(code);
export const patchFetchPolyfill = code =>
code.replace(fetchSupportFlag, fetchSupportReplaceStr).replace(toggleFlag, toggleReplaceStr);
|
/*
* See https://github.com/jhen0409/react-native-debugger/issues/209
*
* Patch whatwg-fetch code to get `support` var,
* so we could use it to fix the issue.
*/
const isFetch = /"node_modules\/@?[a-zA-Z-_/]*whatwg-fetch\/fetch.js"/;
const fetchSupportFlag = /(if \(self.fetch\) {\n\s+return;\n\s+}\n\s+var support )(=)( {)/g;
const fetchSupportReplaceStr = '$1= self.__FETCH_SUPPORT__ =$3';
const toggleFlag = 'if (support.arrayBuffer) {';
// Toggle Network Inspect after define `support` var.
// We have been set up `__NETWORK_INSPECT__` in Worker before import application script.
const toggleReplaceStr = `self.__NETWORK_INSPECT__ && self.__NETWORK_INSPECT__(true);${toggleFlag}`;
export const checkFetchExists = code => isFetch.test(code);
export const patchFetchPolyfill = code =>
code.replace(fetchSupportFlag, fetchSupportReplaceStr).replace(toggleFlag, toggleReplaceStr);
|
Change import order in memories
|
# Copyright 2017 reinforce.io. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from tensorforce.core.memories.memory import Memory
from tensorforce.core.memories.queue import Queue
from tensorforce.core.memories.latest import Latest
from tensorforce.core.memories.replay import Replay
from tensorforce.core.memories.prioritized_replay import PrioritizedReplay
memories = dict(
latest=Latest,
replay=Replay,
prioritized_replay=PrioritizedReplay
# prioritized_replay=PrioritizedReplay,
# naive_prioritized_replay=NaivePrioritizedReplay
)
__all__ = ['memories', 'Memory', 'Queue', 'Latest', 'Replay', 'PrioritizedReplay']
|
# Copyright 2017 reinforce.io. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from tensorforce.core.memories.memory import Memory
from tensorforce.core.memories.prioritized_replay import PrioritizedReplay
from tensorforce.core.memories.queue import Queue
from tensorforce.core.memories.latest import Latest
from tensorforce.core.memories.replay import Replay
memories = dict(
latest=Latest,
replay=Replay,
prioritized_replay=PrioritizedReplay
# prioritized_replay=PrioritizedReplay,
# naive_prioritized_replay=NaivePrioritizedReplay
)
__all__ = ['memories', 'Memory', 'Queue', 'Latest', 'Replay', 'PrioritizedReplay']
|
Fix the deepExtend logic to copy class instances by reference.
|
Krang.deepExtend = function(destination, source) {
for (var property in source) {
var type = typeof source[property], deep = true;
if (type !== 'object' || Object.isElement(source[property]) ||
(source[property].constructor && source[property].constructor !== Object)) {
deep = false;
}
if (deep) {
destination[property] = destination[property] || {};
arguments.callee(destination[property], source[property]);
} else {
destination[property] = source[property];
}
}
return destination;
};
Krang.Mixin = {};
Krang.Mixin.Configurable = {
setOptions: function(options) {
this.options = {};
var constructor = this.constructor;
if (constructor.superclass) {
// Build the inheritance chain.
var chain = [], klass = constructor;
while (klass = klass.superclass)
chain.push(klass);
chain = chain.reverse();
for (var i = 0, l = chain.length; i < l; i++)
Krang.deepExtend(this.options, chain[i].DEFAULT_OPTIONS || {});
}
Krang.deepExtend(this.options, constructor.DEFAULT_OPTIONS);
return Krang.deepExtend(this.options, options || {});
}
};
|
Krang.deepExtend = function(destination, source) {
for (var property in source) {
var type = typeof source[property];
if (type === 'object' && !Object.isElement(source[property])) {
destination[property] = destination[property] || {};
arguments.callee(destination[property], source[property]);
} else {
destination[property] = source[property];
}
}
return destination;
};
Krang.Mixin = {};
Krang.Mixin.Configurable = {
setOptions: function(options) {
this.options = {};
var constructor = this.constructor;
if (constructor.superclass) {
// Build the inheritance chain.
var chain = [], klass = constructor;
while (klass = klass.superclass)
chain.push(klass);
chain = chain.reverse();
for (var i = 0, l = chain.length; i < l; i++)
Krang.deepExtend(this.options, chain[i].DEFAULT_OPTIONS || {});
}
Krang.deepExtend(this.options, constructor.DEFAULT_OPTIONS);
return Krang.deepExtend(this.options, options || {});
}
};
|
Use the german version of grako_map.
|
var EC = protractor.ExpectedConditions;
var map = require('./map/map.page');
describe('map', function() {
it('should include a heatmap on the grako_map page', function() {
browser.get('/project/grako_map?lang=de');
var heatmap = map.getHeatmap();
expect(heatmap.isPresent()).toBe(true);
});
it('it should show some markers for small result size', function () {
browser.get('/map?zoom=12&lat=50.42116487566384&lng=4.902398681640625');
var marker = map.getMarkers();
expect(marker.count()).not.toBeLessThan(1);
});
xit('should show as many markers as many previous storage places exist', function() {
browser.get('/entity/1076902');
browser.sleep(500).then(function() {
var marker = map.getMarkers();
expect(marker.count()).toBe(3);
})
})
});
|
var EC = protractor.ExpectedConditions;
var map = require('./map/map.page');
describe('map', function() {
it('should include a heatmap on the grako_map page', function() {
browser.get('/project/grako_map');
var heatmap = map.getHeatmap();
expect(heatmap.isPresent()).toBe(true);
});
it('it should show some markers for small result size', function () {
browser.get('/map?zoom=12&lat=50.42116487566384&lng=4.902398681640625');
var marker = map.getMarkers();
expect(marker.count()).not.toBeLessThan(1);
});
xit('should show as many markers as many previous storage places exist', function() {
browser.get('/entity/1076902');
browser.sleep(500).then(function() {
var marker = map.getMarkers();
expect(marker.count()).toBe(3);
})
})
});
|
Create a broadcast api: send
|
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO, send, emit
import json
app = Flask(__name__, template_folder='./templates')
# Websocket setting
app.config['SECRET_KEY'] = '12qwaszx'
socketio = SocketIO(app)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/send', methods=['GET', 'POST'])
def send():
"""Receive a message and brodcast to all connected clients
"""
jsonobj_content = request.json
socketio.emit('server_response', {'data':str(jsonobj_content)}, broadcast=True)
return '', 200
# @app.route('/<string:page_name>/')
# def static_page(page_name):
# return render_template('%s.html' % page_name)
@socketio.on('connect_event')
def connected_event(msg):
"""WebSocket connect event
This will trigger responsing a message to client by
"""
print('Received msg: %s', msg)
emit('server_response', {'data': msg['data']})
if __name__=='__main__':
socketio.run(app)
|
from flask import Flask, render_template
from flask_socketio import SocketIO, send, emit
app = Flask(__name__, template_folder='./templates')
# Websocket setting
app.config['SECRET_KEY'] = '12qwaszx'
socketio = SocketIO(app)
@app.route('/')
def index():
return render_template('index.html')
# @app.route('/<string:page_name>/')
# def static_page(page_name):
# return render_template('%s.html' % page_name)
@socketio.on('message')
def handle_message(message):
print('received message: ' + message)
@socketio.on('connect_event')
def connected_event(msg):
print('Received msg: %s', msg)
emit('server_response', {'data': msg['data']}, broadcast=True)
@socketio.on('save receipt')
def handle_json(json):
print('Received json: ' + str(json))
emit('save-reveipt response', {'isSuccess': 'true'})
if __name__=='__main__':
socketio.run(app)
|
FIX fiscal position no source tax
|
from openerp import models, api, fields
class account_fiscal_position(models.Model):
_inherit = 'account.fiscal.position'
@api.v7
def map_tax(self, cr, uid, fposition_id, taxes, context=None):
result = super(account_fiscal_position, self).map_tax(
cr, uid, fposition_id, taxes, context=context)
print 'fposition_id', fposition_id
if fposition_id:
taxes_without_src_ids = [
x.tax_dest_id.id for x in fposition_id.tax_ids if not x.tax_src_id]
result = set(result) | set(taxes_without_src_ids)
return list(result)
@api.v8 # noqa
def map_tax(self, taxes):
result = super(account_fiscal_position, self).map_tax(taxes)
taxes_without_src_ids = [
x.tax_dest_id.id for x in self.tax_ids if not x.tax_src_id]
result += result.browse(taxes_without_src_ids)
return result
class account_fiscal_position_tax(models.Model):
_inherit = 'account.fiscal.position.tax'
tax_src_id = fields.Many2one(required=False)
|
from openerp import models, api, fields
class account_fiscal_position(models.Model):
_inherit = 'account.fiscal.position'
@api.v7
def map_tax(self, cr, uid, fposition_id, taxes, context=None):
result = super(account_fiscal_position, self).map_tax(
cr, uid, fposition_id, taxes, context=context)
taxes_without_src_ids = [
x.tax_dest_id.id for x in fposition_id.tax_ids if not x.tax_src_id]
result = set(result) | set(taxes_without_src_ids)
return list(result)
@api.v8 # noqa
def map_tax(self, taxes):
result = super(account_fiscal_position, self).map_tax(taxes)
taxes_without_src_ids = [
x.tax_dest_id.id for x in self.tax_ids if not x.tax_src_id]
result += result.browse(taxes_without_src_ids)
return result
class account_fiscal_position_tax(models.Model):
_inherit = 'account.fiscal.position.tax'
tax_src_id = fields.Many2one(required=False)
|
Change download and documentation URLs.
|
#!/usr/bin/env python
# coding: utf-8
from distribute_setup import use_setuptools
use_setuptools()
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
extra = {}
if sys.version_info >= (3,):
extra['use_2to3'] = True
setup(name='mockito',
version='0.3.0',
packages=['mockito', 'mockito_test', 'mockito_util'],
url='http://code.google.com/p/mockito-python',
download_url='http://code.google.com/p/mockito-python/downloads/list',
maintainer='Mockito Maintainers',
maintainer_email='mockito-python@googlegroups.com',
license='MIT',
description='Spying framework',
long_description='Mockito is a spying framework based on Java library with the same name.',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Testing',
'Programming Language :: Python :: 3'
],
test_loader = 'mockito_util.test:TestLoader',
test_suite = 'mockito_test',
**extra
)
|
#!/usr/bin/env python
# coding: utf-8
from distribute_setup import use_setuptools
use_setuptools()
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
extra = {}
if sys.version_info >= (3,):
extra['use_2to3'] = True
setup(name='mockito',
version='0.3.0',
packages=['mockito', 'mockito_test', 'mockito_util'],
url='http://code.google.com/p/mockito/wiki/MockitoForPython',
download_url='http://bitbucket.org/szczepiq/mockito-python/downloads/',
maintainer='mockito maintainers',
maintainer_email='mockito-python@googlegroups.com',
license='MIT',
description='Spying framework',
long_description='Mockito is a spying framework based on Java library with the same name.',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Testing',
'Programming Language :: Python :: 3'
],
test_loader = 'mockito_util.test:TestLoader',
test_suite = 'mockito_test',
**extra
)
|
Remove the admin from the url resolver
|
# Copyright (C) 2010 Francois Marier <francois@libravatar.org>
#
# This file is part of Libravatar
#
# Libravatar 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.
#
# Libravatar 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 Libravatar. If not, see <http://www.gnu.org/licenses/>.
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^account/', include('libravatar.account.urls')),
(r'^tools/', include('libravatar.tools.urls')),
(r'^$', 'libravatar.public.views.home'),
(r'^resize/', 'libravatar.public.views.resize'),
(r'^resolve/', 'libravatar.public.views.resolve'),
)
|
# Copyright (C) 2010 Francois Marier <francois@libravatar.org>
#
# This file is part of Libravatar
#
# Libravatar 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.
#
# Libravatar 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 Libravatar. If not, see <http://www.gnu.org/licenses/>.
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^account/', include('libravatar.account.urls')),
(r'^tools/', include('libravatar.tools.urls')),
(r'^$', 'libravatar.public.views.home'),
(r'^resize/', 'libravatar.public.views.resize'),
(r'^resolve/', 'libravatar.public.views.resolve'),
(r'^admin/', include(admin.site.urls)),
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
)
|
Fix issue with celery rescheduling task
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
from api.settings import CeleryTasks, Intervals
from api.celery_api import app as celery_app
from experiments.tasks import build_experiment
from projects.models import ExperimentGroup
logger = logging.getLogger('polyaxon.tasks.projects')
@celery_app.task(name=CeleryTasks.EXPERIMENTS_START_GROUP, bind=True)
def start_group_experiments(self, experiment_group_id):
try:
experiment_group = ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
logger.info('ExperimentGroup `{}` does not exist anymore.'.format(experiment_group_id))
return
pending_experiments = experiment_group.pending_experiments
experiment_to_start = experiment_group.n_experiments_to_start
while experiment_to_start > 0 and pending_experiments:
experiment = pending_experiments.pop()
build_experiment.delay(experiment_id=experiment.id)
experiment_to_start -= 1
if pending_experiments:
# Schedule another task
self.retry(countdown=Intervals.EXPERIMENTS_SCHEDULER)
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
from api.settings import CeleryTasks, Intervals
from api.celery_api import app as celery_app
from experiments.tasks import build_experiment
from projects.models import ExperimentGroup
logger = logging.getLogger('polyaxon.tasks.projects')
@celery_app.task(name=CeleryTasks.EXPERIMENTS_START_GROUP, bind=True)
def start_group_experiments(task, experiment_group_id):
try:
experiment_group = ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
logger.info('ExperimentGroup `{}` does not exist anymore.'.format(experiment_group_id))
return
pending_experiments = experiment_group.pending_experiments
experiment_to_start = experiment_group.n_experiments_to_start
while experiment_to_start > 0 and pending_experiments:
experiment = pending_experiments.pop()
build_experiment.delay(experiment_id=experiment.id)
experiment_to_start -= 1
if pending_experiments:
# Schedule another task
task.apply_async(experiment_group_id, countdown=Intervals.EXPERIMENTS_SCHEDULER)
|
Fix Asset Keys For Hashed Assets
Resources seems to be a better property to pull in for the key. But we
need to pass the asset root in as configuration to keep only the part we
want for the manifest key.
|
var path = require('path'),
fs = require('fs');
function AssetManifestPlugin(output, assetRoot) {
this.output = output;
this.assetRoot = assetRoot;
}
AssetManifestPlugin.prototype.apply = function(compiler) {
var assets = {},
output = this.output,
assetRoot = this.assetRoot;
var publicPath = compiler.options.output.publicPath;
function publicRelative(url) {
return publicPath + url;
}
function removeAssetRoot(resource) {
var replaceRoot = new RegExp("^" + assetRoot + "(\/)?");
return resource.replace(replaceRoot, '');
}
function keyForModule(module) {
return removeAssetRoot(module.resource);
}
compiler.plugin('compilation', function(compilation) {
compilation.plugin('module-asset', function(module, file) {
assets[keyForModule(module)] = publicRelative(file);
});
});
compiler.plugin('done', function() {
fs.writeFileSync(output, JSON.stringify(assets, null, 2));
});
};
module.exports = AssetManifestPlugin;
|
var path = require('path'),
fs = require('fs');
function AssetManifestPlugin(output) {
this.output = output;
}
AssetManifestPlugin.prototype.apply = function(compiler) {
var assets = {},
output = this.output;
var outputPath = compiler.options.output.path,
publicPath = compiler.options.output.publicPath;
function publicRelative(url) {
return publicPath + url;
}
function keyForModule(module) {
return Object.keys(module.assets)[0];
}
compiler.plugin('compilation', function(compilation) {
compilation.plugin('module-asset', function(module, file) {
assets[keyForModule(module)] = publicRelative(file);
});
});
compiler.plugin('done', function() {
fs.writeFileSync(output, JSON.stringify(assets, null, 2));
});
};
module.exports = AssetManifestPlugin;
|
Make sure headers are JSON serializable
|
# Copyright 2017 Mastercard
#
# 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.
from celery import Celery
import requests
import utils
app = Celery('tasks', broker=utils.redis_broker_url())
@app.task
def do(method, url, headers, body, callback, insecure):
func = getattr(requests, method.lower())
resp = func(url, headers=headers, data=body, verify=not insecure)
requests.post(callback,
json={'status': '%s %s' % (resp.status_code, resp.reason),
'headers': dict(resp.headers),
'body': resp.content}, verify=not insecure)
return None
|
# Copyright 2017 Mastercard
#
# 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.
from celery import Celery
import requests
import utils
app = Celery('tasks', broker=utils.redis_broker_url())
@app.task
def do(method, url, headers, body, callback, insecure):
func = getattr(requests, method.lower())
resp = func(url, headers=headers, data=body, verify=not insecure)
requests.post(callback,
json={'status': '%s %s' % (resp.status_code, resp.reason),
'headers': resp.headers,
'body': resp.content}, verify=not insecure)
return None
|
Add logic to shorten url
|
package com.naba.url.shortner;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class UrlShortnerController {
@RequestMapping(method = RequestMethod.GET)
public String defaultPage(Model model) {
model.addAttribute("urlShortner", new UrlShortner());
return "index";
}
@RequestMapping(value = "/url-shortner", method = RequestMethod.POST)
public String urlShortner(@ModelAttribute UrlShortner url, Model model) {
url.setShortnedUrl(shortenUrl(url.getOriginalUrl()));
model.addAttribute("urlShortner", url);
return "index";
}
private String shortenUrl(String originalUrl) {
String shortenedUrl = String.valueOf(originalUrl.hashCode());
return shortenedUrl;
}
}
|
package com.naba.url.shortner;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class UrlShortnerController {
@RequestMapping(method = RequestMethod.GET)
public String defaultPage(Model model) {
model.addAttribute("urlShortner", new UrlShortner());
return "index";
}
@RequestMapping(value = "/url-shortner", method = RequestMethod.POST)
public String urlShortner(@ModelAttribute UrlShortner url, Model model) {
url.setShortnedUrl(url.getOriginalUrl() + "/shortned");
model.addAttribute("urlShortner", url);
return "index";
}
}
|
exception: Fix typo in new CoreErrors
|
from __future__ import absolute_import, unicode_literals
class MopidyException(Exception):
def __init__(self, message, *args, **kwargs):
super(MopidyException, self).__init__(message, *args, **kwargs)
self._message = message
@property
def message(self):
"""Reimplement message field that was deprecated in Python 2.6"""
return self._message
@message.setter # noqa
def message(self, message):
self._message = message
class BackendError(MopidyException):
pass
class CoreError(MopidyException):
def __init__(self, message, errno=None):
super(CoreError, self).__init__(message, errno)
self.errno = errno
class ExtensionError(MopidyException):
pass
class FindError(MopidyException):
def __init__(self, message, errno=None):
super(FindError, self).__init__(message, errno)
self.errno = errno
class FrontendError(MopidyException):
pass
class MixerError(MopidyException):
pass
class ScannerError(MopidyException):
pass
class TracklistFull(CoreError):
def __init__(self, message, errno=None):
super(TracklistFull, self).__init__(message, errno)
self.errno = errno
class AudioException(MopidyException):
pass
class ValidationError(ValueError):
pass
|
from __future__ import absolute_import, unicode_literals
class MopidyException(Exception):
def __init__(self, message, *args, **kwargs):
super(MopidyException, self).__init__(message, *args, **kwargs)
self._message = message
@property
def message(self):
"""Reimplement message field that was deprecated in Python 2.6"""
return self._message
@message.setter # noqa
def message(self, message):
self._message = message
class BackendError(MopidyException):
pass
class CoreError(MopidyException):
def __init(self, message, errno=None):
super(CoreError, self).__init(message, errno)
self.errno = errno
class ExtensionError(MopidyException):
pass
class FindError(MopidyException):
def __init__(self, message, errno=None):
super(FindError, self).__init__(message, errno)
self.errno = errno
class FrontendError(MopidyException):
pass
class MixerError(MopidyException):
pass
class ScannerError(MopidyException):
pass
class TracklistFull(CoreError):
def __init(self, message, errno=None):
super(TracklistFull, self).__init(message, errno)
self.errno = errno
class AudioException(MopidyException):
pass
class ValidationError(ValueError):
pass
|
Use correct Response namespace in RendorError trait
|
<?php
namespace RCatlin\Blog\Behavior;
use Assert\Assertion;
use Refinery29\ApiOutput\Resource\ResourceFactory;
use Refinery29\Piston\Response;
trait RenderError
{
public function renderNotFound(Response $response, $message)
{
Assertion::string($message);
$response->setStatusCode(404);
$response->setResult(ResourceFactory::result(['message' => $message]));
return $response;
}
public function renderBadRequest(Response $response, $message)
{
Assertion::string($message);
$response->setStatusCode(400);
$response->setResult(ResourceFactory::result(['message' => $message]));
return $response;
}
public function renderValidationError(Response $response, array $errors)
{
$response->setStatusCode(400);
$response->setResult(ResourceFactory::result(['errors' => $errors]));
return $response;
}
}
|
<?php
namespace RCatlin\Blog\Behavior;
use Assert\Assertion;
use Refinery29\ApiOutput\Resource\ResourceFactory;
use Refinery29\Piston\Http\Response;
trait RenderError
{
public function renderNotFound(Response $response, $message)
{
Assertion::string($message);
$response->setStatusCode(404);
$response->setResult(ResourceFactory::result(['message' => $message]));
return $response;
}
public function renderBadRequest(Response $response, $message)
{
Assertion::string($message);
$response->setStatusCode(400);
$response->setResult(ResourceFactory::result(['message' => $message]));
return $response;
}
public function renderValidationError(Response $response, array $errors)
{
$response->setStatusCode(400);
$response->setResult(ResourceFactory::result(['errors' => $errors]));
return $response;
}
}
|
[f8] Make map zoomable on double-tap
|
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*
* @providesModule ScrollViewPropTypes
*/
'use strict';
var EdgeInsetsPropType = require('EdgeInsetsPropType');
var PointPropType = require('PointPropType');
var PropTypes = require('ReactPropTypes');
var StyleSheetPropType = require('StyleSheetPropType');
var ViewStylePropTypes = require('ViewStylePropTypes');
var nativePropType = require('nativePropType');
var ScrollViewPropTypes = {
automaticallyAdjustContentInsets: nativePropType(PropTypes.bool), // true
contentInset: nativePropType(EdgeInsetsPropType), // zeroes
contentOffset: nativePropType(PointPropType), // zeroes
onScroll: PropTypes.func,
onScrollAnimationEnd: PropTypes.func,
scrollEnabled: nativePropType(PropTypes.bool), // true
scrollIndicatorInsets: nativePropType(EdgeInsetsPropType), // zeros
showsHorizontalScrollIndicator: nativePropType(PropTypes.bool),
showsVerticalScrollIndicator: nativePropType(PropTypes.bool),
style: StyleSheetPropType(ViewStylePropTypes),
throttleScrollCallbackMS: nativePropType(PropTypes.number), // null
};
module.exports = ScrollViewPropTypes;
|
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*
* @providesModule ScrollViewPropTypes
*/
'use strict';
var EdgeInsetsPropType = require('EdgeInsetsPropType');
var PointPropType = require('PointPropType');
var PropTypes = require('ReactPropTypes');
var StyleSheetPropType = require('StyleSheetPropType');
var ViewStylePropTypes = require('ViewStylePropTypes');
var nativePropType = require('nativePropType');
var ScrollViewPropTypes = {
automaticallyAdjustContentInsets: nativePropType(PropTypes.bool), // true
contentInset: nativePropType(EdgeInsetsPropType), // zeroes
contentOffset: nativePropType(PointPropType), // zeroes
onScroll: PropTypes.func,
onScrollAnimationEnd: PropTypes.func,
scrollEnabled: nativePropType(PropTypes.bool), // true
scrollIndicatorInsets: nativePropType(EdgeInsetsPropType), // zeros
showsHorizontalScrollIndicator: nativePropType(PropTypes.bool),
showsVerticalScrollIndicator: nativePropType(PropTypes.bool),
style: StyleSheetPropType(ViewStylePropTypes),
throttleScrollCallbackMS: nativePropType(PropTypes.number), // 200ms
};
module.exports = ScrollViewPropTypes;
|
Fix vee-validate collision with errors property of v-text-fields
|
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import VeeValidate from 'vee-validate'
let en = require('../store/lang/en.json'),
pl = require('../store/lang/pl.json'),
de = require('../store/lang/de.json'),
es = require('../store/lang/es.json');
Vue.use(VueI18n)
Vue.locale('en', en)
Vue.locale('pl', pl)
Vue.locale('de', de)
Vue.locale('es', es)
function toLambdas(obj) {
let newObj = {}
for (let key in obj) {
newObj[key] = () => obj[key]
}
return newObj
}
Vue.use(VeeValidate, {
locale: 'en',
dictionary: {
pl: {
messages: toLambdas(pl.validation)
},
en: {
messages: toLambdas(en.validation)
},
de: {
messages: toLambdas(en.validation)
},
es: {
messages: toLambdas(es.validation)
}
},
errorBagName: 'verrors'
})
|
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import VeeValidate from 'vee-validate'
let en = require('../store/lang/en.json'),
pl = require('../store/lang/pl.json'),
de = require('../store/lang/de.json'),
es = require('../store/lang/es.json');
Vue.use(VueI18n)
Vue.locale('en', en)
Vue.locale('pl', pl)
Vue.locale('de', de)
Vue.locale('es', es)
function toLambdas(obj) {
let newObj = {}
for (let key in obj) {
newObj[key] = () => obj[key]
}
return newObj
}
Vue.use(VeeValidate, {
locale: 'en',
dictionary: {
pl: {
messages: toLambdas(pl.validation)
},
en: {
messages: toLambdas(en.validation)
},
de: {
messages: toLambdas(en.validation)
},
es: {
messages: toLambdas(es.validation)
}
}
})
|
Remove prefix in the forwarded messages from IRC
|
'use strict';
module.exports = function(config, ircbot) {
const Rcon = require('rcon');
const client = new Rcon(config.rcon.host, config.rcon.port, config.rcon.password);
client.on('auth', function() {
console.log('RCON authentication successful');
}).on('response', function(str) {
console.log('RCON got response: ' + str);
}).on('end', function() {
console.log('RCON socket closed');
});
client.connect();
ircbot.addListener('action', function(from, to, text) {
if (to !== config.channel) {
return;
}
client.send('say * ' + from + ' ' + text);
});
ircbot.addListener('message' + config.channel, function(from, text) {
client.send('say <' + from + '> ' + text);
});
};
|
'use strict';
module.exports = function(config, ircbot) {
const Rcon = require('rcon');
const client = new Rcon(config.rcon.host, config.rcon.port, config.rcon.password);
client.on('auth', function() {
console.log('RCON authentication successful');
}).on('response', function(str) {
console.log('RCON got response: ' + str);
}).on('end', function() {
console.log('RCON socket closed');
});
client.connect();
ircbot.addListener('action', function(from, to, text) {
if (to !== config.channel) {
return;
}
client.send('say IRC> * ' + from + ' ' + text);
});
ircbot.addListener('message' + config.channel, function(from, text) {
client.send('say IRC> <' + from + '> ' + text);
});
};
|
Add version of the package when generating the documentation
|
'use strict';
var execSync = require('execSync');
var fs = require('fs');
var calculateVersion = require('ember-cli-calculate-version').calculatedVersion;
module.exports = {
name: 'yuidoc',
description: 'Generates html documentation using YUIDoc',
run: function(options, rawArgs) {
console.log('calculatedVersion', calculatedVersion);
var config;
try {
var buffer = fs.readFileSync('yuidoc.json');
config = JSON.parse(buffer);
} catch(e){
console.log("No yuidoc.json file in root folder. Run `ember g yuidoc` to generate one.");
process.exit(1);
}
console.log('Generating documentation...');
var command = fs.realpathSync('./node_modules/ember-cli-yuidoc/node_modules/.bin/yuidoc') + ' -q --project-version ' + calculateVersion();
execSync.run("mkdir -p " + config.options.outdir);
execSync.run(command);
}
}
|
'use strict';
var execSync = require('execSync');
var fs = require('fs');
var calculatedVersion = require('ember-cli-calculate-version').calculatedVersion();
module.exports = {
name: 'yuidoc',
description: 'Generates html documentation using YUIDoc',
run: function(options, rawArgs) {
console.log('calculatedVersion', calculatedVersion);
var config;
try {
var buffer = fs.readFileSync('yuidoc.json');
config = JSON.parse(buffer);
} catch(e){
console.log("No yuidoc.json file in root folder. Run `ember g yuidoc` to generate one.");
process.exit(1);
}
console.log('Generating documentation...');
var command = fs.realpathSync('./node_modules/ember-cli-yuidoc/node_modules/.bin/yuidoc') + ' -q';
execSync.run("mkdir -p " + config.options.outdir);
execSync.run(command);
}
}
|
Sort registrations. Separate classes of imports. Add API key display.
|
from django.contrib import admin
from server.models import *
class ApiKeyAdmin(admin.ModelAdmin):
list_display = ('name', 'public_key', 'private_key')
class MachineAdmin(admin.ModelAdmin):
list_display = ('hostname', 'serial')
class MachineGroupAdmin(admin.ModelAdmin):
readonly_fields = ('key',)
admin.site.register(ApiKey, ApiKeyAdmin)
admin.site.register(BusinessUnit)
admin.site.register(Condition)
admin.site.register(Fact)
admin.site.register(HistoricalFact)
admin.site.register(InstalledUpdate)
admin.site.register(Machine, MachineAdmin)
admin.site.register(MachineDetailPlugin)
admin.site.register(MachineGroup, MachineGroupAdmin)
# admin.site.register(OSQueryColumn)
# admin.site.register(OSQueryResult)
admin.site.register(PendingAppleUpdate)
admin.site.register(PendingUpdate)
admin.site.register(Plugin)
admin.site.register(PluginScriptRow)
admin.site.register(PluginScriptSubmission)
admin.site.register(Report)
admin.site.register(SalSetting)
admin.site.register(UpdateHistory)
admin.site.register(UpdateHistoryItem)
admin.site.register(UserProfile)
|
from django.contrib import admin
from server.models import *
class MachineGroupAdmin(admin.ModelAdmin):
readonly_fields = ('key',)
class MachineAdmin(admin.ModelAdmin):
list_display = ('hostname', 'serial')
admin.site.register(UserProfile)
admin.site.register(BusinessUnit)
admin.site.register(MachineGroup, MachineGroupAdmin)
admin.site.register(Machine, MachineAdmin)
admin.site.register(Fact)
admin.site.register(PluginScriptSubmission)
admin.site.register(PluginScriptRow)
admin.site.register(HistoricalFact)
admin.site.register(Condition)
admin.site.register(PendingUpdate)
admin.site.register(InstalledUpdate)
admin.site.register(PendingAppleUpdate)
admin.site.register(ApiKey)
admin.site.register(Plugin)
admin.site.register(Report)
# admin.site.register(OSQueryResult)
# admin.site.register(OSQueryColumn)
admin.site.register(SalSetting)
admin.site.register(UpdateHistory)
admin.site.register(UpdateHistoryItem)
admin.site.register(MachineDetailPlugin)
|
Update ntofication for channel usage and not user channel usage
|
<?php
namespace Kregel\Radio\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
use Kregel\FormModel\Traits\Formable;
use Kregel\Warden\Traits\Wardenable;
class Notification extends Model
{
use Formable;
protected $table = 'radio_notifications';
protected $fillable = [
'channel_id', 'user_id', 'is_unread', 'name', 'description', 'link', 'type'
];
public static function boot()
{
Notification::created(function (Notification $notify) {
$data = collect($notify->toArray())->merge([
'uuid' => $notify->channel->uuid,
'is_unread' => 1
]);
Redis::publish($data['uuid'], collect($data));
});
}
protected $casts = [
'is_unread' => 'bool'
];
public function user()
{
return $this->belongsTo(config('auth.providers.users.model'));
}
public function channel()
{
return $this->belongsTo(Channel::class);
}
}
|
<?php
namespace Kregel\Radio\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
use Kregel\FormModel\Traits\Formable;
use Kregel\Warden\Traits\Wardenable;
class Notification extends Model
{
use Formable;
protected $table = 'radio_notifications';
protected $fillable = [
'channel_id', 'user_id', 'is_unread', 'name', 'description' , 'link', 'type'
];
public static function boot()
{
Notification::created(function (Notification $notify){
$data = collect($notify->toArray())->merge([
'uuid' => $notify->user->channel->uuid,
'is_unread' => 1
]);
Redis::publish($data['uuid'], collect($data));
});
}
protected $casts = [
'is_unread' => 'bool'
];
public function user()
{
return $this->belongsTo(config('auth.providers.users.model'));
}
}
|
Check that GreatestCommonDivisor accepts both arguments negative
|
package se.ericthelin.fractions;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class GreatestCommonDivisorTest {
@Test
public void returnsFirstWhenSecondIsZero() {
assertThat(GreatestCommonDivisor.of(6, 0), is(6));
}
@Test
public void returnsSecondWhenFirstIsZero() {
assertThat(GreatestCommonDivisor.of(0, 4), is(4));
}
@Test
public void returnsGreatestCommonDivisorOfFirstAndSecond() {
assertThat(GreatestCommonDivisor.of(6, 4), is(2));
}
@Test
public void acceptsArgumentsInReverseOrder() {
assertThat(GreatestCommonDivisor.of(4, 6), is(2));
}
@Test
public void acceptsNegativeFirstArgument() {
assertThat(GreatestCommonDivisor.of(-6, 4), is(-2));
}
@Test
public void acceptsNegativeSecondArgument() {
assertThat(GreatestCommonDivisor.of(6, -4), is(2));
}
@Test
public void acceptsBothArgumentsNegative() {
assertThat(GreatestCommonDivisor.of(-6, -4), is(-2));
}
}
|
package se.ericthelin.fractions;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class GreatestCommonDivisorTest {
@Test
public void returnsFirstWhenSecondIsZero() {
assertThat(GreatestCommonDivisor.of(6, 0), is(6));
}
@Test
public void returnsSecondWhenFirstIsZero() {
assertThat(GreatestCommonDivisor.of(0, 4), is(4));
}
@Test
public void returnsGreatestCommonDivisorOfFirstAndSecond() {
assertThat(GreatestCommonDivisor.of(6, 4), is(2));
}
@Test
public void acceptsArgumentsInReverseOrder() {
assertThat(GreatestCommonDivisor.of(4, 6), is(2));
}
@Test
public void acceptsNegativeFirstArgument() {
assertThat(GreatestCommonDivisor.of(-6, 4), is(-2));
}
@Test
public void acceptsNegativeSecondArgument() {
assertThat(GreatestCommonDivisor.of(6, -4), is(2));
}
}
|
Make walletextension non-mandatory for now since it's not in use.
|
package fi.bittiraha.walletd;
import org.bitcoinj.core.*;
import org.bitcoinj.kits.WalletAppKit;
import net.minidev.json.*;
import com.google.common.collect.ImmutableList;
import java.util.*;
import java.io.File;
/**
* This class extends WalletAppKit to add ability to tag individual addresses
* with account names to emulate bitcoind's accounts. However, emulation in
* this version is incomplete and only useful in searching for incoming txs.
*/
public class WalletAccountManager extends WalletAppKit {
AccountManager manager;
public WalletAccountManager(NetworkParameters params, File directory, String filePrefix) {
super(params,directory,filePrefix);
manager = new AccountManager();
}
protected class AccountManager extends JSONObject implements WalletExtension {
public void deserializeWalletExtension(Wallet containingWallet, byte[] data) {
Object parsed = JSONValue.parse(data);
if (parsed instanceof JSONObject) {
this.merge((JSONObject)parsed);
}
}
public String getWalletExtensionID() {
return "fi.bittiraha.walletd.WalletAccountManager";
}
public boolean isWalletExtensionMandatory() {
// FIXME, set this to true when this module actually does something
return false;
}
public byte[] serializeWalletExtension() {
return this.toJSONString(JSONStyle.MAX_COMPRESS).getBytes();
}
}
protected List<WalletExtension> provideWalletExtensions() throws Exception {
return ImmutableList.of((WalletExtension)manager);
}
public Map<String,Object> getAccountMap() {
return manager;
}
}
|
package fi.bittiraha.walletd;
import org.bitcoinj.core.*;
import org.bitcoinj.kits.WalletAppKit;
import net.minidev.json.*;
import com.google.common.collect.ImmutableList;
import java.util.*;
import java.io.File;
/**
* This class extends WalletAppKit to add ability to tag individual addresses
* with account names to emulate bitcoind's accounts. However, emulation in
* this version is incomplete and only useful in searching for incoming txs.
*/
public class WalletAccountManager extends WalletAppKit {
AccountManager manager;
public WalletAccountManager(NetworkParameters params, File directory, String filePrefix) {
super(params,directory,filePrefix);
manager = new AccountManager();
}
protected class AccountManager extends JSONObject implements WalletExtension {
public void deserializeWalletExtension(Wallet containingWallet, byte[] data) {
Object parsed = JSONValue.parse(data);
if (parsed instanceof JSONObject) {
this.merge((JSONObject)parsed);
}
}
public String getWalletExtensionID() {
return "fi.bittiraha.walletd.WalletAccountManager";
}
public boolean isWalletExtensionMandatory() {
return true;
}
public byte[] serializeWalletExtension() {
return this.toJSONString(JSONStyle.MAX_COMPRESS).getBytes();
}
}
protected List<WalletExtension> provideWalletExtensions() throws Exception {
return ImmutableList.of((WalletExtension)manager);
}
public Map<String,Object> getAccountMap() {
return manager;
}
}
|
Disable PluginsCategories till it is fixed
|
<?php
/*
* This file is part of PhuninCake.
*
** (c) 2013 Cees-Jan Kiewiet
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace WyriHaximus\PhuninCake\Event;
use Cake\Event\EventListenerInterface;
use WyriHaximus\PhuninNode\Plugins;
class StockPluginsListener implements EventListenerInterface
{
/**
* @return array
*/
public function implementedEvents() {
return [
StartEvent::EVENT => 'start',
];
}
/**
* @param StartEvent $event
*/
public function start(StartEvent $event) {
$event->getNode()->addPlugin(new Plugins\Plugins());
//$event->getNode()->addPlugin(new Plugins\PluginsCategories());
$event->getNode()->addPlugin(new Plugins\MemoryUsage());
$event->getNode()->addPlugin(new Plugins\Uptime());
}
}
|
<?php
/*
* This file is part of PhuninCake.
*
** (c) 2013 Cees-Jan Kiewiet
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace WyriHaximus\PhuninCake\Event;
use Cake\Event\EventListenerInterface;
use WyriHaximus\PhuninNode\Plugins;
class StockPluginsListener implements EventListenerInterface
{
/**
* @return array
*/
public function implementedEvents() {
return [
StartEvent::EVENT => 'start',
];
}
/**
* @param StartEvent $event
*/
public function start(StartEvent $event) {
$event->getNode()->addPlugin(new Plugins\Plugins());
$event->getNode()->addPlugin(new Plugins\PluginsCategories());
$event->getNode()->addPlugin(new Plugins\MemoryUsage());
$event->getNode()->addPlugin(new Plugins\Uptime());
}
}
|
Add support for Laravel 5.4
|
<?php
namespace Casinelli\CampaignMonitor;
use Illuminate\Support\ServiceProvider;
class CampaignMonitorServiceProvider extends ServiceProvider
{
protected $defer = true;
public function boot()
{
$this->publishes([
__DIR__.'/../../config/campaignmonitor.php' => config_path('campaignmonitor.php'),
], 'config');
}
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../../config/campaignmonitor.php', 'campaignmonitor');
$this->app->singleton('campaignmonitor', function ($app) {
return new CampaignMonitor($app);
});
}
public function provides()
{
return ['campaignmonitor'];
}
}
|
<?php
namespace Casinelli\CampaignMonitor;
use Illuminate\Support\ServiceProvider;
class CampaignMonitorServiceProvider extends ServiceProvider
{
protected $defer = true;
public function boot()
{
$this->publishes([
__DIR__.'/../../config/campaignmonitor.php' => config_path('campaignmonitor.php'),
], 'config');
}
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../../config/campaignmonitor.php', 'campaignmonitor');
$this->app['campaignmonitor'] = $this->app->share(function ($app) {
return new CampaignMonitor($app);
});
}
public function provides()
{
return ['campaignmonitor'];
}
}
|
Add missing R class to WebView resource rewriting.
We weren't rewriting the resources for web_contents_delegate_android,
resulting in crashes any time a resource was loaded by that component
(e.g. popup bubbles for HTML form validation failures). Add it to the
list and also clean up outdated comments here that refer to previous
versions of this code. Add a TODO to track finding a better way to do
this which is less fragile.
BUG=490826
Review URL: https://codereview.chromium.org/1154853005
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#331356}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package com.android.webview.chromium;
/**
* Helper class used to fix up resource ids.
*/
class ResourceRewriter {
/**
* Rewrite the R 'constants' for the WebView library apk.
*/
public static void rewriteRValues(final int packageId) {
// This list must be kept up to date to include all R classes depended on directly or
// indirectly by android_webview_java.
// TODO(torne): find a better way to do this, http://crbug.com/492166.
com.android.webview.chromium.R.onResourcesLoaded(packageId);
org.chromium.android_webview.R.onResourcesLoaded(packageId);
org.chromium.components.web_contents_delegate_android.R.onResourcesLoaded(packageId);
org.chromium.content.R.onResourcesLoaded(packageId);
org.chromium.ui.R.onResourcesLoaded(packageId);
}
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package com.android.webview.chromium;
/**
* Helper class used to fix up resource ids.
* This is mostly a copy of the code in frameworks/base/core/java/android/app/LoadedApk.java.
* TODO: Remove if a cleaner mechanism is provided (either public API or AAPT is changed to generate
* this code).
*/
class ResourceRewriter {
/**
* Rewrite the R 'constants' for the WebView library apk.
*/
public static void rewriteRValues(final int packageId) {
// TODO: We should use jarjar to remove the redundant R classes here, but due
// to a bug in jarjar it's not possible to rename classes with '$' in their name.
// See b/15684775.
com.android.webview.chromium.R.onResourcesLoaded(packageId);
org.chromium.android_webview.R.onResourcesLoaded(packageId);
org.chromium.content.R.onResourcesLoaded(packageId);
org.chromium.ui.R.onResourcesLoaded(packageId);
}
}
|
Add stats logging for GOG tasks
|
""" Compare GOG games to the Lutris library """
import os
from celery import task
from celery.utils.log import get_task_logger
from django.conf import settings
from providers.gog import load_games_from_gogdb, match_from_gogdb
from common.models import save_action_log
LOGGER = get_task_logger(__name__)
@task
def load_gog_games():
"""Task to load GOG games from a GOGDB dump"""
file_path = os.path.join(settings.GOG_CACHE_PATH, "gogdb.json")
if not os.path.exists(file_path):
LOGGER.error("No file present at %s", file_path)
return None
stats = load_games_from_gogdb(file_path)
save_action_log("load_gog_games", stats)
return stats
@task
def match_gog_games():
"""Match GOG games with Lutris games"""
stats = match_from_gogdb(create_missing=True)
save_action_log("match_gog_games", stats)
return stats
|
""" Compare GOG games to the Lutris library """
import os
from celery import task
from celery.utils.log import get_task_logger
from django.conf import settings
from providers.gog import load_games_from_gogdb, match_from_gogdb
LOGGER = get_task_logger(__name__)
@task
def load_gog_games():
"""Task to load GOG games from a GOGDB dump"""
file_path = os.path.join(settings.GOG_CACHE_PATH, "gogdb.json")
if not os.path.exists(file_path):
LOGGER.error("No file present at %s", file_path)
return None
return load_games_from_gogdb(file_path)
@task
def match_gog_games():
"""Match GOG games with Lutris games"""
return match_from_gogdb(create_missing=True)
|
feat: Add base install argument to commander new command
|
"use strict";
var program = require('commander');
var path = require('path');
var os = require('os');
var newCommand = require('./commands/new');
var pkg = require(path.resolve(__dirname, '..', 'package.json'));
/**
* Get the ball-rolling for the whole program
*/
module.exports = function() {
setProgramBaseSettings();
setNewCommand();
initProgram();
}
/**
* Setup the 'new' command
*/
function setNewCommand() {
program
.command('new [env]')
.description('Create a new project (on-screen wizard)')
.option("-B, --base", "Use the base install pre-set")
.action(function(env, options) {
//console.log('Base install mode: ', options.base)
newCommand.init(getProgramOptions());
});
}
/**
* Initialise program
*/
function initProgram() {
program.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp();
}
}
/**
* Get program option flags
*/
function getProgramOptions() {
return {
silent: program.silent,
verbose: program.verbose
}
}
/**
* Set program base settings: version, option flags
*/
function setProgramBaseSettings() {
program
.version(pkg.version)
.option('-s, --silent', 'Surpress all on-screen messages')
.option('-v, --verbose', 'Show all on-screen messages');
}
|
"use strict";
var program = require('commander');
var path = require('path');
var os = require('os');
var newCommand = require('./commands/new');
var pkg = require(path.resolve(__dirname, '..', 'package.json'));
/**
* Get the ball-rolling for the whole program
*/
module.exports = function() {
setProgramBaseSettings();
setNewCommand();
initProgram();
}
/**
* Setup the 'new' command
*/
function setNewCommand() {
program
.command('new')
.description('Create a new project (on-screen wizard)')
.action(function() {
newCommand.init(getProgramOptions());
});
}
/**
* Initialise program
*/
function initProgram() {
program.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp();
}
}
/**
* Get program option flags
*/
function getProgramOptions() {
return {
silent: program.silent,
verbose: program.verbose
}
}
/**
* Set program base settings: version, option flags
*/
function setProgramBaseSettings() {
program
.version(pkg.version)
.option('-s, --silent', 'Surpress all on-screen messages')
.option('-v, --verbose', 'Show all on-screen messages');
}
|
Update SQLAlchemy and Geoalchemy2 version range
|
#! /usr/bin/env python
# coding: utf-8
from setuptools import find_packages, setup
setup(name='egoio',
author='NEXT ENERGY, Reiner Lemoine Institut gGmbH, ZNES',
author_email='ulf.p.mueller@hs-flensburg.de',
description='ego input/output repository',
version='0.3.0',
url='https://github.com/openego/ego.io',
packages=find_packages(),
license='GNU Affero General Public License v3.0',
install_requires=[
'geoalchemy2 >= 0.3.0, <= 0.4.1',
'sqlalchemy >= 1.0.11, <= 1.2.0',
'keyring >= 4.0',
'psycopg2'],
extras_require={
"sqlalchemy": 'postgresql'},
package_data={'tools': 'sqlacodegen_oedb.sh'}
)
|
#! /usr/bin/env python
# coding: utf-8
from setuptools import find_packages, setup
setup(name='egoio',
author='NEXT ENERGY, Reiner Lemoine Institut gGmbH, ZNES',
author_email='ulf.p.mueller@hs-flensburg.de',
description='ego input/output repository',
version='0.3.0',
url='https://github.com/openego/ego.io',
packages=find_packages(),
license='GNU Affero General Public License v3.0',
install_requires=[
'geoalchemy2 >= 0.3.0, <= 0.4.0',
'sqlalchemy >= 1.0.11, <= 1.1.15',
'keyring >= 4.0',
'psycopg2'],
extras_require={
"sqlalchemy": 'postgresql'},
package_data={'tools': 'sqlacodegen_oedb.sh'}
)
|
Add note to render_plugin[s] that render_region should be preferred
|
from django import template
from django.utils.html import mark_safe
register = template.Library()
@register.simple_tag(takes_context=True)
def render_plugin(context, plugin):
"""
Render a single plugin. See :mod:`feincms3.renderer` for additional
details.
In general you should prefer
:func:`~feincms3.templatetags.feincms3_renderer.render_region` over this
tag.
"""
return context['renderer'].render_plugin_in_context(plugin, context)
@register.simple_tag(takes_context=True)
def render_plugins(context, plugins):
"""
Render and concatenate a list of plugins. See
:mod:`feincms3.renderer` for additional details.
In general you should prefer
:func:`~feincms3.templatetags.feincms3_renderer.render_region` over this
tag.
"""
renderer = context['renderer']
return mark_safe(''.join(
renderer.render_plugin_in_context(plugin, context)
for plugin in plugins
))
@register.simple_tag(takes_context=True)
def render_region(context, regions, region, **kwargs):
"""
Render a single region. See :class:`~feincms3.renderer.Regions` for
additional details. Any and all keyword arguments are forwarded to the
``render`` method of the ``Regions`` instance.
"""
return regions.render(region, context, **kwargs)
|
from django import template
from django.utils.html import mark_safe
register = template.Library()
@register.simple_tag(takes_context=True)
def render_plugin(context, plugin):
"""
Render a single plugin. See :mod:`feincms3.renderer` for additional
details.
"""
return context['renderer'].render_plugin_in_context(plugin, context)
@register.simple_tag(takes_context=True)
def render_plugins(context, plugins):
"""
Render and concatenate a list of plugins. See
:mod:`feincms3.renderer` for additional details.
"""
renderer = context['renderer']
return mark_safe(''.join(
renderer.render_plugin_in_context(plugin, context)
for plugin in plugins
))
@register.simple_tag(takes_context=True)
def render_region(context, regions, region, **kwargs):
"""
Render a single region. See :class:`~feincms3.renderer.Regions` for
additional details. Any and all keyword arguments are forwarded to the
``render`` method of the ``Regions`` instance.
"""
return regions.render(region, context, **kwargs)
|
Handle download errors since testing environment doesn't have fetch
|
const FluentDOM = require('@fluent/dom');
const Fluent = require('@fluent/bundle');
const availableLanguages = {
'en-US': ['/fluent/en-US/main.ftl'],
'es-MX': ['/fluent/es-MX/main.ftl'],
};
let bundle;
async function load() {
// const links = document.querySelectorAll('link[rel="localization"]');
let language = 'en-US'; // navigator.language;
let links = availableLanguages[language];
if (!links) {
language = 'en-US';
links = availableLanguages[language];
}
bundle = new Fluent.FluentBundle(language);
for (const link of links) {
try {
const res = await fetch(link);
const text = await res.text();
bundle.addResource(new Fluent.FluentResource(text));
} catch (e) {
console.warn('Unable to download language pack', e);
}
}
}
async function *generateBundles(_resourceIds) {
if (!bundle) {
await load();
}
yield bundle;
}
const l10n = new FluentDOM.DOMLocalization([], generateBundles);
function init() {
l10n.connectRoot(document.documentElement);
l10n.translateRoots();
}
function getMessage(id) {
const obj = bundle.getMessage(id);
if (!obj) {
console.warn('Missing id', id);
return `<${id}>`;
}
return obj.value;
}
module.exports = {
load,
l10n,
init,
getMessage,
};
|
const FluentDOM = require('@fluent/dom');
const Fluent = require('@fluent/bundle');
const availableLanguages = {
'en-US': ['/fluent/en-US/main.ftl'],
'es-MX': ['/fluent/es-MX/main.ftl'],
};
let bundle;
async function load() {
// const links = document.querySelectorAll('link[rel="localization"]');
let language = 'en-US'; // navigator.language;
let links = availableLanguages[language];
if (!links) {
language = 'en-US';
links = availableLanguages[language];
}
bundle = new Fluent.FluentBundle(language);
for (const link of links) {
const res = await fetch(link);
const text = await res.text();
bundle.addResource(new Fluent.FluentResource(text));
}
}
async function *generateBundles(_resourceIds) {
if (!bundle) {
await load();
}
yield bundle;
}
const l10n = new FluentDOM.DOMLocalization([], generateBundles);
function init() {
l10n.connectRoot(document.documentElement);
l10n.translateRoots();
}
function getMessage(id) {
const obj = bundle.getMessage(id);
if (!obj) {
console.warn('Missing id', id);
return `<${id}>`;
}
return obj.value;
}
module.exports = {
load,
l10n,
init,
getMessage,
};
|
Fix gpio to uppercase GPIO
|
#!/usr/bin/env python
import RPi.GPIO as GPIO
LED_PIN = 23
SWITCH_PIN = 24
# new style class
class PiThing(object):
"""Raspberry Pi Internet 'Thing'."""
def __init__(self):
# use BCM numbering scheme when using Adafruit pi cobbler. Don't use board scheme.
GPIO.setmode(GPIO.BCM)
# led as output
GPIO.setup(LED_PIN, GPIO.OUT)
# switch as input
GPIO.setup(SWITCH_PIN, GPIO.IN)
def read_switch(self):
"""returns true if switch is high, false if switch is low
"""
return GPIO.input(SWITCH_PIN)
def set_led(self, value):
"""Set the LED to the passed in value, True for on, False for off.
"""
GPIO.output(LED_PIN, value)
|
#!/usr/bin/env python
import RPi.GPIO as GPIO
LED_PIN = 23
SWITCH_PIN = 24
# new style class
class PiThing(object):
"""Raspberry Pi Internet 'Thing'."""
def __init__(self):
# use BCM numbering scheme when using Adafruit pi cobbler. Don't use board scheme.
GPIO.setmode(GPIO.BCM)
# led as output
GPIO.setup(LED_PIN, GPIO.OUT)
# switch as input
GPIO.setup(SWITCH_PIN, GPIO.IN)
def read_switch(self):
"""returns true if switch is high, false if switch is low
"""
return gpio.input(SWITCH_PIN)
def set_led(self, value):
"""Set the LED to the passed in value, True for on, False for off.
"""
GPIO.output(LED_PIN, value)
|
Fix error in getting config env
|
const express = require('express');
const morgan = require('morgan');
const compression = require('compression');
const config = require('./config');
const { generateTitle, lorem } = require('./lib/utils');
const app = express();
app.locals = Object.assign({}, app.locals, config.locals);
app.set('env', config.env);
app.set('view engine', 'pug');
app.use(compression());
app.use(morgan('dev'));
app.use('/css', express.static(config.outputDirs.stylesheets));
app.use('/img', express.static(config.outputDirs.images));
app.use('/js', express.static(config.outputDirs.scripts));
app.get('/', (req, res) => {
res.render('index');
});
app.get('/blog', (req, res) => {
const title = generateTitle(app.locals.title, 'Blog');
res.render('blog', {title});
});
app.get('/projects', (req, res) => {
const title = generateTitle(app.locals.title, 'Projects');
res.render('projects', {title});
});
if (app.get('env') === 'production') {
const server = app.listen(config.PORT, () => {
console.log('Starting app on port ', server.address().port);
});
} else {
app.listen(8000);
}
|
const express = require('express');
const morgan = require('morgan');
const compression = require('compression');
const { generateTitle, lorem } = require('./lib/utils');
const config = require('./config');
const app = express();
app.locals = Object.assign({}, app.locals, config.locals);
app.set('env', config.ENV);
app.set('view engine', 'pug');
app.use(compression());
app.use(morgan('dev'));
app.use('/css', express.static(config.outputDirs.stylesheets));
app.use('/img', express.static(config.outputDirs.images));
app.use('/js', express.static(config.outputDirs.scripts));
app.get('/', (req, res) => {
res.render('index');
});
app.get('/blog', (req, res) => {
const title = generateTitle(app.locals.title, 'Blog');
res.render('blog', {title});
});
app.get('/projects', (req, res) => {
const title = generateTitle(app.locals.title, 'Projects');
res.render('projects', {title});
});
if (app.get('env') === 'production') {
const server = app.listen(config.PORT, () => {
console.log('Starting app on port ', server.address().port);
});
} else {
app.listen(8000);
}
|
Move a comment to a real comment field
|
@extends('layouts.admin')
@section('title') Pitch #{{ $pitch->id }} @endsection
@section('content')
{{ Form::model($pitch, ['route' => ['sysop.pitches.update', $pitch->id], 'method' => 'put']) }}
{{ Form::label('name', 'From') }}
{{ Form::text('name') }}
{{ Form::label('email', 'Email') }}
{{ Form::email('email') }}
{{ Form::label('status', 'Submission Status') }}
{{ Form::select('status', $menu) }}
{{ Form::label('blurb', 'The Pitch') }}
{{ Form::textarea('blurb', null, ['class'=>'input-block-level', 'rows'=>15]) }}
{{ Form::label('notes', 'Editorial Notes') }}
{{ Form::textarea('notes', null, ['class'=>'input-block-level', 'rows'=>10]) }}
<p>
{{ Form::submit('Update', ['class'=>'btn btn-primary']) }}
{{ Html::linkRoute('sysop.pitches.index', 'Back', null, ['class'=>'btn'])}}
</p>
{{ Form::close() }}
@endsection
{{-- TODO way to link stories and pitches --}}
|
@extends('layouts.admin')
@section('title') Pitch #{{ $pitch->id }} @endsection
@section('content')
{{ Form::model($pitch, ['route' => ['sysop.pitches.update', $pitch->id], 'method' => 'put']) }}
{{ Form::label('name', 'From') }}
{{ Form::text('name') }}
{{ Form::label('email', 'Email') }}
{{ Form::email('email') }}
{{ Form::label('status', 'Submission Status') }}
{{ Form::select('status', $menu) }}
{{ Form::label('blurb', 'The Pitch') }}
{{ Form::textarea('blurb', null, ['class'=>'input-block-level', 'rows'=>15]) }}
{{ Form::label('notes', 'Editorial Notes') }}
{{ Form::textarea('notes', null, ['class'=>'input-block-level', 'rows'=>10]) }}
<p><em>To Do: link author_id and story_id up here</em></p>
<p>
{{ Form::submit('Update', ['class'=>'btn btn-primary']) }}
{{ Html::linkRoute('sysop.pitches.index', 'Back', null, ['class'=>'btn'])}}
</p>
{{ Form::close() }}
@endsection
|
Change success message text-language to german
|
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "Bitte alle Felder ausfüllen!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'mail@roadgenius.de'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Roadgenius - Nachricht von $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@roadgenius.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
|
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'mail@roadgenius.de'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@roadgenius.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
|
Rename var path & change title value
|
<?php
namespace Drupal\acme\Controller;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Slang Default Controller
*/
class DemoController implements ContainerInjectionInterface {
/**
* @var \TwigEnvironment
*/
protected $twig;
/**
* Constructor
*
* @param \TwigEnvironment $twig
*/
public function __construct(\TwigEnvironment $twig) {
$this->twig = $twig;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('twig'));
}
/**
* helloAction
*
* @param String $name
*/
public function helloAction($name) {
$twigFilePath = drupal_get_path('module', 'acme') . '/templates/hello.html.twig';
$template = $this->twig->loadTemplate($twigFilePath);
drupal_set_title("Acme Demo Module");
return $template->render(array('name' => $name));
}
}
|
<?php
namespace Drupal\acme\Controller;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Slang Default Controller
*/
class DemoController implements ContainerInjectionInterface {
/**
* @var \TwigEnvironment
*/
protected $twig;
/**
* Constructor
*
* @param \TwigEnvironment $twig
*/
public function __construct(\TwigEnvironment $twig) {
$this->twig = $twig;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('twig'));
}
/**
* helloAction
*
* @param String $name
*/
public function helloAction($name) {
$path = drupal_get_path('module', 'acme') . '/templates/hello.html.twig';
$template = $this->twig->loadTemplate($path);
drupal_set_title("Acme demo");
return $template->render(array('name' => $name));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.