text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Use dialer instead of initer, it's clearer
package utp import ( "log" "net" "sync" "testing" _ "github.com/anacrolix/envpprof" "golang.org/x/net/nettest" ) func init() { log.SetFlags(log.Flags() | log.Lshortfile) } func TestNettestLocalhostUDP(t *testing.T) { nettest.TestConn(t, func() (c1, c2 net.Conn, stop func(), err error) { s, err := NewSocket("udp", "localhost:0") if err != nil { return } c1, c2 = connPairSocket(s) stop = func() { s.Close() } return }) } func connPairSocket(s *Socket) (dialed, accepted net.Conn) { var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() var err error dialed, err = s.Dial(s.Addr().String()) if err != nil { panic(err) } }() accepted, err := s.Accept() if err != nil { panic(err) } wg.Wait() return }
package utp import ( "log" "net" "sync" "testing" _ "github.com/anacrolix/envpprof" "golang.org/x/net/nettest" ) func init() { log.SetFlags(log.Flags() | log.Lshortfile) } func TestNettestLocalhostUDP(t *testing.T) { nettest.TestConn(t, func() (c1, c2 net.Conn, stop func(), err error) { s, err := NewSocket("udp", "localhost:0") if err != nil { return } c1, c2 = connPairSocket(s) stop = func() { s.Close() } return }) } func connPairSocket(s *Socket) (initer, accepted net.Conn) { var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() var err error initer, err = s.Dial(s.Addr().String()) if err != nil { panic(err) } }() accepted, err := s.Accept() if err != nil { panic(err) } wg.Wait() return }
Copy and paste tidy up.
<?php class Controller_Tag extends Controller_Abstract { public function get($tagId, $slug = null) { $tag = $this->_getContainer()->Tag()->load($tagId); // While we only need tag ID, ensure that we use tag slug for SEO if ($slug != $tag->getSlug()) { header("Location: " . $tag->getUrl(), true, 301); } $posts = $this->_getContainer()->Post()->fetchByTagId($tagId); echo $this->_getTwig()->render('tag.html.twig', array( 'session' => $this->_getSession(), 'tag' => $tag, 'posts' => $posts, 'local_config' => $this->_getContainer()->LocalConfig(), )); } }
<?php class Controller_Tag extends Controller_Abstract { public function get($tagId, $slug = null) { $tag = $this->_getContainer()->Tag()->load($tagId); // While we only need post ID, ensure that we use post slug for SEO if ($slug != $tag->getSlug()) { header("Location: " . $tag->getUrl(), true, 301); } $posts = $this->_getContainer()->Post()->fetchByTagId($tagId); echo $this->_getTwig()->render('tag.html.twig', array( 'session' => $this->_getSession(), 'tag' => $tag, 'posts' => $posts, 'local_config' => $this->_getContainer()->LocalConfig(), )); } }
Add test for cyrillic characters.
"use strict"; var slugTestCases = [ ["", ""] ,[" Jack & Jill like numbers 1,2,3 and 4 and silly characters ?%.$!/", "jack-jill-like-numbers-123-and-4-and-silly-characters"] ,["Un éléphant à l'orée du bois", "un-elephant-a-loree-du-bois"] ,["Iñtërnâtiônàlizætiøn", "internationalizaetion"] ,['щЫПЮ', 'schipyu'] ]; describe("slugify-service", function() { beforeEach(module("slugifier")); describe("slugify", function() { it("should produce a correct slug from string input", inject(function(Slug) { var input, expected; for (var i = 0; i < slugTestCases.length; i++) { input = slugTestCases[i][0]; expected = slugTestCases[i][1]; expect(Slug.slugify(input)).toEqual(expected); } })); }); });
"use strict"; var slugTestCases = [ ["", ""] ,[" Jack & Jill like numbers 1,2,3 and 4 and silly characters ?%.$!/", "jack-jill-like-numbers-123-and-4-and-silly-characters"] ,["Un éléphant à l'orée du bois", "un-elephant-a-loree-du-bois"] ,["Iñtërnâtiônàlizætiøn", "internationalizaetion"] ]; describe("slugify-service", function() { beforeEach(module("slugifier")); describe("slugify", function() { it("should produce a correct slug from string input", inject(function(Slug) { var input, expected; for (var i = 0; i < slugTestCases.length; i++) { input = slugTestCases[i][0]; expected = slugTestCases[i][1]; expect(Slug.slugify(input)).toEqual(expected); } })); }); });
Add where clause in moloquent inheritance scope
<?php namespace ThibaudDauce\MoloquentInheritance; use Illuminate\Database\Eloquent\ScopeInterface; use Illuminate\Database\Eloquent\Builder; class MoloquentInheritanceScope implements ScopeInterface { /** * All of the extensions to be added to the builder. * * @var array */ protected $extensions = ['OnlyParent']; /** * Apply the scope to a given Eloquent query builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return void */ public function apply(Builder $builder) { $builder->where('parent_classes', 'all', [static::class]); } /** * Remove the scope from the given Eloquent query builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return void */ public function remove(Builder $builder) { } /** * Extend the query builder with the needed functions. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return void */ public function extend(Builder $builder) { } /** * Add the only-trashed extension to the builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return void */ protected function addOnlyParent(Builder $builder) { } }
<?php namespace ThibaudDauce\MoloquentInheritance; use Illuminate\Database\Eloquent\ScopeInterface; use Illuminate\Database\Eloquent\Builder; class MoloquentInheritanceScope implements ScopeInterface { /** * All of the extensions to be added to the builder. * * @var array */ protected $extensions = ['OnlyParent']; /** * Apply the scope to a given Eloquent query builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return void */ public function apply(Builder $builder) { } /** * Remove the scope from the given Eloquent query builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return void */ public function remove(Builder $builder) { } /** * Extend the query builder with the needed functions. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return void */ public function extend(Builder $builder) { } /** * Add the only-trashed extension to the builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return void */ protected function addOnlyParent(Builder $builder) { } }
Use master path as the argument, which is crucial for single-locale repositories
import commonware import os from celery.task import task from django.conf import settings from pontoon.base.models import Project from pontoon.administration.views import _update_from_repository log = commonware.log.getLogger('pontoon') @task() def update_projects_from_repository(): for project in Project.objects.all(): try: repository_type = project.repository_type repository_url = project.repository repository_path_master = os.path.join(settings.MEDIA_ROOT, repository_type, project.name) _update_from_repository( project, repository_type, repository_url, repository_path_master) except Exception as e: log.debug('UpdateFromRepositoryTaskError: %s' % unicode(e))
import commonware from celery.task import task from pontoon.base.models import Project from pontoon.administration.views import _update_from_repository log = commonware.log.getLogger('pontoon') @task() def update_projects_from_repository(): for project in Project.objects.all(): try: repository_type = project.repository_type repository_url = project.repository repository_path_master = project.repository_path _update_from_repository( project, repository_type, repository_url, repository_path_master) except Exception as e: log.debug('UpdateFromRepositoryTaskError: %s' % unicode(e))
Fix typo in logging results on error.
module.exports = function (grunt) { var _ = require('lodash'), scsslint = require('./lib/scss-lint').init(grunt); grunt.registerMultiTask('scsslint', 'Validate `.scss` files with `scss-lint`.', function() { var done = this.async(), files = this.filesSrc, fileCount = this.filesSrc.length, target = this.target, opts; opts = this.options({ config: '.scss-lint.yml', reporterOutput: null }); grunt.verbose.writeflags(opts, 'scss-lint options'); grunt.log.writeln('Running scss-lint on ' + target); scsslint.lint(files, opts, function (results) { var success = _.isEmpty(results); if (success) { grunt.log.oklns(fileCount + ' files are lint free'); } else { grunt.log.writeln(results); } if (opts.reporterOutput) { grunt.log.writeln('Results have been written to: ' + opts.reporterOutput); } done(success); }); }); };
module.exports = function (grunt) { var _ = require('lodash'), scsslint = require('./lib/scss-lint').init(grunt); grunt.registerMultiTask('scsslint', 'Validate `.scss` files with `scss-lint`.', function() { var done = this.async(), files = this.filesSrc, fileCount = this.filesSrc.length, target = this.target, opts; opts = this.options({ config: '.scss-lint.yml', reporterOutput: null }); grunt.verbose.writeflags(opts, 'scss-lint options'); grunt.log.writeln('Running scss-lint on ' + target); scsslint.lint(files, opts, function (results) { var success = _.isEmpty(results); if (success) { grunt.log.oklns(fileCount + ' files are lint free'); } else { grunt.log.writeln(result); } if (opts.reporterOutput) { grunt.log.writeln('Results have been written to: ' + opts.reporterOutput); } done(success); }); }); };
FieldNaming: Update strategy to use IDENTITY as default strategy Used when annotation is not present. Former-commit-id: 60bb3a59db4bcf2180b272d683c8e2f4df05c356
package com.vmware.http.json; import com.google.gson.FieldNamingPolicy; import com.google.gson.FieldNamingStrategy; import java.lang.reflect.Field; import java.util.Map; public class RuntimeFieldNamingStrategy implements FieldNamingStrategy { private FieldNamingStrategy defaultStrategy = FieldNamingPolicy.IDENTITY; private Map<String, String> runtimeFieldNameMappings; public RuntimeFieldNamingStrategy(Map<String, String> runtimeFieldNameMappings) { this.runtimeFieldNameMappings = runtimeFieldNameMappings; } @Override public String translateName(Field field) { RuntimeFieldName runtimeFieldName = field.getAnnotation(RuntimeFieldName.class); if (runtimeFieldName == null) { return defaultStrategy.translateName(field); } String fieldVariableName = runtimeFieldName.value(); if (!runtimeFieldNameMappings.containsKey(fieldVariableName)) { throw new RuntimeException("No field name mapping for variable " + field.getName()); } return runtimeFieldNameMappings.get(fieldVariableName); } }
package com.vmware.http.json; import com.google.gson.FieldNamingStrategy; import java.lang.reflect.Field; import java.util.Map; public class RuntimeFieldNamingStrategy implements FieldNamingStrategy { private Map<String, String> runtimeFieldNameMappings; public RuntimeFieldNamingStrategy(Map<String, String> runtimeFieldNameMappings) { this.runtimeFieldNameMappings = runtimeFieldNameMappings; } @Override public String translateName(Field field) { RuntimeFieldName runtimeFieldName = field.getAnnotation(RuntimeFieldName.class); if (runtimeFieldName == null) { return field.getName(); } String fieldVariableName = runtimeFieldName.value(); if (!runtimeFieldNameMappings.containsKey(fieldVariableName)) { throw new RuntimeException("No field name mapping for variable " + field.getName()); } return runtimeFieldNameMappings.get(fieldVariableName); } }
Enable search whenever a user profile is saved (to allow easier recovery from accounts created incorrectly).
from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.conf import settings from vumi.persist.riak_manager import RiakManager from go.vumitools.account import AccountStore from go.base.utils import vumi_api_for_user def get_account_store(): return AccountStore(RiakManager.from_config( settings.VUMI_API_CONFIG['riak_manager'])) def create_user_profile(sender, instance, created, **kwargs): if created: account = get_account_store().new_user(unicode(instance.username)) UserProfile.objects.create(user=instance, user_account=account.key) user_api = vumi_api_for_user(instance) # Enable search for the contact & group stores user_api.contact_store.contacts.enable_search() user_api.contact_store.groups.enable_search() post_save.connect(create_user_profile, sender=User, dispatch_uid='go.base.models.create_user_profile') class UserProfile(models.Model): """A profile for a user""" user = models.OneToOneField('auth.User') user_account = models.CharField(max_length=100) def __unicode__(self): return u' '.join([self.user.first_name, self.user.last_name]) def get_user_account(self): return get_account_store().get_user(self.user_account)
from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.conf import settings from vumi.persist.riak_manager import RiakManager from go.vumitools.account import AccountStore from go.base.utils import vumi_api_for_user def get_account_store(): return AccountStore(RiakManager.from_config( settings.VUMI_API_CONFIG['riak_manager'])) def create_user_profile(sender, instance, created, **kwargs): if created: account = get_account_store().new_user(unicode(instance.username)) UserProfile.objects.create(user=instance, user_account=account.key) user_api = vumi_api_for_user(instance) # Enable search for the contact & group stores user_api.contact_store.contacts.enable_search() user_api.contact_store.groups.enable_search() post_save.connect(create_user_profile, sender=User, dispatch_uid='go.base.models.create_user_profile') class UserProfile(models.Model): """A profile for a user""" user = models.OneToOneField('auth.User') user_account = models.CharField(max_length=100) def __unicode__(self): return u' '.join([self.user.first_name, self.user.last_name]) def get_user_account(self): return get_account_store().get_user(self.user_account)
Set up the variable names
var getMongoPodLabels = function() { return process.env.MONGO_SIDECAR_POD_LABELS || false; }; var getMongoPodLabelCollection = function() { var podLabels = getMongoPodLabels(); if (!podLabels) { return false; } var labels = process.env.MONGO_SIDECAR_POD_LABELS.split(','); for (var i in labels) { var keyAndValue = labels[i].split('='); labels[i] = { key: keyAndValue[0], value: keyAndValue[1] }; } return labels; }; var getKubernetesROServiceAddress = function() { return process.env.KUBERNETES_RO_SERVICE_HOST + ":" + process.env.KUBERNETES_RO_SERVICE_PORT }; module.exports = { loopSleepSeconds: process.env.MONGO_SIDECAR_SLEEP_SECONDS || 5, unhealthySeconds: process.env.MONGO_SIDECAR_UNHEALTHY_SECONDS || 15, env: process.env.NODE_ENV || 'local', mongoPodLabels: getMongoPodLabels(), mongoPodLabelCollection: getMongoPodLabelCollection(), kubernetesROServiceAddress: getKubernetesROServiceAddress() };
var getMongoPodLabels = function() { return process.env.LL_MONGO_POD_LABELS || false; }; var getMongoPodLabelCollection = function() { var podLabels = getMongoPodLabels(); if (!podLabels) { return false; } var labels = process.env.LL_MONGO_POD_LABELS.split(','); for (var i in labels) { var keyAndValue = labels[i].split('='); labels[i] = { key: keyAndValue[0], value: keyAndValue[1] }; } return labels; }; var getKubernetesROServiceAddress = function() { return process.env.KUBERNETES_RO_SERVICE_HOST + ":" + process.env.KUBERNETES_RO_SERVICE_PORT }; module.exports = { loopSleepSeconds: process.env.MONGO_SIDECAR_SLEEP_SECONDS || 5, unhealthySeconds: process.env.MONGO_SIDECAR_UNHEALTHY_SECONDS || 15, env: process.env.NODE_ENV || 'local', mongoPodLabels: getMongoPodLabels(), mongoPodLabelCollection: getMongoPodLabelCollection(), kubernetesROServiceAddress: getKubernetesROServiceAddress() };
Use "DjangoTestSuiteRunner" to in Django 1.6.
# -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', }, 'post_office': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', } } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'post_office', ) SECRET_KEY = 'a' ROOT_URLCONF = 'post_office.test_urls' DEFAULT_FROM_EMAIL = 'webmaster@example.com' TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
# -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', }, 'post_office': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', } } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'post_office', ) SECRET_KEY = 'a' ROOT_URLCONF = 'post_office.test_urls' DEFAULT_FROM_EMAIL = 'webmaster@example.com'
Change hardcoded session cookie name
package web import ( "net/http" "github.com/gorilla/sessions" ) const SESSION_NAME = "vmango" const SESSION_USER_KEY = "auth_user" type Session struct { *sessions.Session } func (session *Session) AuthUser() *User { rawUser := session.Values[SESSION_USER_KEY] if user, ok := rawUser.(*User); ok { return user } return &User{FullName: "Anonymous"} } func (session *Session) SetAuthUser(user *User) { session.Values[SESSION_USER_KEY] = user } func (session *Session) IsAuthenticated() bool { return session.AuthUser().Authenticated } func (env *Environ) Session(request *http.Request) *Session { session, err := env.sessions.Get(request, SESSION_NAME) if err != nil { env.logger.Warn().Err(err).Msg("failed to fetch session, creating new one") session.IsNew = true } return &Session{session} }
package web import ( "net/http" "github.com/gorilla/sessions" ) const SESSION_NAME = "funrepo" const SESSION_USER_KEY = "auth_user" type Session struct { *sessions.Session } func (session *Session) AuthUser() *User { rawUser := session.Values[SESSION_USER_KEY] if user, ok := rawUser.(*User); ok { return user } return &User{FullName: "Anonymous"} } func (session *Session) SetAuthUser(user *User) { session.Values[SESSION_USER_KEY] = user } func (session *Session) IsAuthenticated() bool { return session.AuthUser().Authenticated } func (env *Environ) Session(request *http.Request) *Session { session, err := env.sessions.Get(request, SESSION_NAME) if err != nil { env.logger.Warn().Err(err).Msg("failed to fetch session, creating new one") session.IsNew = true } return &Session{session} }
Refactor overhaul to satisfy XO errors
/* eslint-env jest */ import { formatUptime } from './time' describe('time', () => { describe('formatUptime', () => { it('is a function', () => expect(formatUptime).toMatchSnapshot()) it('3 seconds', () => expect(formatUptime(3)).toMatchSnapshot()) it('23 minutes', () => expect(formatUptime(1380)).toMatchSnapshot()) it('29 minutes', () => expect(formatUptime(1740)).toMatchSnapshot()) it('30 minutes', () => expect(formatUptime(1800)).toMatchSnapshot()) it('31 minutes', () => expect(formatUptime(1860)).toMatchSnapshot()) it('3 hours 48 minutes', () => expect(formatUptime(13680)).toMatchSnapshot()) it('4 hours', () => expect(formatUptime(14400)).toMatchSnapshot()) it('23 hours', () => expect(formatUptime(82800)).toMatchSnapshot()) it('23 hours 17 minutes', () => expect(formatUptime(83820)).toMatchSnapshot()) it('23 hours 49 minutes', () => expect(formatUptime(85740)).toMatchSnapshot()) it('1 day 4 hours', () => expect(formatUptime(100800)).toMatchSnapshot()) it('3 days', () => expect(formatUptime(259200)).toMatchSnapshot()) it('3 days 8 minutes', () => expect(formatUptime(259680)).toMatchSnapshot()) }) })
/* eslint-env jest */ import { formatUptime } from './time' describe('time', () => { describe('formatUptime', () => { it('is a function', () => expect(formatUptime).toMatchSnapshot()) it('3 seconds', () => expect(formatUptime(3)).toMatchSnapshot()) it('23 minutes', () => expect(formatUptime(1380)).toMatchSnapshot()) it('29 minutes', () => expect(formatUptime(1740)).toMatchSnapshot()) it('30 minutes', () => expect(formatUptime(1800)).toMatchSnapshot()) it('31 minutes', () => expect(formatUptime(1860)).toMatchSnapshot()) it('3 hours 48 minutes', () => expect(formatUptime(13680)).toMatchSnapshot()) it('4 hours', () => expect(formatUptime(14400)).toMatchSnapshot()) it('23 hours', () => expect(formatUptime(82800)).toMatchSnapshot()) it('23 hours 17 minutes', () => expect(formatUptime(83820)).toMatchSnapshot()) it('23 hours 49 minutes', () => expect(formatUptime(85740)).toMatchSnapshot()) it('1 day 4 hours', () => expect(formatUptime(100800)).toMatchSnapshot()) it('3 days', () => expect(formatUptime(259200)).toMatchSnapshot()) it('3 days 8 minutes', () => expect(formatUptime(259680)).toMatchSnapshot()) }) })
ci: Change Apple ID env variables syntax For the sake of harmonizing environment variables syntax, we make the expected Apple ID variables all caps. This syntax is already the one used by our Github Actions workflow.
// See: https://medium.com/@TwitterArchiveEraser/notarize-electron-apps-7a5f988406db const fs = require('fs') const path = require('path') // eslint-disable-next-line node/no-unpublished-require const electron_notarize = require('electron-notarize') module.exports = async function(params) { // Only notarize the app on Mac OS only. if (process.platform !== 'darwin') { return } // eslint-disable-next-line no-console console.log('afterSign hook triggered', params) // Same appId in electron-builder. const appId = 'io.cozy.desktop' const appPath = path.join( params.appOutDir, `${params.packager.appInfo.productFilename}.app` ) if (!fs.existsSync(appPath)) { throw new Error(`Cannot find application at: ${appPath}`) } // eslint-disable-next-line no-console console.log(`Notarizing ${appId} found at ${appPath}`) try { await electron_notarize.notarize({ appBundleId: appId, appPath: appPath, appleId: process.env.APPLE_ID, appleIdPassword: process.env.APPLE_ID_PASSWORD }) } catch (error) { // eslint-disable-next-line no-console console.error(error) } // eslint-disable-next-line no-console console.log(`Done notarizing ${appId}`) }
// See: https://medium.com/@TwitterArchiveEraser/notarize-electron-apps-7a5f988406db const fs = require('fs') const path = require('path') // eslint-disable-next-line node/no-unpublished-require const electron_notarize = require('electron-notarize') module.exports = async function(params) { // Only notarize the app on Mac OS only. if (process.platform !== 'darwin') { return } // eslint-disable-next-line no-console console.log('afterSign hook triggered', params) // Same appId in electron-builder. const appId = 'io.cozy.desktop' const appPath = path.join( params.appOutDir, `${params.packager.appInfo.productFilename}.app` ) if (!fs.existsSync(appPath)) { throw new Error(`Cannot find application at: ${appPath}`) } // eslint-disable-next-line no-console console.log(`Notarizing ${appId} found at ${appPath}`) try { await electron_notarize.notarize({ appBundleId: appId, appPath: appPath, appleId: process.env.appleId, appleIdPassword: process.env.appleIdPassword }) } catch (error) { // eslint-disable-next-line no-console console.error(error) } // eslint-disable-next-line no-console console.log(`Done notarizing ${appId}`) }
Fix naming of Handler to Reciever
import asynchat import asyncore import socket class Reciver(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): self.buffer += data def found_terminator(self): line, self.buffer = self.buffer, '' for handler in self.server.handlers: handler(line) class Listener(asyncore.dispatcher): def __init__(self, port=12345): asyncore.dispatcher.__init__(self) self.port = port self.handlers = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(('', self.port)) self.listen(5) def handle_accept(self): Reciver(self, self.accept()) def add(self, handler): self.handlers.append(handler)
import asynchat import asyncore import socket class Handler(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): self.buffer += data def found_terminator(self): line, self.buffer = self.buffer, '' for handler in self.server.handlers: handler(line) class Listener(asyncore.dispatcher): def __init__(self, port=12345): asyncore.dispatcher.__init__(self) self.port = port self.handlers = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(('', self.port)) self.listen(5) def handle_accept(self): Handler(self, self.accept()) def add(self, handler): self.handlers.append(handler)
Make _ip_address_for_interface easier to use
import fcntl import socket import struct from contextlib import contextmanager @contextmanager def use_interface(ifname): """ :type ifname: str """ ip = _ip_address_for_interface(ifname) original_socket = socket.socket def rebound_socket(*args, **kwargs): sock = original_socket(*args, **kwargs) sock.bind((ip, 0)) return sock socket.socket = rebound_socket yield socket.socket = original_socket def _ip_address_for_interface(ifname): """ :type ifname: str :rtype: str """ ifname = ifname.encode('ascii') sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( sock.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24])
import fcntl import socket import struct from contextlib import contextmanager @contextmanager def use_interface(ifname): """ :type ifname: str """ ip = _ip_address_for_interface(ifname.encode('ascii')) original_socket = socket.socket def rebound_socket(*args, **kwargs): sock = original_socket(*args, **kwargs) sock.bind((ip, 0)) return sock socket.socket = rebound_socket yield socket.socket = original_socket def _ip_address_for_interface(ifname): """ :type ifname: bytes :rtype: str """ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( sock.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24])
Add default API version to client.
/** * index.js * Client entry point. * * @author Francis Brito <fr.br94@gmail.com> * @license MIT */ 'use strict'; /** * Client * Provides methods to access PrintHouse's API. * * @param {String} apiKey API key identifying account owner. * @param {Object} opts Contains options to be passed to the client */ var Client = function Client(apiKey, opts) { opts = opts || {}; if (!apiKey) { throw new Error('No API key provided.'); } this._apiUrl = opts.apiUrl || Client.DEFAULT_API_URL; }; /** * Default API endpoint. * Used if no API endpoint is passed in opts parameter when constructing a client. * * @type {String} */ Client.DEFAULT_API_URL = 'http://printhouse.io/api'; /** * Default API version. * Used if no API version is passed in opts parameter when constructing a client. * * @type {String} */ Client.DEFAULT_API_VERSION = 1; module.exports = { Client: Client };
/** * index.js * Client entry point. * * @author Francis Brito <fr.br94@gmail.com> * @license MIT */ 'use strict'; /** * Client * Provides methods to access PrintHouse's API. * * @param {String} apiKey API key identifying account owner. * @param {Object} opts Contains options to be passed to the client */ var Client = function Client(apiKey, opts) { opts = opts || {}; if (!apiKey) { throw new Error('No API key provided.'); } this._apiUrl = opts.apiUrl || Client.DEFAULT_API_URL; }; /** * Default API endpoint. * Used if no API endpoint is passed in opts parameter when constructing a client. * * @type {String} */ Client.DEFAULT_API_URL = 'http://printhouse.io/api'; module.exports = { Client: Client };
Add react-dom to the devDependency list for React Native projects
const mergeDirs = require('merge-dirs').default; const helpers = require('../../lib/helpers'); const path = require('path'); const shell = require('shelljs'); const latestVersion = require('latest-version'); module.exports = latestVersion('@storybook/react-native').then(version => { // copy all files from the template directory to project directory mergeDirs(path.resolve(__dirname, 'template/'), '.', 'overwrite'); // set correct project name on entry files if possible const dirname = shell.ls('-d', 'ios/*.xcodeproj').stdout; const projectName = dirname && dirname.slice('ios/'.length, dirname.length - '.xcodeproj'.length - 1); if (projectName) { shell.sed('-i', '%APP_NAME%', projectName, 'storybook/index.ios.js'); shell.sed('-i', '%APP_NAME%', projectName, 'storybook/index.android.js'); } const packageJson = helpers.getPackageJson(); packageJson.dependencies = packageJson.dependencies || {}; packageJson.devDependencies = packageJson.devDependencies || {}; packageJson.devDependencies['@storybook/react-native'] = `^${version}`; if (!packageJson.dependencies['react-dom'] && !packageJson.devDependencies['react-dom']) { packageJson.devDependencies['react-dom'] = '^15.5.4'; } packageJson.scripts = packageJson.scripts || {}; packageJson.scripts['storybook'] = 'storybook start -p 7007'; helpers.writePackageJson(packageJson); });
const mergeDirs = require('merge-dirs').default; const helpers = require('../../lib/helpers'); const path = require('path'); const shell = require('shelljs'); const latestVersion = require('latest-version'); module.exports = latestVersion('@storybook/react-native').then(version => { // copy all files from the template directory to project directory mergeDirs(path.resolve(__dirname, 'template/'), '.', 'overwrite'); // set correct project name on entry files if possible const dirname = shell.ls('-d', 'ios/*.xcodeproj').stdout; const projectName = dirname && dirname.slice('ios/'.length, dirname.length - '.xcodeproj'.length - 1); if (projectName) { shell.sed('-i', '%APP_NAME%', projectName, 'storybook/index.ios.js'); shell.sed('-i', '%APP_NAME%', projectName, 'storybook/index.android.js'); } const packageJson = helpers.getPackageJson(); packageJson.devDependencies = packageJson.devDependencies || {}; packageJson.devDependencies['@storybook/react-native'] = `^${version}`; packageJson.scripts = packageJson.scripts || {}; packageJson.scripts['storybook'] = 'storybook start -p 7007'; helpers.writePackageJson(packageJson); });
Fix typo in button name.
$('#dripbot-title').css({ "display": "inline-block", "margin-right": "20px" }); $('#dripbot').css({ "text-align": "left" }); $('#dripbot-toggle.stop').css({ "background-color": "#e9656d", "color": "white", "margin-top": "-10px" }); $('#dripbot ul li p').css({ "margin-bottom":"5px", "margin-right": "40px", "display": "inline-block" }); $('img#dripbot-logo').css({ "margin-bottom": "10px", "margin-right": "5px" }); $('div#dripbot-update').css({ "background-color": "#47a447", "padding": "10px" }); $('div#dripbot-update h1').css({ "font-weight": "800", }); $('#save-game').css({ "background-color": "#47a447", "color": "white", "margin-left": "20px" })
$('#dripbot-title').css({ "display": "inline-block", "margin-right": "20px" }); $('#dripbot').css({ "text-align": "left" }); $('#dripbot-toggle.stop').css({ "background-color": "#e9656d", "color": "white", "margin-top": "-10px" }); $('#dripbot ul li p').css({ "margin-bottom":"5px", "margin-right": "40px", "display": "inline-block" }); $('img#dripbot-logo').css({ "margin-bottom": "10px", "margin-right": "5px" }); $('div#dripbot-update').css({ "background-color": "#47a447", "padding": "10px" }); $('div#dripbot-update h1').css({ "font-weight": "800", }); $('#save-button').css({ "background-color": "#47a447", "color": "white", "margin-left": "20px" })
Print stack trace if Nimbus is not avaible
package org.robockets.runqueue.client; import javax.swing.SwingUtilities; import javax.swing.UIManager; import org.robockets.runqueue.client.controllers.Controllers; public class Main { public static void main(String args[]) { try { // Nimbus theme for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { e.printStackTrace(); } SwingUtilities.invokeLater(new Runnable () { public void run () { Controllers.main.show(); } }); } }
package org.robockets.runqueue.client; import javax.swing.SwingUtilities; import javax.swing.UIManager; import org.robockets.runqueue.client.controllers.Controllers; public class Main { public static void main(String args[]) { try { // Nimbus theme for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { System.out.println(e); } SwingUtilities.invokeLater(new Runnable () { public void run () { Controllers.main.show(); } }); } }
Add support for NCLOB sql type
package nl.idgis.publisher.provider.database.messages; import java.io.Serializable; import nl.idgis.publisher.domain.service.Type; public class DatabaseColumnInfo implements Serializable { private static final long serialVersionUID = 8052868017910750424L; private final String name; private final String typeName; public DatabaseColumnInfo(String name, String typeName) { this.name = name; this.typeName = typeName; } public String getName() { return name; } public String getTypeName() { return typeName; } public Type getType() { switch(typeName.toUpperCase()) { case "NUMBER": return Type.NUMERIC; case "DATE": return Type.DATE; case "VARCHAR2": case "NVARCHAR2": case "NCHAR": case "CHAR": case "CLOB": case "NCLOB": return Type.TEXT; case "SDO_GEOMETRY": case "ST_GEOMETRY": return Type.GEOMETRY; } return null; } @Override public String toString() { return "DatabaseColumnInfo [name=" + name + ", typeName=" + typeName + "]"; } }
package nl.idgis.publisher.provider.database.messages; import java.io.Serializable; import nl.idgis.publisher.domain.service.Type; public class DatabaseColumnInfo implements Serializable { private static final long serialVersionUID = 8052868017910750424L; private final String name; private final String typeName; public DatabaseColumnInfo(String name, String typeName) { this.name = name; this.typeName = typeName; } public String getName() { return name; } public String getTypeName() { return typeName; } public Type getType() { switch(typeName.toUpperCase()) { case "NUMBER": return Type.NUMERIC; case "DATE": return Type.DATE; case "VARCHAR2": case "NVARCHAR2": case "NCHAR": case "CHAR": case "CLOB": return Type.TEXT; case "SDO_GEOMETRY": case "ST_GEOMETRY": return Type.GEOMETRY; } return null; } @Override public String toString() { return "DatabaseColumnInfo [name=" + name + ", typeName=" + typeName + "]"; } }
Add import statement for os
#!/usr/bin/env python ########################################################################## # scripts/ec2/terminate_all.py # # Part of Project Thrill - http://project-thrill.org # # Copyright (C) 2015 Timo Bingmann <tb@panthema.net> # # All rights reserved. Published under the BSD-2 license in the LICENSE file. ########################################################################## import boto3 import os from subprocess import call ec2 = boto3.resource('ec2') filters = [{'Name': 'instance-state-name', 'Values': ['running']}] if "EC2_KEY_NAME" in os.environ: filters.append({'Name': 'key-name', 'Values': [os.environ['EC2_KEY_NAME']]}) instances = ec2.instances.filter(Filters=filters) ids = [instance.id for instance in instances] print("Terminating:", ids) ec2.instances.filter(InstanceIds=ids).terminate() ##########################################################################
#!/usr/bin/env python ########################################################################## # scripts/ec2/terminate_all.py # # Part of Project Thrill - http://project-thrill.org # # Copyright (C) 2015 Timo Bingmann <tb@panthema.net> # # All rights reserved. Published under the BSD-2 license in the LICENSE file. ########################################################################## import boto3 from subprocess import call ec2 = boto3.resource('ec2') filters = [{'Name': 'instance-state-name', 'Values': ['running']}] if "EC2_KEY_NAME" in os.environ: filters.append({'Name': 'key-name', 'Values': [os.environ['EC2_KEY_NAME']]}) instances = ec2.instances.filter(Filters=filters) ids = [instance.id for instance in instances] print("Terminating:", ids) ec2.instances.filter(InstanceIds=ids).terminate() ##########################################################################
Redefine public static func primaryKey
<?php /* * Domain plugin for HiPanel * * @link https://github.com/hiqdev/hipanel-module-domain * @package hipanel-module-domain * @license BSD-3-Clause * @copyright Copyright (c) 2014-2015, HiQDev (http://hiqdev.com/) */ namespace hipanel\modules\domain\cart; use hipanel\modules\domain\models\Domain; use Yii; class DomainRenewalProduct extends AbstractDomainProduct { protected $_operation = 'renewal'; public static function primaryKey() { return ['model_id']; } public function load($data, $formName = null) { $result = parent::load($data, ''); if ($result) { $this->_model = Domain::findOne($this->model_id); $this->name = $this->_model->domain; $this->description = Yii::t('app', 'Renewal'); } return $result; } public function getId() { return implode('_', ['domain', 'renewal', $this->_model->id]); } }
<?php /* * Domain plugin for HiPanel * * @link https://github.com/hiqdev/hipanel-module-domain * @package hipanel-module-domain * @license BSD-3-Clause * @copyright Copyright (c) 2014-2015, HiQDev (http://hiqdev.com/) */ namespace hipanel\modules\domain\cart; use hipanel\modules\domain\models\Domain; use Yii; class DomainRenewalProduct extends AbstractDomainProduct { protected $_operation = 'renewal'; public function load($data, $formName = null) { $result = parent::load($data, ''); if ($result) { $this->_model = Domain::findOne($this->model_id); $this->name = $this->_model->domain; $this->description = Yii::t('app', 'Renewal'); } return $result; } public function getId() { return implode('_', ['domain', 'renewal', $this->_model->id]); } }
Switch to preg_replace in Something Positive plugin
<?php class Af_SomethingPositive extends Plugin { function about() { return array(0.1, "Fetch image from Something Positive webcomic", "Markus Wiik"); } function init($host) { $host->add_hook($host::HOOK_ARTICLE_FILTER, $this); } function hook_article_filter($article) { $owner_uid = $article["owner_uid"]; if (strpos($article["link"], "somethingpositive.net") !== FALSE) { if (strpos($article["plugin_data"], "somethingpositive,$owner_uid:") === FALSE) { $image_url = preg_replace("/shtml/", "png", $article['link']); $article["content"] = '<img src="' . $image_url . '"/>'; $article["plugin_data"] = "somethingpositive,$owner_uid:" . $article["plugin_data"]; } else if (isset($article["stored"]["content"])) { $article["content"] = $article["stored"]["content"]; } } return $article; } } ?>
<?php class Af_SomethingPositive extends Plugin { function about() { return array(0.1, "Fetch image from Something Positive webcomic", "Markus Wiik"); } function init($host) { $host->add_hook($host::HOOK_ARTICLE_FILTER, $this); } function hook_article_filter($article) { $owner_uid = $article["owner_uid"]; if (strpos($article["link"], "somethingpositive.net") !== FALSE) { if (strpos($article["plugin_data"], "somethingpositive,$owner_uid:") === FALSE) { $url = parse_url($article["link"]); $image_name = substr($url["path"], 0, -5) . "png"; $article["content"] = '<img src="http://' . $url["host"] . '/' . $image_name . '"/>'; $article["plugin_data"] = "somethingpositive,$owner_uid:" . $article["plugin_data"]; } else if (isset($article["stored"]["content"])) { $article["content"] = $article["stored"]["content"]; } } return $article; } } ?>
Remove HTML comments from wrapper
<!doctype html> <html <?php language_attributes(); ?>> <?php get_template_part('partials/head'); ?> <body <?php body_class(); ?>> <!--[if IE]> <div class="alert alert-warning"> <?php _e('You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.', 'sage'); ?> </div> <![endif]--> <?php do_action('get_header'); get_template_part('partials/header'); ?> <div class="wrap container" role="document"> <div class="content row"> <main class="main"> <?php include App\template()->main(); ?> </main> <?php if (App\display_sidebar()) : ?> <aside class="sidebar"> <?php App\template_part('partials/sidebar'); ?> </aside> <?php endif; ?> </div> </div> <?php do_action('get_footer'); get_template_part('partials/footer'); wp_footer(); ?> </body> </html>
<!doctype html> <html <?php language_attributes(); ?>> <?php get_template_part('partials/head'); ?> <body <?php body_class(); ?>> <!--[if IE]> <div class="alert alert-warning"> <?php _e('You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.', 'sage'); ?> </div> <![endif]--> <?php do_action('get_header'); get_template_part('partials/header'); ?> <div class="wrap container" role="document"> <div class="content row"> <main class="main"> <?php include App\template()->main(); ?> </main><!-- /.main --> <?php if (App\display_sidebar()) : ?> <aside class="sidebar"> <?php App\template_part('partials/sidebar'); ?> </aside><!-- /.sidebar --> <?php endif; ?> </div><!-- /.content --> </div><!-- /.wrap --> <?php do_action('get_footer'); get_template_part('partials/footer'); wp_footer(); ?> </body> </html>
Update module test code to avoid pycs (that are not used)
# -*- coding: utf-8 -*- import os import ast import unittest from ansible import utils class TestModules(unittest.TestCase): def list_all_modules(self): paths = utils.plugins.module_finder._get_paths() paths = [x for x in paths if os.path.isdir(x)] module_list = [] for path in paths: for (dirpath, dirnames, filenames) in os.walk(path): for filename in filenames: (path, ext) = os.path.splitext(filename) if ext == ".py": module_list.append(os.path.join(dirpath, filename)) return module_list def test_ast_parse(self): module_list = self.list_all_modules() ERRORS = [] # attempt to parse each module with ast for m in module_list: try: ast.parse(''.join(open(m))) except Exception, e: ERRORS.append((m, e)) assert len(ERRORS) == 0, "get_docstring errors: %s" % ERRORS
# -*- coding: utf-8 -*- import os import ast import unittest from ansible import utils class TestModules(unittest.TestCase): def list_all_modules(self): paths = utils.plugins.module_finder._get_paths() paths = [x for x in paths if os.path.isdir(x)] module_list = [] for path in paths: for (dirpath, dirnames, filenames) in os.walk(path): for filename in filenames: (path, ext) = os.path.splitext(filename) if ext != ".ps1": module_list.append(os.path.join(dirpath, filename)) return module_list def test_ast_parse(self): module_list = self.list_all_modules() ERRORS = [] # attempt to parse each module with ast for m in module_list: try: ast.parse(''.join(open(m))) except Exception, e: ERRORS.append((m, e)) assert len(ERRORS) == 0, "get_docstring errors: %s" % ERRORS
Change types to get the tests to complete.
from llvm import * from llvm.core import * from llvm.ee import * import logging tp_int = Type.int(64) tp_float = Type.float() def py_type_to_llvm(tp): if tp == int: return tp_int elif tp == float: return tp_float else: raise TypeError("Unknown type " + tp) def get_generic_value(tp, val): if type(val) == int: return GenericValue.int(tp, val) elif type(val) == float: return GenericValue.real(tp, val) def llvm_to_py(tp, val): if tp == int: return val.as_int_signed() elif tp == float: return val.as_real(py_type_to_llvm(tp)) else: raise Exception ("Unknown type {0}".format(tp))
from llvm import * from llvm.core import * from llvm.ee import * import logging tp_int = Type.int() tp_float = Type.float() def py_type_to_llvm(tp): if tp == int: return tp_int elif tp == float: return tp_float else: raise TypeError("Unknown type " + tp) def get_generic_value(tp, val): if type(val) == int: return GenericValue.int(tp, val) elif type(val) == float: return GenericValue.real(tp, val) def llvm_to_py(tp, val): if tp == int: return val.as_int() elif tp == float: return val.as_real(py_type_to_llvm(tp)) else: raise Exception ("Unknown type {0}".format(tp))
Handle case where page parameter is not set.
<?php require "WhatsNew.inc"; // dynamic pages need to include dynamics scripts $pageParam = isset($_REQUEST['page']) ? $_REQUEST['page'] : 'about'; switch($pageParam) { // dynamic cases case "statistics": require "statistics.php"; break; // static cases case "background": $device_phrases = array( "Webkit" => "iPhone, Android, and Palm webOS phones", "Touch" => "touchscreen phones", "Basic" => "non-touchscreen phones" ); $device_phrase = $device_phrases[$page->branch]; case "requirements": case "credits": require "$page->branch/{$_REQUEST['page']}.html"; $page->cache(); $page->output(); break; case "about": default: $whats_new = new WhatsNew(); $whats_new_count = $whats_new->count(WhatsNew::getLastTime()); require "$page->branch/index.html"; $page->output(); } ?>
<?php require "WhatsNew.inc"; // dynamic pages need to include dynamics scripts switch($_REQUEST['page']) { // dynamic cases case "statistics": require "statistics.php"; break; // static cases case "background": $device_phrases = array( "Webkit" => "iPhone, Android, and Palm webOS phones", "Touch" => "touchscreen phones", "Basic" => "non-touchscreen phones" ); $device_phrase = $device_phrases[$page->branch]; case "requirements": case "credits": require "$page->branch/{$_REQUEST['page']}.html"; $page->cache(); $page->output(); break; case "about": default: $whats_new = new WhatsNew(); $whats_new_count = $whats_new->count(WhatsNew::getLastTime()); require "$page->branch/index.html"; $page->output(); } ?>
Add tests for parameters (verified broken), fix next commit
package model_test import ( "encoding/json" "github.com/crezam/actions-on-google-golang/internal/test" "github.com/crezam/actions-on-google-golang/model" "os" "testing" "time" ) func TestRequestParsing(t *testing.T) { var req model.ApiAiRequest file, _ := os.Open("./data/sample_request1.json") dec := json.NewDecoder(file) err := dec.Decode(&req) // test if any issues decoding file test.Ok(t, err) // assert correct parsing test.Equals(t, "209eefa7-adb5-4d03-a8b9-9f7ae68a0c11", req.Id) expectedTimestamp, _ := time.Parse(time.RFC3339Nano, "2016-10-10T07:41:40.098Z") test.Equals(t, expectedTimestamp, req.Timestamp) test.Equals(t, "Hi, my name is Sam!", req.Result.ResolvedQuery) test.Equals(t, "agent", req.Result.Source) test.Equals(t, "greetings", req.Result.Action) test.Equals(t, false, req.Result.ActionIncomplete) test.Equals(t, "Sam", req.Result.Parameters.Parameters["user_name"]) }
package model_test import ( "encoding/json" "github.com/crezam/actions-on-google-golang/internal/test" "github.com/crezam/actions-on-google-golang/model" "os" "testing" "time" ) func TestRequestParsing(t *testing.T) { var req model.ApiAiRequest file, _ := os.Open("./data/sample_request1.json") dec := json.NewDecoder(file) err := dec.Decode(&req) // test if any issues decoding file test.Ok(t, err) // assert correct parsing test.Equals(t, "209eefa7-adb5-4d03-a8b9-9f7ae68a0c11", req.Id) expectedTimestamp, _ := time.Parse(time.RFC3339Nano, "2016-10-10T07:41:40.098Z") test.Equals(t, expectedTimestamp, req.Timestamp) test.Equals(t, "Hi, my name is Sam!", req.Result.ResolvedQuery) }
Add i18n for Boolean Field
<?php defined('SYSPATH') or die('No direct script access.'); class Jelly_Field_Boolean extends Jelly_Field { /** * @var mixed How TRUE is represented in the database */ public $true = 1; /** * @var string How TRUE is represented to users (mainly in forms) */ public $pretty_true = __("Yes"); /** * @var stringHow FALSE is represented in the database */ public $false = 0; /** * @var string How FALSE is represented to users (mainly in forms) */ public $pretty_false = __("No"); /** * Validates a boolean out of the value with filter_var * * @param mixed $value * @return void * @author Jonathan Geiger */ public function set($value) { $this->value = filter_var($value, FILTER_VALIDATE_BOOLEAN); } /** * Returns the value as it should be represented in the database * * @param string $loaded * @return void * @author Jonathan Geiger */ public function save($loaded) { return ($this->value) ? $this->true : $this->false; } }
<?php defined('SYSPATH') or die('No direct script access.'); class Jelly_Field_Boolean extends Jelly_Field { /** * @var mixed How TRUE is represented in the database */ public $true = 1; /** * @var string How TRUE is represented to users (mainly in forms) */ public $pretty_true = "Yes"; /** * @var stringHow FALSE is represented in the database */ public $false = 0; /** * @var string How FALSE is represented to users (mainly in forms) */ public $pretty_false = "No"; /** * Validates a boolean out of the value with filter_var * * @param mixed $value * @return void * @author Jonathan Geiger */ public function set($value) { $this->value = filter_var($value, FILTER_VALIDATE_BOOLEAN); } /** * Returns the value as it should be represented in the database * * @param string $loaded * @return void * @author Jonathan Geiger */ public function save($loaded) { return ($this->value) ? $this->true : $this->false; } }
retention: Fix migration making archive_transaction field not null. DELETing from archive tables and ALTERing ArchivedMessage needs to be split into separate transactions. zerver_archivedattachment_messages needs to be cleared out before zerver_archivedattachment.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): """ Tables cannot have data deleted from them and be altered in a single transaction, but we need the DELETEs to be atomic together. So we set atomic=False for the migration in general, and run the DELETEs in one transaction, and AlterField in another. """ atomic = False dependencies = [ ('zerver', '0231_add_archive_transaction_model'), ] operations = [ migrations.RunSQL(""" BEGIN; DELETE FROM zerver_archivedusermessage; DELETE FROM zerver_archivedreaction; DELETE FROM zerver_archivedsubmessage; DELETE FROM zerver_archivedattachment_messages; DELETE FROM zerver_archivedattachment; DELETE FROM zerver_archivedmessage; DELETE FROM zerver_archivetransaction; COMMIT; """), migrations.AlterField( model_name='archivedmessage', name='archive_transaction', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.ArchiveTransaction'), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('zerver', '0231_add_archive_transaction_model'), ] operations = [ migrations.RunSQL("DELETE FROM zerver_archivedusermessage"), migrations.RunSQL("DELETE FROM zerver_archivedreaction"), migrations.RunSQL("DELETE FROM zerver_archivedsubmessage"), migrations.RunSQL("DELETE FROM zerver_archivedattachment"), migrations.RunSQL("DELETE FROM zerver_archivedattachment_messages"), migrations.RunSQL("DELETE FROM zerver_archivedmessage"), migrations.RunSQL("DELETE FROM zerver_archivetransaction"), migrations.AlterField( model_name='archivedmessage', name='archive_transaction', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.ArchiveTransaction'), ), ]
Fix wrong path composition for data directory
import os import time from dj_experiment.tasks.tasks import longtime_add, netcdf_save from example.settings import DJ_EXPERIMENT_BASE_DATA_DIR if __name__ == '__main__': result = longtime_add.delay(1, 2) # at this time, our task is not finished, so it will return False print 'Task finished? ', result.ready() print 'Task result: ', result.result # sleep 10 seconds to ensure the task has been finished time.sleep(10) # now the task should be finished and ready method will return True print 'Task finished? ', result.ready() print 'Task result: ', result.result rcmdatadir = DJ_EXPERIMENT_BASE_DATA_DIR result1 = netcdf_save.delay(14, rcmdatadir) print 'Task netcdf finished? ', result1.ready() print 'Task result1: ', result1.result time.sleep(10) print 'Task netcdf finished? ', result1.ready() print 'Task result1: ', result1.result
import os import time from dj_experiment.tasks.tasks import longtime_add, netcdf_save from example.settings import (DJ_EXPERIMENT_BASE_DATA_DIR, DJ_EXPERIMENT_DATA_DIR) if __name__ == '__main__': result = longtime_add.delay(1, 2) # at this time, our task is not finished, so it will return False print 'Task finished? ', result.ready() print 'Task result: ', result.result # sleep 10 seconds to ensure the task has been finished time.sleep(10) # now the task should be finished and ready method will return True print 'Task finished? ', result.ready() print 'Task result: ', result.result rcmdatadir = os.path.join(DJ_EXPERIMENT_BASE_DATA_DIR, DJ_EXPERIMENT_DATA_DIR) result1 = netcdf_save.delay(14, rcmdatadir) print 'Task netcdf finished? ', result1.ready() print 'Task result1: ', result1.result time.sleep(10) print 'Task netcdf finished? ', result1.ready() print 'Task result1: ', result1.result
Use a different default port
from attrs import define, field from tak import mcts import torch from typing import Optional @define(slots=False) class Config: device: str = "cuda" server_port: int = 5432 lr: float = 1e-3 size: int = 3 rollout_config: mcts.Config = field( factory=lambda: mcts.Config( simulation_limit=25, root_noise_alpha=1.0, root_noise_mix=0.25, ) ) rollout_resignation_threshold: float = 0.95 rollout_ply_limit: int = 100 rollout_workers: int = 50 rollouts_per_step: int = 100 replay_buffer_steps: int = 4 train_batch: int = 64 train_positions: int = 1024 train_dtype: torch.dtype = torch.float32 serve_dtype: torch.dtype = torch.float16 save_path: Optional[str] = None save_freq: int = 10 train_steps: int = 10 wandb: bool = False job_name: Optional[str] = None project: str = "taktician-alphazero" def __attrs_post_init__(self): if self.device == "cpu": self.serve_dtype = torch.float32
from attrs import define, field from tak import mcts import torch from typing import Optional @define(slots=False) class Config: device: str = "cuda" server_port: int = 5001 lr: float = 1e-3 size: int = 3 rollout_config: mcts.Config = field( factory=lambda: mcts.Config( simulation_limit=25, root_noise_alpha=1.0, root_noise_mix=0.25, ) ) rollout_resignation_threshold: float = 0.95 rollout_ply_limit: int = 100 rollout_workers: int = 50 rollouts_per_step: int = 100 replay_buffer_steps: int = 4 train_batch: int = 64 train_positions: int = 1024 train_dtype: torch.dtype = torch.float32 serve_dtype: torch.dtype = torch.float16 save_path: Optional[str] = None save_freq: int = 10 train_steps: int = 10 wandb: bool = False job_name: Optional[str] = None project: str = "taktician-alphazero" def __attrs_post_init__(self): if self.device == "cpu": self.serve_dtype = torch.float32
Switch python to grpc protocol
/* * Copyright 2018 the original author or authors. * * 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 utils import ( "path/filepath" "github.com/projectriff/riff/riff-cli/pkg/options" ) func ResolveOptions(functionArtifact string, language string, opts *options.InitOptions) { if opts.Input == "" { opts.Input = opts.FunctionName } if opts.Artifact == "" { opts.Artifact = filepath.Base(functionArtifact) } protocolForLanguage := map[string]string{ "shell": "grpc", "java": "grpc", "js": "grpc", "node": "grpc", "python": "grpc", } if opts.Protocol == "" { opts.Protocol = protocolForLanguage[language] } }
/* * Copyright 2018 the original author or authors. * * 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 utils import ( "path/filepath" "github.com/projectriff/riff/riff-cli/pkg/options" ) func ResolveOptions(functionArtifact string, language string, opts *options.InitOptions) { if opts.Input == "" { opts.Input = opts.FunctionName } if opts.Artifact == "" { opts.Artifact = filepath.Base(functionArtifact) } protocolForLanguage := map[string]string{ "shell": "grpc", "java": "grpc", "js": "grpc", "node": "grpc", "python": "stdio", } if opts.Protocol == "" { opts.Protocol = protocolForLanguage[language] } }
Resolve pytest warning about TestRPCProvider
import pytest from web3.manager import ( RequestManager, ) from web3.providers.tester import ( TestRPCProvider as TheTestRPCProvider, is_testrpc_available, ) from web3.utils.compat import socket def get_open_port(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 0)) s.listen(1) port = s.getsockname()[1] s.close() return port @pytest.mark.skipif(not is_testrpc_available, reason="`eth-testrpc` is not installed") def test_making_provider_request(): from testrpc.rpc import RPCMethods provider = TheTestRPCProvider(port=get_open_port()) rm = RequestManager(None, provider) response = rm.request_blocking(method="web3_clientVersion", params=[]) assert response == RPCMethods.web3_clientVersion()
import pytest from web3.manager import ( RequestManager, ) from web3.providers.tester import ( TestRPCProvider, is_testrpc_available, ) from web3.utils.compat import socket def get_open_port(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 0)) s.listen(1) port = s.getsockname()[1] s.close() return port @pytest.mark.skipif(not is_testrpc_available, reason="`eth-testrpc` is not installed") def test_making_provider_request(): from testrpc.rpc import RPCMethods provider = TestRPCProvider(port=get_open_port()) rm = RequestManager(None, provider) response = rm.request_blocking(method="web3_clientVersion", params=[]) assert response == RPCMethods.web3_clientVersion()
Fix bug in AesKey printing, quote strings.
package shade import ( "fmt" "time" ) type File struct { Filename string Filesize int64 ModifiedTime time.Time Chunksize int Chunks []Chunk AesKey []byte } type Chunk struct { Index int Sha256 []byte } func (f *File) String() string { out := fmt.Sprintf("{Filename: %q, Filesize: %d, Chunksize: %d, AesKey: %q, Chunks:", f.Filename, f.Filesize, f.Chunksize, f.AesKey) sep := ", " if len(f.Chunks) < 2 { out += " " } else { out += "\n" sep = ",\n" } for i, c := range f.Chunks { if i == len(f.Chunks) { out += c.String() + sep } else { out += c.String() } } return out } func (c *Chunk) String() string { return fmt.Sprintf("{Index: %d, Sha256: %x}", c.Index, c.Sha256) }
package shade import ( "fmt" "time" ) type File struct { Filename string Filesize int64 ModifiedTime time.Time Chunksize int Chunks []Chunk AesKey []byte } type Chunk struct { Index int Sha256 []byte } func (f *File) String() string { out := fmt.Sprintf("{Filename: %s, Filesize: %d, Chunksize: %d, AesKey: %s, Chunks:", f.Filename, f.Filesize, f.Chunksize) sep := ", " if len(f.Chunks) < 2 { out += " " } else { out += "\n" sep = ",\n" } for i, c := range f.Chunks { if i == len(f.Chunks) { out += c.String() + sep } else { out += c.String() } } return out } func (c *Chunk) String() string { return fmt.Sprintf("{Index: %d, Sha256: %x}", c.Index, c.Sha256) }
Use test_docs as directory for test documents for solr server
#!/usr/bin/python # # SCRIPT FOR POPULATING TEST SOLR SERVER CORE WITH TEST DOCUMENTS # # Usage: python setup-test-docs.py <Solr Endpoint Url> # # Solr endpoint URL should be in the form: # https://example.com/solr/<core-name>/ # # .txt files in the directory ./txt/ will be committed to user-provided Solr # core matching the name <core-name>. import os from os import listdir from os.path import isfile, join import json import sys TEST_DOC_DIR = 'test_docs' arguments = sys.argv solrApiUrl = arguments[1] filePaths = [f for f in listdir(TEST_DOC_DIR) if isfile(join(TEST_DOC_DIR, f))] TEMPLATE = """ { "add": { "doc": {"title":"%s", "body": %s}, "boost":1.0, "overwrite":true, "commitWithin":1000 } } """ headers = {'Content-type': 'application/json'} for i, path in enumerate(filePaths): print str(i) + '\tProcessing ' + path f = open(TEST_DOC_DIR + '/' + path) text = f.read() commandJson = TEMPLATE % (path.replace('.txt', ''), json.dumps(text)) os.system("curl " + solrApiUrl + "update?commit=true -H 'Content-type:application/json' -d '%s'" % commandJson) print '\nDone.\n----------------------------------'
#!/usr/bin/python # # SCRIPT FOR POPULATING TEST SOLR SERVER CORE WITH TEST DOCUMENTS # # Usage: python setup-test-docs.py <Solr Endpoint Url> # # Solr endpoint URL should be in the form: # https://example.com/solr/<core-name>/ # # .txt files in the directory ./txt/ will be committed to user-provided Solr # core matching the name <core-name>. import os from os import listdir from os.path import isfile, join import json import sys arguments = sys.argv solrApiUrl = arguments[1] filePaths = [f for f in listdir('txt') if isfile(join('txt', f))] TEMPLATE = """ { "add": { "doc": {"title":"%s", "body": %s}, "boost":1.0, "overwrite":true, "commitWithin":1000 } } """ headers = {'Content-type': 'application/json'} for i, path in enumerate(filePaths): print str(i) + '\tProcessing ' + path f = open('txt/' + path) text = f.read() commandJson = TEMPLATE % (path.replace('.txt', ''), json.dumps(text)) os.system("curl " + solrApiUrl + "update?commit=true -H 'Content-type:application/json' -d '%s'" % commandJson) print '\nDone.\n----------------------------------'
Add an Overlaps function to Rectangle.
// Copyright 2014 Arne Roomann-Kurrik // // 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 twodee type Point struct { X float32 Y float32 } func Pt(x, y float32) Point { return Point{x, y} } type Rectangle struct { Min Point Max Point } func Rect(x1, y1, x2, y2 float32) Rectangle { return Rectangle{ Min: Pt(x1, y1), Max: Pt(x2, y2), } } func (r Rectangle) Overlaps(s Rectangle) bool { return s.Min.X < r.Max.X && s.Max.X > r.Min.X && s.Min.Y < r.Max.Y && s.Max.Y > r.Min.Y }
// Copyright 2014 Arne Roomann-Kurrik // // 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 twodee import () type Point struct { X float32 Y float32 } func Pt(x, y float32) Point { return Point{x, y} } type Rectangle struct { Min Point Max Point } func Rect(x1, y1, x2, y2 float32) Rectangle { return Rectangle{ Min: Pt(x1, y1), Max: Pt(x2, y2), } }
Remove the custom `isFloat` function and use `Number.isInteger`
'use strict'; const metrics = ['label', 'time', 'size', 'gzip', 'originalsize', 'originalgzip']; class Measure { constructor(stats) { this.each(function (key) { this[key] = stats ? stats[key] : Number.NaN; }); } each(fn) { // eslint-disable-next-line unicorn/no-array-callback-reference, unicorn/no-array-for-each, unicorn/no-array-method-this-argument metrics.forEach(fn, this); } add(stats) { this.each(function (key) { this[key] += stats ? stats[key] : Number.NaN; }); } isValid() { return ('time' in this) && !Number.isNaN(this.time); } equal(key, measure) { return this[key] === measure[key]; } format(key, type) { let value = this[key]; if (!Number.isInteger(value)) { value = Number(value.toFixed(2)); } if (type === 'byte') { return `${value} bytes`; } if (type === 'time') { return `${value} ms`; } } } module.exports = Measure;
'use strict'; function isFloat(n) { return n === Number(n) && n !== (Math.trunc(n)); } const metrics = ['label', 'time', 'size', 'gzip', 'originalsize', 'originalgzip']; class Measure { constructor(stats) { this.each(function (key) { this[key] = stats ? stats[key] : Number.NaN; }); } each(fn) { // eslint-disable-next-line unicorn/no-array-callback-reference, unicorn/no-array-for-each, unicorn/no-array-method-this-argument metrics.forEach(fn, this); } add(stats) { this.each(function (key) { this[key] += stats ? stats[key] : Number.NaN; }); } isValid() { return ('time' in this) && !Number.isNaN(this.time); } equal(key, measure) { return this[key] === measure[key]; } format(key, type) { let value = this[key]; if (isFloat(value)) { value = Number(value.toFixed(2)); } if (type === 'byte') { return `${value} bytes`; } if (type === 'time') { return `${value} ms`; } } } module.exports = Measure;
Fix breaking changes in React Native 0.47 - 'createJSModules' was removed in RN 0.47, so the original code has nothing to override and building fails. Remove the override, but not the function, to maintain BC. - See https://github.com/facebook/react-native/commit/ce6fb337a146e6f261f2afb564aa19363774a7a8
package com.zmxv.RNSound; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; public class RNSoundPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules (ReactApplicationContext context) { List<NativeModule> modules = new ArrayList<>(); modules.add(new RNSoundModule(context)); return modules; } // Deprecated RN 0.47 // @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext context) { return Collections.emptyList(); } }
package com.zmxv.RNSound; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; public class RNSoundPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules (ReactApplicationContext context) { List<NativeModule> modules = new ArrayList<>(); modules.add(new RNSoundModule(context)); return modules; } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext context) { return Collections.emptyList(); } }
Fix for python 2.6 compatibility in subprocess
from __future__ import print_function import os, pyrax, sys import pyrax.exceptions as pexc from termcolor import colored import ConfigParser import subprocess path = os.path.dirname(os.path.realpath(__file__)) config_file = path + "/config.ini" def log(level, message): if level == 'OK': print(colored('[ OK ]', 'green'), "\t", message, file=sys.stderr) elif level == 'INFO': print(colored('[ INFO ]', 'blue'), "\t", message, file=sys.stderr) elif level == 'ERROR': print(colored('[ FAIL ]', 'red'), "\t", message, file=sys.stderr) else: print(message) def authenticate(dc): pyrax.set_setting("identity_type", "rackspace") log("INFO", "Authenticating") try: pyrax.set_credential_file(config_file, region=dc) except pexc.AuthenticationFailed: log('ERROR', 'Authentication Failure') log('OK', 'Authentication Successful') def get_config(group): config = ConfigParser.ConfigParser() config.read(config_file) if config.has_section(group): return config else: raise Exception('Unknown config section') def get_machine_uuid(): name = subprocess.Popen(['xenstore-read name'], shell=True, stdout=subprocess.PIPE).communicate()[0] id = name.strip() return id[9:]
from __future__ import print_function import os, pyrax, sys import pyrax.exceptions as pexc from termcolor import colored import ConfigParser from subprocess import check_output path = os.path.dirname(os.path.realpath(__file__)) config_file = path + "/config.ini" def log(level, message): if level == 'OK': print(colored('[ OK ]', 'green'), "\t", message, file=sys.stderr) elif level == 'INFO': print(colored('[ INFO ]', 'blue'), "\t", message, file=sys.stderr) elif level == 'ERROR': print(colored('[ FAIL ]', 'red'), "\t", message, file=sys.stderr) else: print(message) def authenticate(dc): pyrax.set_setting("identity_type", "rackspace") log("INFO", "Authenticating") try: pyrax.set_credential_file(config_file, region=dc) except pexc.AuthenticationFailed: log('ERROR', 'Authentication Failure') log('OK', 'Authentication Successful') def get_config(group): config = ConfigParser.ConfigParser() config.read(config_file) if config.has_section(group): return config else: raise Exception('Unknown config section') def get_machine_uuid(): name = check_output('xenstore-read name', shell=True) id = name.strip() return id[9:]
Update test to avoid pipeline fail
# -*- coding: utf-8 -*- import os from scout.demo import cnv_report_path from scout.commands import cli def test_load_cnv_report(mock_app, case_obj): """Testing the load delivery report cli command""" # Make sure the path to delivery report is a valid path assert os.path.isfile(cnv_report_path) runner = mock_app.test_cli_runner() assert runner # Test CLI function result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"],) assert "saved report to case!" in result.output assert result.exit_code == 0 def test_invalid_path_load_cnv_report(mock_app, case_obj): """Testing the load delivery report cli command""" runner = mock_app.test_cli_runner() assert runner # Test CLI function result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], "invalid-path", "-u"],) assert "Path 'invalid-path' does not exist." in result.output assert result.exit_code == 2
# -*- coding: utf-8 -*- import os from scout.demo import cnv_report_path from scout.commands import cli def test_load_cnv_report(mock_app, case_obj): """Testing the load delivery report cli command""" # Make sure the path to delivery report is a valid path assert os.path.isfile(cnv_report_path) runner = mock_app.test_cli_runner() assert runner # Test CLI function result = runner.invoke( cli, ["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"], ) assert "saved report to case!" in result.output assert result.exit_code == 0 def test_invalid_path_load_cnv_report(mock_app, case_obj): """Testing the load delivery report cli command""" runner = mock_app.test_cli_runner() assert runner # Test CLI function result = runner.invoke( cli, ["load", "cnv-report", case_obj["_id"], "invalid-path", "-u"], ) assert 'Path "invalid-path" does not exist.' in result.output assert result.exit_code == 2
Add warning for mismatched image size and scale
import data import argparse from model import EDSR parser = argparse.ArgumentParser() parser.add_argument("--dataset",default="data/General-100") parser.add_argument("--imgsize",default=100,type=int) parser.add_argument("--scale",default=2,type=int) parser.add_argument("--layers",default=32,type=int) parser.add_argument("--featuresize",default=256,type=int) parser.add_argument("--batchsize",default=10,type=int) parser.add_argument("--savedir",default='saved_models') parser.add_argument("--iterations",default=1000,type=int) args = parser.parse_args() data.load_dataset(args.dataset,args.imgsize) if args.imgsize % args.scale != 0: print(f"Image size {args.imgsize} is not evenly divisible by scale {arg.scale}") return down_size = args.imgsize//args.scale network = EDSR(down_size,args.layers,args.featuresize,args.scale) network.set_data_fn(data.get_batch,(args.batchsize,args.imgsize,down_size),data.get_test_set,(args.imgsize,down_size)) network.train(args.iterations,args.savedir)
import data import argparse from model import EDSR parser = argparse.ArgumentParser() parser.add_argument("--dataset",default="data/General-100") parser.add_argument("--imgsize",default=100,type=int) parser.add_argument("--scale",default=2,type=int) parser.add_argument("--layers",default=32,type=int) parser.add_argument("--featuresize",default=256,type=int) parser.add_argument("--batchsize",default=10,type=int) parser.add_argument("--savedir",default='saved_models') parser.add_argument("--iterations",default=1000,type=int) args = parser.parse_args() data.load_dataset(args.dataset,args.imgsize) down_size = args.imgsize//args.scale network = EDSR(down_size,args.layers,args.featuresize,args.scale) network.set_data_fn(data.get_batch,(args.batchsize,args.imgsize,down_size),data.get_test_set,(args.imgsize,down_size)) network.train(args.iterations,args.savedir)
Fix slot name in HardwareDevice
""" Module with the HardwareDevice model. """ from launch_control.utils.json import PlainOldData class HardwareDevice(PlainOldData): """ Model representing any HardwareDevice A device is just a "device_type" attribute with a bag of properties and a human readable description. Individual device types can be freely added. For simplicity some common types of devices are provided as class properties DEVICE_xxx. Instances will come from a variety of factory classes, each capable of enumerating devices that it understands. The upside of having a common class like this is that it's easier to store it in the database _and_ not have to agree on a common set of properties for, say, all CPUs. If you want you can create instances manually, like this: >>> cpu = HardwareDevice(HardwareDevice.DEVICE_CPU, ... u"800MHz OMAP3 Processor") >>> cpu.attributes[u'machine'] = u'arm' >>> cpu.attributes[u'mhz'] = '800' >>> cpu.attributes[u'vendor'] = u'Texas Instruments' """ DEVICE_CPU = "device.cpu" DEVICE_MEM = "device.mem" DEVICE_USB = "device.usb" DEVICE_PCI = "device.pci" DEVICE_BOARD = "device.board" __slots__ = ('device_type', 'description', 'attributes') def __init__(self, device_type, description, attributes=None): self.device_type = device_type self.description = description self.attributes = attributes or {}
""" Module with the HardwareDevice model. """ from launch_control.utils.json import PlainOldData class HardwareDevice(PlainOldData): """ Model representing any HardwareDevice A device is just a "device_type" attribute with a bag of properties and a human readable description. Individual device types can be freely added. For simplicity some common types of devices are provided as class properties DEVICE_xxx. Instances will come from a variety of factory classes, each capable of enumerating devices that it understands. The upside of having a common class like this is that it's easier to store it in the database _and_ not have to agree on a common set of properties for, say, all CPUs. If you want you can create instances manually, like this: >>> cpu = HardwareDevice(HardwareDevice.DEVICE_CPU, ... u"800MHz OMAP3 Processor") >>> cpu.attributes[u'machine'] = u'arm' >>> cpu.attributes[u'mhz'] = '800' >>> cpu.attributes[u'vendor'] = u'Texas Instruments' """ DEVICE_CPU = "device.cpu" DEVICE_MEM = "device.mem" DEVICE_USB = "device.usb" DEVICE_PCI = "device.pci" DEVICE_BOARD = "device.board" __slots__ = ('device_type', 'desc', 'attributes') def __init__(self, device_type, description, attributes=None): self.device_type = device_type self.description = description self.attributes = attributes or {}
Make clear we need Python 3.6
from setuptools import setup, find_packages # First update the version in loompy/_version.py, then: # cd loompy (the root loompy folder, not the one inside!) # rm -r dist (otherwise twine will upload the oldest build!) # python setup.py sdist # twine upload dist/* # NOTE: Don't forget to update the release version at loompy.github.io (index.html)! # pylint: disable=exec-used __version__ = '0.0.0' exec(open('loompy/_version.py').read()) setup( name="loompy", version=__version__, packages=find_packages(), install_requires=['h5py', 'numpy', 'scipy', "typing", "setuptools"], python_requires='>=3.6', # metadata for upload to PyPI author="Linnarsson Lab", author_email="sten.linnarsson@ki.se", description="Work with .loom files for single-cell RNA-seq data", license="BSD", keywords="loom omics transcriptomics bioinformatics", url="https://github.com/linnarsson-lab/loompy", download_url=f"https://github.com/linnarsson-lab/loompy/archive/{__version__}.tar.gz", )
from setuptools import setup, find_packages # First update the version in loompy/_version.py, then: # cd loompy (the root loompy folder, not the one inside!) # rm -r dist (otherwise twine will upload the oldest build!) # python setup.py sdist # twine upload dist/* # NOTE: Don't forget to update the release version at loompy.github.io (index.html)! # pylint: disable=exec-used __version__ = '0.0.0' exec(open('loompy/_version.py').read()) setup( name="loompy", version=__version__, packages=find_packages(), install_requires=['h5py', 'numpy', 'scipy', "typing", "setuptools"], # metadata for upload to PyPI author="Linnarsson Lab", author_email="sten.linnarsson@ki.se", description="Work with .loom files for single-cell RNA-seq data", license="BSD", keywords="loom omics transcriptomics bioinformatics", url="https://github.com/linnarsson-lab/loompy", download_url=f"https://github.com/linnarsson-lab/loompy/archive/{__version__}.tar.gz", )
Check source type when raising an unrecognized source exception
<?php namespace Plank\Mediable\Exceptions\MediaUpload; use Plank\Mediable\Exceptions\MediaUploadException; class ConfigurationException extends MediaUploadException { public static function cannotSetAdapter($class) { return new static("Could not set adapter of class `{$class}`. Must implement `\Plank\Mediable\SourceAdapters\SourceAdapterInterface`."); } public static function cannotSetModel($class) { return new static("Could not set `{$class}` as Media model class. Must extend `\Plank\Mediable\Media`."); } public static function noSourceProvided() { return new static('No source provided for upload.'); } public static function unrecognizedSource($source) { if (is_object($source)) { $source = get_class($source); } elseif (is_resource($source)) { $source = get_resource_type($source); } else { $source = (string) $source; } return new static("Could not recognize source, `{$source}` provided."); } public static function diskNotFound($disk) { return new static("Cannot find disk named `{$disk}`."); } }
<?php namespace Plank\Mediable\Exceptions\MediaUpload; use Plank\Mediable\Exceptions\MediaUploadException; class ConfigurationException extends MediaUploadException { public static function cannotSetAdapter($class) { return new static("Could not set adapter of class `{$class}`. Must implement `\Plank\Mediable\SourceAdapters\SourceAdapterInterface`."); } public static function cannotSetModel($class) { return new static("Could not set `{$class}` as Media model class. Must extend `\Plank\Mediable\Media`."); } public static function noSourceProvided() { return new static('No source provided for upload.'); } public static function unrecognizedSource($source) { $source = is_object($source) ? get_class($source) : (string) $source; return new static("Could not recognize source, `{$source}` provided."); } public static function diskNotFound($disk) { return new static("Cannot find disk named `{$disk}`."); } }
Fix failing test after affy update
/* * The gemma-core project * * Copyright (c) 2018 University of British Columbia * * 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 ubic.gemma.core.loader.expression; import static org.junit.Assert.*; import java.util.Map; import org.junit.Test; /** * * * @author paul */ public class AffyPowerToolsProbesetSummarizeTest { @Test public void testLoadMPSNames() { AffyPowerToolsProbesetSummarize t = new AffyPowerToolsProbesetSummarize(); Map<String, Map<String, String>> mpsnames = t.loadMpsNames(); assertEquals( "MoGene-2_1-st.mps", mpsnames.get( "GPL17400" ).get( "mps" ) ); assertEquals( "RaEx-1_0-st-v1.r2.pgf", mpsnames.get( "GPL6247" ).get( "pgf" ) ); } }
/* * The gemma-core project * * Copyright (c) 2018 University of British Columbia * * 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 ubic.gemma.core.loader.expression; import static org.junit.Assert.*; import java.util.Map; import org.junit.Test; /** * * * @author paul */ public class AffyPowerToolsProbesetSummarizeTest { @Test public void testLoadMPSNames() { AffyPowerToolsProbesetSummarize t = new AffyPowerToolsProbesetSummarize(); Map<String, Map<String, String>> mpsnames = t.loadMpsNames(); assertEquals( "MoGene-2_1-st.mps", mpsnames.get( "GPL17400" ).get( "mps" ) ); assertEquals( "RaGene-1_0-st-v1.r4.pgf", mpsnames.get( "GPL6247" ).get( "pgf" ) ); } }
Change sleep timing of gui robot for command box handle which caused some test cases to fail
package guitests.guihandles; import guitests.GuiRobot; import javafx.stage.Stage; /** * A handle to the Command Box in the GUI. */ public class CommandBoxHandle extends GuiHandle{ private static final String COMMAND_INPUT_FIELD_ID = "#commandTextField"; public CommandBoxHandle(GuiRobot guiRobot, Stage primaryStage, String stageTitle) { super(guiRobot, primaryStage, stageTitle); } public void enterCommand(String command) { setTextField(COMMAND_INPUT_FIELD_ID, command); } public String getCommandInput() { return getTextFieldText(COMMAND_INPUT_FIELD_ID); } /** * Enters the given command in the Command Box and presses enter. */ public void runCommand(String command) { enterCommand(command); pressEnter(); guiRobot.sleep(10); if (command.equals("clear")) // any commands that has an alert dialog that pops out pressEnter(); guiRobot.sleep(100); //Give time for the command to take effect } public HelpWindowHandle runHelpCommand() { enterCommand("help"); pressEnter(); return new HelpWindowHandle(guiRobot, primaryStage); } }
package guitests.guihandles; import guitests.GuiRobot; import javafx.stage.Stage; /** * A handle to the Command Box in the GUI. */ public class CommandBoxHandle extends GuiHandle{ private static final String COMMAND_INPUT_FIELD_ID = "#commandTextField"; public CommandBoxHandle(GuiRobot guiRobot, Stage primaryStage, String stageTitle) { super(guiRobot, primaryStage, stageTitle); } public void enterCommand(String command) { setTextField(COMMAND_INPUT_FIELD_ID, command); } public String getCommandInput() { return getTextFieldText(COMMAND_INPUT_FIELD_ID); } /** * Enters the given command in the Command Box and presses enter. */ public void runCommand(String command) { enterCommand(command); pressEnter(); guiRobot.sleep(10); if (command.equals("clear")) // any commands that has an alert dialog that pops out pressEnter(); guiRobot.sleep(700); //Give time for the command to take effect } public HelpWindowHandle runHelpCommand() { enterCommand("help"); pressEnter(); return new HelpWindowHandle(guiRobot, primaryStage); } }
Refactor Transaction to allow for async
//= require ./core //= require_self (function () { "use strict"; Marbles.Transaction = { transaction: function (operationFn) { var tmp = Object.create(this); var eventQueue = []; tmp.trigger = function () { eventQueue.push(arguments); }; var shouldAbort = false; tmp.abortTransaction = function () { shouldAbort = true; }; tmp.finalizeTransaction = function () { if (shouldAbort) { return; } delete tmp.trigger; delete tmp.abortTransaction; delete tmp.finalizeTransaction; for (var k in tmp) { if (tmp.hasOwnProperty(k)) { this[k] = tmp[k]; } } var args; for (var i = 0, len = eventQueue.length; i < len; i++) { args = eventQueue.shift(); this.trigger.apply(this, args); } }.bind(this); if (arguments.length > 0) { operationFn.call(tmp, tmp); tmp.finalizeTransaction(); } else { return tmp; } }, abortTransaction: function () { throw new Error("Must be inside a transaction to abort one."); }, finalizeTransaction: function () { throw new Error("Must be inside a transaction to finalize one."); } }; })();
//= require ./core //= require_self (function () { "use strict"; Marbles.Transaction = { transaction: function (operationFn) { var tmp = Object.create(this); var eventQueue = []; tmp.trigger = function () { eventQueue.push(arguments); }; var shouldAbort = false; tmp.abortTransaction = function () { shouldAbort = true; }; operationFn.call(tmp, tmp); if (shouldAbort) { return; } delete tmp.trigger; delete tmp.abortTransaction; for (var k in tmp) { if (tmp.hasOwnProperty(k)) { this[k] = tmp[k]; } } var args; for (var i = 0, len = eventQueue.length; i < len; i++) { args = eventQueue.shift(); this.trigger.apply(this, args); } }, abortTransaction: function () { throw new Error("Must be inside a transaction to abort one."); } }; })();
Disable warning for unused feature
# -*- coding: utf-8 -*- import os import unittest from flask import Flask from coaster.utils import buid from coaster.sqlalchemy import BaseMixin from nodular.db import db class User(BaseMixin, db.Model): __tablename__ = 'user' userid = db.Column(db.Unicode(22), nullable=False, default=buid, unique=True) username = db.Column(db.Unicode(250), nullable=True) app = Flask(__name__, instance_relative_config=True) app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'postgresql://postgres@localhost/myapp_test') app.config['SQLALCHEMY_ECHO'] = False app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) db.app = app class TestDatabaseFixture(unittest.TestCase): def setUp(self): self.app = app db.create_all() self.user1 = User(username=u'user1') db.session.add(self.user1) app.testing = True def tearDown(self): db.session.rollback() db.drop_all() db.session.remove()
# -*- coding: utf-8 -*- import os import unittest from flask import Flask from coaster.utils import buid from coaster.sqlalchemy import BaseMixin from nodular.db import db class User(BaseMixin, db.Model): __tablename__ = 'user' userid = db.Column(db.Unicode(22), nullable=False, default=buid, unique=True) username = db.Column(db.Unicode(250), nullable=True) app = Flask(__name__, instance_relative_config=True) app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'postgresql://postgres@localhost/myapp_test') app.config['SQLALCHEMY_ECHO'] = False db.init_app(app) db.app = app class TestDatabaseFixture(unittest.TestCase): def setUp(self): self.app = app db.create_all() self.user1 = User(username=u'user1') db.session.add(self.user1) app.testing = True def tearDown(self): db.session.rollback() db.drop_all() db.session.remove()
Revert "support unwrapping of basic types" This reverts commit 86a5a1c8
from django.utils.translation import gettext as _ from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize from corehq.apps.case_search.exceptions import ( CaseFilterError, XPathFunctionException, ) from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS def unwrap_value(value, context): """Returns the value of the node if it is wrapped in a function, otherwise just returns the node """ if isinstance(value, UnaryExpression) and value.op == '-': return -1 * value.right if not isinstance(value, FunctionCall): return value try: return XPATH_VALUE_FUNCTIONS[value.name](value, context) except KeyError: raise CaseFilterError( _("We don't know what to do with the function \"{}\". Accepted functions are: {}").format( value.name, ", ".join(list(XPATH_VALUE_FUNCTIONS.keys())), ), serialize(value) ) except XPathFunctionException as e: raise CaseFilterError(str(e), serialize(value))
from django.utils.translation import gettext as _ from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize from corehq.apps.case_search.exceptions import ( CaseFilterError, XPathFunctionException, ) from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS def unwrap_value(value, context): """Returns the value of the node if it is wrapped in a function, otherwise just returns the node """ if isinstance(value, (str, int, float, bool)): return value if isinstance(value, UnaryExpression) and value.op == '-': return -1 * value.right if not isinstance(value, FunctionCall): return value try: return XPATH_VALUE_FUNCTIONS[value.name](value, context) except KeyError: raise CaseFilterError( _("We don't know what to do with the function \"{}\". Accepted functions are: {}").format( value.name, ", ".join(list(XPATH_VALUE_FUNCTIONS.keys())), ), serialize(value) ) except XPathFunctionException as e: raise CaseFilterError(str(e), serialize(value))
Add newline char to avoid mix of logs Add a '\n' after "unpacking xxx..." to avoid mix of logs such as: ``` unpacking sha256:a7776895af32e34b1fef997e26c79fa988b40c5cf2a3fb48dc22e0584b648d82...DEBU[0005] Extraction not needed, layer snapshot exists DEBU[0005] Extraction not needed, layer snapshot exists DEBU[0005] Extraction not needed, layer snapshot exists DEBU[0005] Extraction not needed, layer snapshot exists DEBU[0005] Extraction not needed, layer snapshot exists DEBU[0005] Extraction not needed, layer snapshot exists done ``` After this commit: ``` unpacking sha256:a7776895af32e34b1fef997e26c79fa988b40c5cf2a3fb48dc22e0584b648d82... DEBU[0008] Extraction not needed, layer snapshot exists DEBU[0008] Extraction not needed, layer snapshot exists DEBU[0008] Extraction not needed, layer snapshot exists DEBU[0008] Extraction not needed, layer snapshot exists DEBU[0008] Extraction not needed, layer snapshot exists DEBU[0008] Extraction not needed, layer snapshot exists done ``` Signed-off-by: Zhang Wei <14976e959b2860fb06a3c1edbdb1945a4e11b8b5@huawei.com>
package main import ( "fmt" "github.com/containerd/containerd/log" "github.com/urfave/cli" ) var pullCommand = cli.Command{ Name: "pull", Usage: "pull an image from a remote", ArgsUsage: "[flags] <ref>", Description: `Fetch and prepare an image for use in containerd. After pulling an image, it should be ready to use the same reference in a run command. As part of this process, we do the following: 1. Fetch all resources into containerd. 2. Prepare the snapshot filesystem with the pulled resources. 3. Register metadata for the image. `, Flags: append(registryFlags, snapshotterFlags...), Action: func(clicontext *cli.Context) error { var ( ref = clicontext.Args().First() ) ctx, cancel := appContext(clicontext) defer cancel() img, err := fetch(ctx, ref, clicontext) if err != nil { return err } log.G(ctx).WithField("image", ref).Debug("unpacking") // TODO: Show unpack status fmt.Printf("unpacking %s...\n", img.Target().Digest) err = img.Unpack(ctx, clicontext.String("snapshotter")) fmt.Println("done") return err }, }
package main import ( "fmt" "github.com/containerd/containerd/log" "github.com/urfave/cli" ) var pullCommand = cli.Command{ Name: "pull", Usage: "pull an image from a remote", ArgsUsage: "[flags] <ref>", Description: `Fetch and prepare an image for use in containerd. After pulling an image, it should be ready to use the same reference in a run command. As part of this process, we do the following: 1. Fetch all resources into containerd. 2. Prepare the snapshot filesystem with the pulled resources. 3. Register metadata for the image. `, Flags: append(registryFlags, snapshotterFlags...), Action: func(clicontext *cli.Context) error { var ( ref = clicontext.Args().First() ) ctx, cancel := appContext(clicontext) defer cancel() img, err := fetch(ctx, ref, clicontext) if err != nil { return err } log.G(ctx).WithField("image", ref).Debug("unpacking") // TODO: Show unpack status fmt.Printf("unpacking %s...", img.Target().Digest) err = img.Unpack(ctx, clicontext.String("snapshotter")) fmt.Println("done") return err }, }
Switch execFile out for spawn and flatten args in tests
/* * Copyright 2017 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import path from 'path' import test from 'tape' import { spawnSync } from 'child_process' import suiteName from './utils/suite' import gitDescribe from '../lib/git-describe' const suite = suiteName(__filename) const repoDir = path.join(__dirname, 'test-repo') test(`${suite} Fail if the given path is not a git repo`, (t) => { t.throws(function () { gitDescribe(repoDir) }, new RegExp(/fatal: Not a git repository:/)) t.end() }) test(`${suite} Return the sha of the parent repo if not given a path`, (t) => { const parentSha = spawnSync('git', ['describe', '--long', '--always']) const sha = gitDescribe() t.equal(parentSha.stdout.toString('utf-8').trim(), sha) t.end() })
/* * Copyright 2017 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import path from 'path' import test from 'tape' import { execFileSync } from 'child_process' import suiteName from './utils/suite' import gitDescribe from '../lib/git-describe' const suite = suiteName(__filename) const repoDir = path.join(__dirname, 'test-repo') test(`${suite} Fail if the given path is not a git repo`, (t) => { t.throws(function () { gitDescribe(repoDir) }, new RegExp(/fatal: Not a git repository:/)) t.end() }) test(`${suite} Return the sha of the parent repo if not given a path`, (t) => { const execArgs = [ 'describe', '--long', '--always' ] const parentSha = execFileSync('git', execArgs) const sha = gitDescribe() t.equal(parentSha.toString('utf-8').trim(), sha) t.end() })
Support direct wiki string passed to calli.parseCreole
// parse-creole.js /* * Copyright (c) 2014 3 Round Stones Inc., Some 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. * */ (function($){ var parser = new creole(); var calli = window.calli || (window.calli={}); calli.parseCreole = function(element) { var pre = element && typeof element == 'object' ? element : this; var textContent = pre && pre.textContent || pre && pre.innerText; var text = typeof element == 'string' ? element : textContent; var div = document.createElement('div'); if (text && typeof text == 'string') { parser.parse(div, text); if (pre != text) { var attrs = pre.attributes; for(var j=attrs.length-1; j>=0; j--) { div.setAttribute(attrs[j].name, attrs[j].value); } div.setAttribute("content", text); } } return div; }; })(window.jQuery);
// parse-creole.js /* * Copyright (c) 2014 3 Round Stones Inc., Some 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. * */ (function($){ var parser = new creole(); var calli = window.calli || (window.calli={}); calli.parseCreole = function(element) { var pre = element && typeof element == 'object' ? element : this; var text = pre && pre.textContent || pre && pre.innerText || pre; var div = document.createElement('div'); if (text && typeof text == 'string') { parser.parse(div, text); if (pre != text) { var attrs = pre.attributes; for(var j=attrs.length-1; j>=0; j--) { div.setAttribute(attrs[j].name, attrs[j].value); } div.setAttribute("content", text); } } return div; }; })(window.jQuery);
Refactor producer behavior to include close.
/* * Copyright (c) 2007-2014, Kaazing Corporation. All rights reserved. */ package org.kaazing.qpid.amqp_1_0.jms; import static javax.jms.Session.AUTO_ACKNOWLEDGE; import org.apache.qpid.amqp_1_0.jms.Connection; import org.apache.qpid.amqp_1_0.jms.ConnectionFactory; import org.apache.qpid.amqp_1_0.jms.MessageProducer; import org.apache.qpid.amqp_1_0.jms.Session; import org.apache.qpid.amqp_1_0.jms.impl.ConnectionFactoryImpl; import org.junit.Rule; import org.junit.Test; import org.kaazing.robot.junit.annotation.Robotic; import org.kaazing.robot.junit.rules.RobotRule; public class TopicProducerIT { @Rule public RobotRule robot = new RobotRule().setScriptRoot("org/kaazing/robot/scripts/amqp_1_0/jms/topic/producer"); @Robotic(script = "create.then.close") @Test(timeout = 1000) public void shouldCreateProducer() throws Exception { ConnectionFactory factory = new ConnectionFactoryImpl("localhost", 5672, null, null, "clientID"); Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(session.createTopic("topic://topic-A")); producer.close(); session.close(); connection.close(); robot.join(); } }
/* * Copyright (c) 2007-2014, Kaazing Corporation. All rights reserved. */ package org.kaazing.qpid.amqp_1_0.jms; import static javax.jms.Session.AUTO_ACKNOWLEDGE; import org.apache.qpid.amqp_1_0.jms.Connection; import org.apache.qpid.amqp_1_0.jms.ConnectionFactory; import org.apache.qpid.amqp_1_0.jms.Session; import org.apache.qpid.amqp_1_0.jms.impl.ConnectionFactoryImpl; import org.junit.Rule; import org.junit.Test; import org.kaazing.robot.junit.annotation.Robotic; import org.kaazing.robot.junit.rules.RobotRule; public class TopicProducerIT { @Rule public RobotRule robot = new RobotRule().setScriptRoot("org/kaazing/robot/scripts/amqp_1_0/jms/topic/producer"); @Robotic(script = "create") @Test(timeout = 1000) public void shouldCreateProducer() throws Exception { ConnectionFactory factory = new ConnectionFactoryImpl("localhost", 5672, null, null, "clientID"); Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, AUTO_ACKNOWLEDGE); session.createProducer(session.createTopic("topic-A")); robot.join(); } }
Add back the "crashed" icon when an AI stopped responding
/** @jsx React.DOM */ var React = require("react"); var GameModel = require("../../GameModel"); var HeroStats = React.createClass({ propTypes: { game: React.PropTypes.instanceOf(GameModel).isRequired, hero: React.PropTypes.object.isRequired }, render: function(){ var hero = this.props.hero; var first = this.props.game.getWinner() === hero.id; var cls = ["hero-stats"]; if (first) cls.push(first); if (hero.crashed) cls.push("crashed"); return <div className={cls.join(" ")}> <img className="cross" src="/assets/img/ui/cross.png" /> <img className="player" src={"/assets/img/ui/player"+hero.id+".png"} /> <img className="award" src="/assets/img/ui/award.png" /> <div className="gold-wrapper"> <span className="gold">{hero.gold}</span> <img src="/assets/img/ui/coin.png" className="coin" /> </div> <a href={"/ai/"+hero.userId}> <span className="name" title={hero.name}>{hero.name}</span> </a> Elo: <span className="elo">{hero.elo}</span> </div>; } }); module.exports = HeroStats;
/** @jsx React.DOM */ var React = require("react"); var GameModel = require("../../GameModel"); var HeroStats = React.createClass({ propTypes: { game: React.PropTypes.instanceOf(GameModel).isRequired, hero: React.PropTypes.object.isRequired }, render: function(){ var hero = this.props.hero; var first = this.props.game.getWinner() === hero.id; return <div className={"hero-stats "+(first ? "first": "")}> <img className="cross" src="/assets/img/ui/cross.png" /> <img className="player" src={"/assets/img/ui/player"+hero.id+".png"} /> <img className="award" src="/assets/img/ui/award.png" /> <div className="gold-wrapper"> <span className="gold">{hero.gold}</span> <img src="/assets/img/ui/coin.png" className="coin" /> </div> <a href={"/ai/"+hero.userId}> <span className="name" title={hero.name}>{hero.name}</span> </a> Elo: <span className="elo">{hero.elo}</span> </div>; } }); module.exports = HeroStats;
Use normal without extra libs
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Generate hastag from a webpage</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> </head> <body> <div class="container-fluid"> <h1>Generate hastag from a webpage</h1> <form class="form-inline" action="<?php echo "http://$_SERVER[HTTP_HOST]/index.php/Hashtags/generate_tags";?>" method="POST"> <div class="form-group"> <input type="text" class="form-control" name="url" placeholder="Enter the site url here" required> </div> <button type="submit" class="btn btn-primary">Go!</button> </form> </div> </body> </html>
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Generate hastag from a webpage</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> </head> <body> <div class="container-fluid"> <h1>Generate hastag from a webpage</h1> <?php $this->load->helper('form'); echo form_open("/Hashtags/generate_tags",array) ?> <form class="form-inline" action="<?php echo "http://$_SERVER[HTTP_HOST]/index.php/Hashtags/generate_tags"?> method="POST"> <div class="form-group"> <input type="text" class="form-control" name="url" placeholder="Enter the site url here" required> </div> <button type="submit" class="btn btn-primary">Go!</button> </form> </div> </body> </html>
Remove options argument to setupFreedom.
Components.utils.import("resource://gre/modules/devtools/Console.jsm"); Components.utils.import("resource://gre/modules/Timer.jsm"); // This module does not support all of es6 promise functionality. // Components.utils.import("resource://gre/modules/Promise.jsm"); const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1", "nsIXMLHttpRequest"); Components.utils.importGlobalProperties(['URL']); var freedom; function setupFreedom(manifest) { if (this.freedom) { return this.freedom; } var lastSlash = manifest.lastIndexOf("/"); var manifestLocation = manifest.substring(0, lastSlash + 1); //var manifestFilename = manifest.substring(lastSlash + 1); firefox_config = { isApp: false, manifest: manifest, portType: 'Worker', stayLocal: true, location: manifestLocation };
Components.utils.import("resource://gre/modules/devtools/Console.jsm"); Components.utils.import("resource://gre/modules/Timer.jsm"); // This module does not support all of es6 promise functionality. // Components.utils.import("resource://gre/modules/Promise.jsm"); const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1", "nsIXMLHttpRequest"); Components.utils.importGlobalProperties(['URL']); var freedom; function setupFreedom(options, manifest) { if (this.freedom) { return this.freedom; } var lastSlash = manifest.lastIndexOf("/"); var manifestLocation = manifest.substring(0, lastSlash + 1); //var manifestFilename = manifest.substring(lastSlash + 1); firefox_config = { isApp: false, manifest: manifest, portType: 'Worker', stayLocal: true, location: manifestLocation };
Drop xflux binary from debian package
#!/usr/bin/env python from distutils.core import setup data_files=[('share/icons/hicolor/scalable/apps', ['fluxgui.svg', 'fluxgui-light.svg', 'fluxgui-dark.svg']), ('share/applications', ['desktop/fluxgui.desktop'])] import os if os.path.exists("xflux"): data_files.append( ('bin', ['xflux']) ) setup(name = "f.lux indicator applet", version = "1.1.8", description = "f.lux indicator applet - better lighting for your computer", author = "Kilian Valkhof, Michael and Lorna Herf, Josh Winters", author_email = "kilian@kilianvalkhof.com", url = "http://www.stereopsis.com/flux/", license = "MIT license", package_dir = {'fluxgui' : 'src/fluxgui'}, packages = ["fluxgui",], package_data = {"fluxgui" : ["*.glade"] }, data_files = data_files, scripts = ["fluxgui"], long_description = """f.lux indicator applet is an indicator applet to control xflux, an application that makes the color of your computer's display adapt to the time of day, warm at nights and like sunlight during the day""", )
#!/usr/bin/env python from distutils.core import setup setup(name = "f.lux indicator applet", version = "1.1.8", description = "f.lux indicator applet - better lighting for your computer", author = "Kilian Valkhof, Michael and Lorna Herf, Josh Winters", author_email = "kilian@kilianvalkhof.com", url = "http://www.stereopsis.com/flux/", license = "MIT license", package_dir = {'fluxgui' : 'src/fluxgui'}, packages = ["fluxgui",], package_data = {"fluxgui" : ["*.glade"] }, data_files=[('share/icons/hicolor/scalable/apps', ['fluxgui.svg', 'fluxgui-light.svg', 'fluxgui-dark.svg']), ('share/applications', ['desktop/fluxgui.desktop']), ('bin', ['xflux']),], scripts = ["fluxgui"], long_description = """f.lux indicator applet is an indicator applet to control xflux, an application that makes the color of your computer's display adapt to the time of day, warm at nights and like sunlight during the day""", )
refactor: Use global API_URL and HEADERS See also: PSOBAT-1197
"""Check Taskid status.""" import logging import requests from tryagain import retries from ..consts import API_URL, HEADERS from ..exceptions import SpinnakerTaskError LOG = logging.getLogger(__name__) @retries(max_attempts=10, wait=10, exceptions=(AssertionError, ValueError)) def check_task(taskid, app_name): """Check task status. Args: taskid: the task id returned from create_elb. app_name: application name related to this task. Returns: polls for task status. """ try: taskurl = taskid.get('ref', '0000') except AttributeError: taskurl = taskid taskid = taskurl.split('/tasks/')[-1] LOG.info('Checking taskid %s', taskid) url = '{0}/applications/{1}/tasks/{2}'.format(API_URL, app_name, taskid) task_response = requests.get(url, headers=HEADERS) LOG.debug(task_response.json()) assert task_response.ok task_state = task_response.json() status = task_state['status'] LOG.info('Current task status: %s', status) if status == 'SUCCEEDED': return status elif status == 'TERMINAL': raise SpinnakerTaskError(task_state) else: raise ValueError
"""Check Taskid status.""" import logging import requests from tryagain import retries from ..exceptions import SpinnakerTaskError HEADERS = {'Content-Type': 'application/json', 'Accept': '*/*'} GATE_URL = "http://gate-api.build.example.com:8084" LOG = logging.getLogger(__name__) @retries(max_attempts=10, wait=10, exceptions=(AssertionError, ValueError)) def check_task(taskid, app_name): """Check task status. Args: taskid: the task id returned from create_elb. app_name: application name related to this task. Returns: polls for task status. """ try: taskurl = taskid.get('ref', '0000') except AttributeError: taskurl = taskid taskid = taskurl.split('/tasks/')[-1] LOG.info('Checking taskid %s', taskid) url = '{0}/applications/{1}/tasks/{2}'.format(GATE_URL, app_name, taskid) task_response = requests.get(url, headers=HEADERS) LOG.debug(task_response.json()) assert task_response.ok task_state = task_response.json() status = task_state['status'] LOG.info('Current task status: %s', status) if status == 'SUCCEEDED': return status elif status == 'TERMINAL': raise SpinnakerTaskError(task_state) else: raise ValueError
Fix project group creation error
app.controller('createprojgrpCtrl',['$scope','$location','$routeSegment','$http', '$timeout','$sessionStorage', function($scope,$location,$routeSegment,$http, $timeout,$sessionStorage) { $scope.sessionToken = $sessionStorage.sessionToken; if($sessionStorage.isLoggedIn){ $("#userDetails").html($sessionStorage.account.emailAddress); } Service.GetProjectList($http, //success function(data){$scope.projects =data; }, function(error) {}, $scope), $scope.submitForm = function() { Service.createProjectGroup($http,$scope, //success function(data){ $scope.successTextAlert = "Your request has been sent successfully."; $scope.showSuccessAlert = true; $scope.form.name=''; $scope.form.desc=''; }, //error function(){$scope.errorTextAlert = "Error, Something gone wrong."; $scope.showErrorAlert = true;}) }; // switch flag $scope.switchBool = function(value) { $scope[value] = !$scope[value]; }; }]);
app.controller('createprojgrpCtrl',['$scope','$location','$routeSegment','$http', '$timeout','$sessionStorage', function($scope,$location,$routeSegment,$http, $timeout,$sessionStorage) { $scope.sessionToken = $sessionStorage.sessionToken; if($sessionStorage.isLoggedIn){ $("#userDetails").html($sessionStorage.account.emailAddress); } Service.GetProjectList($http, //success function(data){$scope.projects =data; }), $scope.submitForm = function() { Service.createProjectGroup($http,$scope, //success function(data){ $scope.successTextAlert = "Your request has been sent successfully."; $scope.showSuccessAlert = true; $scope.form.name=''; $scope.form.desc=''; }, //error function(){$scope.errorTextAlert = "Error, Something gone wrong."; $scope.showErrorAlert = true;}) }; // switch flag $scope.switchBool = function(value) { $scope[value] = !$scope[value]; }; }]);
Break watch task into separate task
module.exports = function(grunt) { require('load-grunt-tasks')(grunt); // Add the grunt-mocha-test tasks. [ 'grunt-mocha-test', 'grunt-contrib-watch' ] .forEach( grunt.loadNpmTasks ); grunt.initConfig({ // Configure a mochaTest task mochaTest: { test: { options: { reporter: 'spec' }, src: ['test/**/*.js' ] }, }, watch: { options: { atBegin: true }, scripts: { files: [ 'src/**/*.js', 'test/**/*.js' ], tasks: ['eslint', 'mochaTest' ] } }, eslint: { target: ['src/**/*.js'] } }); grunt.registerTask( 'default', [ 'eslint' ]); grunt.registerTask( 'debug', [ 'watch' ]); };
module.exports = function(grunt) { require('load-grunt-tasks')(grunt); // Add the grunt-mocha-test tasks. [ 'grunt-mocha-test', 'grunt-contrib-watch' ] .forEach( grunt.loadNpmTasks ); grunt.initConfig({ // Configure a mochaTest task mochaTest: { test: { options: { reporter: 'spec' }, src: ['test/**/*.js' ] }, }, watch: { scripts: { files: [ 'src/**/*.js' , 'test/**/*.js' ], tasks: ['eslint', 'mochaTest' ] } }, eslint: { target: ['src/**/*.js'] } }); grunt.registerTask( 'default' , [ 'eslint' , 'mochaTest' , 'watch' ]); };
Fix mysql check to use checks.d version
import unittest import logging; logger = logging.getLogger() from checks.db.mysql import MySql from tests.common import load_check import time class TestMySql(unittest.TestCase): def testChecks(self): agentConfig = { 'mysql_server': 'localhost', 'mysql_user': "datadog", 'mysql_pass': "phQOrbaXem0kP8JHri1qSMRS", 'version': '0.1', 'api_key': 'toto' } # Initialize the check from checks.d c = load_check('mysql', {'init_config': {}, 'instances':{}},agentConfig) conf = c.parse_agent_config(agentConfig) self.check = load_check('mysql', conf, agentConfig) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 8, metrics) time.sleep(1) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 16, metrics) if __name__ == '__main__': unittest.main()
import unittest import logging; logger = logging.getLogger() from checks.db.mysql import MySql class TestMySql(unittest.TestCase): def setUp(self): # This should run on pre-2.7 python so no skiptest try: import MySQLdb self.mysql = MySql(logger) except ImportError: self.skip = True def testChecks(self): if not self.skip: results = self.mysql.check({"mysql_server": "localhost", "mysql_user": "dog", "mysql_pass": "dog"}) assert results if __name__ == '__main__': unittest.main()
Support webhooks for different branches
<?php require "syno-repo.php"; if(!empty($_REQUEST["payload"])){ $payload = json_decode(stripslashes($_REQUEST["payload"]), true); if(!empty($payload["ref"])){ $_REQUEST['branch'] = preg_replace('/^.*?([^\/]+)$/', '$1', $payload["ref"]); } } if(!empty($_REQUEST['branch'])){ $branch = $_REQUEST['branch']; } else { $beta_channel = isset($_REQUEST['package_update_channel']) && strtolower($_REQUEST['package_update_channel']) == 'beta'; $branch = ($beta_channel) ? 'develop' : 'master'; } // github token $github_token = "xxx"; // github repos $github_repos = array( array( 'user' => 'andreasgrill', 'repo' => 'vpnrouting', 'branch' => $branch, ) ); // file/dir modes $modes = array( 'dir' => 0777, 'file' => 0777); syno_repo($github_repos, $github_token, $modes); // file_put_contents("post.txt", var_export($_REQUEST, true). var_export($github_repos, true)); // chmod("post.txt", 0777); ?>
<?php require "syno-repo.php"; if(!empty($_REQUEST['branch'])){ $branch = $_REQUEST['branch']; } else { $beta_channel = isset($_REQUEST['package_update_channel']) && strtolower($_REQUEST['package_update_channel']) == 'beta'; $branch = ($beta_channel) ? 'develop' : 'master'; } // github token $github_token = "xxx"; // github repos $github_repos = array( array( 'user' => 'andreasgrill', 'repo' => 'vpnrouting', 'branch' => $branch, ) ); // file/dir modes $modes = array( 'dir' => 0777, 'file' => 0777); syno_repo($github_repos, $github_token, $modes); // file_put_contents("post.txt", var_export($_REQUEST, true). var_export($github_repos, true)); // chmod("post.txt", 0777); ?>
Remove my stupid admin/ redirect fix which doesnt work lol
<?php namespace Roots\Sage\Extras; use Roots\Sage\Setup; /** * Add <body> classes */ function body_class($classes) { // Add page slug if it doesn't exist if (is_single() || is_page() && !is_front_page()) { if (!in_array(basename(get_permalink()), $classes)) { $classes[] = basename(get_permalink()); } } // Add class if sidebar is active if (Setup\display_sidebar()) { $classes[] = 'sidebar-primary'; } return $classes; } add_filter('body_class', __NAMESPACE__ . '\\body_class'); /** * Clean up the_excerpt() */ function excerpt_more() { return ' &hellip; <a href="' . get_permalink() . '">' . __('Continued', 'sage') . '</a>'; } add_filter('excerpt_more', __NAMESPACE__ . '\\excerpt_more');
<?php namespace Roots\Sage\Extras; use Roots\Sage\Setup; /** * Add <body> classes */ function body_class($classes) { // Add page slug if it doesn't exist if (is_single() || is_page() && !is_front_page()) { if (!in_array(basename(get_permalink()), $classes)) { $classes[] = basename(get_permalink()); } } // Add class if sidebar is active if (Setup\display_sidebar()) { $classes[] = 'sidebar-primary'; } return $classes; } add_filter('body_class', __NAMESPACE__ . '\\body_class'); /** * Clean up the_excerpt() */ function excerpt_more() { return ' &hellip; <a href="' . get_permalink() . '">' . __('Continued', 'sage') . '</a>'; } add_filter('excerpt_more', __NAMESPACE__ . '\\excerpt_more'); /** * Prevent '/admin' from redirecting to '/careers/administrative-jobs/' */ function redirect_exceptions($redirect_url, $requested_url) { if(strpos($requested_url, 'admin') !== false) { $redirect_url = $requested_url; } return $redirect_url; } add_filter('redirect_canonical', __NAMESPACE__ . '\\redirect_exceptions');
Make the ViewHolder a static class
/* * The MIT License (MIT) * * Copyright (c) 2015 Mohammed Sazid-Al-Rashid * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mohammedsazid.android.launsz; import android.widget.ImageView; import android.widget.TextView; /** * Created by sazid on 7/14/2015. */ public static class AppsViewHolder { ImageView appIcon; TextView appLabel; // TextView appName; }
/* * The MIT License (MIT) * * Copyright (c) 2015 Mohammed Sazid-Al-Rashid * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mohammedsazid.android.launsz; import android.widget.ImageView; import android.widget.TextView; /** * Created by sazid on 7/14/2015. */ public class AppsViewHolder { ImageView appIcon; TextView appLabel; // TextView appName; }
Modify to avoid excessive logger initialization
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import from __future__ import unicode_literals import logbook import pytablewriter import simplesqlite logger = logbook.Logger("sqliteschema") logger.disable() def set_logger(is_enable): if is_enable != logger.disabled: return if is_enable: logger.enable() else: logger.disable() pytablewriter.set_logger(is_enable=is_enable) simplesqlite.set_logger(is_enable=is_enable) def set_log_level(log_level): """ Set logging level of this module. Using `logbook <http://logbook.readthedocs.io/en/stable/>`__ module for logging. :param int log_level: One of the log level of `logbook <http://logbook.readthedocs.io/en/stable/api/base.html>`__. Disabled logging if ``log_level`` is ``logbook.NOTSET``. """ if log_level == logger.level: return if log_level == logbook.NOTSET: set_logger(is_enable=False) else: set_logger(is_enable=True) logger.level = log_level pytablewriter.set_log_level(log_level) simplesqlite.set_log_level(log_level)
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import from __future__ import unicode_literals import logbook import pytablewriter import simplesqlite logger = logbook.Logger("sqliteschema") logger.disable() def set_logger(is_enable): pytablewriter.set_logger(is_enable=is_enable) simplesqlite.set_logger(is_enable=is_enable) if is_enable: logger.enable() else: logger.disable() def set_log_level(log_level): """ Set logging level of this module. Using `logbook <http://logbook.readthedocs.io/en/stable/>`__ module for logging. :param int log_level: One of the log level of `logbook <http://logbook.readthedocs.io/en/stable/api/base.html>`__. Disabled logging if ``log_level`` is ``logbook.NOTSET``. """ pytablewriter.set_log_level(log_level) simplesqlite.set_log_level(log_level) if log_level == logbook.NOTSET: set_logger(is_enable=False) else: set_logger(is_enable=True) logger.level = log_level
Change the exposed channel to receive-only
package beanstalk import "sync" // ConsumerPool maintains a pool of Consumer objects. type ConsumerPool struct { // The channel on which newly reserved jobs are offered. C <-chan *Job c chan *Job consumers []*Consumer sync.Mutex } // NewConsumerPool creates a pool of Consumer objects. func NewConsumerPool(sockets []string, tubes []string, options *Options) *ConsumerPool { c := make(chan *Job) pool := &ConsumerPool{C: c, c: c} for _, socket := range sockets { pool.consumers = append(pool.consumers, NewConsumer(socket, tubes, pool.c, options)) } return pool } // Stop shuts down all the consumers in the pool. func (pool *ConsumerPool) Stop() { pool.Lock() defer pool.Unlock() for i, consumer := range pool.consumers { consumer.Stop() pool.consumers[i] = nil } pool.consumers = []*Consumer{} } // Play tells all the consumers to start reservering jobs. func (pool *ConsumerPool) Play() { pool.Lock() defer pool.Unlock() for _, consumer := range pool.consumers { consumer.Play() } } // Pause tells all the consumer to stop reservering jobs. func (pool *ConsumerPool) Pause() { pool.Lock() defer pool.Unlock() for _, consumer := range pool.consumers { consumer.Pause() } }
package beanstalk import "sync" // ConsumerPool maintains a pool of Consumer objects. type ConsumerPool struct { C chan *Job consumers []*Consumer sync.Mutex } // NewConsumerPool creates a pool of Consumer objects. func NewConsumerPool(sockets []string, tubes []string, options *Options) *ConsumerPool { pool := &ConsumerPool{C: make(chan *Job)} for _, socket := range sockets { pool.consumers = append(pool.consumers, NewConsumer(socket, tubes, pool.C, options)) } return pool } // Stop shuts down all the consumers in the pool. func (pool *ConsumerPool) Stop() { pool.Lock() defer pool.Unlock() for i, consumer := range pool.consumers { consumer.Stop() pool.consumers[i] = nil } pool.consumers = []*Consumer{} } // Play tells all the consumers to start reservering jobs. func (pool *ConsumerPool) Play() { pool.Lock() defer pool.Unlock() for _, consumer := range pool.consumers { consumer.Play() } } // Pause tells all the consumer to stop reservering jobs. func (pool *ConsumerPool) Pause() { pool.Lock() defer pool.Unlock() for _, consumer := range pool.consumers { consumer.Pause() } }
Fix markdown style load error
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // @ts-check 'use strict'; (function () { const unloadedStyles = []; const onStyleLoadError = (event) => { const source = event.target.dataset.source; unloadedStyles.push(source); }; window.addEventListener('DOMContentLoaded', () => { for (const link of document.getElementsByClassName('code-user-style')) { if (link.dataset.source) { link.onerror = onStyleLoadError; } } }) window.addEventListener('load', () => { if (!unloadedStyles.length) { return; } window.parent.postMessage({ command: '_markdown.onPreviewStyleLoadError', args: [unloadedStyles] }, '*'); }); }());
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // @ts-check 'use strict'; (function () { const unloadedStyles = []; const onStyleLoadError = (event) => { const source = event.target.dataset.source; unloadedStyles.push(source); }; window.addEventListener('DOMContentLoaded', () => { for (const link of document.getElementsByClassName('code-user-style')) { if (link.dataset.source) { link.onerror = onStyleLoadError; } } }) window.addEventListener('load', () => { if (!unloadedStyles.length) { return; } const args = [unloadedStyles]; window.parent.postMessage({ command: 'did-click-link', data: `command:_markdown.onPreviewStyleLoadError?${encodeURIComponent(JSON.stringify(args))}` }, '*'); }); }());
Use lowercase for google chrome
<li class="story-item" data-id="<?= $item->item_id ?>" data-url="<?= $_SESSION['space']['url']; ?>item/<?= $item->item_id ?>"> <h3> <?php if ($item->time_left > 0) : ?><div class="timeleft tooltip" title="Original estimate: <?= $item->estimate ?> hrs"><?= $item->time_left ?></div><?php endif; ?> <a target="_blank" href="<?= $item->link ?>"><?= $item->title ?></a> </h3> <div class="story-item-details" <?php if (!$item->responsible) { print 'style="display:none;"'; } ?>> <?php if ($item->responsible) : ?> <div class="responsible"> <?//= substr($item->responsible['name'], 0, strpos($item->responsible['name'], ' ')); ?> <?= $item->responsible['name']; ?> </div> <?php endif; ?> </div> </li>
<li class="story-item" data-id="<?= $item->item_id ?>" data-url="<?= $_SESSION['space']['url']; ?>item/<?= $item->item_id ?>"> <h3> <?php if ($item->time_left > 0) : ?><div class="timeleft tooltip" title="Original estimate: <?= $item->estimate ?> hrs"><?= $item->time_left ?></div><?php endif; ?> <a target="_BLANK" href="<?= $item->link ?>"><?= $item->title ?></a> </h3> <div class="story-item-details" <?php if (!$item->responsible) { print 'style="display:none;"'; } ?>> <?php if ($item->responsible) : ?> <div class="responsible"> <?//= substr($item->responsible['name'], 0, strpos($item->responsible['name'], ' ')); ?> <?= $item->responsible['name']; ?> </div> <?php endif; ?> </div> </li>
Change file image size parameter
"use strict"; const express = require("express"); const app = express(); // install request const request = require('request'); const PORT = process.env.PORT || 3000; const rovi = process.env.ROVI_APIKEY || ''; // API page with CORS header app.get('/api/:artist/:sig', (req, res) => { const artist = req.params.artist; const sig = req.params.sig; console.log(artist); console.log(sig); console.log(rovi); console.log(PORT); console.log(process.env); const url = "http://api.rovicorp.com/search/v2.1/music/search?apikey=" + rovi + "&sig=" + sig + "&query=" + artist + "&entitytype=artist&size=1&include=images,musicbio,discography,videos&formatid=16"; console.log(url); request.get(url, (err, response, body) => { if (err) throw err; res.header('Access-Control-Allow-Origin', '*'); res.send(JSON.parse(body)); }); }); app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
"use strict"; const express = require("express"); const app = express(); // install request const request = require('request'); const PORT = process.env.PORT || 3000; const rovi = process.env.ROVI_APIKEY || ''; // API page with CORS header app.get('/api/:artist/:sig', (req, res) => { const artist = req.params.artist; const sig = req.params.sig; console.log(artist); console.log(sig); console.log(rovi); console.log(PORT); console.log(process.env); const url = "http://api.rovicorp.com/search/v2.1/music/search?apikey=" + rovi + "&sig=" + sig + "&query=" + artist + "&entitytype=artist&size=1&include=images,musicbio,discography,videos"; console.log(url); request.get(url, (err, response, body) => { if (err) throw err; res.header('Access-Control-Allow-Origin', '*'); res.send(JSON.parse(body)); }); }); app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
Add styles for loading text view/text
import { StyleSheet, Dimensions } from 'react-native'; export default StyleSheet.create({ mainContainer: { // flex: 3, width: Dimensions.get('window').width * .97, height: Dimensions.get('window').height * .95, marginLeft: Dimensions.get('window').width / 60, marginTop: Dimensions.get('window').width / 20, }, startingActorView: { flex: 1.6, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', // borderWidth: 1, }, endingActorView: { flex: 1.6, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', // borderWidth: 1, }, pathsView: { flex: 3, justifyContent: 'center', // borderWidth: 1, // left: 0, }, path: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-around', padding: 5, // alignItems: 'flex-start', }, buttonView: { flex: .11, flexDirection: 'row', justifyContent: 'space-between', }, loadingView: { marginTop: Dimensions.get('window').height / 1.03 }, loadingText: { fontFamily: 'Faster One' } })
import { StyleSheet, Dimensions } from 'react-native'; export default StyleSheet.create({ mainContainer: { // flex: 3, width: Dimensions.get('window').width * .97, height: Dimensions.get('window').height * .95, marginLeft: Dimensions.get('window').width / 60, marginTop: Dimensions.get('window').width / 20, }, startingActorView: { flex: 1.6, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', // borderWidth: 1, }, endingActorView: { flex: 1.6, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', // borderWidth: 1, }, pathsView: { flex: 3, justifyContent: 'center', // borderWidth: 1, // left: 0, }, path: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-around', padding: 5, // alignItems: 'flex-start', }, buttonView: { flex: .11, flexDirection: 'row', justifyContent: 'space-between', }, })
Return Loading from Loading methods.
'use strict'; var EventEmitter = require('events'), util = require('util'); /** * The emitter returned by methods that load data from an external source. * @constructor * @fires Loading#error * @fires Loading#loaded */ function Loading(config) { EventEmitter.call(this); } util.inherits(Loading, EventEmitter); Loading.prototype.loaded = function(data) { this.emit('loaded', data); return this; }; Loading.prototype.error = function(error) { if (typeof error === 'string') { this.emit('error', new Error(error)); return this; } else if (typeof error === 'object') { if (error instanceof String) { this.emit('error', new Error(error)); return this; } else if (error instanceof Error) { this.emit('error', error); return this; } } this.emit('error', '' + error); return this; }; Loading.prototype.onLoaded = function(handler) { this.on('loaded', handler); return this; }; Loading.prototype.onError = function(handler) { this.on('error', handler); return this; }; /** * Emitted when there is an error loading the data. * @event Loading#error */ /** * Emitted when the data has been loaded successfuly. * @event Loading#loaded */ module.exports = Loading;
'use strict'; var EventEmitter = require('events'), util = require('util'); /** * The emitter returned by methods that load data from an external source. * @constructor * @fires Loading#error * @fires Loading#loaded */ function Loading(config) { EventEmitter.call(this); } util.inherits(Loading, EventEmitter); Loading.prototype.loaded = function(data) { this.emit('loaded', data); }; Loading.prototype.error = function(error) { if (typeof error === 'string') { this.emit('error', new Error(error)); return; } else if (typeof error === 'object') { if (error instanceof String) { this.emit('error', new Error(error)); return; } else if (error instanceof Error) { this.emit('error', error); return; } } this.emit('error', '' + error); }; Loading.prototype.onLoaded = function(handler) { this.on('loaded', handler); }; Loading.prototype.onError = function(handler) { this.on('error', handler); }; /** * Emitted when there is an error loading the data. * @event Loading#error */ /** * Emitted when the data has been loaded successfuly. * @event Loading#loaded */ module.exports = Loading;
Create migration directory if not exists
<?php /** * * @author Soshnikov Artem <213036@skobka.com> * @version 1.0 * @copyright (c) 15.04.2016 13:33 * @website http://skobka.com * @license http://skobka.com/license.html * @project annotation-test */ namespace skobka\yii2\Controllers; use skobka\yii2\migration\Generator; use yii\console\Controller; use yii\helpers\BaseFileHelper; class MigrationGeneratorController extends Controller { public $defaultAction = 'generate'; public $migrationsDir = '@app/migrations'; public function actionGenerate($class){ $generator = new Generator; $dir = \Yii::getAlias($this->migrationsDir); BaseFileHelper::createDirectory($dir); $generator->generate($class, $dir); $this->stdout("Migration for $class was successfully generated"); } }
<?php /** * * @author Soshnikov Artem <213036@skobka.com> * @version 1.0 * @copyright (c) 15.04.2016 13:33 * @website http://skobka.com * @license http://skobka.com/license.html * @project annotation-test */ namespace skobka\yii2\Controllers; use skobka\yii2\migration\Generator; use yii\console\Controller; class MigrationGeneratorController extends Controller { public $defaultAction = 'generate'; public $migrationsDir = '@app/migrations'; public function actionGenerate($class){ $generator = new Generator; $dir = \Yii::getAlias($this->migrationsDir); $generator->generate($class, $dir); $this->stdout("Migration for $class was successfully generated"); } }
Build schema by passing commentDescriptions
import { parse } from 'graphql'; import { validate } from 'graphql/validation'; import { buildASTSchema } from 'graphql/utilities/buildASTSchema'; import { GraphQLError } from 'graphql/error'; export function validateSchemaDefinition( schemaDefinition, rules, configuration ) { let ast; try { ast = parse(schemaDefinition); } catch (e) { if (e instanceof GraphQLError) { return [e]; } else { throw e; } } const schema = buildASTSchema(ast, { commentDescriptions: configuration.getCommentDescriptions(), }); const rulesWithConfiguration = rules.map(rule => { return ruleWithConfiguration(rule, configuration); }); const errors = validate(schema, ast, rulesWithConfiguration); const sortedErrors = sortErrors(errors); return sortedErrors; } function sortErrors(errors) { return errors.sort((a, b) => { return a.locations[0].line - b.locations[0].line; }); } function ruleWithConfiguration(rule, configuration) { if (rule.length == 2) { return function(context) { return rule(configuration, context); }; } else { return rule; } }
import { parse } from 'graphql'; import { validate } from 'graphql/validation'; import { buildASTSchema } from 'graphql/utilities/buildASTSchema'; import { GraphQLError } from 'graphql/error'; export function validateSchemaDefinition( schemaDefinition, rules, configuration ) { let ast; try { ast = parse(schemaDefinition); } catch (e) { if (e instanceof GraphQLError) { return [e]; } else { throw e; } } const schema = buildASTSchema(ast); const rulesWithConfiguration = rules.map(rule => { return ruleWithConfiguration(rule, configuration); }); const errors = validate(schema, ast, rulesWithConfiguration); const sortedErrors = sortErrors(errors); return sortedErrors; } function sortErrors(errors) { return errors.sort((a, b) => { return a.locations[0].line - b.locations[0].line; }); } function ruleWithConfiguration(rule, configuration) { if (rule.length == 2) { return function(context) { return rule(configuration, context); }; } else { return rule; } }
Load captcha library only when used
var isRequested = false; var isLoaded = false; var callbacks = []; module.exports = function(callback) { if (!isLoaded) { callbacks.push(callback); } else { callbacks.call(); } if (!isRequested) { var cb = 'kwfUp-recaptchaCallback'.replace('-', '_'); window[cb] = function() { isLoaded = true; callbacks.forEach(function(callback) { callback.call(); }); }; (function(cb){ var el = document.createElement('script'); el.src = 'https://www.google.com/recaptcha/api.js?onload=' + cb + '&render=explicit'; el.type = 'text/javascript'; el.async = true; var targetEl = document.getElementsByTagName('script')[0]; targetEl.parentNode.insertBefore(el, targetEl); })(cb); isRequested = true; } };
var libraryLoaded = false; var callbacks = []; module.exports = function(callback) { if (!libraryLoaded) { callbacks.push(callback); } else { callback.call(); } }; var cb = 'kwfUp-recaptchaCallback'.replace('-', '_'); window[cb] = function() { callbacks.forEach(function(callback) { callback.call(); }); libraryLoaded = true; }; (function(cb){ a='https://www.google.com/recaptcha/api.js?onload=' + cb + '&render=explicit'; b=document;c='script';d=b.createElement(c);d.src=a;d.type='text/java'+c;d.async=true; a=b.getElementsByTagName(c)[0];a.parentNode.insertBefore(d,a); })(cb);
Tweak Content name to be not nullable
export async function up(knex) { await knex.schema.createTable('Resource', (table) => { table.uuid('id').notNullable().primary() table.string('name', 32).notNullable() table.string('mime', 32) table.string('md5') table.integer('status').notNullable() table.bigInteger('createdAt') table.bigInteger('updatedAt') }) await knex.schema.createTable('Content', (table) => { table.increments() table.uuid('resourceId').notNullable().references('Resource.id') table.string('name', 32).notNullable() table.string('title', 255) table.text('description') table.json('data') table.integer('status').notNullable() table.bigInteger('createdAt') table.bigInteger('updatedAt') }) } export async function down(knex) { await knex.schema.dropTableIfExists('Content') await knex.schema.dropTableIfExists('Resource') }
export async function up(knex) { await knex.schema.createTable('Resource', (table) => { table.uuid('id').notNullable().primary() table.string('name', 32).notNullable() table.string('mime', 32) table.string('md5') table.integer('status').notNullable() table.bigInteger('createdAt') table.bigInteger('updatedAt') }) await knex.schema.createTable('Content', (table) => { table.increments() table.uuid('resourceId').notNullable().references('Resource.id') table.string('name', 32) table.string('title', 255) table.text('description') table.json('data') table.integer('status').notNullable() table.bigInteger('createdAt') table.bigInteger('updatedAt') }) } export async function down(knex) { await knex.schema.dropTableIfExists('Content') await knex.schema.dropTableIfExists('Resource') }
Handle `window` object through crowi instance
import queryString from 'query-string' export default class CrowiAuth { constructor(crowi) { this.crowi = crowi this.window = crowi.window this.location = crowi.location this.localStorage = crowi.localStorage this.onStorage = this.onStorage.bind(this) this.subscribeStorage() this.updateState() } isAuthenticated() { const { id, name } = this.crowi.getUser() return !!(id && name) } subscribeStorage() { this.window.addEventListener('storage', this.onStorage) } shouldUpdate() { return this.isAuthenticated() !== this.localStorage.getItem('authenticated') } updateState() { if (this.shouldUpdate()) { this.localStorage.setItem('authenticated', this.isAuthenticated()) } } onStorage(e) { const { key, newValue } = e const isAuthenticated = newValue === 'true' if (key === 'authenticated') { if (isAuthenticated) { this.onLogin() } else { this.onLogout() } } } onLogin() { const { continue: continueUrl } = queryString.parse(this.location.search) if (continueUrl) { top.location.href = continueUrl } else { this.location.reload() } } onLogout() { this.location.reload() } }
import queryString from 'query-string' export default class CrowiAuth { constructor(crowi) { this.crowi = crowi this.location = crowi.location this.localStorage = crowi.localStorage this.onStorage = this.onStorage.bind(this) this.subscribeStorage() this.updateState() } isAuthenticated() { const { id, name } = this.crowi.getUser() return !!(id && name) } subscribeStorage() { window.addEventListener('storage', this.onStorage) } shouldUpdate() { return this.isAuthenticated() !== this.localStorage.getItem('authenticated') } updateState() { if (this.shouldUpdate()) { this.localStorage.setItem('authenticated', this.isAuthenticated()) } } onStorage(e) { const { key, newValue } = e const isAuthenticated = newValue === 'true' if (key === 'authenticated') { if (isAuthenticated) { this.onLogin() } else { this.onLogout() } } } onLogin() { const { continue: continueUrl } = queryString.parse(this.location.search) if (continueUrl) { top.location.href = continueUrl } else { this.location.reload() } } onLogout() { this.location.reload() } }
Fix setting connectivity for NSX offerings
#!/usr/bin/env python import click from Cosmic.CI import * from Cosmic.NSX import * @click.command() @click.option('--marvin-config', '-m', help='Marvin config file', required=True) @click.option('--debug', help="Turn on debugging output", is_flag=True) def main(**kwargs): ci = CI(marvin_config=kwargs.get('marvin_config'), debug=kwargs.get('debug')) nsx = NSX(marvin_config=kwargs.get('marvin_config'), debug=kwargs.get('debug')) ci.wait_for_port(ci.config['mgtSvr'][0]['mgtSvrIp']) ci.copy_marvin_config() ci.deploy_dc() if nsx is not None: print("Setting connectivity for NSX offerings") nsx.add_connectivy_to_offerings() ci.wait_for_templates() if __name__ == '__main__': main()
#!/usr/bin/env python import click from Cosmic.CI import * from Cosmic.NSX import * @click.command() @click.option('--marvin-config', '-m', help='Marvin config file', required=True) @click.option('--debug', help="Turn on debugging output", is_flag=True) def main(**kwargs): ci = CI(marvin_config=kwargs.get('marvin_config'), debug=kwargs.get('debug')) nsx = NSX(marvin_config=kwargs.get('marvin_config'), debug=kwargs.get('debug')) ci.wait_for_port(ci.config['mgtSvr'][0]['mgtSvrIp']) ci.copy_marvin_config() ci.deploy_dc() if nsx: nsx.add_connectivy_to_offerings() ci.wait_for_templates() if __name__ == '__main__': main()
Fix issue where guest does not exist
<?php namespace Anomaly\UsersModule\Role\Command; use Anomaly\Streams\Platform\Support\Authorizer; use Anomaly\UsersModule\Role\Contract\RoleRepositoryInterface; use Illuminate\Contracts\Bus\SelfHandling; /** * Class SetGuestRole * * @link http://pyrocms.com/ * @author PyroCMS, Inc. <support@pyrocms.com> * @author Ryan Thompson <ryan@pyrocms.com> * @package Anomaly\UsersModule\Role\Command */ class SetGuestRole implements SelfHandling { /** * Handle the command. * * @param RoleRepositoryInterface $roles * @param Authorizer $authorizer */ public function handle(RoleRepositoryInterface $roles, Authorizer $authorizer) { if ($guest = $roles->findBySlug('guest')) { $authorizer->setGuest($guest); } } }
<?php namespace Anomaly\UsersModule\Role\Command; use Anomaly\Streams\Platform\Support\Authorizer; use Anomaly\UsersModule\Role\Contract\RoleRepositoryInterface; use Illuminate\Contracts\Bus\SelfHandling; /** * Class SetGuestRole * * @link http://pyrocms.com/ * @author PyroCMS, Inc. <support@pyrocms.com> * @author Ryan Thompson <ryan@pyrocms.com> * @package Anomaly\UsersModule\Role\Command */ class SetGuestRole implements SelfHandling { /** * Handle the command. * * @param RoleRepositoryInterface $roles * @param Authorizer $authorizer */ public function handle(RoleRepositoryInterface $roles, Authorizer $authorizer) { $authorizer->setGuest($roles->findBySlug('guest')); } }
Remove and replace task.id field, instead of Alter
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('django_q', '0002_auto_20150630_1624'), ] operations = [ migrations.AlterModelOptions( name='failure', options={'verbose_name_plural': 'Failed tasks', 'verbose_name': 'Failed task'}, ), migrations.AlterModelOptions( name='schedule', options={'verbose_name_plural': 'Scheduled tasks', 'ordering': ['next_run'], 'verbose_name': 'Scheduled task'}, ), migrations.AlterModelOptions( name='success', options={'verbose_name_plural': 'Successful tasks', 'verbose_name': 'Successful task'}, ), migrations.RemoveField( model_name='task', name='id', ), migrations.AddField( model_name='task', name='id', field=models.CharField(max_length=32, primary_key=True, editable=False, serialize=False), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('django_q', '0002_auto_20150630_1624'), ] operations = [ migrations.AlterModelOptions( name='failure', options={'verbose_name_plural': 'Failed tasks', 'verbose_name': 'Failed task'}, ), migrations.AlterModelOptions( name='schedule', options={'verbose_name_plural': 'Scheduled tasks', 'ordering': ['next_run'], 'verbose_name': 'Scheduled task'}, ), migrations.AlterModelOptions( name='success', options={'verbose_name_plural': 'Successful tasks', 'verbose_name': 'Successful task'}, ), migrations.AlterField( model_name='task', name='id', field=models.CharField(max_length=32, primary_key=True, editable=False, serialize=False), ), ]
Fix off by one error in line number enumeration
from __future__ import print_function import argparse import sys CONFLICT_PATTERNS = [ '<<<<<<< ', '=======', '>>>>>>> ' ] WARNING_MSG = 'Merge conflict string "{0}" found in {1}:{2}' def detect_merge_conflict(argv=None): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*') args = parser.parse_args(argv) retcode = 0 for filename in args.filenames: with open(filename) as inputfile: for i, line in enumerate(inputfile): for pattern in CONFLICT_PATTERNS: if line.startswith(pattern): print(WARNING_MSG.format(pattern, filename, i + 1)) retcode = 1 return retcode if __name__ == '__main__': sys.exit(detect_merge_conflict())
from __future__ import print_function import argparse import sys CONFLICT_PATTERNS = [ '<<<<<<< ', '=======', '>>>>>>> ' ] WARNING_MSG = 'Merge conflict string "{0}" found in {1}:{2}' def detect_merge_conflict(argv=None): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*') args = parser.parse_args(argv) retcode = 0 for filename in args.filenames: with open(filename) as inputfile: for i, line in enumerate(inputfile): for pattern in CONFLICT_PATTERNS: if line.startswith(pattern): print(WARNING_MSG.format(pattern, filename, i)) retcode = 1 return retcode if __name__ == '__main__': sys.exit(detect_merge_conflict())
Make sure afterTransitionLoading is set correctly
import React, { Component, PropTypes } from 'react'; import getRoutePath from './util/getRoutePath'; export default class RedialContainer extends Component { static displayName = 'RedialContainer'; static propTypes = { children: PropTypes.element.isRequired, routerProps: PropTypes.object.isRequired, }; static contextTypes = { redialContext: PropTypes.object.isRequired, }; render() { const { routerProps, ...props } = this.props; const { abortLoading, loading, afterTransitionLoading, reloadComponent, redialMap, } = this.context.redialContext; const mapKey = getRoutePath(routerProps.route, routerProps.routes, routerProps.key); const redialProps = redialMap.get(mapKey); const reload = () => reloadComponent(routerProps.route.component); const abort = () => abortLoading(); return React.cloneElement( this.props.children, { ...props, ...redialProps, ...routerProps, loading, afterTransitionLoading, reload, abort, } ); } }
import React, { Component, PropTypes } from 'react'; import getRoutePath from './util/getRoutePath'; export default class RedialContainer extends Component { static displayName = 'RedialContainer'; static propTypes = { children: PropTypes.element.isRequired, routerProps: PropTypes.object.isRequired, }; static contextTypes = { redialContext: PropTypes.object.isRequired, }; render() { const { routerProps, ...props } = this.props; const { abortLoading, loading, deferredLoading, reloadComponent, redialMap, } = this.context.redialContext; const mapKey = getRoutePath(routerProps.route, routerProps.routes, routerProps.key); const redialProps = redialMap.get(mapKey); const reload = () => reloadComponent(routerProps.route.component); const abort = () => abortLoading(); return React.cloneElement( this.props.children, { ...props, ...redialProps, ...routerProps, loading, deferredLoading, reload, abort, } ); } }
Fix website URL in kpi_dashboard module
# Copyright 2020 Creu Blanca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Kpi Dashboard", "summary": """ Create Dashboards using kpis""", "version": "12.0.1.2.0", "license": "AGPL-3", "author": "Creu Blanca,Odoo Community Association (OCA)", "website": "https://github.com/OCA/reporting-engine", "depends": ["bus", "board", "base_sparse_field", "web_widget_color"], "qweb": ["static/src/xml/dashboard.xml"], "data": [ "wizards/kpi_dashboard_menu.xml", "security/security.xml", "security/ir.model.access.csv", "templates/assets.xml", "views/kpi_menu.xml", "views/kpi_kpi.xml", "views/kpi_dashboard.xml", ], "demo": ["demo/demo_dashboard.xml"], "maintainers": ["etobella"], }
# Copyright 2020 Creu Blanca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Kpi Dashboard", "summary": """ Create Dashboards using kpis""", "version": "12.0.1.2.0", "license": "AGPL-3", "author": "Creu Blanca,Odoo Community Association (OCA)", "website": "https://github.com/reporting-engine", "depends": ["bus", "board", "base_sparse_field", "web_widget_color"], "qweb": ["static/src/xml/dashboard.xml"], "data": [ "wizards/kpi_dashboard_menu.xml", "security/security.xml", "security/ir.model.access.csv", "templates/assets.xml", "views/kpi_menu.xml", "views/kpi_kpi.xml", "views/kpi_dashboard.xml", ], "demo": ["demo/demo_dashboard.xml"], "maintainers": ["etobella"], }
Fix extension activation in tests
const fs = require('fs') const LANGUAGE = 'postfix' const task = process.argv.length > 2 && process.argv[2] const tasksMap = new Map([ ['prerun', prerun], ['pretest', pretest] ]) function prerun() { let pkg = readPackageJson() delete pkg.contributes.languages pkg.activationEvents = [ 'onLanguage:javascript', 'onLanguage:typescript', 'onLanguage:javascriptreact', 'onLanguage:typescriptreact' ] pkg.main = './out/extension' writePackageJson(pkg) } function pretest() { let pkg = readPackageJson() pkg.contributes.languages = [{id: LANGUAGE}] // Activate the extension right after start to avoid delay and failure in first test pkg.activationEvents = ['onStartupFinished'] // Don't use bundler for tests as it breaks template usage tests pkg.main = './out/src/extension' writePackageJson(pkg) } const writePackageJson = (content) => fs.writeFileSync('./package.json', JSON.stringify(content, undefined, '\t')) const readPackageJson = () => require('./package.json') const taskToExecute = tasksMap.get(task) taskToExecute && taskToExecute()
const fs = require('fs') const LANGUAGE = 'postfix' const ACTIVATION_EVENT = `onLanguage:${LANGUAGE}` const task = process.argv.length > 2 && process.argv[2] const tasksMap = new Map([ ['prerun', prerun], ['pretest', pretest] ]) function prerun() { let pkg = readPackageJson() delete pkg.contributes.languages pkg.activationEvents = [ 'onLanguage:javascript', 'onLanguage:typescript', 'onLanguage:javascriptreact', 'onLanguage:typescriptreact' ] pkg.main = './out/extension' writePackageJson(pkg) } function pretest() { let pkg = readPackageJson() pkg.contributes.languages = [{id: LANGUAGE}] pkg.activationEvents = [ACTIVATION_EVENT] // Don't use bundler for tests as it breaks template usage tests pkg.main = './out/src/extension' writePackageJson(pkg) } const writePackageJson = (content) => fs.writeFileSync('./package.json', JSON.stringify(content, undefined, '\t')) const readPackageJson = () => require('./package.json') const taskToExecute = tasksMap.get(task) taskToExecute && taskToExecute()
Fix another moved class name
<?php namespace CoreSphere\CoreBundle\Controller; use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseController; use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference; class ExceptionController extends BaseController { protected function findTemplate($templating, $format, $code, $debug) { $name = $debug ? 'exception' : 'error'; if ($debug && 'html' == $format) { $name = 'exception_full'; } // when not in debug, try to find a template for the specific HTTP status code and format if (!$debug) { $template = new TemplateReference('CoreSphereCoreBundle', 'Exception', $name.$code, $format, 'twig'); if ($templating->exists($template)) { return $template; } } // try to find a template for the given format $template = new TemplateReference('CoreSphereCoreBundle', 'Exception', $name, $format, 'twig'); if ($templating->exists($template)) { return $template; } // default to a generic HTML exception $this->container->get('request')->setRequestFormat('html'); return new TemplateReference('CoreSphereCoreBundle', 'Exception', $name, 'html', 'twig'); } }
<?php namespace CoreSphere\CoreBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\ExceptionController as BaseController; use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference; class ExceptionController extends BaseController { protected function findTemplate($templating, $format, $code, $debug) { $name = $debug ? 'exception' : 'error'; if ($debug && 'html' == $format) { $name = 'exception_full'; } // when not in debug, try to find a template for the specific HTTP status code and format if (!$debug) { $template = new TemplateReference('CoreSphereCoreBundle', 'Exception', $name.$code, $format, 'twig'); if ($templating->exists($template)) { return $template; } } // try to find a template for the given format $template = new TemplateReference('CoreSphereCoreBundle', 'Exception', $name, $format, 'twig'); if ($templating->exists($template)) { return $template; } // default to a generic HTML exception $this->container->get('request')->setRequestFormat('html'); return new TemplateReference('CoreSphereCoreBundle', 'Exception', $name, 'html', 'twig'); } }
Add console command for adding items easily
<?php namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ Commands\AddItem::class, ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command('inspire') // ->hourly(); } /** * Register the Closure based commands for the application. * * @return void */ protected function commands() { require base_path('routes/console.php'); } }
<?php namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ // ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command('inspire') // ->hourly(); } /** * Register the Closure based commands for the application. * * @return void */ protected function commands() { require base_path('routes/console.php'); } }
Hide images in article content too.
var articleParent = document.querySelector('#storyContent'); var articleParas = document.querySelectorAll('#storyContent p'); var storyImages = document.querySelectorAll('span.story-image'); for(var x = 0; x < articleParas.length; x += 1){ articleParas[x].style.display = "none"; } for(var y = 0; y < storyImages.length; y += 1){ storyImages[y].style.display = "none"; } var adMessage = document.createElement('div'); adMessage.innerHTML = '<p style="border: 5px solid #a7a59b; padding: 1em; margin-bottom: 1em;">This article will be back shortly. We have delayed your access to it for a short while because we believe you are using ad blocking technology. The FT generates income from advertising on the site which helps ensure we can bring you intesting content like the article you will shortly be reading.</p>'; articleParent.insertBefore(adMessage, articleParent.firstChild); function showContent() { adMessage.style.display = 'none'; for(var z = 0; z < articleParas.length; z += 1){ articleParas[z].style.display = "block"; } for(var w = 0; w < storyImages.length; w += 1){ storyImages[y].style.display = "block"; } } window.setTimeout(showContent, 10000);
var articleParent = document.querySelector('#storyContent'); var articleParas = document.querySelectorAll('#storyContent p'); for(var x = 0; x < articleParas.length; x += 1){ articleParas[x].style.display = "none"; } var adMessage = document.createElement('div'); adMessage.innerHTML = '<p style="border: 5px solid #a7a59b; padding: 1em; margin-bottom: 1em;">This article will be back shortly. We have delayed your access to it for a short while because we believe you are using ad blocking technology. The FT generates income from advertising on the site which helps ensure we can bring you intesting content like the article you will shortly be reading.</p>'; articleParent.insertBefore(adMessage, articleParent.firstChild); function showContent() { adMessage.style.display = 'none'; for(var x = 0; x < articleParas.length; x += 1){ articleParas[x].style.display = "block"; } } window.setTimeout(showContent, 10000);
Disable strict struct checks by default.
// The dawa package can be used to de-serialize structures received from "Danmarks Adressers Web API (DAWA)" (Addresses of Denmark Web API). // // This package allows to de-serialize JSON responses from the web api into typed structs. // The package also allows importing JSON or CSV downloads from the official web page. // See the /examples folder for more information. // // Package home: https://github.com/klauspost/dawa // // Information abou the format and download/API options, see http://dawa.aws.dk/ // // Description text in Danish: // // Danmarks Adressers Web API (DAWA) udstiller data og funktionalitet vedrørende Danmarks adresser, adgangsadresser, vejnavne samt postnumre. // DAWA anvendes til etablering af adressefunktionalitet i it-systemer. Målgruppen for nærværende website er udviklere, som ønsker at indbygge adressefunktionalitet i deres it-systemer. package dawa // modify JSONStrictFieldCheck to return an error on unknown fields on JSON import. // If true, return an error if a map in the stream has a key which does not map to any field; else read and discard the key and value in the stream and proceed to the next. var JSONStrictFieldCheck = false
// The dawa package can be used to de-serialize structures received from "Danmarks Adressers Web API (DAWA)" (Addresses of Denmark Web API). // // This package allows to de-serialize JSON responses from the web api into typed structs. // The package also allows importing JSON or CSV downloads from the official web page. // See the /examples folder for more information. // // Package home: https://github.com/klauspost/dawa // // Information abou the format and download/API options, see http://dawa.aws.dk/ // // Description text in Danish: // // Danmarks Adressers Web API (DAWA) udstiller data og funktionalitet vedrørende Danmarks adresser, adgangsadresser, vejnavne samt postnumre. // DAWA anvendes til etablering af adressefunktionalitet i it-systemer. Målgruppen for nærværende website er udviklere, som ønsker at indbygge adressefunktionalitet i deres it-systemer. package dawa // modify JSONStrictFieldCheck to return an error on unknown fields on JSON import. // If true, return an error if a map in the stream has a key which does not map to any field; else read and discard the key and value in the stream and proceed to the next. var JSONStrictFieldCheck = true
Use sys.executable as the default python executable
import json import logging import os import sys log_format = "[{levelname}][{name}] {message}" def configure_logging(log_level): logging.basicConfig(level = log_level, format = log_format, style = "{") logging.addLevelName(logging.DEBUG, "Debug") logging.addLevelName(logging.INFO, "Info") logging.addLevelName(logging.WARNING, "Warning") logging.addLevelName(logging.ERROR, "Error") logging.addLevelName(logging.CRITICAL, "Critical") logging.getLogger("werkzeug").setLevel(logging.WARNING) def create_default_environment(): return { "git_executable": "git", "python3_executable": sys.executable, "scp_executable": "scp", "ssh_executable": "ssh", } def load_environment(): env = create_default_environment() env.update(_load_environment_transform(os.path.join(os.path.expanduser("~"), "environment.json"))) env.update(_load_environment_transform("environment.json")) return env def _load_environment_transform(transform_file_path): if not os.path.exists(transform_file_path): return {} with open(transform_file_path) as transform_file: return json.load(transform_file)
import json import logging import os log_format = "[{levelname}][{name}] {message}" def configure_logging(log_level): logging.basicConfig(level = log_level, format = log_format, style = "{") logging.addLevelName(logging.DEBUG, "Debug") logging.addLevelName(logging.INFO, "Info") logging.addLevelName(logging.WARNING, "Warning") logging.addLevelName(logging.ERROR, "Error") logging.addLevelName(logging.CRITICAL, "Critical") logging.getLogger("werkzeug").setLevel(logging.WARNING) def create_default_environment(): return { "git_executable": "git", "python3_executable": "python3", "scp_executable": "scp", "ssh_executable": "ssh", } def load_environment(): env = create_default_environment() env.update(_load_environment_transform(os.path.join(os.path.expanduser("~"), "environment.json"))) env.update(_load_environment_transform("environment.json")) return env def _load_environment_transform(transform_file_path): if not os.path.exists(transform_file_path): return {} with open(transform_file_path) as transform_file: return json.load(transform_file)
Put SMS answer job in very high priority
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2018 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # ############################################################################## import logging import json from odoo import http, tools from odoo.http import request from ..tools import SmsNotificationAnswer async = not tools.config.get('test_enable') _logger = logging.getLogger(__name__) class RestController(http.Controller): @http.route('/sms/mnc/', type='http', auth='public', methods=['GET'], csrf=False) def sms_notification(self, **parameters): _logger.info("SMS Request received : {}".format( json.dumps(parameters))) notification_env = request.env['sms.notification'].sudo() (notification_env.with_delay(priority=1) if async else notification_env).send_sms_answer(parameters) return SmsNotificationAnswer([], costs=[]).get_answer()
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2018 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # ############################################################################## import logging import json from odoo import http, tools from odoo.http import request from ..tools import SmsNotificationAnswer async = not tools.config.get('test_enable') _logger = logging.getLogger(__name__) class RestController(http.Controller): @http.route('/sms/mnc/', type='http', auth='public', methods=['GET'], csrf=False) def sms_notification(self, **parameters): _logger.info("SMS Request received : {}".format( json.dumps(parameters))) notification_env = request.env['sms.notification'].sudo() (notification_env.with_delay() if async else notification_env) \ .send_sms_answer(parameters) return SmsNotificationAnswer([], costs=[]).get_answer()
8: Create documentation of DataSource Settings Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dsidlist = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dsidlist.append(str(db).replace('"','')) n += 1 dsidlist.sort() for dsid in dsidlist: propertySet = AdminConfig.showAttribute(dsid,"propertySet") print propertySet propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines() print propertyList
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dsidlist = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dsidlist.append(str(db).replace('"','')) n += 1 dsidlist.sort() for dsid in dsidlist: propertySet = AdminConfig.showAttribute(dsid,"propertySet") propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines() print propertyList
Add missing ChannelEvent extends to leave event
/* * * Copyright (C) 2013-2015 Matt Baxter http://kitteh.org * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.kitteh.irc.client.library.event.client; import org.kitteh.irc.client.library.Client; import org.kitteh.irc.client.library.event.helper.ChannelEvent; /** * I have left the channel I wanted! Will fire each time the client leaves a * channel added via {@link Client#addChannel} and not removed via {@link * Client#removeChannel}. */ public interface RequestedChannelLeaveEvent extends ChannelEvent { }
/* * * Copyright (C) 2013-2015 Matt Baxter http://kitteh.org * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.kitteh.irc.client.library.event.client; import org.kitteh.irc.client.library.Client; /** * I have left the channel I wanted! Will fire each time the client leaves a * channel added via {@link Client#addChannel} and not removed via {@link * Client#removeChannel}. */ public interface RequestedChannelLeaveEvent { }
Check auth status in initial state
import {CHANGE_FORM, SET_AUTH, SENDING_REQUEST} from '../actions/constants' import auth from '../auth'; let assign = Object.assign let initialState = { formState: { username: '', password: '' }, currentlySending: false, loggedIn: auth.loggedIn() } function reducer (state = initialState, action) { switch (action.type) { case CHANGE_FORM: return assign({}, state, { formState: action.newState }) case SET_AUTH: return assign({}, state, { loggedIn: action.newState }) case SENDING_REQUEST: return assign({}, state, { currentlySending: action.sending }) default: return state } } export default reducer
import {CHANGE_FORM, SET_AUTH, SENDING_REQUEST} from '../actions/constants' let assign = Object.assign let initialState = { formState: { username: '', password: '' }, currentlySending: false, loggedIn: false } function reducer (state = initialState, action) { switch (action.type) { case CHANGE_FORM: return assign({}, state, { formState: action.newState }) case SET_AUTH: return assign({}, state, { loggedIn: action.newState }) case SENDING_REQUEST: return assign({}, state, { currentlySending: action.sending }) default: return state } } export default reducer
Tidy up info a little for the PluginModule popup edit form git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@40390 b456876b-0849-0410-b77d-98878d47e9d5
<?php // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ //this script may only be included - so its better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) { header("location: index.php"); exit; } function module_top_visited_faqs_info() { return array( 'name' => tra('Top Visited FAQs'), 'description' => tra('Display the specified number of FAQs with links to them, from the most visited one to the least.'), 'prefs' => array('feature_faqs'), 'params' => array(), 'common_params' => array('nonums', 'rows') ); } function module_top_visited_faqs($mod_reference, $module_params) { global $smarty; $faqlib = TikiLib::lib('faq'); $ranking = $faqlib->list_faqs(0, $mod_reference["rows"], 'hits_desc', ''); $smarty->assign('modTopVisitedFaqs', $ranking["data"]); }
<?php // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ //this script may only be included - so its better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) { header("location: index.php"); exit; } function module_top_visited_faqs_info() { return array( 'name' => tra('Most-Read FAQs'), 'description' => tra('Displays the specified number of FAQs with links to them, from the most visited one to the least.'), 'prefs' => array('feature_faqs'), 'params' => array(), 'common_params' => array('nonums', 'rows') ); } function module_top_visited_faqs($mod_reference, $module_params) { global $smarty; $faqlib = TikiLib::lib('faq'); $ranking = $faqlib->list_faqs(0, $mod_reference["rows"], 'hits_desc', ''); $smarty->assign('modTopVisitedFaqs', $ranking["data"]); }
Fix time display in Month view
<?php if (count($context)) { ?> <a href="<?php echo $context->getURL(); ?>"><?php echo $context->getDateTime()->format('j')?></a> <?php } else { echo $context->getDateTime()->format('j'); } ?> <ul class="month-day-listing"> <?php foreach ($context as $e) { //Start building an array of row classes $classes = array('event'); if ($e->isAllDay()) { $classes[] = 'all-day'; } if ($e->isInProgress()) { $classes[] = 'in-progress'; } if ($e->isOnGoing()) { $classes[] = 'ongoing'; } ?> <li class="<?php echo implode(' ', $classes); ?>"> <?php echo $savvy->render($e, 'EventInstance/TimeOnly.tpl.php') ?> <a href="<?php echo $e->getURL(); ?>"><?php echo $savvy->dbStringtoHtml($e->event->title)?></a> </li> <?php } ?> </ul>
<?php if (count($context)) { ?> <a href="<?php echo $context->getURL(); ?>"><?php echo $context->getDateTime()->format('j')?></a> <?php } else { echo $context->getDateTime()->format('j'); } ?> <ul class="month-day-listing"> <?php foreach ($context as $e) { //Start building an array of row classes $classes = array('event'); if ($e->isAllDay()) { $classes[] = 'all-day'; } if ($e->isInProgress()) { $classes[] = 'in-progress'; } if ($e->isOnGoing()) { $classes[] = 'ongoing'; } ?> <li class="<?php echo implode(' ', $classes); ?>"> <?php echo $savvy->render($e, 'EventInstance/Date.tpl.php') ?> <span class="date-title-separator">:</span> <a href="<?php echo $e->getURL(); ?>"><?php echo $savvy->dbStringtoHtml($e->event->title)?></a> </li> <?php } ?> </ul>
Remove select2 library from config
/* * EksiOkuyucu - unofficial eksisozluk client * http://eksiokuyucu.com/ * * Copyright (C) 2014 Onur Aslan <onuraslan@gmail.com> * Licensed under MIT * https://github.com/onuraslan/EksiOkuyucu/blob/master/COPYING */ require.config ({ paths: { requireLib: 'libs/require', jquery: 'libs/jquery-1.11.0.min', underscore: 'libs/underscore-min', backbone: 'libs/backbone-min', text: 'libs/text', bootstrap: 'libs/bootstrap.min', templates: '../templates' }, shim: { 'bootstrap': { deps: ["jquery"] } } }); require([ 'app', ], function (App) { App.initialize (); });
/* * EksiOkuyucu - unofficial eksisozluk client * http://eksiokuyucu.com/ * * Copyright (C) 2014 Onur Aslan <onuraslan@gmail.com> * Licensed under MIT * https://github.com/onuraslan/EksiOkuyucu/blob/master/COPYING */ require.config ({ paths: { requireLib: 'libs/require', jquery: 'libs/jquery-1.11.0.min', underscore: 'libs/underscore-min', backbone: 'libs/backbone-min', text: 'libs/text', bootstrap: 'libs/bootstrap.min', select2: 'libs/select2.min', templates: '../templates' }, shim: { 'bootstrap': { deps: ["jquery"] }, 'select2': { deps: ["jquery"] } } }); require([ 'app', ], function (App) { App.initialize (); });
Send 1k messages on startup for testing.
var ProtoBuf = dcodeIO.ProtoBuf; var Builder = ProtoBuf.loadProtoFile("proto/ClientMessage.proto"); ProtoBuf.loadProtoFile("proto/Login.proto", Builder); var Message = Builder.build("msg"); var ClientMessage = Message.ClientMessage; var LoginMessage = Message.Login; var loginMsg = new LoginMessage("integr@gmail.com","secret"); var clientMsg = new ClientMessage({ "msgType" : "LoginType", "login":{ "email":"integr@gmail.com", "password":"secret"}}); var ws; window.onload=function(){ ws=new WebSocket("ws://localhost:8080/index"); ws.onmessage = function(evt) { console.log(evt.data); var loginFormSection = document.getElementById("loginFormSection"); if(evt.data == "AUTHPLS") { loginFormSection.style.display = "block"; } if(evt.data == "AUTHOKTHX") { loginFormSection.style.display = "none"; document.getElementById("portal").style.display = "block"; } }; ws.onopen=function(evt){ // ws.send("Hello"); for(i = 0; i < 1000; i++) { ws.send(clientMsg.toArrayBuffer()); } }; }; window.onclose=function(){ ws.close(); }; function loginSubmitEvent () { var email = document.getElementById("loginEmail").value; var password = document.getElementById("loginPassword").value; ws.send(email + ":" + password); }
var ProtoBuf = dcodeIO.ProtoBuf; var Builder = ProtoBuf.loadProtoFile("proto/ClientMessage.proto"); ProtoBuf.loadProtoFile("proto/Login.proto", Builder); var Message = Builder.build("msg"); var ClientMessage = Message.ClientMessage; var LoginMessage = Message.Login; var loginMsg = new LoginMessage("integr@gmail.com","secret"); var clientMsg = new ClientMessage({ "msgType" : "LoginType", "login":{ "email":"integr@gmail.com", "password":"secret"}}); var ws; window.onload=function(){ ws=new WebSocket("ws://localhost:8080/index"); ws.onmessage = function(evt) { console.log(evt.data); var loginFormSection = document.getElementById("loginFormSection"); if(evt.data == "AUTHPLS") { loginFormSection.style.display = "block"; } if(evt.data == "AUTHOKTHX") { loginFormSection.style.display = "none"; document.getElementById("portal").style.display = "block"; } }; ws.onopen=function(evt){ // ws.send("Hello"); ws.send(clientMsg.toArrayBuffer()); }; }; window.onclose=function(){ ws.close(); }; function loginSubmitEvent () { var email = document.getElementById("loginEmail").value; var password = document.getElementById("loginPassword").value; ws.send(email + ":" + password); }
Put back to 12 hours.
import os import time from crawl import crawl import tweepy class TwitterAPI: """ Class for accessing the Twitter API. Requires API credentials to be available in environment variables. These will be set appropriately if the bot was created with init.sh included with the heroku-twitterbot-starter """ def __init__(self): consumer_key = os.environ.get('TWITTER_CONSUMER_KEY') consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET') auth = tweepy.OAuthHandler(consumer_key, consumer_secret) access_token = os.environ.get('TWITTER_ACCESS_TOKEN') access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET') auth.set_access_token(access_token, access_token_secret) self.api = tweepy.API(auth) def tweet(self, message): """Send a tweet""" self.api.update_status(message) if __name__ == "__main__": twitter = TwitterAPI() while True: tweet = crawl() if tweet: twitter.tweet(tweet) time.sleep(43200) # 12 hours
import os import time from crawl import crawl import tweepy class TwitterAPI: """ Class for accessing the Twitter API. Requires API credentials to be available in environment variables. These will be set appropriately if the bot was created with init.sh included with the heroku-twitterbot-starter """ def __init__(self): consumer_key = os.environ.get('TWITTER_CONSUMER_KEY') consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET') auth = tweepy.OAuthHandler(consumer_key, consumer_secret) access_token = os.environ.get('TWITTER_ACCESS_TOKEN') access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET') auth.set_access_token(access_token, access_token_secret) self.api = tweepy.API(auth) def tweet(self, message): """Send a tweet""" self.api.update_status(message) if __name__ == "__main__": twitter = TwitterAPI() while True: tweet = crawl() if tweet: twitter.tweet(tweet) time.sleep(60) #time.sleep(43200) # 12 hours
Change optimized dir prefix to tinyme-optimized
/** * Node modules */ const path = require('path'); const util = require('util'); const ncp = util.promisify(require('ncp').ncp); /** * FileSystem helper. * * @class FileSystem * @package Helpers * @author Patrick Ferreira <paatrickferreira@gmail.com> */ class FileSystem { /** * Checks if a file is an image based on a list of valid extensions. * * @static * @param {string} file * @returns {boolean} * * @memberof FileSystem */ static isImage(file) { const ext = file.split('.').pop().toLocaleLowerCase(); const validExtensions = ['png', 'jpg', 'jpeg']; return validExtensions.includes(ext); } /** * Clones the origial dir with a "-tinyme-optimized" prefix at the same level of the * original dir. * * @static * @param {string} dir * @param {string} [prefix='tinyme-optimized'] * @returns {string} * * @memberof FileSystem */ static async cloneDir(dir, prefix = 'tinyme-optimized') { const originalDir = path.resolve(dir); const clonedDir = `${originalDir}-${prefix}`; try { await ncp(originalDir, clonedDir); } catch (err) { throw new Error('Could not clone given dir'); } return clonedDir; } } module.exports = FileSystem;
/** * Node modules */ const path = require('path'); const util = require('util'); const ncp = util.promisify(require('ncp').ncp); /** * FileSystem helper. * * @class FileSystem * @package Helpers * @author Patrick Ferreira <paatrickferreira@gmail.com> */ class FileSystem { /** * Checks if a file is an image based on a list of valid extensions. * * @static * @param {string} file * @returns {boolean} * * @memberof FileSystem */ static isImage(file) { const ext = file.split('.').pop().toLocaleLowerCase(); const validExtensions = ['png', 'jpg', 'jpeg']; return validExtensions.includes(ext); } /** * Clones the origial dir with a "-tinyme-optimized" prefix at the same level of the * original dir. * * @static * @param {string} dir * @param {string} [prefix='optimized'] * @returns {string} * * @memberof FileSystem */ static async cloneDir(dir, prefix = 'tinyme-optimized') { const originalDir = path.resolve(dir); const clonedDir = `${originalDir}-${prefix}`; try { await ncp(originalDir, clonedDir, { clobber: false }); } catch (err) { throw new Error('Could not clone given dir'); } return clonedDir; } } module.exports = FileSystem;
Allow local override of api key and secret.
<?php class ShippingEasy_SignedUrl { public function __construct($http_method=null, $path=null, $params=null, $json_body=null, $api_timestamp=null, $api_secret = null, $api_key = null) { $api_secret = isset($api_secret) ? $api_secret : ShippingEasy::$apiSecret; $params["api_key"] = isset($api_key) ? $api_key : ShippingEasy::$apiKey; $params["api_timestamp"] = isset($api_timestamp) ? $api_timestamp : time(); $signature_object = new ShippingEasy_Signature($api_secret, $http_method, $path, $params, $json_body); $params["api_signature"] = $signature_object->encrypted(); $this->params = $params; $this->path = $path; } public function getParams() { return $this->params; } public function getPath() { return $this->path; } public function toString() { $url = ShippingEasy::$apiBase; $url .= $this->getPath(); $url .= "?" . http_build_query($this->getParams()); return $url; } }
<?php class ShippingEasy_SignedUrl { public function __construct($http_method=null, $path=null, $params=null, $json_body=null, $api_timestamp=null) { $secret = ShippingEasy::$apiSecret; $params["api_key"] = ShippingEasy::$apiKey; $params["api_timestamp"] = isset($api_timestamp) ? $api_timestamp : time(); $signature_object = new ShippingEasy_Signature($secret, $http_method, $path, $params, $json_body); $params["api_signature"] = $signature_object->encrypted(); $this->params = $params; $this->path = $path; } public function getParams() { return $this->params; } public function getPath() { return $this->path; } public function toString() { $url = ShippingEasy::$apiBase; $url .= $this->getPath(); $url .= "?" . http_build_query($this->getParams()); return $url; } }