prompt large_stringlengths 70 991k | completion large_stringlengths 0 1.02k |
|---|---|
<|file_name|>main.py<|end_file_name|><|fim▁begin|>## Adding ./getresults to the Python path so that the modules in folder can be imported
import sys
sys.path.insert(0, './getresults')
import datetime
from flightsearch import flightsearch, flightresult
import os
import uuid
import time
from pprint import pprint
def main():
flyfrom = 'YYZ' #input("Enter departure city or airport code, e.g. Toronto or YYZ:\n")
datefrom = '2017-04-26' #input("Enter departure date and time, e.g. 2017-03-31 12:00:\n")
flyto = 'LHR' #input("Enter arrival city or airport code, e.g. London or LHR:\n")
dateto = '2017-05-26' #input("Enter arrival date and time, e.g. 2017-03-31 20:00:\n")
<|fim▁hole|>
search = flightsearch(searchuuid = searchuuid, searchbegintime = searchbegintime, flyfrom = flyfrom,
datefrom = datefrom, flyto = flyto, dateto = dateto)
results = aggregatedflights(search)
search.searchendtime = time.time()
for key, value in results.items():
for item in value:
pprint(vars(item))
## This function aggegates the various results obtained from the modules in the ./getresults folder
def aggregatedflights(flightsearch):
getresultsdir = './getresults'
resultdict = {}
for filename in os.listdir(getresultsdir):
if filename.startswith("get") and filename.endswith(".py"):
modulename = filename.split('.')[0]
mod = __import__(modulename)
resultdict[modulename] = mod.getresult(flightsearch)
else:
continue
return sortbyprice(resultdict)
def sortbyprice(flightresult):
## Coming soon
return flightresult
if __name__ == '__main__':
main()<|fim▁end|> | searchuuid = uuid.uuid4()
searchbegintime = time.time() |
<|file_name|>0039_auto__add_field_course_riw_style.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Course.riw_style'
db.add_column(u'core_course', 'riw_style',
self.gf('django.db.models.fields.BooleanField')(default=False),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Course.riw_style'
db.delete_column(u'core_course', 'riw_style')
models = {
u'accounts.city': {
'Meta': {'object_name': 'City'},
'code': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '80'}),
'uf': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounts.State']"})
},
u'accounts.discipline': {
'Meta': {'object_name': 'Discipline'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'visible': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
u'accounts.educationlevel': {
'Meta': {'object_name': 'EducationLevel'},
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '3', 'primary_key': 'True'})
},
u'accounts.occupation': {
'Meta': {'object_name': 'Occupation'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'accounts.school': {
'Meta': {'object_name': 'School'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'school_type': ('django.db.models.fields.CharField', [], {'max_length': '2'})
},
u'accounts.state': {
'Meta': {'object_name': 'State'},
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'uf': ('django.db.models.fields.CharField', [], {'max_length': '2', 'primary_key': 'True'}),
'uf_code': ('django.db.models.fields.CharField', [], {'max_length': '5'})
},
u'accounts.timtecuser': {
'Meta': {'object_name': 'TimtecUser'},
'accepted_terms': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'biography': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'business_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
'city': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounts.City']", 'null': 'True', 'blank': 'True'}),
'cpf': ('django.db.models.fields.CharField', [], {'max_length': '14', 'null': 'True', 'blank': 'True'}),
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'disciplines': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['accounts.Discipline']", 'null': 'True', 'blank': 'True'}),
'education_levels': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['accounts.EducationLevel']", 'null': 'True', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '75'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '60', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '60', 'blank': 'True'}),
'occupation': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'occupations': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['accounts.Occupation']", 'null': 'True', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'phone': ('django.db.models.fields.CharField', [], {'max_length': '15', 'null': 'True', 'blank': 'True'}),
'picture': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'rg': ('django.db.models.fields.CharField', [], {'max_length': '12', 'null': 'True', 'blank': 'True'}),
'schools': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['accounts.School']", 'null': 'True', 'through': u"orm['accounts.TimtecUserSchool']", 'blank': 'True'}),
'site': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'})
},
u'accounts.timtecuserschool': {
'Meta': {'object_name': 'TimtecUserSchool'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'professor': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounts.TimtecUser']"}),
'school': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounts.School']"})
},
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'core.class': {
'Meta': {'object_name': 'Class'},
'assistant': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'professor_classes'", 'null': 'True', 'to': u"orm['accounts.TimtecUser']"}),
'course': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['core.Course']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'students': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'classes'", 'blank': 'True', 'to': u"orm['accounts.TimtecUser']"})
},
u'core.course': {
'Meta': {'object_name': 'Course'},
'abstract': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'application': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'authors': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'authorcourses'", 'symmetrical': 'False', 'through': u"orm['core.CourseAuthor']", 'to': u"orm['accounts.TimtecUser']"}),
'complete_profile': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'default_class': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'default_course'", 'unique': 'True', 'null': 'True', 'to': u"orm['core.Class']"}),
'home_position': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'home_published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'home_thumbnail': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'intro_text': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'intro_video': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['core.Video']", 'null': 'True', 'blank': 'True'}),
'left_tag': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'modal_text': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'payment_url': ('django.db.models.fields.TextField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'private': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'professors': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'professorcourse_set'", 'symmetrical': 'False', 'through': u"orm['core.CourseProfessor']", 'to': u"orm['accounts.TimtecUser']"}),
'pronatec': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'requirement': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'right_tag': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'riw_style': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '255'}),
'start_date': ('django.db.models.fields.DateField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.CharField', [], {'default': "'draft'", 'max_length': '64'}),
'structure': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'students': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'studentcourse_set'", 'symmetrical': 'False', 'through': u"orm['core.CourseStudent']", 'to': u"orm['accounts.TimtecUser']"}),
'subscribe_date_limit': ('django.db.models.fields.DateField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'thumbnail': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'tuition': ('django.db.models.fields.DecimalField', [], {'default': '0.0', 'max_digits': '9', 'decimal_places': '2'}),
'workload': ('django.db.models.fields.TextField', [], {'blank': 'True'})
},
u'core.courseauthor': {
'Meta': {'ordering': "['position']", 'unique_together': "(('user', 'course'),)", 'object_name': 'CourseAuthor'},
'biography': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'course': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'course_authors'", 'to': u"orm['core.Course']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.TextField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}),
'picture': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),<|fim▁hole|> 'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'authoring_courses'", 'null': 'True', 'to': u"orm['accounts.TimtecUser']"})
},
u'core.courseprofessor': {
'Meta': {'unique_together': "(('user', 'course'),)", 'object_name': 'CourseProfessor'},
'biography': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'course': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'course_professors'", 'to': u"orm['core.Course']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_course_author': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'name': ('django.db.models.fields.TextField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}),
'picture': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'role': ('django.db.models.fields.CharField', [], {'default': "'assistant'", 'max_length': '128'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'teaching_courses'", 'null': 'True', 'to': u"orm['accounts.TimtecUser']"})
},
u'core.coursestudent': {
'Meta': {'ordering': "['course__start_date']", 'unique_together': "(('user', 'course'),)", 'object_name': 'CourseStudent'},
'course': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['core.Course']"}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'status': ('django.db.models.fields.CharField', [], {'default': "'1'", 'max_length': '1'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounts.TimtecUser']"})
},
u'core.emailtemplate': {
'Meta': {'object_name': 'EmailTemplate'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'subject': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'template': ('django.db.models.fields.TextField', [], {})
},
u'core.lesson': {
'Meta': {'ordering': "['position']", 'object_name': 'Lesson'},
'course': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'lessons'", 'to': u"orm['core.Course']"}),
'desc': ('django.db.models.fields.TextField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'notes': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
'position': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'slug': ('autoslug.fields.AutoSlugField', [], {'unique': 'True', 'max_length': '255', 'populate_from': "'name'", 'unique_with': '()'}),
'status': ('django.db.models.fields.CharField', [], {'default': "'draft'", 'max_length': '64'})
},
u'core.professormessage': {
'Meta': {'object_name': 'ProfessorMessage'},
'course': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['core.Course']", 'null': 'True'}),
'date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'message': ('django.db.models.fields.TextField', [], {}),
'professor': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounts.TimtecUser']"}),
'subject': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'users': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'messages'", 'symmetrical': 'False', 'to': u"orm['accounts.TimtecUser']"})
},
u'core.studentprogress': {
'Meta': {'unique_together': "(('user', 'unit'),)", 'object_name': 'StudentProgress'},
'complete': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_access': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'unit': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'progress'", 'to': u"orm['core.Unit']"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounts.TimtecUser']"})
},
u'core.unit': {
'Meta': {'ordering': "['lesson', 'position']", 'object_name': 'Unit'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'lesson': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'units'", 'to': u"orm['core.Lesson']"}),
'position': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'side_notes': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
'video': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'unit'", 'null': 'True', 'to': u"orm['core.Video']"})
},
u'core.video': {
'Meta': {'object_name': 'Video'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'youtube_id': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['core']<|fim▁end|> | 'position': ('django.db.models.fields.IntegerField', [], {'default': '100', 'null': 'True', 'blank': 'True'}), |
<|file_name|>app.component.js<|end_file_name|><|fim▁begin|>"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
<|fim▁hole|> return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var router_1 = require('@angular/router');
var app_service_1 = require("./app-service");
var AppComponent = (function () {
function AppComponent(breadCrumbSvc, _router) {
this.breadCrumbSvc = breadCrumbSvc;
this._router = _router;
this.breadCrumbSvc.setBreadCrumb('Project Dashboard');
}
AppComponent.prototype.navigateHome = function () {
this._router.navigate(['home']);
;
};
AppComponent = __decorate([
core_1.Component({
selector: 'ts-app',
templateUrl: '/app/app-component.html'
}),
__metadata('design:paramtypes', [app_service_1.BreadcrumbService, router_1.Router])
], AppComponent);
return AppComponent;
}());
exports.AppComponent = AppComponent;<|fim▁end|> | |
<|file_name|>fake_cpu_manager.go<|end_file_name|><|fim▁begin|>/*
Copyright 2017 The Kubernetes 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 cpumanager
import (
"k8s.io/api/core/v1"
"k8s.io/klog"
"k8s.io/kubernetes/pkg/kubelet/cm/cpumanager/containermap"
"k8s.io/kubernetes/pkg/kubelet/cm/cpumanager/state"
"k8s.io/kubernetes/pkg/kubelet/cm/topologymanager"
"k8s.io/kubernetes/pkg/kubelet/config"
"k8s.io/kubernetes/pkg/kubelet/status"
)
type fakeManager struct {
state state.State
}
func (m *fakeManager) Start(activePods ActivePodsFunc, sourcesReady config.SourcesReady, podStatusProvider status.PodStatusProvider, containerRuntime runtimeService, initialContainers containermap.ContainerMap) error {
klog.Info("[fake cpumanager] Start()")
return nil
}
func (m *fakeManager) Policy() Policy {
klog.Info("[fake cpumanager] Policy()")
return NewNonePolicy()
}
func (m *fakeManager) Allocate(pod *v1.Pod, container *v1.Container) error {
klog.Infof("[fake cpumanager] Allocate (pod: %s, container: %s", pod.Name, container.Name)
return nil
}
func (m *fakeManager) AddContainer(pod *v1.Pod, container *v1.Container, containerID string) error {
klog.Infof("[fake cpumanager] AddContainer (pod: %s, container: %s, container id: %s)", pod.Name, container.Name, containerID)
return nil<|fim▁hole|> return nil
}
func (m *fakeManager) GetTopologyHints(pod *v1.Pod, container *v1.Container) map[string][]topologymanager.TopologyHint {
klog.Infof("[fake cpumanager] Get Topology Hints")
return map[string][]topologymanager.TopologyHint{}
}
func (m *fakeManager) State() state.Reader {
return m.state
}
// NewFakeManager creates empty/fake cpu manager
func NewFakeManager() Manager {
return &fakeManager{
state: state.NewMemoryState(),
}
}<|fim▁end|> | }
func (m *fakeManager) RemoveContainer(containerID string) error {
klog.Infof("[fake cpumanager] RemoveContainer (container id: %s)", containerID) |
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>#
# Copyright (C) 2014 Tommy Winther
# http://tommy.winther.nu
#
# Modified for FTV Guide (09/2014 onwards)
# by Thomas Geppert [bluezed] - bluezed.apps@gmail.com
#
# This Program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This Program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this Program; see the file LICENSE.txt. If not, write to
# the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
# http://www.gnu.org/copyleft/gpl.html
#
import datetime
import json
import os
import threading
import time
import xbmc
import xbmcgui
import source as src
from notification import Notification
from strings import *
import streaming
from utils import reset_playing
DEBUG = False
MODE_EPG = 'EPG'
MODE_TV = 'TV'
MODE_OSD = 'OSD'
ACTION_LEFT = 1
ACTION_RIGHT = 2
ACTION_UP = 3
ACTION_DOWN = 4
ACTION_PAGE_UP = 5
ACTION_PAGE_DOWN = 6
ACTION_SELECT_ITEM = 7
ACTION_PARENT_DIR = 9
ACTION_PREVIOUS_MENU = 10
ACTION_SHOW_INFO = 11
ACTION_NEXT_ITEM = 14
ACTION_PREV_ITEM = 15
ACTION_MOUSE_WHEEL_UP = 104
ACTION_MOUSE_WHEEL_DOWN = 105
ACTION_MOUSE_MOVE = 107
KEY_NAV_BACK = 92
KEY_CONTEXT_MENU = 117
KEY_HOME = 159
KEY_ESC = 61467
CHANNELS_PER_PAGE = 8
HALF_HOUR = datetime.timedelta(minutes=30)
SKIN = ADDON.getSetting('skin')
def debug(s):
if DEBUG: xbmc.log(str(s), xbmc.LOGDEBUG)
class Point(object):
def __init__(self):
self.x = self.y = 0
def __repr__(self):
return 'Point(x=%d, y=%d)' % (self.x, self.y)
class EPGView(object):
def __init__(self):
self.top = self.left = self.right = self.bottom = self.width = self.cellHeight = 0
class ControlAndProgram(object):
def __init__(self, control, program):
self.control = control
self.program = program
class TVGuide(xbmcgui.WindowXML):
C_MAIN_DATE_LONG = 3999
C_MAIN_DATE = 4000
C_MAIN_TITLE = 4020
C_MAIN_TIME = 4021
C_MAIN_DESCRIPTION = 4022
C_MAIN_IMAGE = 4023
C_MAIN_LOGO = 4024
C_MAIN_TIMEBAR = 4100
C_MAIN_LOADING = 4200
C_MAIN_LOADING_PROGRESS = 4201
C_MAIN_LOADING_TIME_LEFT = 4202
C_MAIN_LOADING_CANCEL = 4203
C_MAIN_MOUSE_CONTROLS = 4300
C_MAIN_MOUSE_HOME = 4301
C_MAIN_MOUSE_LEFT = 4302
C_MAIN_MOUSE_UP = 4303
C_MAIN_MOUSE_DOWN = 4304
C_MAIN_MOUSE_RIGHT = 4305
C_MAIN_MOUSE_EXIT = 4306
C_MAIN_BACKGROUND = 4600
C_MAIN_EPG = 5000
C_MAIN_EPG_VIEW_MARKER = 5001
C_MAIN_OSD = 6000
C_MAIN_OSD_TITLE = 6001
C_MAIN_OSD_TIME = 6002
C_MAIN_OSD_DESCRIPTION = 6003
C_MAIN_OSD_CHANNEL_LOGO = 6004
C_MAIN_OSD_CHANNEL_TITLE = 6005
def __new__(cls):
return super(TVGuide, cls).__new__(cls, 'script-tvguide-main.xml', ADDON.getAddonInfo('path'), SKIN)
def __init__(self):
super(TVGuide, self).__init__()
self.notification = None
self.redrawingEPG = False
self.isClosing = False
self.controlAndProgramList = list()
self.ignoreMissingControlIds = list()
self.channelIdx = 0
self.focusPoint = Point()
self.epgView = EPGView()
self.streamingService = streaming.StreamsService(ADDON)
self.player = xbmc.Player()
self.database = None
self.proc_file = xbmc.translatePath(os.path.join(ADDON.getAddonInfo('profile'), 'proc'))
if not os.path.exists(self.proc_file):
self.reset_playing()
self.mode = MODE_EPG
self.currentChannel = None
self.osdEnabled = ADDON.getSetting('enable.osd') == 'true' and ADDON.getSetting(
'alternative.playback') != 'true'
self.alternativePlayback = ADDON.getSetting('alternative.playback') == 'true'
self.osdChannel = None
self.osdProgram = None
# find nearest half hour
self.viewStartDate = datetime.datetime.today()
self.viewStartDate -= datetime.timedelta(minutes=self.viewStartDate.minute % 30,
seconds=self.viewStartDate.second)
def getControl(self, controlId):
try:
return super(TVGuide, self).getControl(controlId)
except:
if controlId in self.ignoreMissingControlIds:
return None
if not self.isClosing:
self.close()
return None
def close(self):
if not self.isClosing:
self.isClosing = True
if self.player.isPlaying():
if ADDON.getSetting('background.stream') == 'false':
self.reset_playing()
self.player.stop()
if self.database:
self.database.close(super(TVGuide, self).close)
else:
super(TVGuide, self).close()
def onInit(self):
is_playing, play_data = self.check_is_playing()
self._hideControl(self.C_MAIN_MOUSE_CONTROLS, self.C_MAIN_OSD)
self._showControl(self.C_MAIN_EPG, self.C_MAIN_LOADING)
self.setControlLabel(self.C_MAIN_LOADING_TIME_LEFT, strings(BACKGROUND_UPDATE_IN_PROGRESS))
self.setFocusId(self.C_MAIN_LOADING_CANCEL)
control = self.getControl(self.C_MAIN_EPG_VIEW_MARKER)
if control:
left, top = control.getPosition()
self.focusPoint.x = left
self.focusPoint.y = top
self.epgView.left = left
self.epgView.top = top
self.epgView.right = left + control.getWidth()
self.epgView.bottom = top + control.getHeight()
self.epgView.width = control.getWidth()
self.epgView.cellHeight = control.getHeight() / CHANNELS_PER_PAGE
if is_playing and 'idx' in play_data:
self.viewStartDate = datetime.datetime.today()
self.viewStartDate -= datetime.timedelta(minutes=self.viewStartDate.minute % 30,
seconds=self.viewStartDate.second)
self.channelIdx = play_data['idx']
if self.database and 'y' in play_data:
self.focusPoint.y = play_data['y']
self.onRedrawEPG(self.channelIdx, self.viewStartDate,
focusFunction=self._findCurrentTimeslot)
elif self.database:
self.onRedrawEPG(self.channelIdx, self.viewStartDate)
else:
try:
self.database = src.Database()
except src.SourceNotConfiguredException:
self.onSourceNotConfigured()
self.close()
return
self.database.initialize(self.onSourceInitialized,
self.isSourceInitializationCancelled)
self.updateTimebar()
def onAction(self, action):
debug('Mode is: %s' % self.mode)
if self.mode == MODE_TV:
self.onActionTVMode(action)
elif self.mode == MODE_OSD:
self.onActionOSDMode(action)
elif self.mode == MODE_EPG:
self.onActionEPGMode(action)
def onActionTVMode(self, action):
if action.getId() == ACTION_PAGE_UP:
self._channelUp()
elif action.getId() == ACTION_PAGE_DOWN:
self._channelDown()
elif not self.osdEnabled:
pass # skip the rest of the actions
elif action.getId() in [ACTION_PARENT_DIR, KEY_NAV_BACK, KEY_CONTEXT_MENU, ACTION_PREVIOUS_MENU]:
self.onRedrawEPG(self.channelIdx, self.viewStartDate)
elif action.getId() == ACTION_SHOW_INFO:
self._showOsd()
def onActionOSDMode(self, action):
if action.getId() == ACTION_SHOW_INFO:
self._hideOsd()
elif action.getId() in [ACTION_PARENT_DIR, KEY_NAV_BACK, KEY_CONTEXT_MENU, ACTION_PREVIOUS_MENU]:
self._hideOsd()
self.onRedrawEPG(self.channelIdx, self.viewStartDate)
elif action.getId() == ACTION_SELECT_ITEM:
if self.playChannel(self.osdChannel, self.osdProgram):
self._hideOsd()
elif action.getId() == ACTION_PAGE_UP:
self._channelUp()
self._showOsd()
elif action.getId() == ACTION_PAGE_DOWN:
self._channelDown()
self._showOsd()
elif action.getId() == ACTION_UP:
self.osdChannel = self.database.getPreviousChannel(self.osdChannel)
self.osdProgram = self.database.getCurrentProgram(self.osdChannel)
self._showOsd()
elif action.getId() == ACTION_DOWN:
self.osdChannel = self.database.getNextChannel(self.osdChannel)
self.osdProgram = self.database.getCurrentProgram(self.osdChannel)
self._showOsd()
elif action.getId() == ACTION_LEFT:
previousProgram = self.database.getPreviousProgram(self.osdProgram)
if previousProgram:
self.osdProgram = previousProgram
self._showOsd()
elif action.getId() == ACTION_RIGHT:
nextProgram = self.database.getNextProgram(self.osdProgram)
if nextProgram:
self.osdProgram = nextProgram
self._showOsd()
def onActionEPGMode(self, action):
if action.getId() in [ACTION_PARENT_DIR, KEY_NAV_BACK]:
self.close()
return
# catch the ESC key
elif action.getId() == ACTION_PREVIOUS_MENU and action.getButtonCode() == KEY_ESC:
self.close()
return
elif action.getId() == ACTION_MOUSE_MOVE:
self._showControl(self.C_MAIN_MOUSE_CONTROLS)
return
elif action.getId() == KEY_CONTEXT_MENU:
if self.player.isPlaying():
self._hideEpg()
controlInFocus = None
currentFocus = self.focusPoint
try:
controlInFocus = self.getFocus()
if controlInFocus in [elem.control for elem in self.controlAndProgramList]:
(left, top) = controlInFocus.getPosition()
currentFocus = Point()
currentFocus.x = left + (controlInFocus.getWidth() / 2)
currentFocus.y = top + (controlInFocus.getHeight() / 2)
except Exception:
control = self._findControlAt(self.focusPoint)
if control is None and len(self.controlAndProgramList) > 0:
control = self.controlAndProgramList[0].control
if control is not None:
self.setFocus(control)
return
if action.getId() == ACTION_LEFT:
self._left(currentFocus)
elif action.getId() == ACTION_RIGHT:
self._right(currentFocus)
elif action.getId() == ACTION_UP:
self._up(currentFocus)
elif action.getId() == ACTION_DOWN:
self._down(currentFocus)
elif action.getId() == ACTION_NEXT_ITEM:
self._nextDay()
elif action.getId() == ACTION_PREV_ITEM:
self._previousDay()
elif action.getId() == ACTION_PAGE_UP:
self._moveUp(CHANNELS_PER_PAGE)
elif action.getId() == ACTION_PAGE_DOWN:
self._moveDown(CHANNELS_PER_PAGE)
elif action.getId() == ACTION_MOUSE_WHEEL_UP:
self._moveUp(scrollEvent=True)
elif action.getId() == ACTION_MOUSE_WHEEL_DOWN:
self._moveDown(scrollEvent=True)
elif action.getId() == KEY_HOME:
self.viewStartDate = datetime.datetime.today()
self.viewStartDate -= datetime.timedelta(minutes=self.viewStartDate.minute % 30,
seconds=self.viewStartDate.second)
self.onRedrawEPG(self.channelIdx, self.viewStartDate)
elif action.getId() in [KEY_CONTEXT_MENU, ACTION_PREVIOUS_MENU] and controlInFocus is not None:
program = self._getProgramFromControl(controlInFocus)
if program is not None:
self._showContextMenu(program)
else:
xbmc.log('[script.ftvguide] Unhandled ActionId: ' + str(action.getId()), xbmc.LOGDEBUG)
def onClick(self, controlId):
if controlId in [self.C_MAIN_LOADING_CANCEL, self.C_MAIN_MOUSE_EXIT]:
self.close()
return
if self.isClosing:
return
if controlId == self.C_MAIN_MOUSE_HOME:
self.viewStartDate = datetime.datetime.today()
self.viewStartDate -= datetime.timedelta(minutes=self.viewStartDate.minute % 30,
seconds=self.viewStartDate.second)
self.onRedrawEPG(self.channelIdx, self.viewStartDate)
return
elif controlId == self.C_MAIN_MOUSE_LEFT:
self.viewStartDate -= datetime.timedelta(hours=2)
self.onRedrawEPG(self.channelIdx, self.viewStartDate)
return
elif controlId == self.C_MAIN_MOUSE_UP:
self._moveUp(count=CHANNELS_PER_PAGE)
return
elif controlId == self.C_MAIN_MOUSE_DOWN:
self._moveDown(count=CHANNELS_PER_PAGE)
return
elif controlId == self.C_MAIN_MOUSE_RIGHT:
self.viewStartDate += datetime.timedelta(hours=2)
self.onRedrawEPG(self.channelIdx, self.viewStartDate)
return
program = self._getProgramFromControl(self.getControl(controlId))
if program is None:
return
if not self.playChannel(program.channel, program):
result = self.streamingService.detectStream(program.channel)
if not result:
# could not detect stream, show context menu
self._showContextMenu(program)
elif type(result) == str:
# one single stream detected, save it and start streaming
self.database.setCustomStreamUrl(program.channel, result)
self.playChannel(program.channel, program)
else:
# multiple matches, let user decide
d = ChooseStreamAddonDialog(result)
d.doModal()
if d.stream is not None:
self.database.setCustomStreamUrl(program.channel, d.stream)
self.playChannel(program.channel, program)
def _showContextMenu(self, program):
self._hideControl(self.C_MAIN_MOUSE_CONTROLS)
d = PopupMenu(self.database, program, not program.notificationScheduled)
d.doModal()
buttonClicked = d.buttonClicked
del d
if buttonClicked == PopupMenu.C_POPUP_REMIND:
if program.notificationScheduled:
self.notification.removeNotification(program)
else:
self.notification.addNotification(program)
self.onRedrawEPG(self.channelIdx, self.viewStartDate)
elif buttonClicked == PopupMenu.C_POPUP_CHOOSE_STREAM:
d = StreamSetupDialog(self.database, program.channel)
d.doModal()
del d
elif buttonClicked == PopupMenu.C_POPUP_PLAY:
self.playChannel(program.channel, program)
elif buttonClicked == PopupMenu.C_POPUP_CHANNELS:
d = ChannelsMenu(self.database)
d.doModal()
del d
self.onRedrawEPG(self.channelIdx, self.viewStartDate)
elif buttonClicked == PopupMenu.C_POPUP_QUIT:
self.close()
elif buttonClicked == PopupMenu.C_POPUP_LIBMOV:
xbmc.executebuiltin('ActivateWindow(Videos,videodb://movies/titles/)')
elif buttonClicked == PopupMenu.C_POPUP_LIBTV:
xbmc.executebuiltin('ActivateWindow(Videos,videodb://tvshows/titles/)')
elif buttonClicked == PopupMenu.C_POPUP_VIDEOADDONS:
xbmc.executebuiltin('ActivateWindow(Videos,addons://sources/video/)')
elif buttonClicked == PopupMenu.C_POPUP_PLAY_BEGINNING:
title = program.title.replace(" ", "%20").replace(",", "").replace(u"\u2013", "-")
title = unicode.encode(title, "ascii", "ignore")
if program.is_movie == "Movie":
selection = 0
elif program.season is not None:
selection = 1
else:
selection = xbmcgui.Dialog().select("Choose media type", ["Search as Movie", "Search as TV Show"])
if selection == 0:
xbmc.executebuiltin("RunPlugin(plugin://plugin.video.meta/movies/play_by_name/%s/%s)" % (
title, program.language))
elif selection == 1:
if program.season and program.episode:
xbmc.executebuiltin("RunPlugin(plugin://plugin.video.meta/tv/play_by_name/%s/%s/%s/%s)" % (
title, program.season, program.episode, program.language))
else:
xbmc.executebuiltin("RunPlugin(plugin://plugin.video.meta/tv/play_by_name_only/%s/%s)" % (
title, program.language))
def setFocusId(self, controlId):
control = self.getControl(controlId)
if control:
self.setFocus(control)
def setFocus(self, control):
<|fim▁hole|> if control in [elem.control for elem in self.controlAndProgramList]:
debug('Focus before %s' % self.focusPoint)
(left, top) = control.getPosition()
if left > self.focusPoint.x or left + control.getWidth() < self.focusPoint.x:
self.focusPoint.x = left
self.focusPoint.y = top + (control.getHeight() / 2)
debug('New focus at %s' % self.focusPoint)
super(TVGuide, self).setFocus(control)
def onFocus(self, controlId):
try:
controlInFocus = self.getControl(controlId)
except Exception:
return
program = self._getProgramFromControl(controlInFocus)
if program is None:
return
title = '[B]%s[/B]' % program.title
if program.season is not None and program.episode is not None:
title += " [B]S%sE%s[/B]" % (program.season, program.episode)
if program.is_movie == "Movie":
title += " [B](Movie)[/B]"
self.setControlLabel(self.C_MAIN_TITLE, title)
if program.startDate or program.endDate:
self.setControlLabel(self.C_MAIN_TIME,
'[B]%s - %s[/B]' % (
self.formatTime(program.startDate), self.formatTime(program.endDate)))
else:
self.setControlLabel(self.C_MAIN_TIME, '')
if program.description:
description = program.description
else:
description = strings(NO_DESCRIPTION)
self.setControlText(self.C_MAIN_DESCRIPTION, description)
if program.channel.logo is not None:
self.setControlImage(self.C_MAIN_LOGO, program.channel.logo)
else:
self.setControlImage(self.C_MAIN_LOGO, '')
if program.imageSmall is not None:
self.setControlImage(self.C_MAIN_IMAGE, program.imageSmall)
else:
self.setControlImage(self.C_MAIN_IMAGE, 'tvguide-logo-epg.png')
if ADDON.getSetting('program.background.enabled') == 'true' and program.imageLarge is not None:
self.setControlImage(self.C_MAIN_BACKGROUND, program.imageLarge)
if self.player.isPlaying() and not self.osdEnabled and \
ADDON.getSetting('background.stream') == 'false':
self.reset_playing()
self.player.stop()
def _left(self, currentFocus):
control = self._findControlOnLeft(currentFocus)
if control is not None:
self.setFocus(control)
elif control is None:
self.viewStartDate -= datetime.timedelta(hours=2)
self.focusPoint.x = self.epgView.right
self.onRedrawEPG(self.channelIdx, self.viewStartDate, focusFunction=self._findControlOnLeft)
def _right(self, currentFocus):
control = self._findControlOnRight(currentFocus)
if control is not None:
self.setFocus(control)
elif control is None:
self.viewStartDate += datetime.timedelta(hours=2)
self.focusPoint.x = self.epgView.left
self.onRedrawEPG(self.channelIdx, self.viewStartDate, focusFunction=self._findControlOnRight)
def _up(self, currentFocus):
currentFocus.x = self.focusPoint.x
control = self._findControlAbove(currentFocus)
if control is not None:
self.setFocus(control)
elif control is None:
self.focusPoint.y = self.epgView.bottom
self.onRedrawEPG(self.channelIdx - CHANNELS_PER_PAGE, self.viewStartDate,
focusFunction=self._findControlAbove)
def _down(self, currentFocus):
currentFocus.x = self.focusPoint.x
control = self._findControlBelow(currentFocus)
if control is not None:
self.setFocus(control)
elif control is None:
self.focusPoint.y = self.epgView.top
self.onRedrawEPG(self.channelIdx + CHANNELS_PER_PAGE, self.viewStartDate,
focusFunction=self._findControlBelow)
def _nextDay(self):
self.viewStartDate += datetime.timedelta(days=1)
self.onRedrawEPG(self.channelIdx, self.viewStartDate)
def _previousDay(self):
self.viewStartDate -= datetime.timedelta(days=1)
self.onRedrawEPG(self.channelIdx, self.viewStartDate)
def _moveUp(self, count=1, scrollEvent=False):
if scrollEvent:
self.onRedrawEPG(self.channelIdx - count, self.viewStartDate)
else:
self.focusPoint.y = self.epgView.bottom
self.onRedrawEPG(self.channelIdx - count, self.viewStartDate, focusFunction=self._findControlAbove)
def _moveDown(self, count=1, scrollEvent=False):
if scrollEvent:
self.onRedrawEPG(self.channelIdx + count, self.viewStartDate)
else:
self.focusPoint.y = self.epgView.top
self.onRedrawEPG(self.channelIdx + count, self.viewStartDate, focusFunction=self._findControlBelow)
def _channelUp(self):
channel = self.database.getNextChannel(self.currentChannel)
program = self.database.getCurrentProgram(channel)
self.playChannel(channel, program)
def _channelDown(self):
channel = self.database.getPreviousChannel(self.currentChannel)
program = self.database.getCurrentProgram(channel)
self.playChannel(channel, program)
def playChannel(self, channel, program=None):
self.currentChannel = channel
wasPlaying = self.player.isPlaying()
url = self.database.getStreamUrl(channel)
if url:
self.set_playing()
if str.startswith(url, "plugin://plugin.video.meta") and program is not None:
import urllib
title = urllib.quote(program.title)
url += "/%s/%s" % (title, program.language)
if url[0:9] == 'plugin://':
if self.alternativePlayback:
xbmc.executebuiltin('XBMC.RunPlugin(%s)' % url)
elif self.osdEnabled:
xbmc.executebuiltin('PlayMedia(%s,1)' % url)
else:
xbmc.executebuiltin('PlayMedia(%s)' % url)
else:
self.player.play(item=url, windowed=self.osdEnabled)
if not wasPlaying:
self._hideEpg()
threading.Timer(1, self.waitForPlayBackStopped).start()
self.osdProgram = self.database.getCurrentProgram(self.currentChannel)
return url is not None
def waitForPlayBackStopped(self):
for retry in range(0, 100):
time.sleep(0.1)
if self.player.isPlaying():
break
while self.player.isPlaying() and not xbmc.abortRequested and not self.isClosing:
time.sleep(0.5)
self.onPlayBackStopped()
def _showOsd(self):
if not self.osdEnabled:
return
if self.mode != MODE_OSD:
self.osdChannel = self.currentChannel
if self.osdProgram is not None:
self.setControlLabel(self.C_MAIN_OSD_TITLE, '[B]%s[/B]' % self.osdProgram.title)
if self.osdProgram.startDate or self.osdProgram.endDate:
self.setControlLabel(self.C_MAIN_OSD_TIME, '[B]%s - %s[/B]' % (
self.formatTime(self.osdProgram.startDate), self.formatTime(self.osdProgram.endDate)))
else:
self.setControlLabel(self.C_MAIN_OSD_TIME, '')
self.setControlText(self.C_MAIN_OSD_DESCRIPTION, self.osdProgram.description)
self.setControlLabel(self.C_MAIN_OSD_CHANNEL_TITLE, self.osdChannel.title)
if self.osdProgram.channel.logo is not None:
self.setControlImage(self.C_MAIN_OSD_CHANNEL_LOGO, self.osdProgram.channel.logo)
else:
self.setControlImage(self.C_MAIN_OSD_CHANNEL_LOGO, '')
self.mode = MODE_OSD
self._showControl(self.C_MAIN_OSD)
def _hideOsd(self):
self.mode = MODE_TV
self._hideControl(self.C_MAIN_OSD)
def _hideEpg(self):
self._hideControl(self.C_MAIN_EPG)
self.mode = MODE_TV
self._clearEpg()
def onRedrawEPG(self, channelStart, startTime, focusFunction=None):
if self.redrawingEPG or (self.database is not None and self.database.updateInProgress) or self.isClosing:
debug('onRedrawEPG - already redrawing')
return # ignore redraw request while redrawing
debug('onRedrawEPG')
self.redrawingEPG = True
self.mode = MODE_EPG
self._showControl(self.C_MAIN_EPG)
self.updateTimebar(scheduleTimer=False)
# show Loading screen
self.setControlLabel(self.C_MAIN_LOADING_TIME_LEFT, strings(CALCULATING_REMAINING_TIME))
self._showControl(self.C_MAIN_LOADING)
self.setFocusId(self.C_MAIN_LOADING_CANCEL)
# remove existing controls
self._clearEpg()
try:
self.channelIdx, channels, programs = self.database.getEPGView(channelStart, startTime,
self.onSourceProgressUpdate,
clearExistingProgramList=False)
except src.SourceException:
self.onEPGLoadError()
return
channelsWithoutPrograms = list(channels)
# date and time row
self.setControlLabel(self.C_MAIN_DATE, self.formatDate(self.viewStartDate, False))
self.setControlLabel(self.C_MAIN_DATE_LONG, self.formatDate(self.viewStartDate, True))
for col in range(1, 5):
self.setControlLabel(4000 + col, self.formatTime(startTime))
startTime += HALF_HOUR
if programs is None:
self.onEPGLoadError()
return
# set channel logo or text
showLogo = ADDON.getSetting('logos.enabled') == 'true'
for idx in range(0, CHANNELS_PER_PAGE):
if idx >= len(channels):
self.setControlImage(4110 + idx, ' ')
self.setControlLabel(4010 + idx, ' ')
else:
channel = channels[idx]
self.setControlLabel(4010 + idx, channel.title)
if (channel.logo is not None and showLogo == True):
self.setControlImage(4110 + idx, channel.logo)
else:
self.setControlImage(4110 + idx, ' ')
for program in programs:
idx = channels.index(program.channel)
if program.channel in channelsWithoutPrograms:
channelsWithoutPrograms.remove(program.channel)
startDelta = program.startDate - self.viewStartDate
stopDelta = program.endDate - self.viewStartDate
cellStart = self._secondsToXposition(startDelta.seconds)
if startDelta.days < 0:
cellStart = self.epgView.left
cellWidth = self._secondsToXposition(stopDelta.seconds) - cellStart
if cellStart + cellWidth > self.epgView.right:
cellWidth = self.epgView.right - cellStart
if cellWidth > 1:
if program.notificationScheduled:
noFocusTexture = 'tvguide-program-red.png'
focusTexture = 'tvguide-program-red-focus.png'
else:
noFocusTexture = 'tvguide-program-grey.png'
focusTexture = 'tvguide-program-grey-focus.png'
if cellWidth < 25:
title = '' # Text will overflow outside the button if it is too narrow
else:
title = program.title
control = xbmcgui.ControlButton(
cellStart,
self.epgView.top + self.epgView.cellHeight * idx,
cellWidth - 2,
self.epgView.cellHeight - 2,
title,
noFocusTexture=noFocusTexture,
focusTexture=focusTexture
)
self.controlAndProgramList.append(ControlAndProgram(control, program))
for channel in channelsWithoutPrograms:
idx = channels.index(channel)
control = xbmcgui.ControlButton(
self.epgView.left,
self.epgView.top + self.epgView.cellHeight * idx,
(self.epgView.right - self.epgView.left) - 2,
self.epgView.cellHeight - 2,
strings(NO_PROGRAM_AVAILABLE),
noFocusTexture='tvguide-program-grey.png',
focusTexture='tvguide-program-grey-focus.png'
)
program = src.Program(channel, strings(NO_PROGRAM_AVAILABLE), None, None, None)
self.controlAndProgramList.append(ControlAndProgram(control, program))
# add program controls
if focusFunction is None:
focusFunction = self._findControlAt
focusControl = focusFunction(self.focusPoint)
controls = [elem.control for elem in self.controlAndProgramList]
self.addControls(controls)
if focusControl is not None:
debug('onRedrawEPG - setFocus %d' % focusControl.getId())
self.setFocus(focusControl)
self.ignoreMissingControlIds.extend([elem.control.getId() for elem in self.controlAndProgramList])
if focusControl is None and len(self.controlAndProgramList) > 0:
self.setFocus(self.controlAndProgramList[0].control)
self._hideControl(self.C_MAIN_LOADING)
self.redrawingEPG = False
def _clearEpg(self):
controls = [elem.control for elem in self.controlAndProgramList]
try:
self.removeControls(controls)
except RuntimeError:
for elem in self.controlAndProgramList:
try:
self.removeControl(elem.control)
except RuntimeError:
pass # happens if we try to remove a control that doesn't exist
del self.controlAndProgramList[:]
def onEPGLoadError(self):
self.redrawingEPG = False
self._hideControl(self.C_MAIN_LOADING)
xbmcgui.Dialog().ok(strings(LOAD_ERROR_TITLE), strings(LOAD_ERROR_LINE1), strings(LOAD_ERROR_LINE2))
self.close()
def onSourceNotConfigured(self):
self.redrawingEPG = False
self._hideControl(self.C_MAIN_LOADING)
xbmcgui.Dialog().ok(strings(LOAD_ERROR_TITLE), strings(LOAD_ERROR_LINE1), strings(CONFIGURATION_ERROR_LINE2))
self.close()
def isSourceInitializationCancelled(self):
return xbmc.abortRequested or self.isClosing
def onSourceInitialized(self, success):
if success:
self.notification = Notification(self.database, ADDON.getAddonInfo('path'))
self.onRedrawEPG(0, self.viewStartDate)
def onSourceProgressUpdate(self, percentageComplete):
control = self.getControl(self.C_MAIN_LOADING_PROGRESS)
if percentageComplete < 1:
if control:
control.setPercent(1)
self.progressStartTime = datetime.datetime.now()
self.progressPreviousPercentage = percentageComplete
elif percentageComplete != self.progressPreviousPercentage:
if control:
control.setPercent(percentageComplete)
self.progressPreviousPercentage = percentageComplete
delta = datetime.datetime.now() - self.progressStartTime
if percentageComplete < 20:
self.setControlLabel(self.C_MAIN_LOADING_TIME_LEFT, strings(CALCULATING_REMAINING_TIME))
else:
secondsLeft = int(delta.seconds) / float(percentageComplete) * (100.0 - percentageComplete)
if secondsLeft > 30:
secondsLeft -= secondsLeft % 10
self.setControlLabel(self.C_MAIN_LOADING_TIME_LEFT, strings(TIME_LEFT) % secondsLeft)
return not xbmc.abortRequested and not self.isClosing
def check_is_playing(self):
is_playing = self.player.isPlaying()
play_data = {}
if not self.isClosing:
f = open(self.proc_file, 'r')
data = f.read()
if len(data) > 0:
is_playing = True
play_data = json.loads(data)
f.close()
debug('[%s] Checking Play-State... is_playing: %s, data: %s '
% (ADDON.getAddonInfo('id'), str(is_playing), str(play_data)))
return is_playing, play_data
def set_playing(self):
f = open(self.proc_file, 'w')
data = {'timestamp': datetime.datetime.now().strftime('%Y%m%d%H%M%S'),
'y': self.focusPoint.y, 'idx': self.channelIdx}
f.write(json.dumps(data))
f.close()
def reset_playing(self):
reset_playing()
def onPlayBackStopped(self):
if not self.player.isPlaying() and not self.isClosing:
is_playing, play_data = self.check_is_playing()
self._hideControl(self.C_MAIN_OSD)
self.viewStartDate = datetime.datetime.today()
self.viewStartDate -= datetime.timedelta(minutes=self.viewStartDate.minute % 30,
seconds=self.viewStartDate.second)
if is_playing and 'idx' in play_data:
self.viewStartDate = datetime.datetime.today()
self.viewStartDate -= datetime.timedelta(minutes=self.viewStartDate.minute % 30,
seconds=self.viewStartDate.second)
self.channelIdx = play_data['idx']
if self.database and 'y' in play_data:
self.focusPoint.y = play_data['y']
self.onRedrawEPG(self.channelIdx, self.viewStartDate,
focusFunction=self._findCurrentTimeslot)
self.reset_playing()
def _secondsToXposition(self, seconds):
return self.epgView.left + (seconds * self.epgView.width / 7200)
def _findControlOnRight(self, point):
distanceToNearest = 10000
nearestControl = None
for elem in self.controlAndProgramList:
control = elem.control
(left, top) = control.getPosition()
x = left + (control.getWidth() / 2)
y = top + (control.getHeight() / 2)
if point.x < x and point.y == y:
distance = abs(point.x - x)
if distance < distanceToNearest:
distanceToNearest = distance
nearestControl = control
return nearestControl
def _findControlOnLeft(self, point):
distanceToNearest = 10000
nearestControl = None
for elem in self.controlAndProgramList:
control = elem.control
(left, top) = control.getPosition()
x = left + (control.getWidth() / 2)
y = top + (control.getHeight() / 2)
if point.x > x and point.y == y:
distance = abs(point.x - x)
if distance < distanceToNearest:
distanceToNearest = distance
nearestControl = control
return nearestControl
def _findControlBelow(self, point):
nearestControl = None
for elem in self.controlAndProgramList:
control = elem.control
(leftEdge, top) = control.getPosition()
y = top + (control.getHeight() / 2)
if point.y < y:
rightEdge = leftEdge + control.getWidth()
if leftEdge <= point.x < rightEdge and (
nearestControl is None or nearestControl.getPosition()[1] > top):
nearestControl = control
return nearestControl
def _findControlAbove(self, point):
nearestControl = None
for elem in self.controlAndProgramList:
control = elem.control
(leftEdge, top) = control.getPosition()
y = top + (control.getHeight() / 2)
if point.y > y:
rightEdge = leftEdge + control.getWidth()
if leftEdge <= point.x < rightEdge and (
nearestControl is None or nearestControl.getPosition()[1] < top):
nearestControl = control
return nearestControl
def _findControlAt(self, point):
for elem in self.controlAndProgramList:
control = elem.control
(left, top) = control.getPosition()
bottom = top + control.getHeight()
right = left + control.getWidth()
if left <= point.x <= right and top <= point.y <= bottom:
return control
return None
def _findCurrentTimeslot(self, point):
y = point.y
control = self.getControl(self.C_MAIN_TIMEBAR)
if control:
(x, _) = control.getPosition()
else:
x = point.x
for elem in self.controlAndProgramList:
control = elem.control
(left, top) = control.getPosition()
bottom = top + control.getHeight()
right = left + control.getWidth()
if left <= x <= right and top <= y <= bottom:
return control
return None
def _getProgramFromControl(self, control):
for elem in self.controlAndProgramList:
if elem.control == control:
return elem.program
return None
def _hideControl(self, *controlIds):
"""
Visibility is inverted in skin
"""
for controlId in controlIds:
control = self.getControl(controlId)
if control:
control.setVisible(True)
def _showControl(self, *controlIds):
"""
Visibility is inverted in skin
"""
for controlId in controlIds:
control = self.getControl(controlId)
if control:
control.setVisible(False)
def formatTime(self, timestamp):
if timestamp:
format = xbmc.getRegion('time').replace(':%S', '').replace('%H%H', '%H')
return timestamp.strftime(format)
else:
return ''
def formatDate(self, timestamp, longdate=False):
if timestamp:
if longdate == True:
format = xbmc.getRegion('datelong')
else:
format = xbmc.getRegion('dateshort')
return timestamp.strftime(format)
else:
return ''
def setControlImage(self, controlId, image):
control = self.getControl(controlId)
if control:
control.setImage(image.encode('utf-8'))
def setControlLabel(self, controlId, label):
control = self.getControl(controlId)
if control and label:
control.setLabel(label)
def setControlText(self, controlId, text):
control = self.getControl(controlId)
if control:
control.setText(text)
def updateTimebar(self, scheduleTimer=True):
# move timebar to current time
timeDelta = datetime.datetime.today() - self.viewStartDate
control = self.getControl(self.C_MAIN_TIMEBAR)
if control:
(x, y) = control.getPosition()
try:
# Sometimes raises:
# exceptions.RuntimeError: Unknown exception thrown from the call "setVisible"
control.setVisible(timeDelta.days == 0)
except:
pass
control.setPosition(self._secondsToXposition(timeDelta.seconds), y)
if scheduleTimer and not xbmc.abortRequested and not self.isClosing:
threading.Timer(1, self.updateTimebar).start()
class PopupMenu(xbmcgui.WindowXMLDialog):
C_POPUP_PLAY = 4000
C_POPUP_CHOOSE_STREAM = 4001
C_POPUP_REMIND = 4002
C_POPUP_CHANNELS = 4003
C_POPUP_QUIT = 4004
C_POPUP_PLAY_BEGINNING = 4005
C_POPUP_CHANNEL_LOGO = 4100
C_POPUP_CHANNEL_TITLE = 4101
C_POPUP_PROGRAM_TITLE = 4102
C_POPUP_LIBMOV = 80000
C_POPUP_LIBTV = 80001
C_POPUP_VIDEOADDONS = 80002
def __new__(cls, database, program, showRemind):
return super(PopupMenu, cls).__new__(cls, 'script-tvguide-menu.xml', ADDON.getAddonInfo('path'), SKIN)
def __init__(self, database, program, showRemind):
"""
@type database: source.Database
@param program:
@type program: source.Program
@param showRemind:
"""
super(PopupMenu, self).__init__()
self.database = database
self.program = program
self.showRemind = showRemind
self.buttonClicked = None
def onInit(self):
playControl = self.getControl(self.C_POPUP_PLAY)
remindControl = self.getControl(self.C_POPUP_REMIND)
channelLogoControl = self.getControl(self.C_POPUP_CHANNEL_LOGO)
channelTitleControl = self.getControl(self.C_POPUP_CHANNEL_TITLE)
programTitleControl = self.getControl(self.C_POPUP_PROGRAM_TITLE)
programPlayBeginningControl = self.getControl(self.C_POPUP_PLAY_BEGINNING)
playControl.setLabel(strings(WATCH_CHANNEL, self.program.channel.title))
if not self.program.channel.isPlayable():
playControl.setEnabled(False)
self.setFocusId(self.C_POPUP_CHOOSE_STREAM)
if self.database.getCustomStreamUrl(self.program.channel):
chooseStrmControl = self.getControl(self.C_POPUP_CHOOSE_STREAM)
chooseStrmControl.setLabel(strings(REMOVE_STRM_FILE))
if self.program.channel.logo is not None:
channelLogoControl.setImage(self.program.channel.logo)
channelTitleControl.setVisible(False)
else:
channelTitleControl.setLabel(self.program.channel.title)
channelLogoControl.setVisible(False)
programTitleControl.setLabel(self.program.title)
if self.program.startDate:
remindControl.setEnabled(True)
if self.showRemind:
remindControl.setLabel(strings(REMIND_PROGRAM))
else:
remindControl.setLabel(strings(DONT_REMIND_PROGRAM))
else:
remindControl.setEnabled(False)
def onAction(self, action):
if action.getId() in [ACTION_PARENT_DIR, ACTION_PREVIOUS_MENU, KEY_NAV_BACK, KEY_CONTEXT_MENU]:
self.close()
return
def onClick(self, controlId):
if controlId == self.C_POPUP_CHOOSE_STREAM and self.database.getCustomStreamUrl(self.program.channel):
self.database.deleteCustomStreamUrl(self.program.channel)
chooseStrmControl = self.getControl(self.C_POPUP_CHOOSE_STREAM)
chooseStrmControl.setLabel(strings(CHOOSE_STRM_FILE))
if not self.program.channel.isPlayable():
playControl = self.getControl(self.C_POPUP_PLAY)
playControl.setEnabled(False)
else:
self.buttonClicked = controlId
self.close()
def onFocus(self, controlId):
pass
class ChannelsMenu(xbmcgui.WindowXMLDialog):
C_CHANNELS_LIST = 6000
C_CHANNELS_SELECTION_VISIBLE = 6001
C_CHANNELS_SELECTION = 6002
C_CHANNELS_SAVE = 6003
C_CHANNELS_CANCEL = 6004
def __new__(cls, database):
return super(ChannelsMenu, cls).__new__(cls, 'script-tvguide-channels.xml', ADDON.getAddonInfo('path'), SKIN)
def __init__(self, database):
"""
@type database: source.Database
"""
super(ChannelsMenu, self).__init__()
self.database = database
self.channelList = database.getChannelList(onlyVisible=False)
self.swapInProgress = False
self.selectedChannel = 0
def onInit(self):
self.updateChannelList()
self.setFocusId(self.C_CHANNELS_LIST)
def onAction(self, action):
if action.getId() in [ACTION_PARENT_DIR, KEY_NAV_BACK]:
self.close()
return
if self.getFocusId() == self.C_CHANNELS_LIST and action.getId() in [ACTION_PREVIOUS_MENU, KEY_CONTEXT_MENU,
ACTION_LEFT]:
listControl = self.getControl(self.C_CHANNELS_LIST)
idx = listControl.getSelectedPosition()
self.selectedChannel = idx
buttonControl = self.getControl(self.C_CHANNELS_SELECTION)
buttonControl.setLabel('[B]%s[/B]' % self.channelList[idx].title)
self.getControl(self.C_CHANNELS_SELECTION_VISIBLE).setVisible(False)
self.setFocusId(self.C_CHANNELS_SELECTION)
elif self.getFocusId() == self.C_CHANNELS_SELECTION and action.getId() in [ACTION_RIGHT, ACTION_SELECT_ITEM]:
self.getControl(self.C_CHANNELS_SELECTION_VISIBLE).setVisible(True)
xbmc.sleep(350)
self.setFocusId(self.C_CHANNELS_LIST)
elif self.getFocusId() == self.C_CHANNELS_SELECTION and action.getId() in [ACTION_PREVIOUS_MENU,
KEY_CONTEXT_MENU]:
listControl = self.getControl(self.C_CHANNELS_LIST)
idx = listControl.getSelectedPosition()
self.swapChannels(self.selectedChannel, idx)
self.getControl(self.C_CHANNELS_SELECTION_VISIBLE).setVisible(True)
xbmc.sleep(350)
self.setFocusId(self.C_CHANNELS_LIST)
elif self.getFocusId() == self.C_CHANNELS_SELECTION and action.getId() == ACTION_UP:
listControl = self.getControl(self.C_CHANNELS_LIST)
idx = listControl.getSelectedPosition()
if idx > 0:
self.swapChannels(idx, idx - 1)
elif self.getFocusId() == self.C_CHANNELS_SELECTION and action.getId() == ACTION_DOWN:
listControl = self.getControl(self.C_CHANNELS_LIST)
idx = listControl.getSelectedPosition()
if idx < listControl.size() - 1:
self.swapChannels(idx, idx + 1)
def onClick(self, controlId):
if controlId == self.C_CHANNELS_LIST:
listControl = self.getControl(self.C_CHANNELS_LIST)
item = listControl.getSelectedItem()
channel = self.channelList[int(item.getProperty('idx'))]
channel.visible = not channel.visible
if channel.visible:
iconImage = 'tvguide-channel-visible.png'
else:
iconImage = 'tvguide-channel-hidden.png'
item.setIconImage(iconImage)
elif controlId == self.C_CHANNELS_SAVE:
self.database.saveChannelList(self.close, self.channelList)
elif controlId == self.C_CHANNELS_CANCEL:
self.close()
def onFocus(self, controlId):
pass
def updateChannelList(self):
listControl = self.getControl(self.C_CHANNELS_LIST)
listControl.reset()
for idx, channel in enumerate(self.channelList):
if channel.visible:
iconImage = 'tvguide-channel-visible.png'
else:
iconImage = 'tvguide-channel-hidden.png'
item = xbmcgui.ListItem('%3d. %s' % (idx + 1, channel.title), iconImage=iconImage)
item.setProperty('idx', str(idx))
listControl.addItem(item)
def updateListItem(self, idx, item):
channel = self.channelList[idx]
item.setLabel('%3d. %s' % (idx + 1, channel.title))
if channel.visible:
iconImage = 'tvguide-channel-visible.png'
else:
iconImage = 'tvguide-channel-hidden.png'
item.setIconImage(iconImage)
item.setProperty('idx', str(idx))
def swapChannels(self, fromIdx, toIdx):
if self.swapInProgress:
return
self.swapInProgress = True
c = self.channelList[fromIdx]
self.channelList[fromIdx] = self.channelList[toIdx]
self.channelList[toIdx] = c
# recalculate weight
for idx, channel in enumerate(self.channelList):
channel.weight = idx
listControl = self.getControl(self.C_CHANNELS_LIST)
self.updateListItem(fromIdx, listControl.getListItem(fromIdx))
self.updateListItem(toIdx, listControl.getListItem(toIdx))
listControl.selectItem(toIdx)
xbmc.sleep(50)
self.swapInProgress = False
class StreamSetupDialog(xbmcgui.WindowXMLDialog):
C_STREAM_STRM_TAB = 101
C_STREAM_FAVOURITES_TAB = 102
C_STREAM_ADDONS_TAB = 103
C_STREAM_STRM_BROWSE = 1001
C_STREAM_STRM_FILE_LABEL = 1005
C_STREAM_STRM_PREVIEW = 1002
C_STREAM_STRM_OK = 1003
C_STREAM_STRM_CANCEL = 1004
C_STREAM_FAVOURITES = 2001
C_STREAM_FAVOURITES_PREVIEW = 2002
C_STREAM_FAVOURITES_OK = 2003
C_STREAM_FAVOURITES_CANCEL = 2004
C_STREAM_ADDONS = 3001
C_STREAM_ADDONS_STREAMS = 3002
C_STREAM_ADDONS_NAME = 3003
C_STREAM_ADDONS_DESCRIPTION = 3004
C_STREAM_ADDONS_PREVIEW = 3005
C_STREAM_ADDONS_OK = 3006
C_STREAM_ADDONS_CANCEL = 3007
C_STREAM_VISIBILITY_MARKER = 100
VISIBLE_STRM = 'strm'
VISIBLE_FAVOURITES = 'favourites'
VISIBLE_ADDONS = 'addons'
def __new__(cls, database, channel):
return super(StreamSetupDialog, cls).__new__(cls, 'script-tvguide-streamsetup.xml', ADDON.getAddonInfo('path'),
SKIN)
def __init__(self, database, channel):
"""
@type database: source.Database
@type channel:source.Channel
"""
super(StreamSetupDialog, self).__init__()
self.database = database
self.channel = channel
self.player = xbmc.Player()
self.previousAddonId = None
self.strmFile = None
self.streamingService = streaming.StreamsService(ADDON)
def close(self):
if self.player.isPlaying():
self.player.stop()
super(StreamSetupDialog, self).close()
def onInit(self):
self.getControl(self.C_STREAM_VISIBILITY_MARKER).setLabel(self.VISIBLE_STRM)
favourites = self.streamingService.loadFavourites()
items = list()
for label, value in favourites:
item = xbmcgui.ListItem(label)
item.setProperty('stream', value)
items.append(item)
listControl = self.getControl(StreamSetupDialog.C_STREAM_FAVOURITES)
listControl.addItems(items)
items = list()
for id in self.streamingService.getAddons():
try:
addon = xbmcaddon.Addon(id) # raises Exception if addon is not installed
item = xbmcgui.ListItem(addon.getAddonInfo('name'), iconImage=addon.getAddonInfo('icon'))
item.setProperty('addon_id', id)
items.append(item)
except Exception:
pass
listControl = self.getControl(StreamSetupDialog.C_STREAM_ADDONS)
listControl.addItems(items)
self.updateAddonInfo()
def onAction(self, action):
if action.getId() in [ACTION_PARENT_DIR, ACTION_PREVIOUS_MENU, KEY_NAV_BACK, KEY_CONTEXT_MENU]:
self.close()
return
elif self.getFocusId() == self.C_STREAM_ADDONS:
self.updateAddonInfo()
def onClick(self, controlId):
if controlId == self.C_STREAM_STRM_BROWSE:
stream = xbmcgui.Dialog().browse(1, ADDON.getLocalizedString(30304), 'video', '.strm')
if stream:
self.database.setCustomStreamUrl(self.channel, stream)
self.getControl(self.C_STREAM_STRM_FILE_LABEL).setText(stream)
self.strmFile = stream
elif controlId == self.C_STREAM_ADDONS_OK:
listControl = self.getControl(self.C_STREAM_ADDONS_STREAMS)
item = listControl.getSelectedItem()
if item:
stream = item.getProperty('stream')
self.database.setCustomStreamUrl(self.channel, stream)
self.close()
elif controlId == self.C_STREAM_FAVOURITES_OK:
listControl = self.getControl(self.C_STREAM_FAVOURITES)
item = listControl.getSelectedItem()
if item:
stream = item.getProperty('stream')
self.database.setCustomStreamUrl(self.channel, stream)
self.close()
elif controlId == self.C_STREAM_STRM_OK:
self.database.setCustomStreamUrl(self.channel, self.strmFile)
self.close()
elif controlId in [self.C_STREAM_ADDONS_CANCEL, self.C_STREAM_FAVOURITES_CANCEL, self.C_STREAM_STRM_CANCEL]:
self.close()
elif controlId in [self.C_STREAM_ADDONS_PREVIEW, self.C_STREAM_FAVOURITES_PREVIEW, self.C_STREAM_STRM_PREVIEW]:
if self.player.isPlaying():
self.player.stop()
self.getControl(self.C_STREAM_ADDONS_PREVIEW).setLabel(strings(PREVIEW_STREAM))
self.getControl(self.C_STREAM_FAVOURITES_PREVIEW).setLabel(strings(PREVIEW_STREAM))
self.getControl(self.C_STREAM_STRM_PREVIEW).setLabel(strings(PREVIEW_STREAM))
return
stream = None
visible = self.getControl(self.C_STREAM_VISIBILITY_MARKER).getLabel()
if visible == self.VISIBLE_ADDONS:
listControl = self.getControl(self.C_STREAM_ADDONS_STREAMS)
item = listControl.getSelectedItem()
if item:
stream = item.getProperty('stream')
elif visible == self.VISIBLE_FAVOURITES:
listControl = self.getControl(self.C_STREAM_FAVOURITES)
item = listControl.getSelectedItem()
if item:
stream = item.getProperty('stream')
elif visible == self.VISIBLE_STRM:
stream = self.strmFile
if stream is not None:
self.player.play(item=stream, windowed=True)
if self.player.isPlaying():
self.getControl(self.C_STREAM_ADDONS_PREVIEW).setLabel(strings(STOP_PREVIEW))
self.getControl(self.C_STREAM_FAVOURITES_PREVIEW).setLabel(strings(STOP_PREVIEW))
self.getControl(self.C_STREAM_STRM_PREVIEW).setLabel(strings(STOP_PREVIEW))
def onFocus(self, controlId):
if controlId == self.C_STREAM_STRM_TAB:
self.getControl(self.C_STREAM_VISIBILITY_MARKER).setLabel(self.VISIBLE_STRM)
elif controlId == self.C_STREAM_FAVOURITES_TAB:
self.getControl(self.C_STREAM_VISIBILITY_MARKER).setLabel(self.VISIBLE_FAVOURITES)
elif controlId == self.C_STREAM_ADDONS_TAB:
self.getControl(self.C_STREAM_VISIBILITY_MARKER).setLabel(self.VISIBLE_ADDONS)
def updateAddonInfo(self):
listControl = self.getControl(self.C_STREAM_ADDONS)
item = listControl.getSelectedItem()
if item is None:
return
if item.getProperty('addon_id') == self.previousAddonId:
return
self.previousAddonId = item.getProperty('addon_id')
addon = xbmcaddon.Addon(id=item.getProperty('addon_id'))
self.getControl(self.C_STREAM_ADDONS_NAME).setLabel('[B]%s[/B]' % addon.getAddonInfo('name'))
self.getControl(self.C_STREAM_ADDONS_DESCRIPTION).setText(addon.getAddonInfo('description'))
streams = self.streamingService.getAddonStreams(item.getProperty('addon_id'))
items = list()
for (label, stream) in streams:
if item.getProperty('addon_id') == "plugin.video.meta":
label = self.channel.title
stream = stream.replace("<channel>", self.channel.title.replace(" ", "%20"))
item = xbmcgui.ListItem(label)
item.setProperty('stream', stream)
items.append(item)
listControl = self.getControl(StreamSetupDialog.C_STREAM_ADDONS_STREAMS)
listControl.reset()
listControl.addItems(items)
class ChooseStreamAddonDialog(xbmcgui.WindowXMLDialog):
C_SELECTION_LIST = 1000
def __new__(cls, addons):
return super(ChooseStreamAddonDialog, cls).__new__(cls, 'script-tvguide-streamaddon.xml',
ADDON.getAddonInfo('path'), SKIN)
def __init__(self, addons):
super(ChooseStreamAddonDialog, self).__init__()
self.addons = addons
self.stream = None
def onInit(self):
items = list()
for id, label, url in self.addons:
addon = xbmcaddon.Addon(id)
item = xbmcgui.ListItem(label, addon.getAddonInfo('name'), addon.getAddonInfo('icon'))
item.setProperty('stream', url)
items.append(item)
listControl = self.getControl(ChooseStreamAddonDialog.C_SELECTION_LIST)
listControl.addItems(items)
self.setFocus(listControl)
def onAction(self, action):
if action.getId() in [ACTION_PARENT_DIR, ACTION_PREVIOUS_MENU, KEY_NAV_BACK]:
self.close()
def onClick(self, controlId):
if controlId == ChooseStreamAddonDialog.C_SELECTION_LIST:
listControl = self.getControl(ChooseStreamAddonDialog.C_SELECTION_LIST)
self.stream = listControl.getSelectedItem().getProperty('stream')
self.close()
def onFocus(self, controlId):
pass<|fim▁end|> | debug('setFocus %d' % control.getId())
|
<|file_name|>karma-dist-minified.conf.js<|end_file_name|><|fim▁begin|>// Karma configuration
// Generated on Thu Aug 21 2014 10:24:39 GMT+0200 (CEST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai-jquery', 'jquery-1.8.3', 'sinon-chai'],
plugins: [
'karma-mocha',
'karma-chai',
'karma-sinon-chai',
'karma-chrome-launcher',
'karma-phantomjs-launcher',
'karma-jquery',
'karma-chai-jquery',
'karma-mocha-reporter'
],
// list of files / patterns to load in the browser
files: [
'bower/angular/angular.js',
'bower/angular-sanitize/angular-sanitize.js',
'bower/angular-mocks/angular-mocks.js',
'dist/ac-components.min.js',
'test/unit/**/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['mocha'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});<|fim▁hole|><|fim▁end|> | }; |
<|file_name|>tls.rs<|end_file_name|><|fim▁begin|>#![allow(unused_variables)]
#![allow(unused_imports)]
/// Note: Fred must be compiled with the `enable-tls` feature for this to work.
extern crate fred;
extern crate tokio_core;
extern crate futures;
use fred::RedisClient;
use fred::owned::RedisClientOwned;
use fred::types::*;
use tokio_core::reactor::Core;
use futures::Future;
fn main() {
let config = RedisConfig::Centralized {
// Note: this must match the hostname tied to the cert
host: "foo.bar.com".into(),
port: 6379,
key: Some("key".into()),
// if compiled without `enable-tls` setting this to `true` does nothing, which is done to avoid requiring TLS dependencies unless necessary
tls: true
};
// otherwise usage is the same as the non-tls client...
let mut core = Core::new().unwrap();
let handle = core.handle();
println!("Connecting to {:?}...", config);
let client = RedisClient::new(config, None);
let connection = client.connect(&handle);
let commands = client.on_connect().and_then(|client| {
println!("Client connected.");
client.select(0)
})
.and_then(|client| {
println!("Selected database.");
client.info(None)
})
.and_then(|(client, info)| {
println!("Redis server info: {}", info);
client.get("foo")
})
.and_then(|(client, result)| {<|fim▁hole|> .and_then(|(client, result)| {
println!("Set 'bar' at 'foo'? {}. Subscribing to 'baz'...", result);
client.subscribe("baz")
})
.and_then(|(client, result)| {
println!("Subscribed to 'baz'. Now subscribed to {} channels. Now exiting...", result);
client.quit()
});
let (reason, client) = match core.run(connection.join(commands)) {
Ok((r, c)) => (r, c),
Err(e) => panic!("Connection closed abruptly: {}", e)
};
println!("Connection closed gracefully with error: {:?}", reason);
}<|fim▁end|> | println!("Got foo: {:?}", result);
client.set("foo", "bar", Some(Expiration::PX(1000)), Some(SetOptions::NX))
}) |
<|file_name|>writer.py<|end_file_name|><|fim▁begin|>from mediaviewer.models.person import Person<|fim▁hole|> db_table = 'writer'<|fim▁end|> |
class Writer(Person):
class Meta:
app_label = 'mediaviewer' |
<|file_name|>AbstractConfigValue.java<|end_file_name|><|fim▁begin|>/**
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
*/
package org.deephacks.confit.internal.core.property.typesafe.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.deephacks.confit.internal.core.property.typesafe.ConfigMergeable;
import org.deephacks.confit.internal.core.property.typesafe.ConfigRenderOptions;
import org.deephacks.confit.internal.core.property.typesafe.ConfigException;
import org.deephacks.confit.internal.core.property.typesafe.ConfigObject;
import org.deephacks.confit.internal.core.property.typesafe.ConfigOrigin;
import org.deephacks.confit.internal.core.property.typesafe.ConfigValue;
/**
*
* Trying very hard to avoid a parent reference in typesafe values; when you have
* a tree like this, the availability of parent() tends to result in a lot of
* improperly-factored and non-modular code. Please don't add parent().
*
*/
abstract class AbstractConfigValue implements ConfigValue, MergeableValue {
final private SimpleConfigOrigin origin;
AbstractConfigValue(ConfigOrigin origin) {
this.origin = (SimpleConfigOrigin) origin;
}
@Override
public SimpleConfigOrigin origin() {
return this.origin;
}
/**
* This exception means that a value is inherently not resolveable, at the
* moment the only known cause is a cycle of substitutions. This is a
* checked exception since it's internal to the library and we want to be
* sure we handle it before passing it out to public API. This is only
* supposed to be thrown by the target of a cyclic reference and it's
* supposed to be caught by the ConfigReference looking up that reference,
* so it should be impossible for an outermost resolve() to throw this.
*
* Contrast with ConfigException.NotResolved which just means nobody called
* resolve().
*/
static class NotPossibleToResolve extends Exception {
private static final long serialVersionUID = 1L;
final private String traceString;
NotPossibleToResolve(ResolveContext context) {
super("was not possible to resolve");
this.traceString = context.traceString();
}
String traceString() {
return traceString;
}
}
/**
* Called only by ResolveContext.resolve().
*
* @param context
* state of the current resolve
* @return a new value if there were changes, or this if no changes
*/
AbstractConfigValue resolveSubstitutions(ResolveContext context)
throws NotPossibleToResolve {
return this;
}
ResolveStatus resolveStatus() {
return ResolveStatus.RESOLVED;
}
/**
* This is used when including one file in another; the included file is
* relativized to the path it's included into in the parent file. The point
* is that if you include a file at foo.bar in the parent, and the included
* file as a substitution ${a.b.c}, the included substitution now needs to
* be ${foo.bar.a.b.c} because we resolve substitutions globally only after
* parsing everything.
*
* @param prefix
* @return value relativized to the given path or the same value if nothing
* to do
*/
AbstractConfigValue relativized(Path prefix) {
return this;
}
protected interface Modifier {
// keyOrNull is null for non-objects
AbstractConfigValue modifyChildMayThrow(String keyOrNull, AbstractConfigValue v)
throws Exception;
}
protected abstract class NoExceptionsModifier implements Modifier {
@Override
public final AbstractConfigValue modifyChildMayThrow(String keyOrNull, AbstractConfigValue v)
throws Exception {
try {
return modifyChild(keyOrNull, v);
} catch (RuntimeException e) {
throw e;
} catch(Exception e) {
throw new ConfigException.BugOrBroken("Unexpected exception", e);
}
}
abstract AbstractConfigValue modifyChild(String keyOrNull, AbstractConfigValue v);
}
@Override
public AbstractConfigValue toFallbackValue() {
return this;
}
protected abstract AbstractConfigValue newCopy(ConfigOrigin origin);
// this is virtualized rather than a field because only some subclasses
// really need to store the boolean, and they may be able to pack it
// with another boolean to save space.
protected boolean ignoresFallbacks() {
// if we are not resolved, then somewhere in this value there's
// a substitution that may need to look at the fallbacks.
return resolveStatus() == ResolveStatus.RESOLVED;
}
protected AbstractConfigValue withFallbacksIgnored() {
if (ignoresFallbacks())
return this;
else
throw new ConfigException.BugOrBroken(
"value class doesn't implement forced fallback-ignoring " + this);
}
// the withFallback() implementation is supposed to avoid calling
// mergedWith* if we're ignoring fallbacks.
protected final void requireNotIgnoringFallbacks() {
if (ignoresFallbacks())
throw new ConfigException.BugOrBroken(
"method should not have been called with ignoresFallbacks=true "
+ getClass().getSimpleName());
}
protected AbstractConfigValue constructDelayedMerge(ConfigOrigin origin,
List<AbstractConfigValue> stack) {
return new ConfigDelayedMerge(origin, stack);
}
protected final AbstractConfigValue mergedWithTheUnmergeable(
Collection<AbstractConfigValue> stack, Unmergeable fallback) {
requireNotIgnoringFallbacks();
// if we turn out to be an object, and the fallback also does,
// then a merge may be required; delay until we resolve.
List<AbstractConfigValue> newStack = new ArrayList<AbstractConfigValue>();
newStack.addAll(stack);
newStack.addAll(fallback.unmergedValues());
return constructDelayedMerge(AbstractConfigObject.mergeOrigins(newStack), newStack);
}
private final AbstractConfigValue delayMerge(Collection<AbstractConfigValue> stack,
AbstractConfigValue fallback) {
// if we turn out to be an object, and the fallback also does,
// then a merge may be required.
// if we contain a substitution, resolving it may need to look
// back to the fallback.
List<AbstractConfigValue> newStack = new ArrayList<AbstractConfigValue>();
newStack.addAll(stack);
newStack.add(fallback);
return constructDelayedMerge(AbstractConfigObject.mergeOrigins(newStack), newStack);
}
protected final AbstractConfigValue mergedWithObject(Collection<AbstractConfigValue> stack,
AbstractConfigObject fallback) {
requireNotIgnoringFallbacks();
if (this instanceof AbstractConfigObject)
throw new ConfigException.BugOrBroken("Objects must reimplement mergedWithObject");
return mergedWithNonObject(stack, fallback);
}
protected final AbstractConfigValue mergedWithNonObject(Collection<AbstractConfigValue> stack,
AbstractConfigValue fallback) {
requireNotIgnoringFallbacks();
if (resolveStatus() == ResolveStatus.RESOLVED) {
// falling back to a non-object doesn't merge anything, and also
// prohibits merging any objects that we fall back to later.
// so we have to switch to ignoresFallbacks mode.
return withFallbacksIgnored();
} else {
// if unresolved, we may have to look back to fallbacks as part of
// the resolution process, so always delay
return delayMerge(stack, fallback);
}
}
protected AbstractConfigValue mergedWithTheUnmergeable(Unmergeable fallback) {
requireNotIgnoringFallbacks();
return mergedWithTheUnmergeable(Collections.singletonList(this), fallback);
}
protected AbstractConfigValue mergedWithObject(AbstractConfigObject fallback) {
requireNotIgnoringFallbacks();
return mergedWithObject(Collections.singletonList(this), fallback);
}
protected AbstractConfigValue mergedWithNonObject(AbstractConfigValue fallback) {
requireNotIgnoringFallbacks();
return mergedWithNonObject(Collections.singletonList(this), fallback);
}
public AbstractConfigValue withOrigin(ConfigOrigin origin) {
if (this.origin == origin)
return this;
else
return newCopy(origin);
}
// this is only overridden to change the return type
@Override
public AbstractConfigValue withFallback(ConfigMergeable mergeable) {
if (ignoresFallbacks()) {
return this;
} else {
ConfigValue other = ((MergeableValue) mergeable).toFallbackValue();
if (other instanceof Unmergeable) {
return mergedWithTheUnmergeable((Unmergeable) other);
} else if (other instanceof AbstractConfigObject) {
return mergedWithObject((AbstractConfigObject) other);
} else {
return mergedWithNonObject((AbstractConfigValue) other);
}
}
}
protected boolean canEqual(Object other) {
return other instanceof ConfigValue;
}
@Override
public boolean equals(Object other) {
// note that "origin" is deliberately NOT part of equality
if (other instanceof ConfigValue) {
return canEqual(other)
&& (this.valueType() ==
((ConfigValue) other).valueType())
&& ConfigImplUtil.equalsHandlingNull(this.unwrapped(),
((ConfigValue) other).unwrapped());
} else {
return false;
}
}
@Override
public int hashCode() {
// note that "origin" is deliberately NOT part of equality
Object o = this.unwrapped();
if (o == null)
return 0;
else
return o.hashCode();
}
@Override
public final String toString() {
StringBuilder sb = new StringBuilder();
render(sb, 0, null /* atKey */, ConfigRenderOptions.concise());
return getClass().getSimpleName() + "(" + sb.toString() + ")";
}<|fim▁hole|> protected static void indent(StringBuilder sb, int indent, ConfigRenderOptions options) {
if (options.getFormatted()) {
int remaining = indent;
while (remaining > 0) {
sb.append(" ");
--remaining;
}
}
}
protected void render(StringBuilder sb, int indent, String atKey, ConfigRenderOptions options) {
if (atKey != null) {
String renderedKey;
if (options.getJson())
renderedKey = ConfigImplUtil.renderJsonString(atKey);
else
renderedKey = ConfigImplUtil.renderStringUnquotedIfPossible(atKey);
sb.append(renderedKey);
if (options.getJson()) {
if (options.getFormatted())
sb.append(" : ");
else
sb.append(":");
} else {
// in non-JSON we can omit the colon or equals before an object
if (this instanceof ConfigObject) {
if (options.getFormatted())
sb.append(' ');
} else {
sb.append("=");
}
}
}
render(sb, indent, options);
}
protected void render(StringBuilder sb, int indent, ConfigRenderOptions options) {
Object u = unwrapped();
sb.append(u.toString());
}
@Override
public final String render() {
return render(ConfigRenderOptions.defaults());
}
@Override
public final String render(ConfigRenderOptions options) {
StringBuilder sb = new StringBuilder();
render(sb, 0, null, options);
return sb.toString();
}
// toString() is a debugging-oriented string but this is defined
// to create a string that would parse back to the value in JSON.
// It only works for primitive values (that would be a single token)
// which are auto-converted to strings when concatenating with
// other strings or by the DefaultTransformer.
String transformToString() {
return null;
}
SimpleConfig atKey(ConfigOrigin origin, String key) {
Map<String, AbstractConfigValue> m = Collections.singletonMap(key, this);
return (new SimpleConfigObject(origin, m)).toConfig();
}
@Override
public SimpleConfig atKey(String key) {
return atKey(SimpleConfigOrigin.newSimple("atKey(" + key + ")"), key);
}
SimpleConfig atPath(ConfigOrigin origin, Path path) {
Path parent = path.parent();
SimpleConfig result = atKey(origin, path.last());
while (parent != null) {
String key = parent.last();
result = result.atKey(origin, key);
parent = parent.parent();
}
return result;
}
@Override
public SimpleConfig atPath(String pathExpression) {
SimpleConfigOrigin origin = SimpleConfigOrigin.newSimple("atPath(" + pathExpression + ")");
return atPath(origin, Path.newPath(pathExpression));
}
}<|fim▁end|> | |
<|file_name|>type-ascription.rs<|end_file_name|><|fim▁begin|>fn main() {
let xxxxxxxxxxx = yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy : SomeTrait<AA, BB, CC>;<|fim▁hole|>
let xxxxxxxxxxxxxxx = yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA;
let z = funk(yyyyyyyyyyyyyyy, zzzzzzzzzzzzzzzz, wwwwww): AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA;
x : u32 - 1u32 / 10f32 : u32
}<|fim▁end|> | |
<|file_name|>reconstructor.py<|end_file_name|><|fim▁begin|># Copyright (c) 2010-2015 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from os.path import join
import random
import time
import itertools
from collections import defaultdict
import six.moves.cPickle as pickle
import shutil
from eventlet import (GreenPile, GreenPool, Timeout, sleep, hubs, tpool,
spawn)
from eventlet.support.greenlets import GreenletExit
from swift import gettext_ as _
from swift.common.utils import (
whataremyips, unlink_older_than, compute_eta, get_logger,
dump_recon_cache, mkdirs, config_true_value, list_from_csv, get_hub,
tpool_reraise, GreenAsyncPile, Timestamp, remove_file)
from swift.common.swob import HeaderKeyDict
from swift.common.bufferedhttp import http_connect
from swift.common.daemon import Daemon
from swift.common.ring.utils import is_local_device
from swift.obj.ssync_sender import Sender as ssync_sender
from swift.common.http import HTTP_OK, HTTP_NOT_FOUND, \
HTTP_INSUFFICIENT_STORAGE
from swift.obj.diskfile import DiskFileRouter, get_data_dir, \
get_tmp_dir
from swift.common.storage_policy import POLICIES, EC_POLICY
from swift.common.exceptions import ConnectionTimeout, DiskFileError, \
SuffixSyncError
SYNC, REVERT = ('sync_only', 'sync_revert')
hubs.use_hub(get_hub())
def _get_partners(frag_index, part_nodes):
"""
Returns the left and right partners of the node whose index is
equal to the given frag_index.
:param frag_index: a fragment index
:param part_nodes: a list of primary nodes
:returns: [<node-to-left>, <node-to-right>]
"""
return [
part_nodes[(frag_index - 1) % len(part_nodes)],
part_nodes[(frag_index + 1) % len(part_nodes)],
]
<|fim▁hole|>
class RebuildingECDiskFileStream(object):
"""
This class wraps the the reconstructed fragment archive data and
metadata in the DiskFile interface for ssync.
"""
def __init__(self, datafile_metadata, frag_index, rebuilt_fragment_iter):
# start with metadata from a participating FA
self.datafile_metadata = datafile_metadata
# the new FA is going to have the same length as others in the set
self._content_length = self.datafile_metadata['Content-Length']
# update the FI and delete the ETag, the obj server will
# recalc on the other side...
self.datafile_metadata['X-Object-Sysmeta-Ec-Frag-Index'] = frag_index
for etag_key in ('ETag', 'Etag'):
self.datafile_metadata.pop(etag_key, None)
self.frag_index = frag_index
self.rebuilt_fragment_iter = rebuilt_fragment_iter
def get_metadata(self):
return self.datafile_metadata
def get_datafile_metadata(self):
return self.datafile_metadata
@property
def content_length(self):
return self._content_length
def reader(self):
for chunk in self.rebuilt_fragment_iter:
yield chunk
class ObjectReconstructor(Daemon):
"""
Reconstruct objects using erasure code. And also rebalance EC Fragment
Archive objects off handoff nodes.
Encapsulates most logic and data needed by the object reconstruction
process. Each call to .reconstruct() performs one pass. It's up to the
caller to do this in a loop.
"""
def __init__(self, conf, logger=None):
"""
:param conf: configuration object obtained from ConfigParser
:param logger: logging object
"""
self.conf = conf
self.logger = logger or get_logger(
conf, log_route='object-reconstructor')
self.devices_dir = conf.get('devices', '/srv/node')
self.mount_check = config_true_value(conf.get('mount_check', 'true'))
self.swift_dir = conf.get('swift_dir', '/etc/swift')
self.bind_ip = conf.get('bind_ip', '0.0.0.0')
self.servers_per_port = int(conf.get('servers_per_port', '0') or 0)
self.port = None if self.servers_per_port else \
int(conf.get('bind_port', 6000))
self.concurrency = int(conf.get('concurrency', 1))
self.stats_interval = int(conf.get('stats_interval', '300'))
self.ring_check_interval = int(conf.get('ring_check_interval', 15))
self.next_check = time.time() + self.ring_check_interval
self.reclaim_age = int(conf.get('reclaim_age', 86400 * 7))
self.partition_times = []
self.interval = int(conf.get('interval') or
conf.get('run_pause') or 30)
self.http_timeout = int(conf.get('http_timeout', 60))
self.lockup_timeout = int(conf.get('lockup_timeout', 1800))
self.recon_cache_path = conf.get('recon_cache_path',
'/var/cache/swift')
self.rcache = os.path.join(self.recon_cache_path, "object.recon")
# defaults subject to change after beta
self.conn_timeout = float(conf.get('conn_timeout', 0.5))
self.node_timeout = float(conf.get('node_timeout', 10))
self.network_chunk_size = int(conf.get('network_chunk_size', 65536))
self.disk_chunk_size = int(conf.get('disk_chunk_size', 65536))
self.headers = {
'Content-Length': '0',
'user-agent': 'obj-reconstructor %s' % os.getpid()}
self.handoffs_first = config_true_value(conf.get('handoffs_first',
False))
self._df_router = DiskFileRouter(conf, self.logger)
def load_object_ring(self, policy):
"""
Make sure the policy's rings are loaded.
:param policy: the StoragePolicy instance
:returns: appropriate ring object
"""
policy.load_ring(self.swift_dir)
return policy.object_ring
def check_ring(self, object_ring):
"""
Check to see if the ring has been updated
:param object_ring: the ring to check
:returns: boolean indicating whether or not the ring has changed
"""
if time.time() > self.next_check:
self.next_check = time.time() + self.ring_check_interval
if object_ring.has_changed():
return False
return True
def _full_path(self, node, part, path, policy):
return '%(replication_ip)s:%(replication_port)s' \
'/%(device)s/%(part)s%(path)s ' \
'policy#%(policy)d frag#%(frag_index)s' % {
'replication_ip': node['replication_ip'],
'replication_port': node['replication_port'],
'device': node['device'],
'part': part, 'path': path,
'policy': policy,
'frag_index': node.get('index', 'handoff'),
}
def _get_response(self, node, part, path, headers, policy):
"""
Helper method for reconstruction that GETs a single EC fragment
archive
:param node: the node to GET from
:param part: the partition
:param path: full path of the desired EC archive
:param headers: the headers to send
:param policy: an instance of
:class:`~swift.common.storage_policy.BaseStoragePolicy`
:returns: response
"""
resp = None
try:
with ConnectionTimeout(self.conn_timeout):
conn = http_connect(node['ip'], node['port'], node['device'],
part, 'GET', path, headers=headers)
with Timeout(self.node_timeout):
resp = conn.getresponse()
if resp.status not in [HTTP_OK, HTTP_NOT_FOUND]:
self.logger.warning(
_("Invalid response %(resp)s from %(full_path)s"),
{'resp': resp.status,
'full_path': self._full_path(node, part, path, policy)})
resp = None
elif resp.status == HTTP_NOT_FOUND:
resp = None
except (Exception, Timeout):
self.logger.exception(
_("Trying to GET %(full_path)s"), {
'full_path': self._full_path(node, part, path, policy)})
return resp
def reconstruct_fa(self, job, node, datafile_metadata):
"""
Reconstructs a fragment archive - this method is called from ssync
after a remote node responds that is missing this object - the local
diskfile is opened to provide metadata - but to reconstruct the
missing fragment archive we must connect to multiple object servers.
:param job: job from ssync_sender
:param node: node that we're rebuilding to
:param datafile_metadata: the datafile metadata to attach to
the rebuilt fragment archive
:returns: a DiskFile like class for use by ssync
:raises DiskFileError: if the fragment archive cannot be reconstructed
"""
part_nodes = job['policy'].object_ring.get_part_nodes(
job['partition'])
part_nodes.remove(node)
# the fragment index we need to reconstruct is the position index
# of the node we're rebuilding to within the primary part list
fi_to_rebuild = node['index']
# KISS send out connection requests to all nodes, see what sticks
headers = self.headers.copy()
headers['X-Backend-Storage-Policy-Index'] = int(job['policy'])
pile = GreenAsyncPile(len(part_nodes))
path = datafile_metadata['name']
for node in part_nodes:
pile.spawn(self._get_response, node, job['partition'],
path, headers, job['policy'])
responses = []
etag = None
for resp in pile:
if not resp:
continue
resp.headers = HeaderKeyDict(resp.getheaders())
if str(fi_to_rebuild) == \
resp.headers.get('X-Object-Sysmeta-Ec-Frag-Index'):
continue
if resp.headers.get('X-Object-Sysmeta-Ec-Frag-Index') in set(
r.headers.get('X-Object-Sysmeta-Ec-Frag-Index')
for r in responses):
continue
responses.append(resp)
etag = sorted(responses, reverse=True,
key=lambda r: Timestamp(
r.headers.get('X-Backend-Timestamp')
))[0].headers.get('X-Object-Sysmeta-Ec-Etag')
responses = [r for r in responses if
r.headers.get('X-Object-Sysmeta-Ec-Etag') == etag]
if len(responses) >= job['policy'].ec_ndata:
break
else:
self.logger.error(
'Unable to get enough responses (%s/%s) '
'to reconstruct %s with ETag %s' % (
len(responses), job['policy'].ec_ndata,
self._full_path(node, job['partition'],
datafile_metadata['name'], job['policy']),
etag))
raise DiskFileError('Unable to reconstruct EC archive')
rebuilt_fragment_iter = self.make_rebuilt_fragment_iter(
responses[:job['policy'].ec_ndata], path, job['policy'],
fi_to_rebuild)
return RebuildingECDiskFileStream(datafile_metadata, fi_to_rebuild,
rebuilt_fragment_iter)
def _reconstruct(self, policy, fragment_payload, frag_index):
return policy.pyeclib_driver.reconstruct(fragment_payload,
[frag_index])[0]
def make_rebuilt_fragment_iter(self, responses, path, policy, frag_index):
"""
Turn a set of connections from backend object servers into a generator
that yields up the rebuilt fragment archive for frag_index.
"""
def _get_one_fragment(resp):
buff = ''
remaining_bytes = policy.fragment_size
while remaining_bytes:
chunk = resp.read(remaining_bytes)
if not chunk:
break
remaining_bytes -= len(chunk)
buff += chunk
return buff
def fragment_payload_iter():
# We need a fragment from each connections, so best to
# use a GreenPile to keep them ordered and in sync
pile = GreenPile(len(responses))
while True:
for resp in responses:
pile.spawn(_get_one_fragment, resp)
try:
with Timeout(self.node_timeout):
fragment_payload = [fragment for fragment in pile]
except (Exception, Timeout):
self.logger.exception(
_("Error trying to rebuild %(path)s "
"policy#%(policy)d frag#%(frag_index)s"),
{'path': path,
'policy': policy,
'frag_index': frag_index,
})
break
if not all(fragment_payload):
break
rebuilt_fragment = self._reconstruct(
policy, fragment_payload, frag_index)
yield rebuilt_fragment
return fragment_payload_iter()
def stats_line(self):
"""
Logs various stats for the currently running reconstruction pass.
"""
if (self.device_count and self.part_count and
self.reconstruction_device_count):
elapsed = (time.time() - self.start) or 0.000001
rate = self.reconstruction_part_count / elapsed
total_part_count = (self.part_count *
self.device_count /
self.reconstruction_device_count)
self.logger.info(
_("%(reconstructed)d/%(total)d (%(percentage).2f%%)"
" partitions of %(device)d/%(dtotal)d "
"(%(dpercentage).2f%%) devices"
" reconstructed in %(time).2fs "
"(%(rate).2f/sec, %(remaining)s remaining)"),
{'reconstructed': self.reconstruction_part_count,
'total': self.part_count,
'percentage':
self.reconstruction_part_count * 100.0 / self.part_count,
'device': self.reconstruction_device_count,
'dtotal': self.device_count,
'dpercentage':
self.reconstruction_device_count * 100.0 / self.device_count,
'time': time.time() - self.start, 'rate': rate,
'remaining': '%d%s' %
compute_eta(self.start,
self.reconstruction_part_count,
total_part_count)})
if self.suffix_count and self.partition_times:
self.logger.info(
_("%(checked)d suffixes checked - "
"%(hashed).2f%% hashed, %(synced).2f%% synced"),
{'checked': self.suffix_count,
'hashed': (self.suffix_hash * 100.0) / self.suffix_count,
'synced': (self.suffix_sync * 100.0) / self.suffix_count})
self.partition_times.sort()
self.logger.info(
_("Partition times: max %(max).4fs, "
"min %(min).4fs, med %(med).4fs"),
{'max': self.partition_times[-1],
'min': self.partition_times[0],
'med': self.partition_times[
len(self.partition_times) // 2]})
else:
self.logger.info(
_("Nothing reconstructed for %s seconds."),
(time.time() - self.start))
def kill_coros(self):
"""Utility function that kills all coroutines currently running."""
for coro in list(self.run_pool.coroutines_running):
try:
coro.kill(GreenletExit)
except GreenletExit:
pass
def heartbeat(self):
"""
Loop that runs in the background during reconstruction. It
periodically logs progress.
"""
while True:
sleep(self.stats_interval)
self.stats_line()
def detect_lockups(self):
"""
In testing, the pool.waitall() call very occasionally failed to return.
This is an attempt to make sure the reconstructor finishes its
reconstruction pass in some eventuality.
"""
while True:
sleep(self.lockup_timeout)
if self.reconstruction_count == self.last_reconstruction_count:
self.logger.error(_("Lockup detected.. killing live coros."))
self.kill_coros()
self.last_reconstruction_count = self.reconstruction_count
def _get_hashes(self, policy, path, recalculate=None, do_listdir=False):
df_mgr = self._df_router[policy]
hashed, suffix_hashes = tpool_reraise(
df_mgr._get_hashes, path, recalculate=recalculate,
do_listdir=do_listdir, reclaim_age=self.reclaim_age)
self.logger.update_stats('suffix.hashes', hashed)
return suffix_hashes
def get_suffix_delta(self, local_suff, local_index,
remote_suff, remote_index):
"""
Compare the local suffix hashes with the remote suffix hashes
for the given local and remote fragment indexes. Return those
suffixes which should be synced.
:param local_suff: the local suffix hashes (from _get_hashes)
:param local_index: the local fragment index for the job
:param remote_suff: the remote suffix hashes (from remote
REPLICATE request)
:param remote_index: the remote fragment index for the job
:returns: a list of strings, the suffix dirs to sync
"""
suffixes = []
for suffix, sub_dict_local in local_suff.items():
sub_dict_remote = remote_suff.get(suffix, {})
if (sub_dict_local.get(None) != sub_dict_remote.get(None) or
sub_dict_local.get(local_index) !=
sub_dict_remote.get(remote_index)):
suffixes.append(suffix)
return suffixes
def rehash_remote(self, node, job, suffixes):
try:
with Timeout(self.http_timeout):
conn = http_connect(
node['replication_ip'], node['replication_port'],
node['device'], job['partition'], 'REPLICATE',
'/' + '-'.join(sorted(suffixes)),
headers=self.headers)
conn.getresponse().read()
except (Exception, Timeout):
self.logger.exception(
_("Trying to sync suffixes with %s") % self._full_path(
node, job['partition'], '', job['policy']))
def _get_suffixes_to_sync(self, job, node):
"""
For SYNC jobs we need to make a remote REPLICATE request to get
the remote node's current suffix's hashes and then compare to our
local suffix's hashes to decide which suffixes (if any) are out
of sync.
:param: the job dict, with the keys defined in ``_get_part_jobs``
:param node: the remote node dict
:returns: a (possibly empty) list of strings, the suffixes to be
synced with the remote node.
"""
# get hashes from the remote node
remote_suffixes = None
try:
with Timeout(self.http_timeout):
resp = http_connect(
node['replication_ip'], node['replication_port'],
node['device'], job['partition'], 'REPLICATE',
'', headers=self.headers).getresponse()
if resp.status == HTTP_INSUFFICIENT_STORAGE:
self.logger.error(
_('%s responded as unmounted'),
self._full_path(node, job['partition'], '',
job['policy']))
elif resp.status != HTTP_OK:
full_path = self._full_path(node, job['partition'], '',
job['policy'])
self.logger.error(
_("Invalid response %(resp)s from %(full_path)s"),
{'resp': resp.status, 'full_path': full_path})
else:
remote_suffixes = pickle.loads(resp.read())
except (Exception, Timeout):
# all exceptions are logged here so that our caller can
# safely catch our exception and continue to the next node
# without logging
self.logger.exception('Unable to get remote suffix hashes '
'from %r' % self._full_path(
node, job['partition'], '',
job['policy']))
if remote_suffixes is None:
raise SuffixSyncError('Unable to get remote suffix hashes')
suffixes = self.get_suffix_delta(job['hashes'],
job['frag_index'],
remote_suffixes,
node['index'])
# now recalculate local hashes for suffixes that don't
# match so we're comparing the latest
local_suff = self._get_hashes(job['policy'], job['path'],
recalculate=suffixes)
suffixes = self.get_suffix_delta(local_suff,
job['frag_index'],
remote_suffixes,
node['index'])
self.suffix_count += len(suffixes)
return suffixes
def delete_reverted_objs(self, job, objects, frag_index):
"""
For EC we can potentially revert only some of a partition
so we'll delete reverted objects here. Note that we delete
the fragment index of the file we sent to the remote node.
:param job: the job being processed
:param objects: a dict of objects to be deleted, each entry maps
hash=>timestamp
:param frag_index: (int) the fragment index of data files to be deleted
"""
df_mgr = self._df_router[job['policy']]
for object_hash, timestamps in objects.items():
try:
df = df_mgr.get_diskfile_from_hash(
job['local_dev']['device'], job['partition'],
object_hash, job['policy'],
frag_index=frag_index)
df.purge(timestamps['ts_data'], frag_index)
except DiskFileError:
self.logger.exception(
'Unable to purge DiskFile (%r %r %r)',
object_hash, timestamps['ts_data'], frag_index)
continue
def process_job(self, job):
"""
Sync the local partition with the remote node(s) according to
the parameters of the job. For primary nodes, the SYNC job type
will define both left and right hand sync_to nodes to ssync with
as defined by this primary nodes index in the node list based on
the fragment index found in the partition. For non-primary
nodes (either handoff revert, or rebalance) the REVERT job will
define a single node in sync_to which is the proper/new home for
the fragment index.
N.B. ring rebalancing can be time consuming and handoff nodes'
fragment indexes do not have a stable order, it's possible to
have more than one REVERT job for a partition, and in some rare
failure conditions there may even also be a SYNC job for the
same partition - but each one will be processed separately
because each job will define a separate list of node(s) to
'sync_to'.
:param: the job dict, with the keys defined in ``_get_job_info``
"""
self.headers['X-Backend-Storage-Policy-Index'] = int(job['policy'])
begin = time.time()
if job['job_type'] == REVERT:
self._revert(job, begin)
else:
self._sync(job, begin)
self.partition_times.append(time.time() - begin)
self.reconstruction_count += 1
def _sync(self, job, begin):
"""
Process a SYNC job.
"""
self.logger.increment(
'partition.update.count.%s' % (job['local_dev']['device'],))
# after our left and right partners, if there's some sort of
# failure we'll continue onto the remaining primary nodes and
# make sure they're in sync - or potentially rebuild missing
# fragments we find
dest_nodes = itertools.chain(
job['sync_to'],
# I think we could order these based on our index to better
# protect against a broken chain
[
n for n in
job['policy'].object_ring.get_part_nodes(job['partition'])
if n['id'] != job['local_dev']['id'] and
n['id'] not in (m['id'] for m in job['sync_to'])
],
)
syncd_with = 0
for node in dest_nodes:
if syncd_with >= len(job['sync_to']):
# success!
break
try:
suffixes = self._get_suffixes_to_sync(job, node)
except SuffixSyncError:
continue
if not suffixes:
syncd_with += 1
continue
# ssync any out-of-sync suffixes with the remote node
success, _ = ssync_sender(
self, node, job, suffixes)()
# let remote end know to rehash it's suffixes
self.rehash_remote(node, job, suffixes)
# update stats for this attempt
self.suffix_sync += len(suffixes)
self.logger.update_stats('suffix.syncs', len(suffixes))
if success:
syncd_with += 1
self.logger.timing_since('partition.update.timing', begin)
def _revert(self, job, begin):
"""
Process a REVERT job.
"""
self.logger.increment(
'partition.delete.count.%s' % (job['local_dev']['device'],))
# we'd desperately like to push this partition back to it's
# primary location, but if that node is down, the next best thing
# is one of the handoff locations - which *might* be us already!
dest_nodes = itertools.chain(
job['sync_to'],
job['policy'].object_ring.get_more_nodes(job['partition']),
)
syncd_with = 0
reverted_objs = {}
for node in dest_nodes:
if syncd_with >= len(job['sync_to']):
break
if node['id'] == job['local_dev']['id']:
# this is as good a place as any for this data for now
break
success, in_sync_objs = ssync_sender(
self, node, job, job['suffixes'])()
self.rehash_remote(node, job, job['suffixes'])
if success:
syncd_with += 1
reverted_objs.update(in_sync_objs)
if syncd_with >= len(job['sync_to']):
self.delete_reverted_objs(
job, reverted_objs, job['frag_index'])
self.logger.timing_since('partition.delete.timing', begin)
def _get_part_jobs(self, local_dev, part_path, partition, policy):
"""
Helper function to build jobs for a partition, this method will
read the suffix hashes and create job dictionaries to describe
the needed work. There will be one job for each fragment index
discovered in the partition.
For a fragment index which corresponds to this node's ring
index, a job with job_type SYNC will be created to ensure that
the left and right hand primary ring nodes for the part have the
corresponding left and right hand fragment archives.
A fragment index (or entire partition) for which this node is
not the primary corresponding node, will create job(s) with
job_type REVERT to ensure that fragment archives are pushed to
the correct node and removed from this one.
A partition may result in multiple jobs. Potentially many
REVERT jobs, and zero or one SYNC job.
:param local_dev: the local device
:param part_path: full path to partition
:param partition: partition number
:param policy: the policy
:returns: a list of dicts of job info
"""
# find all the fi's in the part, and which suffixes have them
hashes = self._get_hashes(policy, part_path, do_listdir=True)
non_data_fragment_suffixes = []
data_fi_to_suffixes = defaultdict(list)
for suffix, fi_hash in hashes.items():
if not fi_hash:
# this is for sanity and clarity, normally an empty
# suffix would get del'd from the hashes dict, but an
# OSError trying to re-hash the suffix could leave the
# value empty - it will log the exception; but there's
# no way to properly address this suffix at this time.
continue
data_frag_indexes = [f for f in fi_hash if f is not None]
if not data_frag_indexes:
non_data_fragment_suffixes.append(suffix)
else:
for fi in data_frag_indexes:
data_fi_to_suffixes[fi].append(suffix)
# helper to ensure consistent structure of jobs
def build_job(job_type, frag_index, suffixes, sync_to):
return {
'job_type': job_type,
'frag_index': frag_index,
'suffixes': suffixes,
'sync_to': sync_to,
'partition': partition,
'path': part_path,
'hashes': hashes,
'policy': policy,
'local_dev': local_dev,
# ssync likes to have it handy
'device': local_dev['device'],
}
# aggregate jobs for all the fragment index in this part
jobs = []
# check the primary nodes - to see if the part belongs here
part_nodes = policy.object_ring.get_part_nodes(partition)
for node in part_nodes:
if node['id'] == local_dev['id']:
# this partition belongs here, we'll need a sync job
frag_index = node['index']
try:
suffixes = data_fi_to_suffixes.pop(frag_index)
except KeyError:
suffixes = []
sync_job = build_job(
job_type=SYNC,
frag_index=frag_index,
suffixes=suffixes,
sync_to=_get_partners(frag_index, part_nodes),
)
# ssync callback to rebuild missing fragment_archives
sync_job['sync_diskfile_builder'] = self.reconstruct_fa
jobs.append(sync_job)
break
# assign remaining data fragment suffixes to revert jobs
ordered_fis = sorted((len(suffixes), fi) for fi, suffixes
in data_fi_to_suffixes.items())
for count, fi in ordered_fis:
revert_job = build_job(
job_type=REVERT,
frag_index=fi,
suffixes=data_fi_to_suffixes[fi],
sync_to=[part_nodes[fi]],
)
jobs.append(revert_job)
# now we need to assign suffixes that have no data fragments
if non_data_fragment_suffixes:
if jobs:
# the first job will be either the sync_job, or the
# revert_job for the fragment index that is most common
# among the suffixes
jobs[0]['suffixes'].extend(non_data_fragment_suffixes)
else:
# this is an unfortunate situation, we need a revert job to
# push partitions off this node, but none of the suffixes
# have any data fragments to hint at which node would be a
# good candidate to receive the tombstones.
jobs.append(build_job(
job_type=REVERT,
frag_index=None,
suffixes=non_data_fragment_suffixes,
# this is super safe
sync_to=part_nodes,
# something like this would be probably be better
# sync_to=random.sample(part_nodes, 3),
))
# return a list of jobs for this part
return jobs
def collect_parts(self, override_devices=None,
override_partitions=None):
"""
Helper for yielding partitions in the top level reconstructor
"""
override_devices = override_devices or []
override_partitions = override_partitions or []
ips = whataremyips(self.bind_ip)
for policy in POLICIES:
if policy.policy_type != EC_POLICY:
continue
self._diskfile_mgr = self._df_router[policy]
self.load_object_ring(policy)
data_dir = get_data_dir(policy)
local_devices = list(itertools.ifilter(
lambda dev: dev and is_local_device(
ips, self.port,
dev['replication_ip'], dev['replication_port']),
policy.object_ring.devs))
if override_devices:
self.device_count = len(override_devices)
else:
self.device_count = len(local_devices)
for local_dev in local_devices:
if override_devices and (local_dev['device'] not in
override_devices):
continue
self.reconstruction_device_count += 1
dev_path = self._df_router[policy].get_dev_path(
local_dev['device'])
if not dev_path:
self.logger.warn(_('%s is not mounted'),
local_dev['device'])
continue
obj_path = join(dev_path, data_dir)
tmp_path = join(dev_path, get_tmp_dir(int(policy)))
unlink_older_than(tmp_path, time.time() -
self.reclaim_age)
if not os.path.exists(obj_path):
try:
mkdirs(obj_path)
except Exception:
self.logger.exception(
'Unable to create %s' % obj_path)
continue
try:
partitions = os.listdir(obj_path)
except OSError:
self.logger.exception(
'Unable to list partitions in %r' % obj_path)
continue
self.part_count += len(partitions)
for partition in partitions:
part_path = join(obj_path, partition)
if not (partition.isdigit() and
os.path.isdir(part_path)):
self.logger.warning(
'Unexpected entity in data dir: %r' % part_path)
remove_file(part_path)
self.reconstruction_part_count += 1
continue
partition = int(partition)
if override_partitions and (partition not in
override_partitions):
continue
part_info = {
'local_dev': local_dev,
'policy': policy,
'partition': partition,
'part_path': part_path,
}
yield part_info
self.reconstruction_part_count += 1
def build_reconstruction_jobs(self, part_info):
"""
Helper function for collect_jobs to build jobs for reconstruction
using EC style storage policy
"""
jobs = self._get_part_jobs(**part_info)
random.shuffle(jobs)
if self.handoffs_first:
# Move the handoff revert jobs to the front of the list
jobs.sort(key=lambda job: job['job_type'], reverse=True)
self.job_count += len(jobs)
return jobs
def _reset_stats(self):
self.start = time.time()
self.job_count = 0
self.part_count = 0
self.device_count = 0
self.suffix_count = 0
self.suffix_sync = 0
self.suffix_hash = 0
self.reconstruction_count = 0
self.reconstruction_part_count = 0
self.reconstruction_device_count = 0
self.last_reconstruction_count = -1
def delete_partition(self, path):
self.logger.info(_("Removing partition: %s"), path)
tpool.execute(shutil.rmtree, path, ignore_errors=True)
def reconstruct(self, **kwargs):
"""Run a reconstruction pass"""
self._reset_stats()
self.partition_times = []
stats = spawn(self.heartbeat)
lockup_detector = spawn(self.detect_lockups)
sleep() # Give spawns a cycle
try:
self.run_pool = GreenPool(size=self.concurrency)
for part_info in self.collect_parts(**kwargs):
if not self.check_ring(part_info['policy'].object_ring):
self.logger.info(_("Ring change detected. Aborting "
"current reconstruction pass."))
return
jobs = self.build_reconstruction_jobs(part_info)
if not jobs:
# If this part belongs on this node, _get_part_jobs
# will *always* build a sync_job - even if there's
# no suffixes in the partition that needs to sync.
# If there's any suffixes in the partition then our
# job list would have *at least* one revert job.
# Therefore we know this part a) doesn't belong on
# this node and b) doesn't have any suffixes in it.
self.run_pool.spawn(self.delete_partition,
part_info['part_path'])
for job in jobs:
self.run_pool.spawn(self.process_job, job)
with Timeout(self.lockup_timeout):
self.run_pool.waitall()
except (Exception, Timeout):
self.logger.exception(_("Exception in top-level"
"reconstruction loop"))
self.kill_coros()
finally:
stats.kill()
lockup_detector.kill()
self.stats_line()
def run_once(self, *args, **kwargs):
start = time.time()
self.logger.info(_("Running object reconstructor in script mode."))
override_devices = list_from_csv(kwargs.get('devices'))
override_partitions = [int(p) for p in
list_from_csv(kwargs.get('partitions'))]
self.reconstruct(
override_devices=override_devices,
override_partitions=override_partitions)
total = (time.time() - start) / 60
self.logger.info(
_("Object reconstruction complete (once). (%.02f minutes)"), total)
if not (override_partitions or override_devices):
dump_recon_cache({'object_reconstruction_time': total,
'object_reconstruction_last': time.time()},
self.rcache, self.logger)
def run_forever(self, *args, **kwargs):
self.logger.info(_("Starting object reconstructor in daemon mode."))
# Run the reconstructor continually
while True:
start = time.time()
self.logger.info(_("Starting object reconstruction pass."))
# Run the reconstructor
self.reconstruct()
total = (time.time() - start) / 60
self.logger.info(
_("Object reconstruction complete. (%.02f minutes)"), total)
dump_recon_cache({'object_reconstruction_time': total,
'object_reconstruction_last': time.time()},
self.rcache, self.logger)
self.logger.debug('reconstruction sleeping for %s seconds.',
self.interval)
sleep(self.interval)<|fim▁end|> | |
<|file_name|>data_class.py<|end_file_name|><|fim▁begin|># DATA class v1.0 written by HR,JB@KIT 2011, 2016
'''
DATA exchange class, also holds global variables for thread management.
Generalized version based on TIP.
'''
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import time
import os
from threading import Lock
import numpy as np
from qkit.storage import store as hdf_lib
from qkit.gui.plot import plot as qviewkit
class DATA(object):
'''
DATA class. Controls all access to parameter values and stored data.
'''
class LOCALHOST(object):
def __init__(self,config):
self.name = config.get('LOCALHOST','name')
self.ip = config.get('LOCALHOST','ip')
self.port = config.getint('LOCALHOST','port')
class REMOTEHOST(object):
def __init__(self,config):
self.name = config.get('REMOTEHOST','name')
self.ip = config.get('REMOTEHOST','ip')
self.port = config.getint('REMOTEHOST','port')
class PARAMETER(object):
def __init__(self,config,p_index,p_attr):
'''
Initialize parameter attributes, mostly taken from the config file.
'''
self.p_index = p_index
self.name = config.get(str(p_attr),'name')
self.interval = config.getfloat(str(p_attr),'interval')
self.data_request_object = lambda: 0 #this is written by server_main.py
self.value = 0
self.timestamp = 0
self.next_schedule = time.time() + self.interval
self.logging = bool(int(config.get(str(p_attr),'logging')))
self.log_path = config.get(str(p_attr),'log_path')<|fim▁hole|> print("Parameter %s loaded."%str(self.name))
def get_all(self):
'''
Get all parameter attributes.
'''
with Lock():
return {
"parameter": self.p_index,
"name":self.name,
"interval":self.interval,
"value":self.value,
"timestamp":self.timestamp,
"next_schedule":self.next_schedule,
}
def set_interval(self,interval):
'''
Setup the scheduling, which corresponds to the value request interval.
'''
interval = float(interval)
if interval == 0:
interval = 120*365*24*3600 #120 years
self.next_schedule += -self.interval+interval #update next schedule
self.interval = interval
def get_last_value(self):
with Lock():
return self.value
def get_timestamp(self):
with Lock():
return self.timestamp
def get_history(self,range,nchunks=100):
'''
Read out the h5 file.
- range: history data range
- nchunks: number of data points to be returned
'''
if self.url_timestamps != None:
try:
with self.log_lock:
timestamps = np.array(self.hf[self.url_timestamps])
values = np.array(self.hf[self.url_values])
data_points_requested_mask = np.where(time.time()-timestamps < range*3600)
timestamps_requested = timestamps[data_points_requested_mask]
data_points_requested = values[data_points_requested_mask]
#return only nchunks data points
if len(data_points_requested) > nchunks:
timestamp_chunks = np.array(np.split(timestamps_requested[:(len(timestamps_requested)-len(timestamps_requested)%nchunks)],nchunks))
timestamps = timestamp_chunks[:,int(0.5*len(timestamps_requested)/nchunks)]
data_chunks = np.array(np.split(data_points_requested[:(len(data_points_requested)-len(data_points_requested)%nchunks)],nchunks))
#calculate medians and return them instead of the mean (due to runaways in the log file)
medians = np.sort(data_chunks,axis=-1)[:,int(0.5*len(data_points_requested)/nchunks)]
return [timestamps,medians]
else:
return [timestamps_requested,data_points_requested]
except KeyError: #AttributeError, NameError:
print('Error opening h5 log file.')
return [0]
else:
return [0]
def store_value(self,value):
'''
Store method, used by the worker.
'''
with Lock():
try:
self.value = float(value)
except ValueError:
print('type cast error, ignoring')
self.timestamp = time.time()
if self.logging:
self.append_to_log()
def create_logfile(self):
print('Create new log file for parameter %s.'%self.name)
self.fname = os.path.join(self.log_path,self.name.replace(' ','_')+time.strftime('%d%m%Y%H%M%S')+'.h5')
#print self.fname
self.hf = hdf_lib.Data(self.fname, mode='a')
self.hdf_t = self.hf.add_coordinate('timestamps')
self.hdf_v = self.hf.add_value_vector('values', x = self.hdf_t)
self.url_timestamps = '/entry/data0/timestamps'
self.url_values = '/entry/data0/values'
view = self.hf.add_view('data_vs_time', x = self.hdf_t, y = self.hdf_v) #fit
def append_to_log(self):
with self.log_lock:
self.hdf_t.append(float(self.get_timestamp()))
self.hdf_v.append(float(self.get_last_value()))
def close_logfile(self):
self.hf.close_file()
def schedule(self):
'''
Specifiy whether the parameter is to be updated,
typicalled called in each worker iteration.
Returns True if new parameter value needs to be read.
'''
if time.time() > self.next_schedule:
while time.time() > self.next_schedule:
self.next_schedule += self.interval
return True
else:
return False
def set_schedule(self):
self.next_schedule = time.time()
return True
def __init__(self,config):
'''
Reads the cfg file and instanciates all parameters accordingly.
'''
self.wants_abort = False
self.debug = True
self.cycle_time = config.getfloat('worker','cycle_time')
p_instances = config.get('parameters','p').split(",") #parameter instance names
#print(p_instances)
self.parameters = [self.PARAMETER(config,i,p) for i,p in enumerate(p_instances)] #instanciate parameter array
for i,p_i in enumerate(p_instances): #create human readable aliases, such that objects are accessible from clients according to the seetings.cfg entry in []
setattr(self,str(p_i),self.parameters[i])
self.localhost = self.LOCALHOST(config)
#self.remotehost = self.REMOTEHOST(config)
self.ctrl_lock = Lock()
def atexit(self):
self.set_wants_abort()
def get_wants_abort(self):
with self.ctrl_lock:
return self.wants_abort
def set_wants_abort(self):
with self.ctrl_lock:
self.wants_abort = True
if __name__ == "__main__":
DATA = DATA()<|fim▁end|> | self.log_lock = Lock()
self.url_timestamps = None |
<|file_name|>DecisionAlternative_XNEWARRAY_Wrong.java<|end_file_name|><|fim▁begin|>package jbse.tree;
public final class DecisionAlternative_XNEWARRAY_Wrong extends DecisionAlternative_XNEWARRAY {
private static final String WRONG_ID = "XNEWARRAY_Wrong";
private static final int HASH_CODE = 2;
DecisionAlternative_XNEWARRAY_Wrong(boolean isConcrete) {
super(isConcrete, (isConcrete ? 1 : HASH_CODE));
}
@Override
public boolean ok() {
return false;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
<|fim▁hole|> return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return true;
}
@Override
public int hashCode() {
return HASH_CODE;
}
@Override
public String toString() {
return WRONG_ID;
}
}<|fim▁end|> | }
if (obj == null) {
|
<|file_name|>fareRules.js<|end_file_name|><|fim▁begin|>const uAPI = require('../../index');
const config = require('../../test/testconfig');
const AirService = uAPI.createAirService(
{
auth: config,
debug: 2,
production: false,
}
);
const AirServiceQuiet = uAPI.createAirService(
{
auth: config,
production: false,<|fim▁hole|>);
const requestPTC = 'ADT';
const shop_params = {
legs: [
{
from: 'LOS',
to: 'IST',
departureDate: '2019-06-18',
},
{
from: 'IST',
to: 'LOS',
departureDate: '2019-06-21',
},
],
passengers: {
[requestPTC]: 1,
},
cabins: ['Economy'],
requestId: 'test',
};
AirServiceQuiet.shop(shop_params)
.then((results) => {
const forwardSegments = results['0'].directions['0']['0'].segments;
const backSegments = results['0'].directions['1']['0'].segments;
const farerules_params = {
segments: forwardSegments.concat(backSegments),
passengers: shop_params.passengers,
long: true,
requestId: 'test',
};
return AirService.fareRules(farerules_params);
})
.then(
(res) => {
console.log(JSON.stringify(res));
},
err => console.error(err)
).catch((err) => {
console.error(err);
});<|fim▁end|> | } |
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>/*
* Copyright (c) 2016-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc.- initial API and implementation
*/
import {Argument} from "./spi/decorator/parameter";
import {Parameter} from "./spi/decorator/parameter";
import {ArgumentProcessor} from "./spi/decorator/argument-processor";
import {Log} from "./spi/log/log";
import {CheDir} from "./internal/dir/che-dir";
import {CheTest} from "./internal/test/che-test";
import {CheAction} from "./internal/action/che-action";
import {ErrorMessage} from "./spi/error/error-message";
/**
* Entry point of this library providing commands.
* @author Florent Benoit
*/
export class EntryPoint {
args: Array<string>;
@Argument({description: "Name of the command to execute from this entry point."})
commandName : string;
@Parameter({names: ["--logger-debug"], description: "Enable the logger in debug mode"})
debugLogger : boolean;
@Parameter({names: ["--logger-prefix-off"], description: "Disable prefix mode in logging"})
prefixOffLogger : boolean;
constructor() {
this.args = ArgumentProcessor.inject(this, process.argv.slice(2));
process.on('SIGINT', () => {
Log.getLogger().warn('CTRL-C hit, exiting...');
process.exit(1);
});
}
/**
* Run this entry point and analyze args to dispatch to the correct entry.
*/
run() : void {
// turn into debugging mode
if (this.debugLogger) {
Log.enableDebug();
}
<|fim▁hole|> }
try {
var promise : Promise<any>;
switch(this.commandName) {
case 'che-test':
let cheTest: CheTest = new CheTest(this.args);
promise = cheTest.run();
break;
case 'che-action':
let cheAction: CheAction = new CheAction(this.args);
promise = cheAction.run();
break;
case 'che-dir':
let cheDir: CheDir = new CheDir(this.args);
promise = cheDir.run();
break;
default:
Log.getLogger().error('Invalid choice of command-name');
process.exit(1);
}
// handle error of the promise
promise.catch((error) => {
let exitCode : number = 1;
if (error instanceof ErrorMessage) {
exitCode = error.getExitCode();
error = error.getError();
}
try {
let errorMessage = JSON.parse(error);
if (errorMessage.message) {
Log.getLogger().error(errorMessage.message);
} else {
Log.getLogger().error(error.toString());
}
} catch (e) {
Log.getLogger().error(error.toString());
if (error instanceof TypeError || error instanceof SyntaxError) {
console.log(error.stack);
}
}
process.exit(exitCode);
});
} catch (e) {
Log.getLogger().error(e);
if (e instanceof TypeError || e instanceof SyntaxError) {
console.log(e.stack);
}
}
}
}
// call run method
new EntryPoint().run();<|fim▁end|> | if (this.prefixOffLogger) {
Log.disablePrefix(); |
<|file_name|>proxy.py<|end_file_name|><|fim▁begin|>import uuid
from path_helpers import path
import numpy as np
try:
from base_node_rpc.proxy import ConfigMixinBase, StateMixinBase
import arduino_helpers.hardware.teensy as teensy
from .node import (Proxy as _Proxy, I2cProxy as _I2cProxy,
SerialProxy as _SerialProxy)
class ProxyMixin(object):
'''
Mixin class to add convenience wrappers around methods of the generated
`node.Proxy` class.
For example, expose config and state getters/setters as attributes.
'''
host_package_name = str(path(__file__).parent.name.replace('_', '-'))
def __init__(self, *args, **kwargs):
super(ProxyMixin, self).__init__(*args, **kwargs)<|fim▁hole|>
class Proxy(ProxyMixin, _Proxy):
pass
class I2cProxy(ProxyMixin, _I2cProxy):
pass
class SerialProxy(ProxyMixin, _SerialProxy):
pass
except (ImportError, TypeError):
Proxy = None
I2cProxy = None
SerialProxy = None<|fim▁end|> | |
<|file_name|>task_7_6.py<|end_file_name|><|fim▁begin|>#Задача 7. Вариант 6
#компьютер загадывает название одного из семи городов России, имеющих действующий метрополитен, а игрок должен его угадать.
#Борщёва В.О
#28.03.2016
import random
subways=('Москва','Санкт-Петербург','Нижний Новгород','Новосибирск','Самара','Екатеринбург','Казань')
subway=random.randint(0,6)
rand=subways[subway]
ball=100
print('я загадал один город,имеющий дейстующий метрополитен')
#print(rand)
otvet=0
while (otvet)!=(rand):
otvet=input("Введите один из городов:")
if(otvet)!=(rand):
print("Вы не угадали. Попробуйте снова.")
ball/=2
elif (otvet)==(rand):
print("Ваш счет:"+ str(ball))
<|fim▁hole|><|fim▁end|> | break
input(" Нажмите Enter для выхода") |
<|file_name|>fr-MU.ts<|end_file_name|><|fim▁begin|>/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
export default [
'fr-MU',
[
['AM', 'PM'],
,
],
,
[
['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],
['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
['di', 'lu', 'ma', 'me', 'je', 've', 'sa']
],
,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.',
'déc.'<|fim▁hole|> [
'janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre',
'octobre', 'novembre', 'décembre'
]
],
, [['av. J.-C.', 'ap. J.-C.'], , ['avant Jésus-Christ', 'après Jésus-Christ']], 1, [6, 0],
['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
[
'{1} {0}',
'{1} \'à\' {0}',
,
],
[',', ' ', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'], 'Rs', 'roupie mauricienne',
function(n: number):
number {
let i = Math.floor(Math.abs(n));
if (i === 0 || i === 1) return 1;
return 5;
}
];<|fim▁end|> | ], |
<|file_name|>tableButton.js<|end_file_name|><|fim▁begin|>//ButtonTable is a very very special case, because I am still not sure why it is a table :-)
// alternate design is to make it a field. Filed looks more logical, but table is more convenient at this time.
// we will review this design later and decide, meanwhile here is the ButtonPane table that DOES NOT inherit from AbstractTable
//button field is only a data structure that is stored under buttons collection
var ButtonField = function (nam, label, actionName)
{
this.name = nam;
this.label = label;
this.actionName = actionName;
};
var ButtonPanel = function ()
{
this.name = null;
this.P2 = null;
this.renderingOption = null;
this.buttons = new Object(); //collection of buttonFields
};
ButtonPanel.prototype.setData = function (dc)
{
var data = dc.grids[this.name];
if (data.length <= 1)
{
if (this.renderingOption == 'nextToEachOther')
{
this.P2.hideOrShowPanels([this.name], 'none');
}
else
{
var listName = this.name + 'ButtonList';
var buttonList = this.P2.doc.getElementById(listName);
//should we do the following or just say buttonList.innerHTML = ''
while (buttonList.options.length)
{
buttonList.remove(0);
}
}
return;
}
data = this.transposeIfRequired(data);
//possible that it was hidden earlier.. Let us show it first
this.P2.hideOrShowPanels([this.name], '');
if (this.renderingOption == 'nextToEachOther')
this.enableButtons(data);
else
this.buildDropDown(data);
};
//enable/disable buttons in a button panel based on data received from server
ButtonPanel.prototype.enableButtons = function (data)
{
var doc = this.P2.doc;
var n = data.length;
if (n <= 1) return;
//if the table has its second column, it is interpreted as Yes/No for enable. 0 or empty string is No, everything else is Yes
var hasFlag = data[0].length > 1;
//for convenience, get the buttons into a collection indexed by name
var btnsToEnable = {};
for (var i = 1; i < n; i++)
{
var row = data[i];
if (hasFlag)
{
var flag = row[1];
if (!flag || flag == '0')
continue;
}
btnsToEnable[row[0]] = true;
}
//now let us go thru each button, and hide or who it
for (var btnName in this.buttons)
{
var ele = doc.getElementById(btnName);
if (!ele)
{
debug('Design Error: Button panel ' + this.name + ' has not produced a DOM element with name ' + btnName);
continue;
}
ele.style.display = btnsToEnable[btnName] ? '' : 'none';
}
};
ButtonPanel.prototype.buildDropDown = function (data)
{
var flag;
var doc = this.P2.doc;
var ele = doc.getElementById(this.name + 'ButtonList');
if (!ele)
{
debug('DESIGN ERROR: Button Panel ' + this.name + ' has not produced a drop-down boc with name = ' + this.Name + 'ButtonList');
return;
}<|fim▁hole|> //that took away the first one also. Add a blank option
var option = doc.createElement('option');
ele.appendChild(option);
//this.buttons has all the button names defined for this panel with value = 'disabled'
// i.e. this.buttons['button1'] = 'disabled';
// for the rows that are in data, mark them as enabled.
var n = data.length;
if (n <= 1) return;
if ((n == 2) && (data[0].length > 1))
{
var hasFlag = data[0].length > 1;
for (var i = 0; i < data[0].length; i++)
{
if (hasFlag)
{
flag = data[1][i];
if (!flag || flag == '0')
continue;
}
var btnName = data[0][i];
var btn = this.buttons[btnName];
if (!btn)
{
debug('Button Panel ' + this.name + ' is not defined with a button with name ' + btnName + ' but server is trying to enable this button');
continue;
}
option = doc.createElement('option');
option.value = btn.actionName;
option.innerHTML = btn.label;
ele.appendChild(option);
}
}
else
{
var hasFlag = data[0].length > 1;
for (var i = 1; i < n; i++)
{
if (hasFlag)
{
flag = data[i][1];
if (!flag || flag == '0')
continue;
}
var btnName = data[i][0];
var btn = this.buttons[btnName];
if (!btn)
{
debug('Button Panel ' + this.name + ' is not defined with a button with name ' + btnName + ' but server is trying to enable this button');
continue;
}
option = doc.createElement('option');
option.value = btn.actionName;
option.innerHTML = btn.label;
ele.appendChild(option);
}
}
};
//Standard way of getting data from server is a grid with first row as header row and rest a data rows.
//But it is possible that server may send button names in first row, and optional second row as enable flag.
//We detect the second case, and transpose the grid, so that a common logic can be used.
ButtonPanel.prototype.transposeIfRequired = function (data)
{
//we need to transpose only if we have one or two rows
var nbrRows = data && data.length;
if (!nbrRows || nbrRows > 2)
return data;
var row = data[0];
var nbrCols = row.length;
if (!nbrCols)
return data;
//We make a simple assumption, that the label for last column can not clash with the name of a button.
if (!this.buttons[row[nbrCols - 1]])
return data;
//we transpose the grid, with an empty header row
var newData = null;
if (data.length == 1) //button name only
{
newData = [['']];
for (var i = 0; i < nbrCols; i++)
newData.push([row[i]]);
}
else
{
//button name with enable flag
newData = [['', '']];
var row1 = data[1];
for (var i = 0; i < nbrCols; i++)
newData.push([row[i], row1[i]]);
}
return newData;
};<|fim▁end|> | //zap options first
ele.innerHTML = ''; |
<|file_name|>spawn-types.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*<|fim▁hole|>
use std::thread::Thread;
use std::sync::mpsc::{channel, Sender};
type ctx = Sender<int>;
fn iotask(_tx: &ctx, ip: String) {
assert_eq!(ip, "localhost".to_string());
}
pub fn main() {
let (tx, _rx) = channel::<int>();
let t = Thread::scoped(move|| iotask(&tx, "localhost".to_string()) );
t.join().ok().unwrap();
}<|fim▁end|> | Make sure we can spawn tasks that take different types of
parameters. This is based on a test case for #520 provided by Rob
Arnold.
*/ |
<|file_name|>plot.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import sys
import numpy as np<|fim▁hole|>from matplotlib import pyplot as plt
def main():
infile = open(sys.argv[1])
data = np.array(map(lambda x:map(float, x.strip('\n').split('\t')), infile.readlines()))
X = data[:, 0:-1]
(N, D) = X.shape
Y = data[:, -1].reshape((N, 1))
plt.plot(X[np.where(Y == 0)[0]][:, 0], X[np.where(Y == 0)[0]][:, 1], 'b.')
plt.plot(X[np.where(Y == 1)[0]][:, 0], X[np.where(Y == 1)[0]][:, 1], 'r.')
plt.show()
infile.close()
if __name__ == '__main__':
main()<|fim▁end|> | |
<|file_name|>privateIdentifierChain.1.js<|end_file_name|><|fim▁begin|>//// [privateIdentifierChain.1.ts]
class A {
a?: A
#b?: A;
getA(): A {
return new A();
}
constructor() {
this?.#b; // Error
this?.a.#b; // Error
this?.getA().#b; // Error
}
}
//// [privateIdentifierChain.1.js]
"use strict";
class A {
constructor() {
<|fim▁hole|> }
#b;
getA() {
return new A();
}
}<|fim▁end|> | this?.#b; // Error
this?.a.#b; // Error
this?.getA().#b; // Error
|
<|file_name|>python_move_group_ns.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Author: William Baker
#
# This test is used to ensure planning with a MoveGroupInterface is
# possbile if the robot's move_group node is in a different namespace
import unittest
import numpy as np
import rospy
import rostest
import os
from moveit_ros_planning_interface._moveit_move_group_interface import MoveGroupInterface
class PythonMoveGroupNsTest(unittest.TestCase):
PLANNING_GROUP = "manipulator"
PLANNING_NS = "test_ns/"
@classmethod
def setUpClass(self):
self.group = MoveGroupInterface(self.PLANNING_GROUP, "%srobot_description"%self.PLANNING_NS, self.PLANNING_NS)
@classmethod
def tearDown(self):
pass
def check_target_setting(self, expect, *args):
if len(args) == 0:
args = [expect]
self.group.set_joint_value_target(*args)
res = self.group.get_joint_value_target()
self.assertTrue(np.all(np.asarray(res) == np.asarray(expect)),
"Setting failed for %s, values: %s" % (type(args[0]), res))
def test_target_setting(self):
n = self.group.get_variable_count()
self.check_target_setting([0.1] * n)
self.check_target_setting((0.2,) * n)
self.check_target_setting(np.zeros(n))
self.check_target_setting([0.3] * n, {name: 0.3 for name in self.group.get_active_joints()})
self.check_target_setting([0.5] + [0.3]*(n-1), "joint_1", 0.5)<|fim▁hole|> self.group.set_joint_value_target(target)
return self.group.compute_plan()
def test_validation(self):
current = np.asarray(self.group.get_current_joint_values())
plan1 = self.plan(current + 0.2)
plan2 = self.plan(current + 0.2)
# first plan should execute
self.assertTrue(self.group.execute(plan1))
# second plan should be invalid now (due to modified start point) and rejected
self.assertFalse(self.group.execute(plan2))
# newly planned trajectory should execute again
plan3 = self.plan(current)
self.assertTrue(self.group.execute(plan3))
if __name__ == '__main__':
PKGNAME = 'moveit_ros_planning_interface'
NODENAME = 'moveit_test_python_move_group'
rospy.init_node(NODENAME)
rostest.rosrun(PKGNAME, NODENAME, PythonMoveGroupNsTest)<|fim▁end|> |
def plan(self, target): |
<|file_name|>example_test.go<|end_file_name|><|fim▁begin|>package html2data_test
import (
"bufio"
"fmt"
"log"
"os"
"github.com/msoap/html2data"
)
func ExampleFromURL() {
doc := html2data.FromURL("http://example.com")
if doc.Err != nil {
log.Fatal(doc.Err)
}
// or with config
doc = html2data.FromURL("http://example.com", html2data.URLCfg{UA: "userAgent", TimeOut: 10, DontDetectCharset: false})
if doc.Err != nil {
log.Fatal(doc.Err)
}
}
func ExampleFromFile() {
doc := html2data.FromFile("file_name.html")
if doc.Err != nil {
log.Fatal(doc.Err)
}
}
func ExampleFromReader() {
doc := html2data.FromReader(bufio.NewReader(os.Stdin))
if doc.Err != nil {<|fim▁hole|>
func ExampleDoc_GetDataSingle() {
// get title
title, err := html2data.FromFile("cmd/html2data/test.html").GetDataSingle("title")
if err != nil {
log.Fatal(err)
}
fmt.Println("Title is:", title)
// Output: Title is: Title
}
func ExampleDoc_GetData() {
texts, _ := html2data.FromURL("http://example.com").GetData(map[string]string{"headers": "h1", "links": "a:attr(href)"})
// get all H1 headers:
if textOne, ok := texts["headers"]; ok {
for _, text := range textOne {
fmt.Println(text)
}
}
// get all urls from links
if links, ok := texts["links"]; ok {
for _, text := range links {
fmt.Println(text)
}
}
}
func ExampleDoc_GetDataFirst() {
texts, err := html2data.FromURL("http://example.com").GetDataFirst(map[string]string{"header": "h1", "first_link": "a:attr(href)"})
if err != nil {
log.Fatal(err)
}
// get H1 header:
fmt.Println("header: ", texts["header"])
// get URL in first link:
fmt.Println("first link: ", texts["first_link"])
}
func ExampleDoc_GetDataNested() {
texts, _ := html2data.FromFile("test.html").GetDataNested("div.article", map[string]string{"headers": "h1", "links": "a:attr(href)"})
for _, article := range texts {
// get all H1 headers inside each <div class="article">:
if textOne, ok := article["headers"]; ok {
for _, text := range textOne {
fmt.Println(text)
}
}
// get all urls from links inside each <div class="article">
if links, ok := article["links"]; ok {
for _, text := range links {
fmt.Println(text)
}
}
}
}
func ExampleDoc_GetDataNestedFirst() {
texts, err := html2data.FromFile("cmd/html2data/test.html").GetDataNestedFirst("div.block", map[string]string{"header": "h1", "link": "a:attr(href)", "sp": "span"})
if err != nil {
log.Fatal(err)
}
fmt.Println("")
for _, block := range texts {
// get first H1 header
fmt.Printf("header - %s\n", block["header"])
// get first link
fmt.Printf("first URL - %s\n", block["link"])
// get not exists span
fmt.Printf("span - '%s'\n", block["span"])
}
// Output:
// header - Head1.1
// first URL - http://url1
// span - ''
// header - Head2.1
// first URL - http://url2
// span - ''
}
func Example() {
doc := html2data.FromURL("http://example.com")
// or with config
// doc := FromURL("http://example.com", URLCfg{UA: "userAgent", TimeOut: 10, DontDetectCharset: true})
if doc.Err != nil {
log.Fatal(doc.Err)
}
// get title
title, _ := doc.GetDataSingle("title")
fmt.Println("Title is:", title)
title, _ = doc.GetDataSingle("title", html2data.Cfg{DontTrimSpaces: true})
fmt.Println("Title as is, with spaces:", title)
texts, _ := doc.GetData(map[string]string{"h1": "h1", "links": "a:attr(href)"})
// get all H1 headers:
if textOne, ok := texts["h1"]; ok {
for _, text := range textOne {
fmt.Println(text)
}
}
// get all urls from links
if links, ok := texts["links"]; ok {
for _, text := range links {
fmt.Println(text)
}
}
}<|fim▁end|> | log.Fatal(doc.Err)
}
} |
<|file_name|>short-fibonacci.rs<|end_file_name|><|fim▁begin|>use short_fibonacci::*;
#[test]
fn test_empty() {
assert_eq!(create_empty(), Vec::new());
}
#[test]
#[ignore]
fn test_buffer() {
for n in 0..10 {
let zeroized = create_buffer(n);
assert_eq!(zeroized.len(), n);
assert!(zeroized.iter().all(|&v| v == 0));
}
}
#[test]<|fim▁hole|> let fibb = fibonacci();
assert_eq!(fibb.len(), 5);
assert_eq!(fibb[0], 1);
assert_eq!(fibb[1], 1);
for window in fibb.windows(3) {
assert_eq!(window[0] + window[1], window[2]);
}
}<|fim▁end|> | #[ignore]
fn test_fibonacci() { |
<|file_name|>style.tsx<|end_file_name|><|fim▁begin|>import { CSSProperties } from "react"
export let ulStyles: CSSProperties = {
display: "flex",
listStyle: "none"
}
export let liStyles: CSSProperties = {
padding: "0 10px"
}
export let activeLinkStyle: CSSProperties = {
fontWeight: "bold",
textDecoration: "none"<|fim▁hole|><|fim▁end|> | } |
<|file_name|>block-copy-example.component.ts<|end_file_name|><|fim▁begin|>import {
Component,
ViewEncapsulation
} from '@angular/core';<|fim▁hole|> encapsulation: ViewEncapsulation.None,
selector: 'block-copy-example',
templateUrl: './block-copy-example.component.html'
})
export class BlockCopyExampleComponent {
activeTab: string = '';
constructor() {}
tabSelected($event: TabDirective): void {
this.activeTab = $event.heading;
}
}<|fim▁end|> |
import { TabDirective } from 'ngx-bootstrap/tabs';
@Component({ |
<|file_name|>server.py<|end_file_name|><|fim▁begin|># Copyright 2019 gRPC 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<|fim▁hole|># 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.
"""The example of four ways of data transmission using gRPC in Python."""
from threading import Thread
from concurrent import futures
import grpc
import demo_pb2_grpc
import demo_pb2
__all__ = 'DemoServer'
SERVER_ADDRESS = 'localhost:23333'
SERVER_ID = 1
class DemoServer(demo_pb2_grpc.GRPCDemoServicer):
# 一元模式(在一次调用中, 客户端只能向服务器传输一次请求数据, 服务器也只能返回一次响应)
# unary-unary(In a single call, the client can only send request once, and the server can
# only respond once.)
def SimpleMethod(self, request, context):
print("SimpleMethod called by client(%d) the message: %s" %
(request.client_id, request.request_data))
response = demo_pb2.Response(
server_id=SERVER_ID,
response_data="Python server SimpleMethod Ok!!!!")
return response
# 客户端流模式(在一次调用中, 客户端可以多次向服务器传输数据, 但是服务器只能返回一次响应)
# stream-unary (In a single call, the client can transfer data to the server several times,
# but the server can only return a response once.)
def ClientStreamingMethod(self, request_iterator, context):
print("ClientStreamingMethod called by client...")
for request in request_iterator:
print("recv from client(%d), message= %s" %
(request.client_id, request.request_data))
response = demo_pb2.Response(
server_id=SERVER_ID,
response_data="Python server ClientStreamingMethod ok")
return response
# 服务端流模式(在一次调用中, 客户端只能一次向服务器传输数据, 但是服务器可以多次返回响应)
# unary-stream (In a single call, the client can only transmit data to the server at one time,
# but the server can return the response many times.)
def ServerStreamingMethod(self, request, context):
print("ServerStreamingMethod called by client(%d), message= %s" %
(request.client_id, request.request_data))
# 创建一个生成器
# create a generator
def response_messages():
for i in range(5):
response = demo_pb2.Response(
server_id=SERVER_ID,
response_data=("send by Python server, message=%d" % i))
yield response
return response_messages()
# 双向流模式 (在一次调用中, 客户端和服务器都可以向对方多次收发数据)
# stream-stream (In a single call, both client and server can send and receive data
# to each other multiple times.)
def BidirectionalStreamingMethod(self, request_iterator, context):
print("BidirectionalStreamingMethod called by client...")
# 开启一个子线程去接收数据
# Open a sub thread to receive data
def parse_request():
for request in request_iterator:
print("recv from client(%d), message= %s" %
(request.client_id, request.request_data))
t = Thread(target=parse_request)
t.start()
for i in range(5):
yield demo_pb2.Response(
server_id=SERVER_ID,
response_data=("send by Python server, message= %d" % i))
t.join()
def main():
server = grpc.server(futures.ThreadPoolExecutor())
demo_pb2_grpc.add_GRPCDemoServicer_to_server(DemoServer(), server)
server.add_insecure_port(SERVER_ADDRESS)
print("------------------start Python GRPC server")
server.start()
server.wait_for_termination()
# If raise Error:
# AttributeError: '_Server' object has no attribute 'wait_for_termination'
# You can use the following code instead:
# import time
# while 1:
# time.sleep(10)
if __name__ == '__main__':
main()<|fim▁end|> | #
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, |
<|file_name|>SvnTreeConflictDataTest.java<|end_file_name|><|fim▁begin|>// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.svn;
import com.intellij.openapi.vcs.VcsConfiguration;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.idea.svn.conflict.ConflictAction;
import org.jetbrains.idea.svn.conflict.ConflictOperation;
import org.jetbrains.idea.svn.conflict.ConflictVersion;
import org.jetbrains.idea.svn.conflict.TreeConflictDescription;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.function.BiConsumer;
import static com.intellij.testFramework.EdtTestUtil.runInEdtAndWait;
import static org.junit.Assert.*;
public class SvnTreeConflictDataTest extends SvnTestCase {
private VirtualFile myTheirs;
private SvnClientRunnerImpl mySvnClientRunner;
@Override
@Before
public void before() throws Exception {
myWcRootName = "wcRootConflictData";
myTraceClient = true;
super.before();
disableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
myTheirs = myTempDirFixture.findOrCreateDir("theirs");
mySvnClientRunner = new SvnClientRunnerImpl(myRunner);
mySvnClientRunner.checkout(myRepoUrl, myTheirs);
}
@Test
public void testFile2File_MINE_UNV_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.FileToFile.MINE_UNV_THEIRS_ADD, false, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
assertNull(beforeDescription.getSourceLeftVersion());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void testFile2File_MINE_EDIT_THEIRS_DELETE() throws Exception {
assertConflict(TreeConflictData.FileToFile.MINE_EDIT_THEIRS_DELETE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.DELETE, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNotNull(leftVersion);
assertTrue(leftVersion.isFile());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isNone());
});
}
private String createConflict(@NotNull TreeConflictData.Data data, boolean createSubtree) throws Exception {
if (createSubtree) {
mySvnClientRunner.testSvnVersion(myWorkingCopyDir);
createSubTree();
}
runInEdtAndWait(() -> new ConflictCreator(vcs, myTheirs, myWorkingCopyDir, data, mySvnClientRunner).create());
return data.getConflictFile();
}
@Test
public void testFile2File_MINE_DELETE_THEIRS_EDIT() throws Exception {
assertConflict(TreeConflictData.FileToFile.MINE_DELETE_THEIRS_EDIT, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.EDIT, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNotNull(leftVersion);
assertTrue(leftVersion.isFile());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void testFile2File_MINE_EDIT_THEIRS_MOVE() throws Exception {
assertConflict(TreeConflictData.FileToFile.MINE_EDIT_THEIRS_MOVE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.DELETE, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNotNull(leftVersion);
assertTrue(leftVersion.isFile());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isNone());
});
}
@Test
public void testFile2File_MINE_UNV_THEIRS_MOVE() throws Exception {
assertConflict(TreeConflictData.FileToFile.MINE_UNV_THEIRS_MOVE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void testFile2File_MINE_MOVE_THEIRS_EDIT() throws Exception {
assertConflict(TreeConflictData.FileToFile.MINE_MOVE_THEIRS_EDIT, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.EDIT, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNotNull(leftVersion);
assertTrue(leftVersion.isFile());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void testFile2File_MINE_MOVE_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.FileToFile.MINE_MOVE_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
//Assert.assertEquals(NodeKind.FILE, leftVersion.getKind());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
//---------------------------------- dirs --------------------------------------------------------
@Test
public void testDir2Dir_MINE_UNV_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.DirToDir.MINE_UNV_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
// not a conflict in Subversion 1.7.7. "mine" file becomes added
/*@Test
public void testDir2Dir_MINE_EDIT_THEIRS_DELETE() throws Exception {
final String conflictFile = createConflict(TreeConflictData.DirToDir.MINE_EDIT_THEIRS_DELETE);
VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty();
ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);<|fim▁hole|> final Change change = changeListManager.getChange(vf);
Assert.assertTrue(change instanceof ConflictedSvnChange);
TreeConflictDescription beforeDescription = ((ConflictedSvnChange)change).getBeforeDescription();
Assert.assertNotNull(beforeDescription);
final TreeConflictDescription afterDescription = ((ConflictedSvnChange)change).getAfterDescription();
Assert.assertNull(afterDescription);
Assert.assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
Assert.assertEquals(ConflictAction.DELETE, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
Assert.assertNotNull(leftVersion);
Assert.assertEquals(NodeKind.DIR, leftVersion.getKind());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
Assert.assertNotNull(version);
Assert.assertEquals(NodeKind.NONE, version.getKind());
}*/
@Test
public void testDir2Dir_MINE_DELETE_THEIRS_EDIT() throws Exception {
assertConflict(TreeConflictData.DirToDir.MINE_DELETE_THEIRS_EDIT, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.EDIT, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNotNull(leftVersion);
assertTrue(leftVersion.isDirectory());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void testDir2Dir_MINE_EDIT_THEIRS_MOVE() throws Exception {
assertConflict(TreeConflictData.DirToDir.MINE_EDIT_THEIRS_MOVE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.DELETE, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNotNull(leftVersion);
assertTrue(leftVersion.isDirectory());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isNone());
});
}
@Test
public void testDir2Dir_MINE_UNV_THEIRS_MOVE() throws Exception {
assertConflict(TreeConflictData.DirToDir.MINE_UNV_THEIRS_MOVE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void testDir2Dir_MINE_MOVE_THEIRS_EDIT() throws Exception {
assertConflict(TreeConflictData.DirToDir.MINE_MOVE_THEIRS_EDIT, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.EDIT, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNotNull(leftVersion);
assertTrue(leftVersion.isDirectory());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void testDir2Dir_MINE_MOVE_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.DirToDir.MINE_MOVE_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
//Assert.assertEquals(NodeKind.DIR, leftVersion.getKind());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
//---------------------------------
@Test
public void testFile2Dir_MINE_UNV_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.FileToDir.MINE_UNV_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void testFile2Dir_MINE_ADD_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.FileToDir.MINE_ADD_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void testFile2Dir_MINE_UNV_THEIRS_MOVE() throws Exception {
assertConflict(TreeConflictData.FileToDir.MINE_UNV_THEIRS_MOVE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void testFile2Dir_MINE_ADD_THEIRS_MOVE() throws Exception {
assertConflict(TreeConflictData.FileToDir.MINE_ADD_THEIRS_MOVE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void testFile2Dir_MINE_MOVE_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.FileToDir.MINE_MOVE_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
//******************************************
// dir -> file (mine, theirs)
@Test
public void testDir2File_MINE_UNV_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.DirToFile.MINE_UNV_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void testDir2File_MINE_ADD_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.DirToFile.MINE_ADD_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void testDir2File_MINE_UNV_THEIRS_MOVE() throws Exception {
assertConflict(TreeConflictData.DirToFile.MINE_UNV_THEIRS_MOVE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void testDir2File_MINE_ADD_THEIRS_MOVE() throws Exception {
assertConflict(TreeConflictData.DirToFile.MINE_ADD_THEIRS_MOVE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void testDir2File_MINE_MOVE_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.DirToFile.MINE_MOVE_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
private void createSubTree() throws Exception {
enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE);
new SubTree(myWorkingCopyDir);
mySvnClientRunner.checkin(myWorkingCopyDir);
mySvnClientRunner.update(myTheirs);
mySvnClientRunner.update(myWorkingCopyDir);
disableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
disableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE);
}
private void assertConflict(@NotNull TreeConflictData.Data data,
@NotNull BiConsumer<TreeConflictDescription, TreeConflictDescription> checker) throws Exception {
assertConflict(data, true, checker);
}
private void assertConflict(@NotNull TreeConflictData.Data data,
boolean createSubtree,
@NotNull BiConsumer<TreeConflictDescription, TreeConflictDescription> checker) throws Exception {
String conflictFile = createConflict(data, createSubtree);
refreshChanges();
Change change;
if (data == TreeConflictData.DirToDir.MINE_DELETE_THEIRS_EDIT ||
data == TreeConflictData.DirToDir.MINE_MOVE_THEIRS_EDIT ||
data == TreeConflictData.DirToDir.MINE_MOVE_THEIRS_ADD) {
change = changeListManager.getChange(VcsUtil.getFilePath(new File(myWorkingCopyDir.getPath(), conflictFile), true));
}
else {
VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(myWorkingCopyDir.getPath(), conflictFile));
assertNotNull(vf);
change = changeListManager.getChange(vf);
}
assertTrue(change instanceof ConflictedSvnChange);
TreeConflictDescription beforeDescription = ((ConflictedSvnChange)change).getBeforeDescription();
TreeConflictDescription afterDescription = ((ConflictedSvnChange)change).getAfterDescription();
assertNotNull(beforeDescription);
assertNull(afterDescription);
checker.accept(beforeDescription, afterDescription);
}
}<|fim▁end|> | changeListManager.ensureUpToDate(false);
VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(myWorkingCopyDir.getPath(), conflictFile));
Assert.assertNotNull(vf); |
<|file_name|>EntityGraphBean.java<|end_file_name|><|fim▁begin|>package com.cosium.spring.data.jpa.entity.graph.repository.support;
import com.google.common.base.MoreObjects;
import org.springframework.core.ResolvableType;
import org.springframework.data.jpa.repository.query.JpaEntityGraph;
import static java.util.Objects.requireNonNull;
/**
* Wrapper class allowing to hold a {@link JpaEntityGraph} with its associated domain class. Created
* on 23/11/16.
*
* @author Reda.Housni-Alaoui
*/
class EntityGraphBean {
private final JpaEntityGraph jpaEntityGraph;
private final Class<?> domainClass;
private final ResolvableType repositoryMethodReturnType;
private final boolean optional;
private final boolean primary;
private final boolean valid;
public EntityGraphBean(
JpaEntityGraph jpaEntityGraph,
Class<?> domainClass,
ResolvableType repositoryMethodReturnType,
boolean optional,
boolean primary) {
this.jpaEntityGraph = requireNonNull(jpaEntityGraph);
this.domainClass = requireNonNull(domainClass);
this.repositoryMethodReturnType = requireNonNull(repositoryMethodReturnType);
this.optional = optional;
this.primary = primary;
this.valid = computeValidity();
}
private boolean computeValidity() {
Class<?> resolvedReturnType = repositoryMethodReturnType.resolve();
if (Void.TYPE.equals(resolvedReturnType) || domainClass.isAssignableFrom(resolvedReturnType)) {
return true;
}
for (Class genericType : repositoryMethodReturnType.resolveGenerics()) {
if (domainClass.isAssignableFrom(genericType)) {
return true;
}
}
return false;
}
/** @return The jpa entity graph */
public JpaEntityGraph getJpaEntityGraph() {
return jpaEntityGraph;
}
/** @return The jpa entity class */
public Class<?> getDomainClass() {
return domainClass;
}
/** @return True if this entity graph is not mandatory */
public boolean isOptional() {
return optional;
}
/** @return True if this EntityGraph seems valid */
public boolean isValid() {
return valid;
}
/**
* @return True if this EntityGraph is a primary one. Default EntityGraph is an example of non
* primary EntityGraph.
*/
public boolean isPrimary() {<|fim▁hole|> public String toString() {
return MoreObjects.toStringHelper(this)
.add("jpaEntityGraph", jpaEntityGraph)
.add("domainClass", domainClass)
.add("repositoryMethodReturnType", repositoryMethodReturnType)
.add("optional", optional)
.toString();
}
}<|fim▁end|> | return primary;
}
@Override |
<|file_name|>tests.rs<|end_file_name|><|fim▁begin|>use protocol::cmd::Cmd;
use protocol::cmd::Delete;
use protocol::cmd::FlushAll;
use protocol::cmd::Get;
use protocol::cmd::GetInstr;
use protocol::cmd::Inc;
use protocol::cmd::IncInstr;
use protocol::cmd::Resp;
use protocol::cmd::Set;
use protocol::cmd::SetInstr;
use protocol::cmd::Stat;
use protocol::cmd::Touch;
use protocol::cmd::Value;
use testlib::test_stream::TestStream;
use super::TcpTransport;
use super::TcpTransportError;
use super::conversions::as_number;
use super::conversions::as_string;
// Conversions
#[test]
fn test_as_string_ok() {
// "a A"
let string = as_string(vec![97, 32, 65]).unwrap();
assert_eq!(string, "a A".to_string());
}
#[test]
fn test_as_string_invalid() {
// "a" + two invalid utf8 bytes
let err = as_string(vec![97, 254, 255]).unwrap_err();
assert_eq!(err, TcpTransportError::Utf8Error);
}
#[test]
fn test_as_number_ok() {
let bytes = b"123".to_vec();
let num = as_number::<u32>(bytes).unwrap();
assert_eq!(num, 123);
}
#[test]
fn test_as_number_invalid() {
let bytes = b"12 3".to_vec();
let err = as_number::<u32>(bytes).unwrap_err();
assert_eq!(err, TcpTransportError::NumberParseError);
}
// Basic methods to consume the stream
#[test]
fn test_read_bytes() {
let ts = TestStream::new(vec![97, 13, 10]);
let mut transport = TcpTransport::new(ts);
let bytes = transport.read_bytes_exact(3).unwrap();
assert_eq!(bytes, b"a\r\n");
}
#[test]
fn test_read_bytes_too_few() {
let ts = TestStream::new(vec![97]);
let mut transport = TcpTransport::new(ts);
let bytes = transport.read_bytes_exact(2).unwrap();
assert_eq!(bytes, b"a");
}
#[test]
fn test_read_bytes_many() {
// "a" * 1mb
let ts = TestStream::new(vec![97; 1 << 20]);
let mut transport = TcpTransport::new(ts);
let bytes = transport.read_bytes_exact(1 << 20).unwrap();
assert_eq!(bytes, vec![97; 1 << 20]);
}
#[test]
fn test_read_word_in_line_one_char() {
let ts = TestStream::new(b"a a".to_vec());
let mut transport = TcpTransport::new(ts);
let (word, eol) = transport.read_word_in_line().unwrap();
assert_eq!(word, b"a");
assert_eq!(false, eol);
}
#[test]
fn test_read_word_in_line_leading_spaces() {
let ts = TestStream::new(b" a ".to_vec());
let mut transport = TcpTransport::new(ts);
let (word, eol) = transport.read_word_in_line().unwrap();
assert_eq!(word, b"a");
assert_eq!(false, eol);
}
#[test]
fn test_read_word_in_line_eol() {
let ts = TestStream::new(b"\r\n".to_vec());
let mut transport = TcpTransport::new(ts);
let (word, eol) = transport.read_word_in_line().unwrap();
assert_eq!(word, b"");
assert_eq!(true, eol);
}
#[test]
fn test_read_line_as_words_ok() {
let ts = TestStream::new(b"aa bb\r\n".to_vec());
let mut transport = TcpTransport::new(ts);
let words = transport.read_line_as_words().unwrap();
assert_eq!(words, &[b"aa", b"bb"]);
}
#[test]
fn test_read_line_as_words_surrounding_space() {
let ts = TestStream::new(b" a b \r\n".to_vec());
let mut transport = TcpTransport::new(ts);
let words = transport.read_line_as_words().unwrap();
assert_eq!(words, &[b"a", b"b"]);
}
// Basic methods to produce the stream
#[test]
fn test_write_bytes() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let bytelen = transport.write_bytes(&vec![97, 98, 99]).unwrap();
assert_eq!(3, bytelen);
transport.flush_writes().unwrap();
assert_eq!(transport.get_stream().outgoing, [97, 98, 99]);
}
#[test]
fn test_write_string() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let bytelen = transport.write_string("abc").unwrap();
transport.flush_writes().unwrap();
assert_eq!(bytelen, 3);
assert_eq!(transport.get_stream().outgoing, [97, 98, 99]);
}
// Command parsing: malformed examples
#[test]
fn test_read_cmd_invalid() {
let cmd_str = b"invalid key 0 0 3\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let err = transport.read_cmd().unwrap_err();
assert_eq!(err, TcpTransportError::InvalidCmd);
}
#[test]
fn test_read_cmd_malterminated() {
let cmd_str = b"stats\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let err = transport.read_cmd().unwrap_err();
assert_eq!(err, TcpTransportError::StreamReadError);
}
// Command parsing: Add
#[test]
fn test_read_cmd_add() {
let cmd_str = b"add x 15 0 3 \r\nabc\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
let exp = Set::new(SetInstr::Add, "x", 15, 0, vec![97, 98, 99], false);
assert_eq!(cmd, Cmd::Set(exp));
}
// Command parsing: Append
#[test]
fn test_read_cmd_append() {
let cmd_str = b"append x 15 0 3 \r\nabc\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
<|fim▁hole|> let exp = Set::new(SetInstr::Append, "x", 15, 0, vec![97, 98, 99], false);
assert_eq!(cmd, Cmd::Set(exp));
}
// Command parsing: Cas
#[test]
fn test_read_cmd_cas() {
let cmd_str = b"cas x 15 0 3 44 \r\nabc\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
let mut exp = Set::new(SetInstr::Cas, "x", 15, 0, vec![97, 98, 99], false);
exp.with_cas_unique(44);
assert_eq!(cmd, Cmd::Set(exp));
}
#[test]
fn test_read_cmd_cas_noreply() {
let cmd_str = b"cas x 15 0 3 44 noreply\r\nabc\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
let mut exp = Set::new(SetInstr::Cas, "x", 15, 0, vec![97, 98, 99], true);
exp.with_cas_unique(44);
assert_eq!(cmd, Cmd::Set(exp));
}
// Command parsing: Decr
#[test]
fn test_read_cmd_decr() {
let cmd_str = b"decr x 5 \r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
assert_eq!(cmd, Cmd::Inc(Inc::new(IncInstr::Decr, "x", 5, false)));
}
#[test]
fn test_read_cmd_decr_noreply() {
let cmd_str = b"decr x 5 noreply\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
assert_eq!(cmd, Cmd::Inc(Inc::new(IncInstr::Decr, "x", 5, true)));
}
// Command parsing: Delete
#[test]
fn test_read_cmd_delete() {
let cmd_str = b"delete x \r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
assert_eq!(cmd, Cmd::Delete(Delete::new("x", false)));
}
#[test]
fn test_read_cmd_delete_noreply() {
let cmd_str = b"delete x noreply\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
assert_eq!(cmd, Cmd::Delete(Delete::new("x", true)));
}
// Command parsing: FlushAll
#[test]
fn test_read_cmd_flush_all() {
let cmd_str = b"flush_all\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
assert_eq!(cmd, Cmd::FlushAll(FlushAll::new(None, false)));
}
// Command parsing: Get
#[test]
fn test_read_cmd_get_one_key() {
let cmd_str = b"get x\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
assert_eq!(cmd, Cmd::Get(Get::one(GetInstr::Get, "x")));
}
#[test]
fn test_read_cmd_get_two_keys() {
let cmd_str = b"get x y\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
let keys = vec!["x".to_string(), "y".to_string()];
assert_eq!(cmd, Cmd::Get(Get::new(GetInstr::Get, keys)));
}
#[test]
fn test_read_cmd_get_non_utf8() {
let cmd_bytes = b"get \xfe\r\n".to_vec();
let ts = TestStream::new(cmd_bytes);
let mut transport = TcpTransport::new(ts);
let err = transport.read_cmd().unwrap_err();
assert_eq!(err, TcpTransportError::Utf8Error);
}
#[test]
fn test_read_cmd_get_malformed() {
fn try_cmd(cmd: &[u8]) {
let ts = TestStream::new(cmd.to_vec());
let mut transport = TcpTransport::new(ts);
let err = transport.read_cmd().unwrap_err();
assert_eq!(err, TcpTransportError::StreamReadError);
}
// Test for truncated stream
try_cmd(b"get x\r");
try_cmd(b"get x");
try_cmd(b"get ");
try_cmd(b"get");
}
// Command parsing: Gets
#[test]
fn test_read_cmd_gets_one_key() {
let cmd_str = b"gets x\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
assert_eq!(cmd, Cmd::Get(Get::one(GetInstr::Gets, "x")));
}
// Command parsing: Incr
#[test]
fn test_read_cmd_incr() {
let cmd_str = b"incr x 5 \r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
assert_eq!(cmd, Cmd::Inc(Inc::new(IncInstr::Incr, "x", 5, false)));
}
#[test]
fn test_read_cmd_incr_noreply() {
let cmd_str = b"incr x 5 noreply\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
assert_eq!(cmd, Cmd::Inc(Inc::new(IncInstr::Incr, "x", 5, true)));
}
// Command parsing: Quit
#[test]
fn test_read_cmd_quit() {
let cmd_str = b"quit\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
assert_eq!(cmd, Cmd::Quit);
}
// Command parsing: Prepend
#[test]
fn test_read_cmd_prepend() {
let cmd_str = b"prepend x 15 0 3 \r\nabc\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
let exp = Set::new(SetInstr::Prepend, "x", 15, 0, vec![97, 98, 99], false);
assert_eq!(cmd, Cmd::Set(exp));
}
// Command parsing: Replace
#[test]
fn test_read_cmd_replace() {
let cmd_str = b"replace x 15 0 3 \r\nabc\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
let exp = Set::new(SetInstr::Replace, "x", 15, 0, vec![97, 98, 99], false);
assert_eq!(cmd, Cmd::Set(exp));
}
// Command parsing: Set
#[test]
fn test_read_cmd_set_ok() {
let cmd_str = b"set x 15 0 3 \r\nabc\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
let exp = Set::new(SetInstr::Set, "x", 15, 0, vec![97, 98, 99], false);
assert_eq!(cmd, Cmd::Set(exp));
}
#[test]
fn test_read_cmd_set_noreply_ok() {
let cmd_str = b"set x 15 0 3 noreply\r\nabc\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
let exp = Set::new(SetInstr::Set, "x", 15, 0, vec![97, 98, 99], true);
assert_eq!(cmd, Cmd::Set(exp));
}
#[test]
fn test_read_cmd_set_under_size() {
let cmd_str = b"set x 0 0 2 \r\nabc\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let err = transport.read_cmd().unwrap_err();
assert_eq!(err, TcpTransportError::CommandParseError);
}
#[test]
fn test_read_cmd_set_over_size() {
let cmd_str = b"set x 0 0 4 \r\nabc\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let err = transport.read_cmd().unwrap_err();
assert_eq!(err, TcpTransportError::CommandParseError);
}
#[test]
fn test_read_cmd_set_malformed() {
fn try_cmd(cmd: &[u8]) {
let ts = TestStream::new(cmd.to_vec());
let mut transport = TcpTransport::new(ts);
transport.read_cmd().unwrap_err();
}
// Test for truncated stream
try_cmd(b"set x 0 0 3 \r\nabc\r");
try_cmd(b"set x 0 0 3 \r\nabc");
try_cmd(b"set x 0 0 3 \r\nab");
try_cmd(b"set x 0 0 3 \r\na");
try_cmd(b"set x 0 0 3 \r\n");
try_cmd(b"set x 0 0 3 \r");
try_cmd(b"set x 0 0 3 ");
try_cmd(b"set x 0 0 3");
try_cmd(b"set x 0 0 ");
try_cmd(b"set x 0 0");
try_cmd(b"set x 0 ");
try_cmd(b"set x 0");
try_cmd(b"set x ");
try_cmd(b"set x");
try_cmd(b"set ");
try_cmd(b"set");
}
// Command parsing: Stats
#[test]
fn test_read_cmd_stats() {
let cmd_str = b"stats\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
assert_eq!(cmd, Cmd::Stats);
}
// Command parsing: Touch
#[test]
fn test_read_cmd_touch() {
let cmd_str = b"touch x 0 \r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
let touch = Touch::new("x", 0, false);
assert_eq!(cmd, Cmd::Touch(touch));
}
#[test]
fn test_read_cmd_touch_noreply() {
let cmd_str = b"touch x 0 noreply\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
let touch = Touch::new("x", 0, true);
assert_eq!(cmd, Cmd::Touch(touch));
}
// Command parsing: Version
#[test]
fn test_read_cmd_version() {
let cmd_str = b"version\r\n".to_vec();
let ts = TestStream::new(cmd_str);
let mut transport = TcpTransport::new(ts);
let cmd = transport.read_cmd().unwrap();
assert_eq!(cmd, Cmd::Version);
}
// Response writing: ClientError
#[test]
fn test_write_resp_clienterror() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let resp = Resp::ClientError("woops my bad".to_string());
transport.write_resp(&resp).unwrap();
let expected = b"CLIENT_ERROR woops my bad\r\n";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}
// Response writing: Deleted
#[test]
fn test_write_resp_deleted() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let resp = Resp::Deleted;
transport.write_resp(&resp).unwrap();
let expected = b"DELETED\r\n";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}
// Response writing: Empty
#[test]
fn test_write_resp_empty() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let resp = Resp::Empty;
transport.write_resp(&resp).unwrap();
let expected = b"";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}
// Response writing: Error
#[test]
fn test_write_resp_error() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let resp = Resp::Error;
transport.write_resp(&resp).unwrap();
let expected = b"ERROR\r\n";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}
// Response writing: Exists
#[test]
fn test_write_resp_exists() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let resp = Resp::Exists;
transport.write_resp(&resp).unwrap();
let expected = b"EXISTS\r\n";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}
// Response writing: IntValue
#[test]
fn test_write_resp_intvalue() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let resp = Resp::IntValue(5);
transport.write_resp(&resp).unwrap();
let expected = b"5\r\n";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}
// Response writing: NotFound
#[test]
fn test_write_resp_not_found() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let resp = Resp::NotFound;
transport.write_resp(&resp).unwrap();
let expected = b"NOT_FOUND\r\n";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}
// Response writing: NotStored
#[test]
fn test_write_resp_not_stored() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let resp = Resp::NotStored;
transport.write_resp(&resp).unwrap();
let expected = b"NOT_STORED\r\n";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}
// Response writing: Ok
#[test]
fn test_write_resp_ok() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let resp = Resp::Ok;
transport.write_resp(&resp).unwrap();
let expected = b"OK\r\n";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}
// Response writing: ServerError
#[test]
fn test_write_resp_servererror() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let resp = Resp::ServerError("woops my bad".to_string());
transport.write_resp(&resp).unwrap();
let expected = b"SERVER_ERROR woops my bad\r\n";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}
// Response writing: Stats
#[test]
fn test_write_resp_stats() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let stat = Stat::new("curr_items", "0".to_string());
let resp = Resp::Stats(vec![stat]);
transport.write_resp(&resp).unwrap();
let expected = b"STAT curr_items 0\r\nEND\r\n";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}
// Response writing: Stored
#[test]
fn test_write_resp_stored() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let resp = Resp::Stored;
transport.write_resp(&resp).unwrap();
let expected = b"STORED\r\n";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}
// Response writing: Touched
#[test]
fn test_write_resp_touched() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let resp = Resp::Touched;
transport.write_resp(&resp).unwrap();
let expected = b"TOUCHED\r\n";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}
// Response writing: Value
#[test]
fn test_write_resp_value_one() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let val1 = Value::new("x", 15, b"abc".to_vec());
let resp = Resp::Values(vec![val1]);
transport.write_resp(&resp).unwrap();
let expected = b"VALUE x 15 3\r\nabc\r\nEND\r\n";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}
#[test]
fn test_write_resp_value_two() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let val1 = Value::new("x", 15, b"abc".to_vec());
let val2 = Value::new("y", 17, b"def".to_vec());
let resp = Resp::Values(vec![val1, val2]);
transport.write_resp(&resp).unwrap();
let expected = b"VALUE x 15 3\r\nabc\r\nVALUE y 17 3\r\ndef\r\nEND\r\n";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}
#[test]
fn test_write_resp_value_one_cas() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let mut val1 = Value::new("x", 15, b"abc".to_vec());
val1.with_cas_unique(45);
let resp = Resp::Values(vec![val1]);
transport.write_resp(&resp).unwrap();
let expected = b"VALUE x 15 3 45\r\nabc\r\nEND\r\n";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}
// Response writing: Version
#[test]
fn test_write_resp_version() {
let ts = TestStream::new(vec![]);
let mut transport = TcpTransport::new(ts);
let resp = Resp::Version("1.0.1".to_string());
transport.write_resp(&resp).unwrap();
let expected = b"VERSION 1.0.1\r\n";
assert_eq!(transport.get_stream().outgoing, expected.to_vec());
}<|fim▁end|> | let cmd = transport.read_cmd().unwrap(); |
<|file_name|>uint.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Operations and constants for architecture-sized unsigned integers (`uint` type)
#[allow(non_uppercase_statics)];
use prelude::*;
use default::Default;
use mem;
use num::{Bitwise, Bounded};
use num::{CheckedAdd, CheckedSub, CheckedMul};
use num::{CheckedDiv, Zero, One, strconv};
use num::{ToStrRadix, FromStrRadix};
use num;
use option::{Option, Some, None};
use str;
use unstable::intrinsics;
uint_module!(uint, int, ::int::bits)
///
/// Divide two numbers, return the result, rounded up.
///
/// # Arguments
///
/// * x - an integer
/// * y - an integer distinct from 0u
///
/// # Return value
///
/// The smallest integer `q` such that `x/y <= q`.
///
pub fn div_ceil(x: uint, y: uint) -> uint {
let div = x / y;
if x % y == 0u { div }
else { div + 1u }
}
///
/// Divide two numbers, return the result, rounded to the closest integer.
///
/// # Arguments
///
/// * x - an integer
/// * y - an integer distinct from 0u
///
/// # Return value
///
/// The integer `q` closest to `x/y`.
///
pub fn div_round(x: uint, y: uint) -> uint {
let div = x / y;
if x % y * 2u < y { div }
else { div + 1u }
}
///
/// Divide two numbers, return the result, rounded down.
///
/// Note: This is the same function as `div`.
///
/// # Arguments
///
/// * x - an integer
/// * y - an integer distinct from 0u
///
/// # Return value
///
/// The smallest integer `q` such that `x/y <= q`. This
/// is either `x/y` or `x/y + 1`.
///
pub fn div_floor(x: uint, y: uint) -> uint { return x / y; }
impl num::Times for uint {
#[inline]<|fim▁hole|> /// Equivalent to `for uint::range(0, x) |_| { ... }`.
///
/// Not defined on all integer types to permit unambiguous
/// use with integer literals of inferred integer-type as
/// the self-value (eg. `100.times(|| { ... })`).
///
fn times(&self, it: ||) {
let mut i = *self;
while i > 0 {
it();
i -= 1;
}
}
}
/// Returns the smallest power of 2 greater than or equal to `n`
#[inline]
pub fn next_power_of_two(n: uint) -> uint {
let halfbits: uint = mem::size_of::<uint>() * 4u;
let mut tmp: uint = n - 1u;
let mut shift: uint = 1u;
while shift <= halfbits { tmp |= tmp >> shift; shift <<= 1u; }
tmp + 1u
}
/// Returns the smallest power of 2 greater than or equal to `n`
#[inline]
pub fn next_power_of_two_opt(n: uint) -> Option<uint> {
let halfbits: uint = mem::size_of::<uint>() * 4u;
let mut tmp: uint = n - 1u;
let mut shift: uint = 1u;
while shift <= halfbits { tmp |= tmp >> shift; shift <<= 1u; }
tmp.checked_add(&1)
}
#[cfg(target_word_size = "32")]
impl CheckedAdd for uint {
#[inline]
fn checked_add(&self, v: &uint) -> Option<uint> {
unsafe {
let (x, y) = intrinsics::u32_add_with_overflow(*self as u32, *v as u32);
if y { None } else { Some(x as uint) }
}
}
}
#[cfg(target_word_size = "64")]
impl CheckedAdd for uint {
#[inline]
fn checked_add(&self, v: &uint) -> Option<uint> {
unsafe {
let (x, y) = intrinsics::u64_add_with_overflow(*self as u64, *v as u64);
if y { None } else { Some(x as uint) }
}
}
}
#[cfg(target_word_size = "32")]
impl CheckedSub for uint {
#[inline]
fn checked_sub(&self, v: &uint) -> Option<uint> {
unsafe {
let (x, y) = intrinsics::u32_sub_with_overflow(*self as u32, *v as u32);
if y { None } else { Some(x as uint) }
}
}
}
#[cfg(target_word_size = "64")]
impl CheckedSub for uint {
#[inline]
fn checked_sub(&self, v: &uint) -> Option<uint> {
unsafe {
let (x, y) = intrinsics::u64_sub_with_overflow(*self as u64, *v as u64);
if y { None } else { Some(x as uint) }
}
}
}
#[cfg(target_word_size = "32")]
impl CheckedMul for uint {
#[inline]
fn checked_mul(&self, v: &uint) -> Option<uint> {
unsafe {
let (x, y) = intrinsics::u32_mul_with_overflow(*self as u32, *v as u32);
if y { None } else { Some(x as uint) }
}
}
}
#[cfg(target_word_size = "64")]
impl CheckedMul for uint {
#[inline]
fn checked_mul(&self, v: &uint) -> Option<uint> {
unsafe {
let (x, y) = intrinsics::u64_mul_with_overflow(*self as u64, *v as u64);
if y { None } else { Some(x as uint) }
}
}
}
#[test]
fn test_next_power_of_two() {
assert!((next_power_of_two(0u) == 0u));
assert!((next_power_of_two(1u) == 1u));
assert!((next_power_of_two(2u) == 2u));
assert!((next_power_of_two(3u) == 4u));
assert!((next_power_of_two(4u) == 4u));
assert!((next_power_of_two(5u) == 8u));
assert!((next_power_of_two(6u) == 8u));
assert!((next_power_of_two(7u) == 8u));
assert!((next_power_of_two(8u) == 8u));
assert!((next_power_of_two(9u) == 16u));
assert!((next_power_of_two(10u) == 16u));
assert!((next_power_of_two(11u) == 16u));
assert!((next_power_of_two(12u) == 16u));
assert!((next_power_of_two(13u) == 16u));
assert!((next_power_of_two(14u) == 16u));
assert!((next_power_of_two(15u) == 16u));
assert!((next_power_of_two(16u) == 16u));
assert!((next_power_of_two(17u) == 32u));
assert!((next_power_of_two(18u) == 32u));
assert!((next_power_of_two(19u) == 32u));
assert!((next_power_of_two(20u) == 32u));
assert!((next_power_of_two(21u) == 32u));
assert!((next_power_of_two(22u) == 32u));
assert!((next_power_of_two(23u) == 32u));
assert!((next_power_of_two(24u) == 32u));
assert!((next_power_of_two(25u) == 32u));
assert!((next_power_of_two(26u) == 32u));
assert!((next_power_of_two(27u) == 32u));
assert!((next_power_of_two(28u) == 32u));
assert!((next_power_of_two(29u) == 32u));
assert!((next_power_of_two(30u) == 32u));
assert!((next_power_of_two(31u) == 32u));
assert!((next_power_of_two(32u) == 32u));
assert!((next_power_of_two(33u) == 64u));
assert!((next_power_of_two(34u) == 64u));
assert!((next_power_of_two(35u) == 64u));
assert!((next_power_of_two(36u) == 64u));
assert!((next_power_of_two(37u) == 64u));
assert!((next_power_of_two(38u) == 64u));
assert!((next_power_of_two(39u) == 64u));
}
#[test]
fn test_overflows() {
use uint;
assert!((uint::max_value > 0u));
assert!((uint::min_value <= 0u));
assert!((uint::min_value + uint::max_value + 1u == 0u));
}
#[test]
fn test_div() {
assert!((div_floor(3u, 4u) == 0u));
assert!((div_ceil(3u, 4u) == 1u));
assert!((div_round(3u, 4u) == 1u));
}
#[test]
pub fn test_times() {
use num::Times;
let ten = 10 as uint;
let mut accum = 0;
ten.times(|| { accum += 1; });
assert!((accum == 10));
}<|fim▁end|> | ///
/// A convenience form for basic repetition. Given a uint `x`,
/// `x.times(|| { ... })` executes the given block x times.
/// |
<|file_name|>test_ossaudiodev.py<|end_file_name|><|fim▁begin|>from test import test_support
test_support.requires('audio')
from test.test_support import verbose, findfile, TestFailed, TestSkipped
import errno
import fcntl
import ossaudiodev
import os
import sys
import select
import sunaudio
import time
import audioop
# Arggh, AFMT_S16_NE not defined on all platforms -- seems to be a
# fairly recent addition to OSS.
try:
from ossaudiodev import AFMT_S16_NE
except ImportError:
if sys.byteorder == "little":
AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
else:
AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
SND_FORMAT_MULAW_8 = 1
def read_sound_file(path):
fp = open(path, 'rb')
size, enc, rate, nchannels, extra = sunaudio.gethdr(fp)
data = fp.read()
fp.close()
if enc != SND_FORMAT_MULAW_8:
print "Expect .au file with 8-bit mu-law samples"
return
# Convert the data to 16-bit signed.
data = audioop.ulaw2lin(data, 2)
return (data, rate, 16, nchannels)
# version of assert that still works with -O
def _assert(expr, message=None):
if not expr:
raise AssertionError(message or "assertion failed")
def play_sound_file(data, rate, ssize, nchannels):
try:
dsp = ossaudiodev.open('w')<|fim▁hole|> raise TestSkipped, msg
raise TestFailed, msg
# at least check that these methods can be invoked
dsp.bufsize()
dsp.obufcount()
dsp.obuffree()
dsp.getptr()
dsp.fileno()
# Make sure the read-only attributes work.
_assert(dsp.closed is False, "dsp.closed is not False")
_assert(dsp.name == "/dev/dsp")
_assert(dsp.mode == 'w', "bad dsp.mode: %r" % dsp.mode)
# And make sure they're really read-only.
for attr in ('closed', 'name', 'mode'):
try:
setattr(dsp, attr, 42)
raise RuntimeError("dsp.%s not read-only" % attr)
except TypeError:
pass
# Compute expected running time of sound sample (in seconds).
expected_time = float(len(data)) / (ssize/8) / nchannels / rate
# set parameters based on .au file headers
dsp.setparameters(AFMT_S16_NE, nchannels, rate)
print ("playing test sound file (expected running time: %.2f sec)"
% expected_time)
t1 = time.time()
dsp.write(data)
dsp.close()
t2 = time.time()
elapsed_time = t2 - t1
percent_diff = (abs(elapsed_time - expected_time) / expected_time) * 100
_assert(percent_diff <= 10.0, \
("elapsed time (%.2f sec) > 10%% off of expected time (%.2f sec)"
% (elapsed_time, expected_time)))
def test_setparameters(dsp):
# Two configurations for testing:
# config1 (8-bit, mono, 8 kHz) should work on even the most
# ancient and crufty sound card, but maybe not on special-
# purpose high-end hardware
# config2 (16-bit, stereo, 44.1kHz) should work on all but the
# most ancient and crufty hardware
config1 = (ossaudiodev.AFMT_U8, 1, 8000)
config2 = (AFMT_S16_NE, 2, 44100)
for config in [config1, config2]:
(fmt, channels, rate) = config
if (dsp.setfmt(fmt) == fmt and
dsp.channels(channels) == channels and
dsp.speed(rate) == rate):
break
else:
raise RuntimeError("unable to set audio sampling parameters: "
"you must have really weird audio hardware")
# setparameters() should be able to set this configuration in
# either strict or non-strict mode.
result = dsp.setparameters(fmt, channels, rate, False)
_assert(result == (fmt, channels, rate),
"setparameters%r: returned %r" % (config, result))
result = dsp.setparameters(fmt, channels, rate, True)
_assert(result == (fmt, channels, rate),
"setparameters%r: returned %r" % (config, result))
def test_bad_setparameters(dsp):
# Now try some configurations that are presumably bogus: eg. 300
# channels currently exceeds even Hollywood's ambitions, and
# negative sampling rate is utter nonsense. setparameters() should
# accept these in non-strict mode, returning something other than
# was requested, but should barf in strict mode.
fmt = AFMT_S16_NE
rate = 44100
channels = 2
for config in [(fmt, 300, rate), # ridiculous nchannels
(fmt, -5, rate), # impossible nchannels
(fmt, channels, -50), # impossible rate
]:
(fmt, channels, rate) = config
result = dsp.setparameters(fmt, channels, rate, False)
_assert(result != config,
"setparameters: unexpectedly got requested configuration")
try:
result = dsp.setparameters(fmt, channels, rate, True)
raise AssertionError("setparameters: expected OSSAudioError")
except ossaudiodev.OSSAudioError, err:
print "setparameters: got OSSAudioError as expected"
def test():
(data, rate, ssize, nchannels) = read_sound_file(findfile('audiotest.au'))
play_sound_file(data, rate, ssize, nchannels)
dsp = ossaudiodev.open("w")
try:
test_setparameters(dsp)
# Disabled because it fails under Linux 2.6 with ALSA's OSS
# emulation layer.
#test_bad_setparameters(dsp)
finally:
dsp.close()
_assert(dsp.closed is True, "dsp.closed is not True")
test()<|fim▁end|> | except IOError, msg:
if msg[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY): |
<|file_name|>storage.py<|end_file_name|><|fim▁begin|>"""
Comprehensive Theming support for Django's collectstatic functionality.
See https://docs.djangoproject.com/en/1.8/ref/contrib/staticfiles/
"""
from __future__ import absolute_import
import os.path
import posixpath
import re
from django.conf import settings
from django.contrib.staticfiles.finders import find
from django.contrib.staticfiles.storage import CachedFilesMixin, StaticFilesStorage
from django.utils._os import safe_join
from django.utils.six.moves.urllib.parse import ( # pylint: disable=no-name-in-module, import-error
unquote,
urldefrag,
urlsplit
)
from pipeline.storage import PipelineMixin
from openedx.core.djangoapps.theming.helpers import (
get_current_theme,
get_project_root_name,
get_theme_base_dir,
get_themes,
is_comprehensive_theming_enabled
)
class ThemeStorage(StaticFilesStorage):
"""
Comprehensive theme aware Static files storage.
"""
# prefix for file path, this prefix is added at the beginning of file path before saving static files during
# collectstatic command.
# e.g. having "edx.org" as prefix will cause files to be saved as "edx.org/images/logo.png"
# instead of "images/logo.png"
prefix = None
def __init__(self, location=None, base_url=None, file_permissions_mode=None,
directory_permissions_mode=None, prefix=None):
self.prefix = prefix
super(ThemeStorage, self).__init__(
location=location,
base_url=base_url,
file_permissions_mode=file_permissions_mode,
directory_permissions_mode=directory_permissions_mode,
)
def url(self, name):
"""
Returns url of the asset, themed url will be returned if the asset is themed otherwise default
asset url will be returned.
Args:
name: name of the asset, e.g. 'images/logo.png'
Returns:
url of the asset, e.g. '/static/red-theme/images/logo.png' if current theme is red-theme and logo
is provided by red-theme otherwise '/static/images/logo.png'
"""
prefix = ''
theme = get_current_theme()
# get theme prefix from site address if if asset is accessed via a url
if theme:
prefix = theme.theme_dir_name
# get theme prefix from storage class, if asset is accessed during collectstatic run
elif self.prefix:
prefix = self.prefix
# join theme prefix with asset name if theme is applied and themed asset exists
if prefix and self.themed(name, prefix):
name = os.path.join(prefix, name)
return super(ThemeStorage, self).url(name)
def themed(self, name, theme):
"""
Returns True if given asset override is provided by the given theme otherwise returns False.
Args:
name: asset name e.g. 'images/logo.png'
theme: theme name e.g. 'red-theme', 'edx.org'
Returns:
True if given asset override is provided by the given theme otherwise returns False
"""
if not is_comprehensive_theming_enabled():
return False
# in debug mode check static asset from within the project directory
if settings.DEBUG:
themes_location = get_theme_base_dir(theme, suppress_error=True)
# Nothing can be themed if we don't have a theme location or required params.
if not all((themes_location, theme, name)):
return False
themed_path = "/".join([
themes_location,
theme,
get_project_root_name(),
"static/"
])
name = name[1:] if name.startswith("/") else name
path = safe_join(themed_path, name)
return os.path.exists(path)
# in live mode check static asset in the static files dir defined by "STATIC_ROOT" setting
else:
return self.exists(os.path.join(theme, name))
class ThemeCachedFilesMixin(CachedFilesMixin):
"""
Comprehensive theme aware CachedFilesMixin.
Main purpose of subclassing CachedFilesMixin is to override the following methods.
1 - _url
2 - url_converter
_url:
This method takes asset name as argument and is responsible for adding hash to the name to support caching.
This method is called during both collectstatic command and live server run.
When called during collectstatic command that name argument will be asset name inside STATIC_ROOT,
for non themed assets it will be the usual path (e.g. 'images/logo.png') but for themed asset it will
also contain themes dir prefix (e.g. 'red-theme/images/logo.png'). So, here we check whether the themed asset
exists or not, if it exists we pass the same name up in the MRO chain for further processing and if it does not
exists we strip theme name and pass the new asset name to the MRO chain for further processing.
When called during server run, we get the theme dir for the current site using `get_current_theme` and
make sure to prefix theme dir to the asset name. This is done to ensure the usage of correct hash in file name.
e.g. if our red-theme overrides 'images/logo.png' and we do not prefix theme dir to the asset name, the hash for
'{platform-dir}/lms/static/images/logo.png' would be used instead of
'{themes_base_dir}/red-theme/images/logo.png'
url_converter:
This function returns another function that is responsible for hashing urls that appear inside assets
(e.g. url("images/logo.png") inside css). The method defined in the superclass adds a hash to file and returns
relative url of the file.
e.g. for url("../images/logo.png") it would return url("../images/logo.790c9a5340cb.png"). However we would
want it to return absolute url (e.g. url("/static/images/logo.790c9a5340cb.png")) so that it works properly
with themes.
The overridden method here simply comments out the line that convert absolute url to relative url,
hence absolute urls are used instead of relative urls.
"""
def _processed_asset_name(self, name):<|fim▁hole|>
See the class docstring for more info.
"""
theme = get_current_theme()
if theme and theme.theme_dir_name not in name:
# during server run, append theme name to the asset name if it is not already there
# this is ensure that correct hash is created and default asset is not always
# used to create hash of themed assets.
name = os.path.join(theme.theme_dir_name, name)
parsed_name = urlsplit(unquote(name))
clean_name = parsed_name.path.strip()
asset_name = name
if not self.exists(clean_name):
# if themed asset does not exists then use default asset
theme = name.split("/", 1)[0]
# verify that themed asset was accessed
if theme in [theme.theme_dir_name for theme in get_themes()]:
asset_name = "/".join(name.split("/")[1:])
return asset_name
def _url(self, hashed_name_func, name, force=False, hashed_files=None):
"""
This override method swaps out `name` with a processed version.
See the class docstring for more info.
"""
processed_asset_name = self._processed_asset_name(name)
return super(ThemeCachedFilesMixin, self)._url(hashed_name_func, processed_asset_name, force, hashed_files)
def url_converter(self, name, hashed_files, template=None):
"""
This is an override of url_converter from CachedFilesMixin.
It changes one line near the end of the method (see the NOTE) in order
to return absolute urls instead of relative urls. This behavior is
necessary for theme overrides, as we get 404 on assets with relative
urls on a themed site.
"""
if template is None:
template = self.default_template
def converter(matchobj):
"""
Convert the matched URL to a normalized and hashed URL.
This requires figuring out which files the matched URL resolves
to and calling the url() method of the storage.
"""
matched, url = matchobj.groups()
# Ignore absolute/protocol-relative and data-uri URLs.
if re.match(r'^[a-z]+:', url):
return matched
# Ignore absolute URLs that don't point to a static file (dynamic
# CSS / JS?). Note that STATIC_URL cannot be empty.
if url.startswith('/') and not url.startswith(settings.STATIC_URL):
return matched
# Strip off the fragment so a path-like fragment won't interfere.
url_path, fragment = urldefrag(url)
if url_path.startswith('/'):
# Otherwise the condition above would have returned prematurely.
assert url_path.startswith(settings.STATIC_URL)
target_name = url_path[len(settings.STATIC_URL):]
else:
# We're using the posixpath module to mix paths and URLs conveniently.
source_name = name if os.sep == '/' else name.replace(os.sep, '/')
target_name = posixpath.join(posixpath.dirname(source_name), url_path)
# Determine the hashed name of the target file with the storage backend.
hashed_url = self._url(
self._stored_name, unquote(target_name),
force=True, hashed_files=hashed_files,
)
# NOTE:
# The line below was commented out so that absolute urls are used instead of relative urls to make themed
# assets work correctly.
#
# The line is commented and not removed to make future django upgrade easier and show exactly what is
# changed in this method override
#
#transformed_url = '/'.join(url_path.split('/')[:-1] + hashed_url.split('/')[-1:])
transformed_url = hashed_url # This line was added.
# Restore the fragment that was stripped off earlier.
if fragment:
transformed_url += ('?#' if '?#' in url else '#') + fragment
# Return the hashed version to the file
return template % unquote(transformed_url)
return converter
class ThemePipelineMixin(PipelineMixin):
"""
Mixin to make sure themed assets are also packaged and used along with non themed assets.
if a source asset for a particular package is not present then the default asset is used.
e.g. in the following package and for 'red-theme'
'style-vendor': {
'source_filenames': [
'js/vendor/afontgarde/afontgarde.css',
'css/vendor/font-awesome.css',
'css/vendor/jquery.qtip.min.css',
'css/vendor/responsive-carousel/responsive-carousel.css',
'css/vendor/responsive-carousel/responsive-carousel.slide.css',
],
'output_filename': 'css/lms-style-vendor.css'
}
'red-theme/css/vendor/responsive-carousel/responsive-carousel.css' will be used of it exists otherwise
'css/vendor/responsive-carousel/responsive-carousel.css' will be used to create 'red-theme/css/lms-style-vendor.css'
"""
packing = True
def post_process(self, paths, dry_run=False, **options):
"""
This post_process hook is used to package all themed assets.
"""
if dry_run:
return
themes = get_themes()
for theme in themes:
css_packages = self.get_themed_packages(theme.theme_dir_name, settings.PIPELINE['STYLESHEETS'])
from pipeline.packager import Packager
packager = Packager(storage=self, css_packages=css_packages)
for package_name in packager.packages['css']:
package = packager.package_for('css', package_name)
output_file = package.output_filename
if self.packing:
packager.pack_stylesheets(package)
paths[output_file] = (self, output_file)
yield output_file, output_file, True
super_class = super(ThemePipelineMixin, self)
if hasattr(super_class, 'post_process'):
for name, hashed_name, processed in super_class.post_process(paths.copy(), dry_run, **options):
yield name, hashed_name, processed
@staticmethod
def get_themed_packages(prefix, packages):
"""
Update paths with the themed assets,
Args:
prefix: theme prefix for which to update asset paths e.g. 'red-theme', 'edx.org' etc.
packages: packages to update
Returns: list of updated paths and a boolean indicating whether any path was path or not
"""
themed_packages = {}
for name in packages:
# collect source file names for the package
source_files = []
for path in packages[name].get('source_filenames', []):
# if themed asset exists use that, otherwise use default asset.
if find(os.path.join(prefix, path)):
source_files.append(os.path.join(prefix, path))
else:
source_files.append(path)
themed_packages[name] = {
'output_filename': os.path.join(prefix, packages[name].get('output_filename', '')),
'source_filenames': source_files,
}
return themed_packages<|fim▁end|> | """
Returns either a themed or unthemed version of the given asset name,
depending on several factors. |
<|file_name|>plotnormal.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import math
mu = 0
variance1 = 20000**2
variance2 = 2000**2
sigma1 = math.sqrt(variance1)
sigma2 = math.sqrt(variance2)
x = np.linspace(mu - 3*sigma1, mu + 3*sigma1, 100)
plt.plot(x, stats.norm.pdf(x, mu, sigma1))
x2 = np.linspace(mu - 3*sigma2, mu + 3*sigma2,100)<|fim▁hole|>plt.plot(x2, stats.norm.pdf(x2, mu, sigma2))
plt.xlim((-50000,50000))
frame1 = plt.gca()
frame1.axes.xaxis.set_ticklabels([])
frame1.axes.yaxis.set_ticklabels([])
plt.show()<|fim▁end|> | #x2 = [i for i in x2] |
<|file_name|>CompileMojoTest.java<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2013 OpenJST Project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openjst.server.commons.maven;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
/**
* @author Sergey Grachev
*/
public final class CompileMojoTest extends AbstractMojoTest {
@Test(groups = "manual")
public void test() throws IOException, MojoFailureException, MojoExecutionException {
final File resourcesPath = makeTempResourcesDirectory();
try {
final CompileMojo mojo = new CompileMojo(new File(resourcesPath, "manifest.xml"));
mojo.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {<|fim▁hole|> }
}<|fim▁end|> | FileUtils.deleteDirectory(resourcesPath);
} |
<|file_name|>production.js<|end_file_name|><|fim▁begin|>'use strict';<|fim▁hole|>// =================================
module.exports = {
// Server IP
ip: process.env.OPENSHIFT_NODEJS_IP ||
process.env.IP ||
undefined,
// Server port
port: process.env.OPENSHIFT_NODEJS_PORT ||
process.env.PORT ||
8080,
// MongoDB connection options
mongo: {
uri: process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
process.env.OPENSHIFT_MONGODB_DB_URL+process.env.OPENSHIFT_APP_NAME ||
'mongodb://localhost/spicyparty'
}
};<|fim▁end|> |
// Production specific configuration |
<|file_name|>fuzz_planner.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | from battle_tested.beta.input_type_combos import input_type_combos |
<|file_name|>app.component.ts<|end_file_name|><|fim▁begin|><|fim▁hole|> styles: [`h1 {
color: white;
background: darkgray;
padding: 20px;
}
`],
template: `
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<h1>{{name}}</h1>
<a [routerLink]="['/']">Home</a> | <a [routerLink]="['/about/', { id: 2 }]">About</a>
<router-outlet></router-outlet>
`,
})
export class AppComponent {
name: string = "Literature Lantern";
constructor() {}
}<|fim▁end|> | import { Component } from '@angular/core';
@Component({
selector: 'my-app', |
<|file_name|>qe_apidoc.py<|end_file_name|><|fim▁begin|>"""
Our version of sphinx-apidoc
@author : Spencer Lyon
@date : 2014-07-16
This file should be called from the command line. It accepts one
additional command line parameter. If we pass the parameter `single`
when running the file, this file will create a single directory named
modules where each module in quantecon will be documented. The index.rst
file will then contain a single list of all modules.
If no argument is passed or if the argument is anything other than
`single`, two directories will be created: models and tools. The models
directory will contain documentation instructions for the different
models in quantecon, whereas the tools directory will contain docs for
the tools in the package. The generated index.rst will then contain
two toctrees, one for models and one for tools.
Examples
--------
$ python qe_apidoc.py # generates the two separate directories
$ python qe_apidoc.py foo_bar # generates the two separate directories
$ python qe_apidoc.py single # generates the single directory
Notes
-----
1. This file can also be run from within ipython using the %%run magic.
To do this, use one of the commands above and replace `python` with
`%%run`
2. Models has been removed. But leaving infrastructure here for qe_apidoc
in the event we need it in the future
"""
import os
import sys
from glob import glob
######################
## String Templates ##
######################
module_template = """{mod_name}
{equals}
.. automodule:: quantecon.{mod_name}
:members:
:undoc-members:
:show-inheritance:
"""
game_theory_module_template = """{mod_name}
{equals}
.. automodule:: quantecon.game_theory.{mod_name}
:members:
:undoc-members:
:show-inheritance:
"""
game_generators_module_template = """{mod_name}
{equals}
.. automodule:: quantecon.game_theory.game_generators.{mod_name}
:members:
:undoc-members:
:show-inheritance:
"""
markov_module_template = """{mod_name}
{equals}
.. automodule:: quantecon.markov.{mod_name}
:members:
:undoc-members:
:show-inheritance:
"""
optimize_module_template = """{mod_name}
{equals}
.. automodule:: quantecon.optimize.{mod_name}
:members:
:undoc-members:
:show-inheritance:
"""
random_module_template = """{mod_name}
{equals}
.. automodule:: quantecon.random.{mod_name}
:members:
:undoc-members:
:show-inheritance:
"""
util_module_template = """{mod_name}
{equals}
.. automodule:: quantecon.util.{mod_name}
:members:
:undoc-members:
:show-inheritance:
"""
all_index_template = """=======================
QuantEcon documentation
=======================
Auto-generated documentation by module:
.. toctree::
:maxdepth: 2
{generated}
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
"""
split_index_template = """=======================
QuantEcon documentation
=======================
The `quantecon` python library consists of a number of modules which
includes game theory (game_theory), markov chains (markov), random
generation utilities (random), a collection of tools (tools),
and other utilities (util) which are
mainly used by developers internal to the package.
.. toctree::
:maxdepth: 2
game_theory
markov
optimize
random
tools
util
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
"""
split_file_template = """{name}
{equals}
.. toctree::
:maxdepth: 2
{files}
"""
######################
## Helper functions ##
######################
def source_join(f_name):
return os.path.join("source", f_name)
####################
## Main functions ##
####################
def all_auto():
# Get list of module names
mod_names = glob("../quantecon/[a-z0-9]*.py")
mod_names = list(map(lambda x: x.split('/')[-1], mod_names))
# Ensure source/modules directory exists
if not os.path.exists(source_join("modules")):
os.makedirs(source_join("modules"))
# Write file for each module
for mod in mod_names:
name = mod.split(".")[0] # drop .py ending
new_path = os.path.join("source", "modules", name + ".rst")
with open(new_path, "w") as f:
gen_module(name, f)
# write index.rst file to include these autogenerated files
with open(source_join("index.rst"), "w") as index:
generated = "\n ".join(list(map(lambda x: "modules/" + x.split(".")[0],
mod_names)))
temp = all_index_template.format(generated=generated)
index.write(temp)
def model_tool():
# list file names with game_theory
game_theory_files = glob("../quantecon/game_theory/[a-z0-9]*.py")
game_theory = list(map(lambda x: x.split('/')[-1][:-3], game_theory_files))
# Alphabetize
game_theory.sort()
# list file names with game_theory/game_generators
game_generators_files = glob("../quantecon/game_theory/game_generators/[a-z0-9]*.py")
game_generators = list(
map(lambda x: x.split('/')[-1][:-3], game_generators_files))
# Alphabetize
game_generators.sort()
# list file names with markov
markov_files = glob("../quantecon/markov/[a-z0-9]*.py")
markov = list(map(lambda x: x.split('/')[-1][:-3], markov_files))
# Alphabetize
markov.sort()
# list file names with optimize
optimize_files = glob("../quantecon/optimize/[a-z0-9]*.py")
optimize = list(map(lambda x: x.split('/')[-1][:-3], optimize_files))
# Alphabetize
optimize.sort()
# list file names with random
random_files = glob("../quantecon/random/[a-z0-9]*.py")
random = list(map(lambda x: x.split('/')[-1][:-3], random_files))
# Alphabetize
random.sort()
# list file names of tools (base level modules)
tool_files = glob("../quantecon/[a-z0-9]*.py")
tools = list(map(lambda x: x.split('/')[-1][:-3], tool_files))
# Alphabetize
tools.remove("version")
tools.sort()
# list file names of utilities
util_files = glob("../quantecon/util/[a-z0-9]*.py")
util = list(map(lambda x: x.split('/')[-1][:-3], util_files))
# Alphabetize
util.sort()
for folder in ["game_theory", "markov", "optimize", "random", "tools", "util"]:
if not os.path.exists(source_join(folder)):
os.makedirs(source_join(folder))
# Write file for each game_theory file
for mod in game_theory:
new_path = os.path.join("source", "game_theory", mod + ".rst")
with open(new_path, "w") as f:
equals = "=" * len(mod)
f.write(game_theory_module_template.format(mod_name=mod, equals=equals))
for mod in game_generators:
new_path = os.path.join("source", "game_theory", "game_generators", mod + ".rst")
with open(new_path, "w") as f:
equals = "=" * len(mod)
f.write(game_generators_module_template.format(
mod_name=mod, equals=equals))
#Add sudirectory to flat game_theory list for index file
game_theory.append("game_generators/{}".format(mod))
# Write file for each markov file
for mod in markov:
new_path = os.path.join("source", "markov", mod + ".rst")
with open(new_path, "w") as f:
equals = "=" * len(mod)
f.write(markov_module_template.format(mod_name=mod, equals=equals))
# Write file for each optimize file
for mod in optimize:
new_path = os.path.join("source", "optimize", mod + ".rst")
with open(new_path, "w") as f:
equals = "=" * len(mod)
f.write(optimize_module_template.format(mod_name=mod, equals=equals))
# Write file for each random file
for mod in random:
new_path = os.path.join("source", "random", mod + ".rst")
with open(new_path, "w") as f:
equals = "=" * len(mod)
f.write(random_module_template.format(mod_name=mod, equals=equals))
# Write file for each tool (base level modules)
for mod in tools:
new_path = os.path.join("source", "tools", mod + ".rst")
with open(new_path, "w") as f:
equals = "=" * len(mod)
f.write(module_template.format(mod_name=mod, equals=equals))
# Write file for each utility
for mod in util:
new_path = os.path.join("source", "util", mod + ".rst")
with open(new_path, "w") as f:<|fim▁hole|> f.write(util_module_template.format(mod_name=mod, equals=equals))
# write (index|models|tools).rst file to include autogenerated files
with open(source_join("index.rst"), "w") as index:
index.write(split_index_template)
gt = "game_theory/" + "\n game_theory/".join(game_theory)
mark = "markov/" + "\n markov/".join(markov)
opti = "optimize/" + "\n optimize/".join(optimize)
rand = "random/" + "\n random/".join(random)
tlz = "tools/" + "\n tools/".join(tools)
utls = "util/" + "\n util/".join(util)
#-TocTree-#
toc_tree_list = {"game_theory": gt,
"markov": mark,
"optimize" : opti,
"tools": tlz,
"random": rand,
"util": utls,
}
for f_name in ("game_theory", "markov", "optimize", "random", "tools", "util"):
with open(source_join(f_name + ".rst"), "w") as f:
m_name = f_name
if f_name == "game_theory":
f_name = "Game Theory" #Produce Nicer Title for Game Theory Module
if f_name == "util":
f_name = "Utilities" #Produce Nicer Title for Utilities Module
if f_name == "optimize":
f_name = "Optimize"
temp = split_file_template.format(name=f_name.capitalize(),
equals="="*len(f_name),
files=toc_tree_list[m_name])
f.write(temp)
if __name__ == '__main__':
if "single" in sys.argv[1:]:
all_auto()
else:
model_tool()<|fim▁end|> | equals = "=" * len(mod) |
<|file_name|>conversion.go<|end_file_name|><|fim▁begin|>package main
import (
"fmt"
"io"
"log"
"os"
"runtime"
"sort"
"strings"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/unversioned"
pkg_runtime "k8s.io/kubernetes/pkg/runtime"
"github.com/golang/glog"
flag "github.com/spf13/pflag"
_ "github.com/openshift/origin/pkg/api"
_ "github.com/openshift/origin/pkg/api/v1"
_ "github.com/openshift/origin/pkg/api/v1beta3"
// install all APIs
_ "github.com/openshift/origin/pkg/api/install"
_ "k8s.io/kubernetes/pkg/api/install"
_ "k8s.io/kubernetes/pkg/apis/extensions/install"
)
var (
functionDest = flag.StringP("funcDest", "f", "-", "Output for conversion functions; '-' means stdout")
group = flag.StringP("group", "g", "", "Group for conversion.")
version = flag.StringP("version", "v", "v1beta3", "Version for conversion.")
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
flag.Parse()
log.SetOutput(os.Stderr)
var funcOut io.Writer
if *functionDest == "-" {
funcOut = os.Stdout
} else {
file, err := os.Create(*functionDest)
if err != nil {
glog.Fatalf("Couldn't open %v: %v", *functionDest, err)
}
defer file.Close()
funcOut = file
}
generator := pkg_runtime.NewConversionGenerator(api.Scheme, "github.com/openshift/origin/pkg/api")
apiShort := generator.AddImport("k8s.io/kubernetes/pkg/api")
generator.AddImport("k8s.io/kubernetes/pkg/api/resource")
generator.AssumePrivateConversions()
// TODO(wojtek-t): Change the overwrites to a flag.
generator.OverwritePackage(*version, "")
gv := unversioned.GroupVersion{Group: *group, Version: *version}
knownTypes := api.Scheme.KnownTypes(gv)
knownTypeKeys := []string{}
for key := range knownTypes {
knownTypeKeys = append(knownTypeKeys, key)
}
sort.Strings(knownTypeKeys)
for _, knownTypeKey := range knownTypeKeys {
knownType := knownTypes[knownTypeKey]
if !strings.Contains(knownType.PkgPath(), "openshift/origin") {
continue
}
if err := generator.GenerateConversionsForType(gv, knownType); err != nil {
glog.Errorf("error while generating conversion functions for %v: %v", knownType, err)
}
}
// generator.RepackImports(sets.NewString("k8s.io/kubernetes/pkg/runtime"))
// the repack changes the name of the import<|fim▁hole|> if err := generator.WriteImports(funcOut); err != nil {
glog.Fatalf("error while writing imports: %v", err)
}
if err := generator.WriteConversionFunctions(funcOut); err != nil {
glog.Fatalf("Error while writing conversion functions: %v", err)
}
if err := generator.RegisterConversionFunctions(funcOut, fmt.Sprintf("%s.Scheme", apiShort)); err != nil {
glog.Fatalf("Error while writing conversion functions: %v", err)
}
}<|fim▁end|> | apiShort = generator.AddImport("k8s.io/kubernetes/pkg/api")
|
<|file_name|>stories.js<|end_file_name|><|fim▁begin|>'use strict';
/**
* Developed by Engagement Lab, 2019
* ==============
* Route to retrieve data by url
* @class api
* @author Johnny Richardson
*
* ==========
*/
const keystone = global.keystone,
mongoose = require('mongoose'),
Bluebird = require('bluebird');
mongoose.Promise = require('bluebird');
let list = keystone.list('Story').model;
var getAdjacent = (results, res, lang) => {
let fields = 'key photo.public_id ';
if (lang === 'en')
fields += 'name';
else if (lang === 'tm')
fields += 'nameTm';
else if (lang === 'hi')
fields += 'nameHi';
// Get one next/prev person from selected person's sortorder
let nextPerson = list.findOne({
sortOrder: {
$gt: results.jsonData.sortOrder
}
}, fields).limit(1);
let prevPerson = list.findOne({
sortOrder: {
$lt: results.jsonData.sortOrder
}
}, fields).sort({<|fim▁hole|> // Poplulate next/prev and output response
Bluebird.props({
next: nextPerson,
prev: prevPerson
}).then(nextPrevResults => {
let output = Object.assign(nextPrevResults, {
person: results.jsonData
});
return res.status(200).json({
status: 200,
data: output
});
}).catch(err => {
console.log(err);
});
};
var buildData = (storyId, res, lang) => {
let data = null;
let fields = 'key photo.public_id ';
if (lang === 'en')
fields += 'name subtitle';
else if (lang === 'tm')
fields += 'nameTm subtitleTm';
else if (lang === 'hi')
fields += 'nameHi subtitleHi';
if (storyId) {
let subFields = ' description.html ';
if (lang === 'tm')
subFields = ' descriptionTm.html ';
else if (lang === 'hi')
subFields = ' descriptionHi.html ';
data = list.findOne({
key: storyId
}, fields + subFields + 'sortOrder -_id');
} else
data = list.find({}, fields + ' -_id').sort([
['sortOrder', 'descending']
]);
Bluebird.props({
jsonData: data
})
.then(results => {
// When retrieving one story, also get next/prev ones
if (storyId)
getAdjacent(results, res, lang);
else {
return res.status(200).json({
status: 200,
data: results.jsonData
});
}
}).catch(err => {
console.log(err);
})
}
/*
* Get data
*/
exports.get = function (req, res) {
let id = null;
if (req.query.id)
id = req.query.id;
let lang = null;
if (req.params.lang)
lang = req.params.lang;
return buildData(id, res, lang);
}<|fim▁end|> | sortOrder: -1
}).limit(1);
|
<|file_name|>renderMenu.js<|end_file_name|><|fim▁begin|>'use strict';
module.exports = function renderMenu(props) {
if (!props.menu) {
return;
}
return props.menu({<|fim▁hole|> gridColumns: props.columns
});
};<|fim▁end|> | className: 'z-header-menu-column', |
<|file_name|>SecretSanta.java<|end_file_name|><|fim▁begin|>import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* Randomly generates Secret Santa assignments for a given group.
* <p>
* All valid possible assignments are equally likely to be generated (uniform distribution).
*
* @author Michael Zaccardo (mzaccardo@aetherworks.com)
*/
public class SecretSanta {
private static final Random random = new Random();
private static final String[] DEFAULT_NAMES = { "Rob", "Ally", "Angus", "Mike", "Shannon", "Greg", "Lewis", "Isabel" };
public static void main(final String[] args) {
final String[] names = getNamesToUse(args);
final List<Integer> assignments = generateAssignments(names.length);
printAssignmentsWithNames(assignments, names);
}
private static String[] getNamesToUse(final String[] args) {
if (args.length >= 2) {
return args;
} else {
System.out.println("Two or more names were not provided -- using default names.\n");
return DEFAULT_NAMES;
}
}
private static List<Integer> generateAssignments(final int size) {
final List<Integer> assignments = generateShuffledList(size);
while (!areValidAssignments(assignments)) {
Collections.shuffle(assignments, random);
}
return assignments;
}
private static List<Integer> generateShuffledList(final int size) {
final List<Integer> list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
list.add(i);
}
Collections.shuffle(list, random);
return list;
}
private static boolean areValidAssignments(final List<Integer> assignments) {
for (int i = 0; i < assignments.size(); i++) {
if (i == assignments.get(i)) {
return false;
}
}
return true;
}
private static void printAssignmentsWithNames(final List<Integer> assignments, final String[] names) {
for (int i = 0; i < assignments.size(); i++) {
System.out.println(names[i] + " --> " + names[assignments.get(i)]);
<|fim▁hole|> }
}
}<|fim▁end|> | |
<|file_name|>resample.go<|end_file_name|><|fim▁begin|>package filter
import (
"fmt"
"github.com/200sc/klangsynthese/audio/filter/supports"
)
// Speed modifies the filtered audio by a speed ratio, changing its sample rate
// in the process while maintaining pitch.
func Speed(ratio float64, pitchShifter PitchShifter) Encoding {
return func(senc supports.Encoding) {
r := ratio
fmt.Println(ratio)
for r < .5 {
r *= 2
pitchShifter.PitchShift(.5)(senc)
}
for r > 2.0 {
r /= 2<|fim▁hole|> pitchShifter.PitchShift(1 / r)(senc)
ModSampleRate(ratio)(senc.GetSampleRate())
}
}<|fim▁end|> | pitchShifter.PitchShift(2.0)(senc)
} |
<|file_name|>TwistedChat.py<|end_file_name|><|fim▁begin|>from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
class NonAnonChat(LineReceiver):
def __init__(self, protocols):
self.users = {'john':'john', 'adastra':'adastra'}
self.userName = None
self.userLogged = False
self.protocols = protocols
def connectionMade(self):
self.sendLine('Your Username: ')
def connectionLost(self, reason):
for protocol in self.protocols:
if protocol != self:
protocol.sendLine('Connection Lost: %s '%(reason))
def lineReceived(self, line):
if self.userName == None:
if self.users.has_key(line):
self.userName = line
self.sendLine('Password: ')
else:
self.sendLine('Wrong Username')
elif self.userLogged == False:
if self.users[self.userName] == line:
self.userLogged = True
self.protocols.append(self)<|fim▁hole|> if protocol != self:
protocol.sendLine('%s Said: %s ' %(self.userName, line))
class NonAnonFactory(Factory):
def __init__(self):
self.protocols = []
def buildProtocol(self, addr):
return NonAnonChat(self.protocols)
reactor.listenTCP(8000, NonAnonFactory())
reactor.run()<|fim▁end|> | else:
self.sendLine('Wrong Password')
elif self.userLogged == True:
for protocol in self.protocols: |
<|file_name|>apps.py<|end_file_name|><|fim▁begin|>from django.apps import AppConfig
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
class AppConfig(AppConfig):
name = '.'.join(__name__.split('.')[:-1])
label = 'icekit_plugins_iiif'
verbose_name = "IIIF Basics"
def ready(self):
# Create custom permission pointing to User, because we have no other
# model to hang it off for now...<|fim▁hole|> User = get_user_model()
try:
# this doesn't work if migrations haven't been updated, resulting
# in "RuntimeError: Error creating new content types. Please make
# sure contenttypes is migrated before trying to migrate apps
# individually."
content_type = ContentType.objects.get_for_model(User)
Permission.objects.get_or_create(
codename='can_use_iiif_image_api',
name='Can Use IIIF Image API',
content_type=content_type,
)
except RuntimeError:
pass<|fim▁end|> | # TODO This is a hack, find a better way |
<|file_name|>070-E-ClimbingStairs.py<|end_file_name|><|fim▁begin|><|fim▁hole|># Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
#
# Note: Given n will be a positive integer.
#
# Example 1:
#
# Input: 2
# Output: 2
# Explanation: There are two ways to climb to the top.
# 1. 1 step + 1 step
# 2. 2 steps
#
# Example 2:
#
# Input: 3
# Output: 3
# Explanation: There are three ways to climb to the top.
# 1. 1 step + 1 step + 1 step
# 2. 1 step + 2 steps
# 3. 2 steps + 1 step
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
table = [1, 2]
i = 2
while i < n:
table.append(table[i-1] + table[i-2])
i += 1
return table[n-1]
# Note:
# Generate two trees one with 1 step and other with 2 step and add both<|fim▁end|> | # You are climbing a stair case. It takes n steps to reach to the top.
# |
<|file_name|>stylieeditor.js<|end_file_name|><|fim▁begin|>/*
* stylie.treeview
* https://github.com/typesettin/stylie.treeview
*
* Copyright (c) 2015 Yaw Joseph Etse. All rights reserved.
*/
'use strict';
var extend = require('util-extend'),
CodeMirror = require('codemirror'),
StylieModals = require('stylie.modals'),
editorModals,
events = require('events'),
classie = require('classie'),
util = require('util');
require('../../node_modules/codemirror/addon/edit/matchbrackets');
require('../../node_modules/codemirror/addon/hint/css-hint');
require('../../node_modules/codemirror/addon/hint/html-hint');
require('../../node_modules/codemirror/addon/hint/javascript-hint');
require('../../node_modules/codemirror/addon/hint/show-hint');
require('../../node_modules/codemirror/addon/lint/css-lint');
require('../../node_modules/codemirror/addon/lint/javascript-lint');
// require('../../node_modules/codemirror/addon/lint/json-lint');
require('../../node_modules/codemirror/addon/lint/lint');
// require('../../node_modules/codemirror/addon/lint/html-lint');
require('../../node_modules/codemirror/addon/comment/comment');
require('../../node_modules/codemirror/addon/comment/continuecomment');
require('../../node_modules/codemirror/addon/fold/foldcode');
require('../../node_modules/codemirror/addon/fold/comment-fold');
require('../../node_modules/codemirror/addon/fold/indent-fold');
require('../../node_modules/codemirror/addon/fold/brace-fold');
require('../../node_modules/codemirror/addon/fold/foldgutter');
require('../../node_modules/codemirror/mode/css/css');
require('../../node_modules/codemirror/mode/htmlembedded/htmlembedded');
require('../../node_modules/codemirror/mode/htmlmixed/htmlmixed');
require('../../node_modules/codemirror/mode/javascript/javascript');
var saveSelection = function () {
if (window.getSelection) {
var sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
return sel.getRangeAt(0);
}
}
else if (document.selection && document.selection.createRange) {
return document.selection.createRange();
}
return null;
};
var restoreSelection = function (range) {
if (range) {
if (window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
else if (document.selection && range.select) {
range.select();
}
}
};
var getInsertTextModal = function (orignialid, mtype) {
var returnDiv = document.createElement('div'),
modaltype = (mtype === 'image') ? 'image' : 'text',
// execcmd = (mtype === 'image') ? 'insertImage' : 'createLink',
samplelink = (mtype === 'image') ? 'https://developers.google.com/+/images/branding/g+138.png' : 'http://example.com',
linktype = (mtype === 'image') ? 'image' : 'link';
returnDiv.setAttribute('id', orignialid + '-insert' + modaltype + '-modal');
returnDiv.setAttribute('data-name', orignialid + '-insert' + modaltype + '-modal');
returnDiv.setAttribute('class', 'ts-modal ts-modal-effect-1 insert' + modaltype + '-modal');
var divInnerHTML = '<section class="ts-modal-content ts-bg-text-primary-color ts-no-heading-margin ts-padding-lg ts-shadow ">';
divInnerHTML += '<div class="ts-form">';
divInnerHTML += '<div class="ts-row">';
divInnerHTML += '<div class="ts-col-span12">';
divInnerHTML += '<h6>Insert a link</h6>';
divInnerHTML += '</div>';
divInnerHTML += '</div>';
// divInnerHTML += '<div class="ts-row">';
// divInnerHTML += '<div class="ts-col-span4">';
// divInnerHTML += '<label class="ts-label">text</label>';
// divInnerHTML += '</div>';
// divInnerHTML += '<div class="ts-col-span8">';
// divInnerHTML += '<input type="text" name="link_url" placeholder="some web link" value="some web link"/>';
// divInnerHTML += '</div>';
// divInnerHTML += '</div>';
divInnerHTML += '<div class="ts-row">';
divInnerHTML += '<div class="ts-col-span4">';
divInnerHTML += '<label class="ts-label">url</label>';
divInnerHTML += '</div>';
divInnerHTML += '<div class="ts-col-span8">';
divInnerHTML += '<input type="text" class="ts-input ts-' + linktype + '_url" name="' + linktype + '_url" placeholder="' + samplelink + '" value="' + samplelink + '"/>';
divInnerHTML += '</div>';
divInnerHTML += '</div>';
divInnerHTML += '<div class="ts-row ts-text-center">';
divInnerHTML += '<div class="ts-col-span6">';
// divInnerHTML += '<button type="button" class="ts-button ts-modal-close ts-button-primary-color" onclick="document.execCommand(\'insertImage\', false, \'http://lorempixel.com/40/20/sports/\');">insert link</button>';
divInnerHTML += '<button type="button" class="ts-button ts-modal-close ts-button-primary-color add-' + linktype + '-button" >insert ' + linktype + '</button>';
divInnerHTML += '</div>';
divInnerHTML += '<div class="ts-col-span6">';
divInnerHTML += '<a class="ts-button ts-modal-close">close</a>';
divInnerHTML += '</div>';
divInnerHTML += '</div>';
divInnerHTML += '</div>';
divInnerHTML += '</section>';
returnDiv.innerHTML = divInnerHTML;
return returnDiv;
};
/**
* A module that represents a StylieTextEditor object, a componentTab is a page composition tool.
* @{@link https://github.com/typesettin/stylie.treeview}
* @author Yaw Joseph Etse
* @copyright Copyright (c) 2015 Typesettin. All rights reserved.
* @license MIT
* @constructor StylieTextEditor
* @requires module:util-extent
* @requires module:util
* @requires module:events
* @param {object} el element of tab container
* @param {object} options configuration options
*/
var StylieTextEditor = function (options) {
events.EventEmitter.call(this);
var defaultOptions = {
type: 'html',
updateOnChange: true
};
this.options = extend(defaultOptions, options);
return this;<|fim▁hole|>
util.inherits(StylieTextEditor, events.EventEmitter);
var createButton = function (options) {
var buttonElement = document.createElement('button');
buttonElement.setAttribute('class', 'ts-button ts-text-xs ' + options.classes);
buttonElement.setAttribute('type', 'button');
buttonElement.innerHTML = options.innerHTML;
for (var key in options) {
if (key !== 'classes' && key !== 'innerHTML' && key !== 'innerhtml') {
buttonElement.setAttribute(key, options[key]);
}
}
return buttonElement;
};
StylieTextEditor.prototype.addMenuButtons = function () {
this.options.buttons.boldButton = createButton({
classes: ' flaticon-bold17 ',
title: 'Bold text',
innerHTML: ' ',
'data-attribute-action': 'bold'
});
this.options.buttons.italicButton = createButton({
classes: ' flaticon-italic9 ',
title: 'Italic text',
innerHTML: ' ',
'data-attribute-action': 'italic'
});
this.options.buttons.underlineButton = createButton({
classes: ' flaticon-underlined5 ',
title: 'Underline text',
innerHTML: ' ',
'data-attribute-action': 'underline'
});
this.options.buttons.unorderedLIButton = createButton({
classes: ' flaticon-list82 ',
innerHTML: ' ',
title: ' Insert unordered list ',
'data-attribute-action': 'unorderedLI'
});
this.options.buttons.orderedLIButton = createButton({
classes: ' flaticon-numbered8 ',
title: ' Insert ordered list ',
innerHTML: ' ',
'data-attribute-action': 'orderedLI'
});
this.options.buttons.lefttextalignButton = createButton({
classes: ' flaticon-text141 ',
innerHTML: ' ',
title: ' left align text ',
'data-attribute-action': 'left-textalign'
}); //flaticon-text141
this.options.buttons.centertextalignButton = createButton({
classes: ' flaticon-text136 ',
innerHTML: ' ',
title: ' center align text ',
'data-attribute-action': 'center-textalign'
}); //flaticon-text136
this.options.buttons.righttextalignButton = createButton({
classes: ' flaticon-text134 ',
innerHTML: ' ',
title: ' right align text ',
'data-attribute-action': 'right-textalign'
}); //flaticon-text134
this.options.buttons.justifytextalignButton = createButton({
classes: ' flaticon-text146 ',
innerHTML: ' ',
title: ' justify align text ',
'data-attribute-action': 'justify-textalign'
}); //flaticon-text146
//flaticon-characters - font
this.options.buttons.textcolorButton = createButton({
classes: ' flaticon-text137 ',
innerHTML: ' ',
title: ' change text color ',
'data-attribute-action': 'text-color'
}); //flaticon-text137 - text color
this.options.buttons.texthighlightButton = createButton({
classes: ' flaticon-paintbrush13 ',
innerHTML: ' ',
title: ' change text highlight ',
'data-attribute-action': 'text-highlight'
}); //flaticon-paintbrush13 - text background color(highlight)
this.options.buttons.linkButton = createButton({
classes: ' flaticon-link56 ',
title: ' Insert a link ',
innerHTML: ' ',
'data-attribute-action': 'link'
});
this.options.buttons.imageButton = createButton({
classes: ' flaticon-images25 ',
title: ' Insert image ',
innerHTML: ' ',
'data-attribute-action': 'image'
});
this.options.buttons.codeButton = createButton({
innerHTML: ' ',
classes: ' flaticon-code39 ',
title: 'Source code editor',
'data-attribute-action': 'code'
});
this.options.buttons.fullscreenButton = createButton({
title: 'Maximize and fullscreen editor',
classes: ' flaticon-logout18 ',
innerHTML: ' ',
'data-attribute-action': 'fullscreen'
});
this.options.buttons.outdentButton = createButton({
title: 'Outdent button',
classes: ' flaticon-paragraph19 ',
innerHTML: ' ',
'data-attribute-action': 'outdent'
});
this.options.buttons.indentButton = createButton({
title: 'Indent button',
classes: ' flaticon-right195 ',
innerHTML: ' ',
'data-attribute-action': 'indent'
});
};
var button_gobold = function () {
document.execCommand('bold', false, '');
};
var button_gounderline = function () {
document.execCommand('underline', false, '');
};
var button_goitalic = function () {
document.execCommand('italic', false, '');
};
var button_golink = function () {
document.execCommand('createLink', true, '');
};
var button_golist = function () {
document.execCommand('insertOrderedList', true, '');
};
var button_gobullet = function () {
document.execCommand('insertUnorderedList', true, '');
};
var button_goimg = function () {
// document.execCommand('insertImage', false, 'http://lorempixel.com/40/20/sports/');
this.saveSelection();
window.editorModals.show(this.options.elementContainer.getAttribute('data-original-id') + '-insertimage-modal');
};
var button_gotextlink = function () {
// console.log(this.options.elementContainer.getAttribute('data-original-id'));
this.saveSelection();
window.editorModals.show(this.options.elementContainer.getAttribute('data-original-id') + '-inserttext-modal');
};
var add_link_to_editor = function () {
this.restoreSelection();
document.execCommand('createLink', false, this.options.forms.add_link_form.querySelector('.ts-link_url').value);
};
var add_image_to_editor = function () {
this.restoreSelection();
document.execCommand('insertImage', false, this.options.forms.add_image_form.querySelector('.ts-image_url').value);
};
var button_gofullscreen = function () {
// console.log('button_gofullscreen this', this);
// if()
classie.toggle(this.options.elementContainer, 'ts-editor-fullscreen');
classie.toggle(this.options.buttons.fullscreenButton, 'ts-button-primary-text-color');
};
var button_togglecodeeditor = function () {
classie.toggle(this.options.codemirror.getWrapperElement(), 'ts-hidden');
classie.toggle(this.options.buttons.codeButton, 'ts-button-primary-text-color');
this.options.codemirror.refresh();
};
var button_gotext_left = function () {
document.execCommand('justifyLeft', true, '');
};
var button_gotext_center = function () {
document.execCommand('justifyCenter', true, '');
};
var button_gotext_right = function () {
document.execCommand('justifyRight', true, '');
};
var button_gotext_justifyfull = function () {
document.execCommand('justifyFull', true, '');
};
// var button_gotext_left = function () {
// document.execCommand('justifyLeft', true, '');
// };
var button_go_outdent = function () {
document.execCommand('outdent', true, '');
};
var button_go_indent = function () {
document.execCommand('indent', true, '');
};
StylieTextEditor.prototype.initButtonEvents = function () {
this.options.buttons.boldButton.addEventListener('click', button_gobold, false);
this.options.buttons.underlineButton.addEventListener('click', button_gounderline, false);
this.options.buttons.italicButton.addEventListener('click', button_goitalic, false);
this.options.buttons.linkButton.addEventListener('click', button_golink, false);
this.options.buttons.unorderedLIButton.addEventListener('click', button_gobullet, false);
this.options.buttons.orderedLIButton.addEventListener('click', button_golist, false);
this.options.buttons.imageButton.addEventListener('click', button_goimg.bind(this), false);
this.options.buttons.linkButton.addEventListener('click', button_gotextlink.bind(this), false);
this.options.buttons.lefttextalignButton.addEventListener('click', button_gotext_left, false);
this.options.buttons.centertextalignButton.addEventListener('click', button_gotext_center, false);
this.options.buttons.righttextalignButton.addEventListener('click', button_gotext_right, false);
this.options.buttons.justifytextalignButton.addEventListener('click', button_gotext_justifyfull, false);
this.options.buttons.outdentButton.addEventListener('click', button_go_outdent, false);
this.options.buttons.indentButton.addEventListener('click', button_go_indent, false);
this.options.buttons.fullscreenButton.addEventListener('click', button_gofullscreen.bind(this), false);
this.options.buttons.codeButton.addEventListener('click', button_togglecodeeditor.bind(this), false);
this.options.buttons.addlinkbutton.addEventListener('click', add_link_to_editor.bind(this), false);
this.options.buttons.addimagebutton.addEventListener('click', add_image_to_editor.bind(this), false);
};
StylieTextEditor.prototype.init = function () {
try {
var previewEditibleDiv = document.createElement('div'),
previewEditibleMenu = document.createElement('div'),
insertImageURLModal = getInsertTextModal(this.options.element.getAttribute('id'), 'image'),
insertTextLinkModal = getInsertTextModal(this.options.element.getAttribute('id'), 'text'),
previewEditibleContainer = document.createElement('div');
this.options.buttons = {};
this.addMenuButtons();
previewEditibleMenu.appendChild(this.options.buttons.boldButton);
previewEditibleMenu.appendChild(this.options.buttons.italicButton);
previewEditibleMenu.appendChild(this.options.buttons.underlineButton);
previewEditibleMenu.appendChild(this.options.buttons.unorderedLIButton);
previewEditibleMenu.appendChild(this.options.buttons.orderedLIButton);
previewEditibleMenu.appendChild(this.options.buttons.lefttextalignButton);
previewEditibleMenu.appendChild(this.options.buttons.centertextalignButton);
previewEditibleMenu.appendChild(this.options.buttons.righttextalignButton);
previewEditibleMenu.appendChild(this.options.buttons.justifytextalignButton);
// previewEditibleMenu.appendChild(this.options.buttons.textcolorButton);
// previewEditibleMenu.appendChild(this.options.buttons.texthighlightButton);
previewEditibleMenu.appendChild(this.options.buttons.outdentButton);
previewEditibleMenu.appendChild(this.options.buttons.indentButton);
previewEditibleMenu.appendChild(this.options.buttons.linkButton);
previewEditibleMenu.appendChild(this.options.buttons.imageButton);
previewEditibleMenu.appendChild(this.options.buttons.codeButton);
previewEditibleMenu.appendChild(this.options.buttons.fullscreenButton);
previewEditibleMenu.setAttribute('class', 'ts-input ts-editor-menu ts-padding-sm');
previewEditibleMenu.setAttribute('style', 'font-family: monospace, Arial,"Times New Roman";');
previewEditibleDiv.setAttribute('class', 'ts-input ts-texteditor');
previewEditibleDiv.setAttribute('contenteditable', 'true');
previewEditibleDiv.setAttribute('tabindex', '1');
previewEditibleContainer.setAttribute('id', this.options.element.getAttribute('id') + '_container');
previewEditibleContainer.setAttribute('data-original-id', this.options.element.getAttribute('id'));
previewEditibleContainer.setAttribute('class', 'ts-editor-container');
previewEditibleContainer.appendChild(previewEditibleMenu);
previewEditibleContainer.appendChild(previewEditibleDiv);
document.querySelector('.ts-modal-hidden-container').appendChild(insertTextLinkModal);
document.querySelector('.ts-modal-hidden-container').appendChild(insertImageURLModal);
this.options.element = this.options.element || document.querySelector(this.options.elementSelector);
previewEditibleDiv.innerHTML = this.options.element.innerText;
this.options.previewElement = previewEditibleDiv;
this.options.forms = {
add_link_form: document.querySelector('.inserttext-modal .ts-form'),
add_image_form: document.querySelector('.insertimage-modal .ts-form')
};
this.options.buttons.addlinkbutton = document.querySelector('.inserttext-modal').querySelector('.add-link-button');
this.options.buttons.addimagebutton = document.querySelector('.insertimage-modal').querySelector('.add-image-button');
//now add code mirror
this.options.elementContainer = previewEditibleContainer;
this.options.element.parentNode.appendChild(previewEditibleContainer);
previewEditibleContainer.appendChild(this.options.element);
this.options.codemirror = CodeMirror.fromTextArea(
this.options.element, {
lineNumbers: true,
lineWrapping: true,
matchBrackets: true,
autoCloseBrackets: true,
mode: (this.options.type === 'ejs') ? 'text/ejs' : 'text/html',
indentUnit: 2,
indentWithTabs: true,
'overflow-y': 'hidden',
'overflow-x': 'auto',
lint: true,
gutters: [
'CodeMirror-linenumbers',
'CodeMirror-foldgutter',
// 'CodeMirror-lint-markers'
],
foldGutter: true
}
);
// this.options.element.parentNode.insertBefore(previewEditibleDiv, this.options.element);
this.options.codemirror.on('blur', function (instance) {
// console.log('editor lost focuss', instance, change);
this.options.previewElement.innerHTML = instance.getValue();
}.bind(this));
this.options.previewElement.addEventListener('blur', function () {
this.options.codemirror.getDoc().setValue(this.options.previewElement.innerHTML);
}.bind(this));
if (this.options.updateOnChange) {
this.options.codemirror.on('change', function (instance) {
// console.log('editor lost focuss', instance, change);
// console.log('document.activeElement === this.options.previewElement', document.activeElement === this.options.previewElement);
setTimeout(function () {
if (document.activeElement !== this.options.previewElement) {
this.options.previewElement.innerHTML = instance.getValue();
}
}.bind(this), 5000);
}.bind(this));
this.options.previewElement.addEventListener('change', function () {
this.options.codemirror.getDoc().setValue(this.options.previewElement.innerHTML);
}.bind(this));
}
//set initial code mirror
this.options.codemirror.getDoc().setValue(this.options.previewElement.innerHTML);
this.options.codemirror.refresh();
classie.add(this.options.codemirror.getWrapperElement(), 'ts-hidden');
// setTimeout(this.options.codemirror.refresh, 1000);
this.initButtonEvents();
editorModals = new StylieModals({});
window.editorModals = editorModals;
return this;
}
catch (e) {
console.error(e);
}
};
StylieTextEditor.prototype.getValue = function () {
return this.options.previewElement.innerText || this.options.codemirror.getValue();
};
StylieTextEditor.prototype.saveSelection = function () {
this.options.selection = (saveSelection()) ? saveSelection() : null;
};
StylieTextEditor.prototype.restoreSelection = function () {
this.options.preview_selection = this.options.selection;
restoreSelection(this.options.selection);
};
module.exports = StylieTextEditor;<|fim▁end|> | // this.getTreeHTML = this.getTreeHTML;
}; |
<|file_name|>MentorsTableSeederinitial.js<|end_file_name|><|fim▁begin|>/*global NULL*/
'use strict';
var sha1 = require('sha1');
module.exports = {
up: function (queryInterface, Sequelize) {
return queryInterface.bulkInsert('Mentors', [{
nameFirst: 'Betty',
nameLast: 'Coder',
email: 'betty@coderevolution.com',
password: sha1('password'),
githubLink: 'http://github.com/bettyc',
skillSet1:'mean',
skillLevel1: 2,
skillSet2:'mern',
skillLevel2: 1,
bio:'Hi, I\'m Betty and I\'ve been coding since I was three.',
userWebLink:'http://mybettyweb.com',
mentorRating:3,
photoLink: 'public/images/fakefemale1.png'
},
{
nameFirst: 'Archi',
nameLast: 'Thompson',
email: 'archi@coderevolution.com',
password: sha1('password'),
githubLink: 'http://github.com/archi',
skillSet1: 'mern',
skillLevel1: 3,
skillSet2:'mean',
skillLevel2: 2,
bio:'I love helping new coders discover web development. Let me teach you the MERN stack.',
userWebLink:'http://comecodewithme.code',
mentorRating:3,
photoLink: 'public/images/archithompson.png'
},
{
nameFirst: 'Cecile',
nameLast: 'Diakonova',
email: 'cjd@coderevolution.com',
password: sha1('password'),
githubLink: 'http://github.com/diakonova',
skillSet1: 'mern',
skillLevel1: 3,
bio:'Fully versed in both LAMP and MERN stacks.',
userWebLink:'http://comecodewithme.code',
mentorRating:3,
photoLink: 'public/images/fakefemale2.png'
},
{
nameFirst: 'Taylor',
nameLast: 'Jackson',<|fim▁hole|> skillSet1: 'mean',
skillLevel1: 3,
bio:'I have been a developer for ten years. I am passionate about learning new technologies.',
userWebLink:'http://comecodewithme.code',
mentorRating:3,
photoLink: 'public/images/taylor.jpeg'
}
], {})
},
down: function (queryInterface, Sequelize) {
/*
Add reverting commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.bulkDelete('Person', null, {});
*/
return queryInterface.bulkDelete('Mentors', null, {});
}
};<|fim▁end|> | email: 'taylor@coderevolution.com',
password: sha1('password'),
githubLink: 'http://github.com/djackson', |
<|file_name|>goma_numeric_types_gen.go<|end_file_name|><|fim▁begin|>package entity
import (
"database/sql"
)
// NOTE: THIS FILE WAS PRODUCED BY THE
// GOMA CODE GENERATION TOOL (github.com/kyokomi/goma)
// DO NOT EDIT
// GomaNumericTypes is generated goma_numeric_types table.
type GomaNumericTypes struct {
ID int64 `goma:"size:20:pk"`
TinyintColumns int `goma:"size:4"`
BoolColumns bool `goma:"size:1"`
SmallintColumns int `goma:"size:6"`
MediumintColumns int `goma:"size:9"`
IntColumns int `goma:"size:11"`
IntegerColumns int `goma:"size:11"`
SerialColumns int64 `goma:"size:20"`
DecimalColumns string `goma:"size:10"`
NumericColumns string `goma:"size:10"`
FloatColumns float32 `goma:""`
DoubleColumns float64 `goma:""`
}
// Scan GomaNumericTypes all scan
func (e *GomaNumericTypes) Scan(rows *sql.Rows) error {
err := rows.Scan(&e.ID, &e.TinyintColumns, &e.BoolColumns, &e.SmallintColumns, &e.MediumintColumns, &e.IntColumns, &e.IntegerColumns, &e.SerialColumns, &e.DecimalColumns, &e.NumericColumns, &e.FloatColumns, &e.DoubleColumns)
return err<|fim▁hole|><|fim▁end|> | } |
<|file_name|>cast_metrics_test_helper.cc<|end_file_name|><|fim▁begin|>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromecast/base/metrics/cast_metrics_test_helper.h"
#include "base/logging.h"
#include "base/macros.h"
#include "chromecast/base/metrics/cast_metrics_helper.h"
namespace chromecast {
namespace metrics {
namespace {
class CastMetricsHelperStub : public CastMetricsHelper {
public:
CastMetricsHelperStub();
~CastMetricsHelperStub() override;
void UpdateCurrentAppInfo(const std::string& app_id,
const std::string& session_id) override;
void UpdateSDKInfo(const std::string& sdk_version) override;
void LogMediaPlay() override;
void LogMediaPause() override;
void LogTimeToFirstAudio() override;
void LogTimeToBufferAv(BufferingType buffering_type,
base::TimeDelta time) override;
std::string GetMetricsNameWithAppName(
const std::string& prefix, const std::string& suffix) const override;
void SetMetricsSink(MetricsSink* delegate) override;
void RecordSimpleAction(const std::string& action) override;
private:
DISALLOW_COPY_AND_ASSIGN(CastMetricsHelperStub);
};
bool stub_instance_exists = false;
CastMetricsHelperStub::CastMetricsHelperStub()
: CastMetricsHelper() {
DCHECK(!stub_instance_exists);
stub_instance_exists = true;
}
CastMetricsHelperStub::~CastMetricsHelperStub() {
DCHECK(stub_instance_exists);
stub_instance_exists = false;
}
void CastMetricsHelperStub::UpdateCurrentAppInfo(
const std::string& app_id,
const std::string& session_id) {
}
void CastMetricsHelperStub::UpdateSDKInfo(const std::string& sdk_version) {
}
void CastMetricsHelperStub::LogMediaPlay() {
}
void CastMetricsHelperStub::LogMediaPause() {
}
void CastMetricsHelperStub::LogTimeToFirstAudio() {
}
<|fim▁hole|>
std::string CastMetricsHelperStub::GetMetricsNameWithAppName(
const std::string& prefix,
const std::string& suffix) const {
return "";
}
void CastMetricsHelperStub::SetMetricsSink(MetricsSink* delegate) {
}
} // namespace
void CastMetricsHelperStub::RecordSimpleAction(const std::string& action) {
}
void InitializeMetricsHelperForTesting() {
if (!stub_instance_exists) {
new CastMetricsHelperStub();
}
}
} // namespace metrics
} // namespace chromecast<|fim▁end|> | void CastMetricsHelperStub::LogTimeToBufferAv(BufferingType buffering_type,
base::TimeDelta time) {
} |
<|file_name|>constants.js<|end_file_name|><|fim▁begin|>/**
* constants.js<|fim▁hole|> */
// TODO: update these to better colors
var SHIELD_COLOR = vec4.fromValues(0.0, 0.0, 1.0, 1.0);
var ARMOR_COLOR = vec4.fromValues(0.0, 1.0, 0.0, 1.0);
var HULL_COLOR = vec4.fromValues(1.0, 0.0, 1.0, 1.0);<|fim▁end|> | |
<|file_name|>pie.js<|end_file_name|><|fim▁begin|>(function () {
var color = window.color;
var getset = color.getset;
color.pie = function () {
var options = {
height: color.available( "height" ),
width: color.available( "width" ),
value: null,
color: null,
hole: 0,
palette: window.color.palettes.default,
data: null,
legend: color.legend()
.color( "key" )
.value( "key" )
.direction( "vertical" )
}
function pie () { return pie.draw( this ) }
pie.height = getset( options, "height" );
pie.width = getset( options, "width" );
pie.value = getset( options, "value" );
pie.color = getset( options, "color" );
pie.hole = getset( options, "hole" );
pie.palette = getset( options, "palette" );
pie.data = getset( options, "data" );
pie.legend = getset( options, "legend" );
pie.draw = function ( selection ) {
if ( selection instanceof Element ) {
selection = d3.selectAll( [ selection ] );
}
selection.each( function ( data ) {
var data = layout( pie, pie.data() || data );
draw( pie, this, data );
})
return this;
}
return pie;
}
function draw( that, el, data ) {
el = d3.select( el );
if ( el.attr( "data-color-chart" ) != "pie" ) {
el.attr( "data-color-chart", "pie" )
.text( "" );
}
el.node().__colorchart = that;
var height = that.height.get( el )
var width = that.width.get( el )
var radius = Math.min( height / 2, width / 2 ) - 10;
var c = color.palette()
.colors( that.palette() )
.domain( data.map( function ( d ) { return d.key } ) )
.scale();
var arc = d3.svg.arc()
.outerRadius( radius )
.innerRadius( radius * that.hole() );
// tooltip
var tooltip = color.tooltip()
.title( function ( d ) {
return !d.key
? that.value()
: d.key
})
.content( function ( d ) {
return !d.key
? d.value
: that.value() + ": " + d.value;
})
// draw the legend
var legend = c.domain().length > 1;
var legend = el.selectAll( "g[data-pie-legend]" )
.data( legend ? [ data ] : [] );
legend.enter().append( "g" )
.attr( "data-pie-legend", "" )
legend.call( that.legend().palette( that.palette() ) );
legend.attr( "transform", function () {
var top = ( height - legend.node().getBBox().height ) / 2;
return "translate(35," + top + ")";
})
// start drawing
var pies = el.selectAll( "g[data-pie]" )
.data( [ data ] );
pies.enter().append( "g" )
.attr( "data-pie", "" )
.attr( "transform", function () {
return "translate(" + ( width / 2 ) + "," + ( height / 2 ) + ")";
});
var slices = pies.selectAll( "path[data-pie-slice]" )
.data( function ( d ) { return d } );
slices.exit().remove();
slices.enter().append( "path" );
slices
.attr( "data-pie-slice", function ( d ) {
return d.key;
})
.attr( "d", arc )
.attr( "fill", function ( d ) {
return c( d.key );
})
.call( tooltip );
}
function layout ( that, data ) {
// extract the values for each obj
data = data.map( function ( d ) {
var v = +d[ that.value() ]
if ( isNaN( v ) ) {
throw new Error( "pie value must be a number" );
}
return { v: v, c: d[ that.color() ], obj: d }
})
// group by colors
data = d3.nest()
.key( function ( d ) { return d.c || "" } )
.rollup ( function ( data ) {
return data.reduce( function ( v, d ) {
return v + d.v;
}, 0 )
})
.entries( data );
// lay out the pie
data = d3.layout.pie()
.sort( null )
.value( function ( d ) {
return d.values
})( data )
.map( function ( d ) {
d.key = d.data.key;
delete d.data;<|fim▁hole|> }
})();<|fim▁end|> | return d;
});
return data; |
<|file_name|>declaration_block.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A property declaration block.
#![deny(missing_docs)]
use context::QuirksMode;
use cssparser::{DeclarationListParser, parse_important, ParserInput, CowRcStr};
use cssparser::{Parser, AtRuleParser, DeclarationParser, Delimiter, ParseError as CssParseError};
use error_reporting::{ParseErrorReporter, ContextualParseError};
use parser::{ParserContext, ParserErrorContext};
use properties::animated_properties::AnimationValue;
use selectors::parser::SelectorParseError;
use shared_lock::Locked;
use smallbitvec::{self, SmallBitVec};
use smallvec::SmallVec;
use std::fmt;
use std::iter::{DoubleEndedIterator, Zip};
use std::slice::Iter;
use style_traits::{PARSING_MODE_DEFAULT, ToCss, ParseError, ParsingMode, StyleParseError};
use stylesheets::{CssRuleType, Origin, UrlExtraData};
use super::*;
use values::computed::Context;
#[cfg(feature = "gecko")] use properties::animated_properties::AnimationValueMap;
/// The animation rules.
///
/// The first one is for Animation cascade level, and the second one is for
/// Transition cascade level.
pub struct AnimationRules(pub Option<Arc<Locked<PropertyDeclarationBlock>>>,
pub Option<Arc<Locked<PropertyDeclarationBlock>>>);
impl AnimationRules {
/// Returns whether these animation rules represents an actual rule or not.
pub fn is_empty(&self) -> bool {
self.0.is_none() && self.1.is_none()
}
}
/// A declaration [importance][importance].
///
/// [importance]: https://drafts.csswg.org/css-cascade/#importance
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Importance {
/// Indicates a declaration without `!important`.
Normal,
/// Indicates a declaration with `!important`.
Important,
}
impl Importance {
/// Return whether this is an important declaration.
pub fn important(self) -> bool {
match self {
Importance::Normal => false,
Importance::Important => true,
}
}
}
/// Overridden declarations are skipped.
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[derive(Clone)]
pub struct PropertyDeclarationBlock {
/// The group of declarations, along with their importance.
///
/// Only deduplicated declarations appear here.
declarations: Vec<PropertyDeclaration>,
/// The "important" flag for each declaration in `declarations`.
declarations_importance: SmallBitVec,
longhands: LonghandIdSet,
}
/// Iterator over `(PropertyDeclaration, Importance)` pairs.
pub struct DeclarationImportanceIterator<'a> {
iter: Zip<Iter<'a, PropertyDeclaration>, smallbitvec::Iter<'a>>,
}
impl<'a> DeclarationImportanceIterator<'a> {
/// Constructor
pub fn new(declarations: &'a [PropertyDeclaration], important: &'a SmallBitVec) -> Self {
DeclarationImportanceIterator {
iter: declarations.iter().zip(important.iter()),
}
}
}
impl<'a> Iterator for DeclarationImportanceIterator<'a> {
type Item = (&'a PropertyDeclaration, Importance);
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(decl, important)|
(decl, if important { Importance::Important } else { Importance::Normal }))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<'a> DoubleEndedIterator for DeclarationImportanceIterator<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
self.iter.next_back().map(|(decl, important)|
(decl, if important { Importance::Important } else { Importance::Normal }))
}
}
/// Iterator over `PropertyDeclaration` for Importance::Normal.
pub struct NormalDeclarationIterator<'a>(DeclarationImportanceIterator<'a>);
impl<'a> NormalDeclarationIterator<'a> {
/// Constructor
pub fn new(declarations: &'a [PropertyDeclaration], important: &'a SmallBitVec) -> Self {
NormalDeclarationIterator(
DeclarationImportanceIterator::new(declarations, important)
)
}
}
impl<'a> Iterator for NormalDeclarationIterator<'a> {
type Item = &'a PropertyDeclaration;
fn next(&mut self) -> Option<Self::Item> {
loop {
let next = self.0.iter.next();
match next {
Some((decl, importance)) => {
if !importance {
return Some(decl);
}
},
None => return None,
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.iter.size_hint()
}
}
/// Iterator for AnimationValue to be generated from PropertyDeclarationBlock.
pub struct AnimationValueIterator<'a, 'cx, 'cx_a:'cx> {
iter: NormalDeclarationIterator<'a>,
context: &'cx mut Context<'cx_a>,
default_values: &'a ComputedValues,
/// Custom properties in a keyframe if exists.
extra_custom_properties: Option<&'a Arc<::custom_properties::CustomPropertiesMap>>,
}
impl<'a, 'cx, 'cx_a:'cx> AnimationValueIterator<'a, 'cx, 'cx_a> {
fn new(
declarations: &'a PropertyDeclarationBlock,
context: &'cx mut Context<'cx_a>,
default_values: &'a ComputedValues,
extra_custom_properties: Option<&'a Arc<::custom_properties::CustomPropertiesMap>>,
) -> AnimationValueIterator<'a, 'cx, 'cx_a> {
AnimationValueIterator {
iter: declarations.normal_declaration_iter(),
context,
default_values,
extra_custom_properties,
}
}
}
impl<'a, 'cx, 'cx_a:'cx> Iterator for AnimationValueIterator<'a, 'cx, 'cx_a> {
type Item = AnimationValue;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
loop {
let next = self.iter.next();
let decl = match next {
Some(decl) => decl,
None => return None,
};
let animation = AnimationValue::from_declaration(
decl,
&mut self.context,
self.extra_custom_properties,
self.default_values,
);
if let Some(anim) = animation {
return Some(anim);
}
}
}
}
impl fmt::Debug for PropertyDeclarationBlock {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.declarations.fmt(f)
}
}
impl PropertyDeclarationBlock {
/// Returns the number of declarations in the block.
pub fn len(&self) -> usize {
self.declarations.len()
}
/// Create an empty block
pub fn new() -> Self {
PropertyDeclarationBlock {
declarations: Vec::new(),
declarations_importance: SmallBitVec::new(),
longhands: LonghandIdSet::new(),
}
}
/// Create a block with a single declaration
pub fn with_one(declaration: PropertyDeclaration, importance: Importance) -> Self {
let mut longhands = LonghandIdSet::new();
if let PropertyDeclarationId::Longhand(id) = declaration.id() {
longhands.insert(id);
}
PropertyDeclarationBlock {
declarations: vec![declaration],
declarations_importance: SmallBitVec::from_elem(1, importance.important()),
longhands: longhands,
}
}
/// The declarations in this block
pub fn declarations(&self) -> &[PropertyDeclaration] {
&self.declarations
}
/// The `important` flags for declarations in this block
pub fn declarations_importance(&self) -> &SmallBitVec {
&self.declarations_importance
}
/// Iterate over `(PropertyDeclaration, Importance)` pairs
pub fn declaration_importance_iter(&self) -> DeclarationImportanceIterator {
DeclarationImportanceIterator::new(&self.declarations, &self.declarations_importance)
}
/// Iterate over `PropertyDeclaration` for Importance::Normal
pub fn normal_declaration_iter(&self) -> NormalDeclarationIterator {
NormalDeclarationIterator::new(&self.declarations, &self.declarations_importance)
}
/// Return an iterator of (AnimatableLonghand, AnimationValue).
pub fn to_animation_value_iter<'a, 'cx, 'cx_a:'cx>(
&'a self,
context: &'cx mut Context<'cx_a>,
default_values: &'a ComputedValues,
extra_custom_properties: Option<&'a Arc<::custom_properties::CustomPropertiesMap>>,
) -> AnimationValueIterator<'a, 'cx, 'cx_a> {
AnimationValueIterator::new(self, context, default_values, extra_custom_properties)
}
/// Returns whether this block contains any declaration with `!important`.
///
/// This is based on the `declarations_importance` bit-vector,
/// which should be maintained whenever `declarations` is changed.
pub fn any_important(&self) -> bool {
!self.declarations_importance.all_false()
}
/// Returns whether this block contains any declaration without `!important`.
///
/// This is based on the `declarations_importance` bit-vector,<|fim▁hole|> !self.declarations_importance.all_true()
}
/// Returns whether this block contains a declaration of a given longhand.
pub fn contains(&self, id: LonghandId) -> bool {
self.longhands.contains(id)
}
/// Get a declaration for a given property.
///
/// NOTE: This is linear time.
pub fn get(&self, property: PropertyDeclarationId) -> Option<(&PropertyDeclaration, Importance)> {
self.declarations.iter().enumerate().find(|&(_, decl)| decl.id() == property).map(|(i, decl)| {
let importance = if self.declarations_importance.get(i as u32) {
Importance::Important
} else {
Importance::Normal
};
(decl, importance)
})
}
/// Find the value of the given property in this block and serialize it
///
/// https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-getpropertyvalue
pub fn property_value_to_css<W>(&self, property: &PropertyId, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
// Step 1.1: done when parsing a string to PropertyId
// Step 1.2
match property.as_shorthand() {
Ok(shorthand) => {
// Step 1.2.1
let mut list = Vec::new();
let mut important_count = 0;
// Step 1.2.2
for &longhand in shorthand.longhands() {
// Step 1.2.2.1
let declaration = self.get(PropertyDeclarationId::Longhand(longhand));
// Step 1.2.2.2 & 1.2.2.3
match declaration {
Some((declaration, importance)) => {
list.push(declaration);
if importance.important() {
important_count += 1;
}
},
None => return Ok(()),
}
}
// If there is one or more longhand with important, and one or more
// without important, we don't serialize it as a shorthand.
if important_count > 0 && important_count != list.len() {
return Ok(());
}
// Step 1.2.3
// We don't print !important when serializing individual properties,
// so we treat this as a normal-importance property
match shorthand.get_shorthand_appendable_value(list) {
Some(appendable_value) =>
append_declaration_value(dest, appendable_value),
None => return Ok(()),
}
}
Err(longhand_or_custom) => {
if let Some((value, _importance)) = self.get(longhand_or_custom) {
// Step 2
value.to_css(dest)
} else {
// Step 3
Ok(())
}
}
}
}
/// https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-getpropertypriority
pub fn property_priority(&self, property: &PropertyId) -> Importance {
// Step 1: done when parsing a string to PropertyId
// Step 2
match property.as_shorthand() {
Ok(shorthand) => {
// Step 2.1 & 2.2 & 2.3
if shorthand.longhands().iter().all(|&l| {
self.get(PropertyDeclarationId::Longhand(l))
.map_or(false, |(_, importance)| importance.important())
}) {
Importance::Important
} else {
Importance::Normal
}
}
Err(longhand_or_custom) => {
// Step 3
self.get(longhand_or_custom).map_or(Importance::Normal, |(_, importance)| importance)
}
}
}
/// Adds or overrides the declaration for a given property in this block,
/// **except** if an existing declaration for the same property is more
/// important.
///
/// Always ensures that the property declaration is at the end.
pub fn extend(&mut self, drain: SourcePropertyDeclarationDrain, importance: Importance) {
self.extend_common(drain, importance, false);
}
/// Adds or overrides the declaration for a given property in this block,
/// **even** if an existing declaration for the same property is more
/// important, and reuses the same position in the block.
///
/// Returns whether anything changed.
pub fn extend_reset(&mut self, drain: SourcePropertyDeclarationDrain,
importance: Importance) -> bool {
self.extend_common(drain, importance, true)
}
fn extend_common(
&mut self,
mut drain: SourcePropertyDeclarationDrain,
importance: Importance,
overwrite_more_important_and_reuse_slot: bool,
) -> bool {
let all_shorthand_len = match drain.all_shorthand {
AllShorthand::NotSet => 0,
AllShorthand::CSSWideKeyword(_) |
AllShorthand::WithVariables(_) => ShorthandId::All.longhands().len()
};
let push_calls_count = drain.declarations.len() + all_shorthand_len;
// With deduplication the actual length increase may be less than this.
self.declarations.reserve(push_calls_count);
let mut changed = false;
for decl in &mut drain.declarations {
changed |= self.push_common(
decl,
importance,
overwrite_more_important_and_reuse_slot,
);
}
match drain.all_shorthand {
AllShorthand::NotSet => {}
AllShorthand::CSSWideKeyword(keyword) => {
for &id in ShorthandId::All.longhands() {
let decl = PropertyDeclaration::CSSWideKeyword(id, keyword);
changed |= self.push_common(
decl,
importance,
overwrite_more_important_and_reuse_slot,
);
}
}
AllShorthand::WithVariables(unparsed) => {
for &id in ShorthandId::All.longhands() {
let decl = PropertyDeclaration::WithVariables(id, unparsed.clone());
changed |= self.push_common(
decl,
importance,
overwrite_more_important_and_reuse_slot,
);
}
}
}
changed
}
/// Adds or overrides the declaration for a given property in this block,
/// **except** if an existing declaration for the same property is more
/// important.
///
/// Ensures that, if inserted, it's inserted at the end of the declaration
/// block.
pub fn push(&mut self, declaration: PropertyDeclaration, importance: Importance) {
self.push_common(declaration, importance, false);
}
fn push_common(
&mut self,
declaration: PropertyDeclaration,
importance: Importance,
overwrite_more_important_and_reuse_slot: bool
) -> bool {
let longhand_id = match declaration.id() {
PropertyDeclarationId::Longhand(id) => Some(id),
PropertyDeclarationId::Custom(..) => None,
};
let definitely_new = longhand_id.map_or(false, |id| {
!self.longhands.contains(id)
});
if !definitely_new {
let mut index_to_remove = None;
for (i, slot) in self.declarations.iter_mut().enumerate() {
if slot.id() == declaration.id() {
let important = self.declarations_importance.get(i as u32);
match (important, importance.important()) {
(false, true) => {}
(true, false) => {
if !overwrite_more_important_and_reuse_slot {
return false
}
}
_ => if *slot == declaration {
return false;
}
}
if overwrite_more_important_and_reuse_slot {
*slot = declaration;
self.declarations_importance.set(i as u32, importance.important());
return true;
}
// NOTE(emilio): We could avoid this and just override for
// properties not affected by logical props, but it's not
// clear it's worth it given the `definitely_new` check.
index_to_remove = Some(i);
break;
}
}
if let Some(index) = index_to_remove {
self.declarations.remove(index);
self.declarations_importance.remove(index as u32);
self.declarations.push(declaration);
self.declarations_importance.push(importance.important());
return true;
}
}
if let Some(id) = longhand_id {
self.longhands.insert(id);
}
self.declarations.push(declaration);
self.declarations_importance.push(importance.important());
true
}
/// Set the declaration importance for a given property, if found.
///
/// Returns whether any declaration was updated.
pub fn set_importance(&mut self, property: &PropertyId, new_importance: Importance) -> bool {
let mut updated_at_least_one = false;
for (i, declaration) in self.declarations.iter().enumerate() {
if declaration.id().is_or_is_longhand_of(property) {
let is_important = new_importance.important();
if self.declarations_importance.get(i as u32) != is_important {
self.declarations_importance.set(i as u32, is_important);
updated_at_least_one = true;
}
}
}
updated_at_least_one
}
/// https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-removeproperty
///
/// Returns whether any declaration was actually removed.
pub fn remove_property(&mut self, property: &PropertyId) -> bool {
if let PropertyId::Longhand(id) = *property {
if !self.longhands.contains(id) {
return false
}
}
let mut removed_at_least_one = false;
let longhands = &mut self.longhands;
let declarations_importance = &mut self.declarations_importance;
let mut i = 0;
self.declarations.retain(|declaration| {
let id = declaration.id();
let remove = id.is_or_is_longhand_of(property);
if remove {
removed_at_least_one = true;
if let PropertyDeclarationId::Longhand(id) = id {
longhands.remove(id);
}
declarations_importance.remove(i);
} else {
i += 1;
}
!remove
});
if let PropertyId::Longhand(_) = *property {
debug_assert!(removed_at_least_one);
}
removed_at_least_one
}
/// Take a declaration block known to contain a single property and serialize it.
pub fn single_value_to_css<W>(
&self,
property: &PropertyId,
dest: &mut W,
computed_values: Option<&ComputedValues>,
custom_properties_block: Option<&PropertyDeclarationBlock>,
) -> fmt::Result
where
W: fmt::Write,
{
match property.as_shorthand() {
Err(_longhand_or_custom) => {
if self.declarations.len() == 1 {
let declaration = &self.declarations[0];
let custom_properties = if let Some(cv) = computed_values {
// If there are extra custom properties for this
// declaration block, factor them in too.
if let Some(block) = custom_properties_block {
// FIXME(emilio): This is not super-efficient
// here...
block.cascade_custom_properties(cv.custom_properties())
} else {
cv.custom_properties().cloned()
}
} else {
None
};
match (declaration, computed_values) {
// If we have a longhand declaration with variables, those variables will be
// stored as unparsed values. As a temporary measure to produce sensible results
// in Gecko's getKeyframes() implementation for CSS animations, if
// |computed_values| is supplied, we use it to expand such variable
// declarations. This will be fixed properly in Gecko bug 1391537.
(&PropertyDeclaration::WithVariables(id, ref unparsed),
Some(ref _computed_values)) => {
unparsed.substitute_variables(
id,
custom_properties.as_ref(),
QuirksMode::NoQuirks,
)
.to_css(dest)
},
(ref d, _) => d.to_css(dest),
}
} else {
Err(fmt::Error)
}
}
Ok(shorthand) => {
if !self.declarations.iter().all(|decl| decl.shorthands().contains(&shorthand)) {
return Err(fmt::Error)
}
let iter = self.declarations.iter();
match shorthand.get_shorthand_appendable_value(iter) {
Some(AppendableValue::Css { css, .. }) => {
dest.write_str(css)
},
Some(AppendableValue::DeclarationsForShorthand(_, decls)) => {
shorthand.longhands_to_css(decls, dest)
}
_ => Ok(())
}
}
}
}
/// Convert AnimationValueMap to PropertyDeclarationBlock.
#[cfg(feature = "gecko")]
pub fn from_animation_value_map(animation_value_map: &AnimationValueMap) -> Self {
let len = animation_value_map.len();
let mut declarations = Vec::with_capacity(len);
let mut longhands = LonghandIdSet::new();
for (property, animation_value) in animation_value_map.iter() {
longhands.insert(*property);
declarations.push(animation_value.uncompute());
}
PropertyDeclarationBlock {
declarations,
longhands,
declarations_importance: SmallBitVec::from_elem(len as u32, false),
}
}
/// Returns true if the declaration block has a CSSWideKeyword for the given
/// property.
#[cfg(feature = "gecko")]
pub fn has_css_wide_keyword(&self, property: &PropertyId) -> bool {
if let PropertyId::Longhand(id) = *property {
if !self.longhands.contains(id) {
return false
}
}
self.declarations.iter().any(|decl|
decl.id().is_or_is_longhand_of(property) &&
decl.get_css_wide_keyword().is_some()
)
}
/// Returns a custom properties map which is the result of cascading custom
/// properties in this declaration block along with context's custom
/// properties.
pub fn cascade_custom_properties_with_context(
&self,
context: &Context,
) -> Option<Arc<::custom_properties::CustomPropertiesMap>> {
self.cascade_custom_properties(context.style().custom_properties())
}
/// Returns a custom properties map which is the result of cascading custom
/// properties in this declaration block along with the given custom
/// properties.
pub fn cascade_custom_properties(
&self,
inherited_custom_properties: Option<&Arc<::custom_properties::CustomPropertiesMap>>,
) -> Option<Arc<::custom_properties::CustomPropertiesMap>> {
let mut custom_properties = None;
let mut seen_custom = PrecomputedHashSet::default();
for declaration in self.normal_declaration_iter() {
if let PropertyDeclaration::Custom(ref name, ref value) = *declaration {
::custom_properties::cascade(
&mut custom_properties,
inherited_custom_properties,
&mut seen_custom,
name,
value.borrow(),
);
}
}
::custom_properties::finish_cascade(
custom_properties,
inherited_custom_properties,
)
}
}
impl ToCss for PropertyDeclarationBlock {
// https://drafts.csswg.org/cssom/#serialize-a-css-declaration-block
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
let mut is_first_serialization = true; // trailing serializations should have a prepended space
// Step 1 -> dest = result list
// Step 2
let mut already_serialized = PropertyDeclarationIdSet::new();
// Step 3
for (declaration, importance) in self.declaration_importance_iter() {
// Step 3.1
let property = declaration.id();
// Step 3.2
if already_serialized.contains(property) {
continue;
}
// Step 3.3
let shorthands = declaration.shorthands();
if !shorthands.is_empty() {
// Step 3.3.1 is done by checking already_serialized while
// iterating below.
// Step 3.3.2
for &shorthand in shorthands {
let properties = shorthand.longhands();
// Substep 2 & 3
let mut current_longhands = SmallVec::<[_; 10]>::new();
let mut important_count = 0;
let mut found_system = None;
let is_system_font =
shorthand == ShorthandId::Font &&
self.declarations.iter().any(|l| {
!already_serialized.contains(l.id()) &&
l.get_system().is_some()
});
if is_system_font {
for (longhand, importance) in self.declaration_importance_iter() {
if longhand.get_system().is_some() || longhand.is_default_line_height() {
current_longhands.push(longhand);
if found_system.is_none() {
found_system = longhand.get_system();
}
if importance.important() {
important_count += 1;
}
}
}
} else {
for (longhand, importance) in self.declaration_importance_iter() {
if longhand.id().is_longhand_of(shorthand) {
current_longhands.push(longhand);
if importance.important() {
important_count += 1;
}
}
}
// Substep 1:
//
// Assuming that the PropertyDeclarationBlock contains no
// duplicate entries, if the current_longhands length is
// equal to the properties length, it means that the
// properties that map to shorthand are present in longhands
if current_longhands.len() != properties.len() {
continue;
}
}
// Substep 4
let is_important = important_count > 0;
if is_important && important_count != current_longhands.len() {
continue;
}
let importance = if is_important {
Importance::Important
} else {
Importance::Normal
};
// Substep 5 - Let value be the result of invoking serialize
// a CSS value of current longhands.
let appendable_value =
match shorthand.get_shorthand_appendable_value(current_longhands.iter().cloned()) {
None => continue,
Some(appendable_value) => appendable_value,
};
// We avoid re-serializing if we're already an
// AppendableValue::Css.
let mut v = String::new();
let value = match (appendable_value, found_system) {
(AppendableValue::Css { css, with_variables }, _) => {
debug_assert!(!css.is_empty());
AppendableValue::Css {
css: css,
with_variables: with_variables,
}
}
#[cfg(feature = "gecko")]
(_, Some(sys)) => {
sys.to_css(&mut v)?;
AppendableValue::Css {
css: &v,
with_variables: false,
}
}
(other, _) => {
append_declaration_value(&mut v, other)?;
// Substep 6
if v.is_empty() {
continue;
}
AppendableValue::Css {
css: &v,
with_variables: false,
}
}
};
// Substeps 7 and 8
// We need to check the shorthand whether it's an alias property or not.
// If it's an alias property, it should be serialized like its longhand.
if shorthand.flags().contains(SHORTHAND_ALIAS_PROPERTY) {
append_serialization::<_, Cloned<slice::Iter< _>>, _>(
dest,
&property,
value,
importance,
&mut is_first_serialization)?;
} else {
append_serialization::<_, Cloned<slice::Iter< _>>, _>(
dest,
&shorthand,
value,
importance,
&mut is_first_serialization)?;
}
for current_longhand in ¤t_longhands {
// Substep 9
already_serialized.insert(current_longhand.id());
}
// FIXME(https://github.com/w3c/csswg-drafts/issues/1774)
// The specification does not include an instruction to abort
// the shorthand loop at this point, but doing so both matches
// Gecko and makes sense since shorthands are checked in
// preferred order.
break;
}
}
// Step 3.3.4
if already_serialized.contains(property) {
continue;
}
use std::iter::Cloned;
use std::slice;
// Steps 3.3.5, 3.3.6 & 3.3.7
// Need to specify an iterator type here even though it’s unused to work around
// "error: unable to infer enough type information about `_`;
// type annotations or generic parameter binding required [E0282]"
// Use the same type as earlier call to reuse generated code.
append_serialization::<_, Cloned<slice::Iter<_>>, _>(
dest,
&property,
AppendableValue::Declaration(declaration),
importance,
&mut is_first_serialization)?;
// Step 3.3.8
already_serialized.insert(property);
}
// Step 4
Ok(())
}
}
/// A convenient enum to represent different kinds of stuff that can represent a
/// _value_ in the serialization of a property declaration.
pub enum AppendableValue<'a, I>
where I: Iterator<Item=&'a PropertyDeclaration>,
{
/// A given declaration, of which we'll serialize just the value.
Declaration(&'a PropertyDeclaration),
/// A set of declarations for a given shorthand.
///
/// FIXME: This needs more docs, where are the shorthands expanded? We print
/// the property name before-hand, don't we?
DeclarationsForShorthand(ShorthandId, I),
/// A raw CSS string, coming for example from a property with CSS variables,
/// or when storing a serialized shorthand value before appending directly.
Css {
/// The raw CSS string.
css: &'a str,
/// Whether the original serialization contained variables or not.
with_variables: bool,
}
}
/// Potentially appends whitespace after the first (property: value;) pair.
fn handle_first_serialization<W>(dest: &mut W,
is_first_serialization: &mut bool)
-> fmt::Result
where W: fmt::Write,
{
if !*is_first_serialization {
dest.write_str(" ")
} else {
*is_first_serialization = false;
Ok(())
}
}
/// Append a given kind of appendable value to a serialization.
pub fn append_declaration_value<'a, W, I>(dest: &mut W,
appendable_value: AppendableValue<'a, I>)
-> fmt::Result
where W: fmt::Write,
I: Iterator<Item=&'a PropertyDeclaration>,
{
match appendable_value {
AppendableValue::Css { css, .. } => {
dest.write_str(css)
},
AppendableValue::Declaration(decl) => {
decl.to_css(dest)
},
AppendableValue::DeclarationsForShorthand(shorthand, decls) => {
shorthand.longhands_to_css(decls, dest)
}
}
}
/// Append a given property and value pair to a serialization.
pub fn append_serialization<'a, W, I, N>(dest: &mut W,
property_name: &N,
appendable_value: AppendableValue<'a, I>,
importance: Importance,
is_first_serialization: &mut bool)
-> fmt::Result
where W: fmt::Write,
I: Iterator<Item=&'a PropertyDeclaration>,
N: ToCss,
{
handle_first_serialization(dest, is_first_serialization)?;
property_name.to_css(dest)?;
dest.write_char(':')?;
// for normal parsed values, add a space between key: and value
match appendable_value {
AppendableValue::Declaration(decl) => {
if !decl.value_is_unparsed() {
// For normal parsed values, add a space between key: and value.
dest.write_str(" ")?
}
},
AppendableValue::Css { with_variables, .. } => {
if !with_variables {
dest.write_str(" ")?
}
}
// Currently append_serialization is only called with a Css or
// a Declaration AppendableValue.
AppendableValue::DeclarationsForShorthand(..) => unreachable!(),
}
append_declaration_value(dest, appendable_value)?;
if importance.important() {
dest.write_str(" !important")?;
}
dest.write_char(';')
}
/// A helper to parse the style attribute of an element, in order for this to be
/// shared between Servo and Gecko.
pub fn parse_style_attribute<R>(input: &str,
url_data: &UrlExtraData,
error_reporter: &R,
quirks_mode: QuirksMode)
-> PropertyDeclarationBlock
where R: ParseErrorReporter
{
let context = ParserContext::new(Origin::Author,
url_data,
Some(CssRuleType::Style),
PARSING_MODE_DEFAULT,
quirks_mode);
let error_context = ParserErrorContext { error_reporter: error_reporter };
let mut input = ParserInput::new(input);
parse_property_declaration_list(&context, &error_context, &mut Parser::new(&mut input))
}
/// Parse a given property declaration. Can result in multiple
/// `PropertyDeclaration`s when expanding a shorthand, for example.
///
/// This does not attempt to parse !important at all.
pub fn parse_one_declaration_into<R>(declarations: &mut SourcePropertyDeclaration,
id: PropertyId,
input: &str,
url_data: &UrlExtraData,
error_reporter: &R,
parsing_mode: ParsingMode,
quirks_mode: QuirksMode)
-> Result<(), ()>
where R: ParseErrorReporter
{
let context = ParserContext::new(Origin::Author,
url_data,
Some(CssRuleType::Style),
parsing_mode,
quirks_mode);
let mut input = ParserInput::new(input);
let mut parser = Parser::new(&mut input);
let start_position = parser.position();
let start_location = parser.current_source_location();
parser.parse_entirely(|parser| {
let name = id.name().into();
PropertyDeclaration::parse_into(declarations, id, name, &context, parser)
.map_err(|e| e.into())
}).map_err(|err| {
let error = ContextualParseError::UnsupportedPropertyDeclaration(
parser.slice_from(start_position), err);
let error_context = ParserErrorContext { error_reporter: error_reporter };
context.log_css_error(&error_context, start_location, error);
})
}
/// A struct to parse property declarations.
struct PropertyDeclarationParser<'a, 'b: 'a> {
context: &'a ParserContext<'b>,
declarations: &'a mut SourcePropertyDeclaration,
}
/// Default methods reject all at rules.
impl<'a, 'b, 'i> AtRuleParser<'i> for PropertyDeclarationParser<'a, 'b> {
type PreludeNoBlock = ();
type PreludeBlock = ();
type AtRule = Importance;
type Error = SelectorParseError<'i, StyleParseError<'i>>;
}
/// Based on NonMozillaVendorIdentifier from Gecko's CSS parser.
fn is_non_mozilla_vendor_identifier(name: &str) -> bool {
(name.starts_with("-") && !name.starts_with("-moz-")) ||
name.starts_with("_")
}
impl<'a, 'b, 'i> DeclarationParser<'i> for PropertyDeclarationParser<'a, 'b> {
type Declaration = Importance;
type Error = SelectorParseError<'i, StyleParseError<'i>>;
fn parse_value<'t>(&mut self, name: CowRcStr<'i>, input: &mut Parser<'i, 't>)
-> Result<Importance, ParseError<'i>> {
let prop_context = PropertyParserContext::new(self.context);
let id = match PropertyId::parse(&name, Some(&prop_context)) {
Ok(id) => id,
Err(()) => {
return Err(if is_non_mozilla_vendor_identifier(&name) {
PropertyDeclarationParseError::UnknownVendorProperty
} else {
PropertyDeclarationParseError::UnknownProperty(name)
}.into());
}
};
input.parse_until_before(Delimiter::Bang, |input| {
PropertyDeclaration::parse_into(self.declarations, id, name, self.context, input)
.map_err(|e| e.into())
})?;
let importance = match input.try(parse_important) {
Ok(()) => Importance::Important,
Err(_) => Importance::Normal,
};
// In case there is still unparsed text in the declaration, we should roll back.
input.expect_exhausted()?;
Ok(importance)
}
}
/// Parse a list of property declarations and return a property declaration
/// block.
pub fn parse_property_declaration_list<R>(context: &ParserContext,
error_context: &ParserErrorContext<R>,
input: &mut Parser)
-> PropertyDeclarationBlock
where R: ParseErrorReporter
{
let mut declarations = SourcePropertyDeclaration::new();
let mut block = PropertyDeclarationBlock::new();
let parser = PropertyDeclarationParser {
context: context,
declarations: &mut declarations,
};
let mut iter = DeclarationListParser::new(input, parser);
while let Some(declaration) = iter.next() {
match declaration {
Ok(importance) => {
block.extend(iter.parser.declarations.drain(), importance);
}
Err(err) => {
iter.parser.declarations.clear();
// If the unrecognized property looks like a vendor-specific property,
// silently ignore it instead of polluting the error output.
if let CssParseError::Custom(SelectorParseError::Custom(
StyleParseError::PropertyDeclaration(
PropertyDeclarationParseError::UnknownVendorProperty))) = err.error {
continue;
}
let error = ContextualParseError::UnsupportedPropertyDeclaration(err.slice, err.error);
context.log_css_error(error_context, err.location, error);
}
}
}
block
}<|fim▁end|> | /// which should be maintained whenever `declarations` is changed.
pub fn any_normal(&self) -> bool { |
<|file_name|>test_del_group.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from random import randrange
from model.group import Group<|fim▁hole|>def test_delete_some_group(app, db, check_ui):
if len(db.get_group_list()) == 0:
app.group.create(Group(name = "test"))
with pytest.allure.step("Given a group list"):
old_groups = db.get_group_list()
with pytest.allure.step("When get random group"):
group = random.choice(old_groups)
with pytest.allure.step("When I delete %s" %group):
app.group.delete_group_by_id(group.id)
with pytest.allure.step("Then the new group list is equal to the old list with the deleted group"):
new_groups = db.get_group_list()
assert len(old_groups) - 1 == len(new_groups)
old_groups.remove(group)
assert old_groups == new_groups
if check_ui:
assert sorted(new_groups, key=Group.id_or_max) == sorted(app.group.get_group_list(), key=Group.id_or_max)<|fim▁end|> | import random
import pytest
|
<|file_name|>ui_profile_dialog.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/Users/lee/backups/code/iblah_py/ui/ui_profile_dialog.ui'
#
# Created: Fri May 6 21:47:58 2011
# by: PyQt4 UI code generator 4.8.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_ProfileDialog(object):
def setupUi(self, ProfileDialog):
ProfileDialog.setObjectName(_fromUtf8("ProfileDialog"))
ProfileDialog.setEnabled(True)
ProfileDialog.resize(470, 300)
self.save_btn = QtGui.QPushButton(ProfileDialog)
self.save_btn.setEnabled(True)
self.save_btn.setGeometry(QtCore.QRect(330, 240, 114, 32))
self.save_btn.setObjectName(_fromUtf8("save_btn"))
self.avatar_label = QtGui.QLabel(ProfileDialog)
self.avatar_label.setGeometry(QtCore.QRect(310, 20, 130, 130))
self.avatar_label.setStyleSheet(_fromUtf8("border: 2px solid #ccc;"))
self.avatar_label.setObjectName(_fromUtf8("avatar_label"))
self.label_2 = QtGui.QLabel(ProfileDialog)
self.label_2.setGeometry(QtCore.QRect(21, 117, 26, 16))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.impresa_text_edit = QtGui.QTextEdit(ProfileDialog)
self.impresa_text_edit.setGeometry(QtCore.QRect(80, 170, 361, 51))
self.impresa_text_edit.setObjectName(_fromUtf8("impresa_text_edit"))
self.fullname_line_edit = QtGui.QLineEdit(ProfileDialog)
self.fullname_line_edit.setGeometry(QtCore.QRect(81, 117, 201, 22))
self.fullname_line_edit.setObjectName(_fromUtf8("fullname_line_edit"))
self.label_3 = QtGui.QLabel(ProfileDialog)
self.label_3.setGeometry(QtCore.QRect(21, 21, 39, 16))
self.label_3.setObjectName(_fromUtf8("label_3"))
self.label_4 = QtGui.QLabel(ProfileDialog)
self.label_4.setGeometry(QtCore.QRect(21, 53, 39, 16))
self.label_4.setObjectName(_fromUtf8("label_4"))
self.cellphone_no_line_edit = QtGui.QLineEdit(ProfileDialog)
self.cellphone_no_line_edit.setEnabled(True)
self.cellphone_no_line_edit.setGeometry(QtCore.QRect(81, 53, 201, 22))<|fim▁hole|> self.fetion_no_line_edit.setEnabled(True)
self.fetion_no_line_edit.setGeometry(QtCore.QRect(81, 21, 201, 22))
self.fetion_no_line_edit.setText(_fromUtf8(""))
self.fetion_no_line_edit.setReadOnly(True)
self.fetion_no_line_edit.setObjectName(_fromUtf8("fetion_no_line_edit"))
self.label_5 = QtGui.QLabel(ProfileDialog)
self.label_5.setGeometry(QtCore.QRect(21, 85, 33, 16))
self.label_5.setObjectName(_fromUtf8("label_5"))
self.email_line_edit = QtGui.QLineEdit(ProfileDialog)
self.email_line_edit.setEnabled(True)
self.email_line_edit.setGeometry(QtCore.QRect(81, 85, 201, 22))
self.email_line_edit.setText(_fromUtf8(""))
self.email_line_edit.setReadOnly(True)
self.email_line_edit.setObjectName(_fromUtf8("email_line_edit"))
self.label_6 = QtGui.QLabel(ProfileDialog)
self.label_6.setGeometry(QtCore.QRect(21, 170, 52, 16))
self.label_6.setObjectName(_fromUtf8("label_6"))
self.retranslateUi(ProfileDialog)
QtCore.QObject.connect(self.save_btn, QtCore.SIGNAL(_fromUtf8("clicked()")), ProfileDialog.accept)
QtCore.QMetaObject.connectSlotsByName(ProfileDialog)
def retranslateUi(self, ProfileDialog):
ProfileDialog.setWindowTitle(QtGui.QApplication.translate("ProfileDialog", "Profile", None, QtGui.QApplication.UnicodeUTF8))
self.save_btn.setText(QtGui.QApplication.translate("ProfileDialog", "关闭 (&C)", None, QtGui.QApplication.UnicodeUTF8))
self.save_btn.setShortcut(QtGui.QApplication.translate("ProfileDialog", "Return", None, QtGui.QApplication.UnicodeUTF8))
self.avatar_label.setText(QtGui.QApplication.translate("ProfileDialog", "avatar", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("ProfileDialog", "姓名", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("ProfileDialog", "飞信号", None, QtGui.QApplication.UnicodeUTF8))
self.label_4.setText(QtGui.QApplication.translate("ProfileDialog", "手机号", None, QtGui.QApplication.UnicodeUTF8))
self.label_5.setText(QtGui.QApplication.translate("ProfileDialog", "EMail", None, QtGui.QApplication.UnicodeUTF8))
self.label_6.setText(QtGui.QApplication.translate("ProfileDialog", "心情短语", None, QtGui.QApplication.UnicodeUTF8))<|fim▁end|> | self.cellphone_no_line_edit.setText(_fromUtf8(""))
self.cellphone_no_line_edit.setReadOnly(True)
self.cellphone_no_line_edit.setObjectName(_fromUtf8("cellphone_no_line_edit"))
self.fetion_no_line_edit = QtGui.QLineEdit(ProfileDialog) |
<|file_name|>PDBConst.py<|end_file_name|><|fim▁begin|># Schema
DB = "db"
Name = "name"
Tables = "tables"
Table = "table"
Columns = "columns"
Column = "column"
Attributes = "attributes"
Initials = "initials"
Initial = "initial"
InitialValue = "initialvalue"<|fim▁hole|>PrimaryKey = "primarykey"<|fim▁end|> | Value = "value" |
<|file_name|>Gruntfile.js<|end_file_name|><|fim▁begin|>module.exports = function(grunt) {
grunt.initConfig({
// insert the bower files in your index.html
wiredep: {
target: {
src: 'index.html'
}
}
});<|fim▁hole|> grunt.registerTask('default', ['wiredep']);
};<|fim▁end|> | grunt.loadNpmTasks('grunt-wiredep'); |
<|file_name|>destroySession.js<|end_file_name|><|fim▁begin|>'use babel'
export default function destroySession(self, sharedSession) {
// Checks if shared session in the stack
let shareStackIndex = self.shareStack.indexOf(sharedSession)
if (shareStackIndex !== -1) {
// Removes share session from the stack and updates UI
self.shareStack.splice(shareStackIndex, 1)
self.updateShareView()
} else {
// Logs an error message
console.error(sharedSession, 'not found')<|fim▁hole|><|fim▁end|> | }
} |
<|file_name|>constants.py<|end_file_name|><|fim▁begin|>import datetime
import os.path
kDirName, filename = os.path.split(os.path.abspath(__file__))
kFixtureFile = os.path.join(kDirName, 'types.db')
kTestFile = os.path.join(kDirName, 'test.db')
kTestDirectory = os.path.join(kDirName, 'tempdir', 'child')
kConfigFile = os.path.join(kDirName, 'testing.ini')
kConfigFile2 = os.path.join(kDirName, 'testing2.ini')
kLockFile = os.path.join(kDirName, 'lockfile')
kAwsBucket = 'orion.aws.testing'
kImportFile = os.path.join(kDirName, 'import.json')
kImportDirectory = os.path.join(kDirName, 'to_import')
kRepoDirectory = os.path.join(kDirName, 'imported')
kImportDatabase = os.path.join(kDirName, 'imported.db')
kExampleTextFile = os.path.join(kDirName, 'example_text_file.txt')
kExampleImageFile = os.path.join(kDirName, 'example_image.png')
kExampleTemporaryImageFile = os.path.join(kDirName, 'example_image_temp.png')
kExampleDownloadedFile = os.path.join(kDirName, 'fetched.dat')
kExampleCheckpointFile = os.path.join(kDirName, 'example_checkpoint.dat')
kExampleNewCheckpointFile = os.path.join(kDirName, 'example_new_checkpoint.dat')
kS3HostName = 's3.amazonaws.com'
kExampleBucket = 'rigor-test-bucket'
kExampleCredentials = 'test_credentials'
kExampleImageDimensions = (1080, 3840, 3)
kNonexistentFile = '/xxxzzfooxxx'
kExamplePercept = {
'annotations': [
{'boundary': ((1, 10), (3, 6), (1, 10), (10, 3)), 'confidence': 4, 'domain': u'test', 'model': u'e', 'properties': {u'prop': u'value'}, 'stamp': datetime.datetime(2015, 2, 3, 20, 16, 7, 252667), 'tags': [ u'test_tag', ]},
{'boundary': ((10, 4), (4, 8), (3, 8), (6, 3)), 'confidence': 5, 'domain': u'test', 'model': u'e', 'stamp': datetime.datetime(2015, 2, 3, 20, 16, 7, 252787)},
{'boundary': ((1, 7), (1, 9), (7, 1), (3, 5)), 'confidence': 4, 'domain': u'test', 'model': u'd', 'stamp': datetime.datetime(2015, 2, 3, 20, 16, 7, 252969)}
],
'device_id': u'device_1938401',
'format': u'image/jpeg',
'hash': u'edd66afcf0eb4f5ef392fd8e94ff0ff2139ddc01',
'locator': u'example://mybucket/182828291',
'properties': {u'val1': u'val2'},
'sensors': {'acceleration_x': 0.1, 'acceleration_y': 0.2, 'acceleration_z': 0.3, 'altitude': 123.0, 'altitude_accuracy': 2.34, 'bearing': 180.1, 'bearing_accuracy': 1.23, 'location': (34.56, -120.2), 'location_accuracy': 0.1, 'location_provider': u'gps', 'speed': 60.1},
'stamp': datetime.datetime(2015, 2, 3, 20, 16, 7, 252487),
'x_size': 800, 'y_size': 600<|fim▁hole|><|fim▁end|> | } |
<|file_name|>whooshsearch.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
sphinx.websupport.search.whooshsearch
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Whoosh search adapter.
:copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from whoosh import index
from whoosh.fields import Schema, ID, TEXT
from whoosh.qparser import QueryParser
from whoosh.analysis import StemmingAnalyzer
from sphinx.util.osutil import ensuredir
from sphinx.websupport.search import BaseSearch
class WhooshSearch(BaseSearch):
"""The whoosh search adapter for sphinx web support."""
# Define the Whoosh Schema for the search index.
schema = Schema(path=ID(stored=True, unique=True),
title=TEXT(field_boost=2.0, stored=True),
text=TEXT(analyzer=StemmingAnalyzer(), stored=True))
def __init__(self, db_path):
ensuredir(db_path)
if index.exists_in(db_path):
self.index = index.open_dir(db_path)
else:
self.index = index.create_in(db_path, schema=self.schema)
self.qparser = QueryParser('text', self.schema)
<|fim▁hole|> for changed_path in changed:
self.index.delete_by_term('path', changed_path)
self.index_writer = self.index.writer()
def finish_indexing(self):
self.index_writer.commit()
def add_document(self, pagename, title, text):
self.index_writer.add_document(path=unicode(pagename),
title=title,
text=text)
def handle_query(self, q):
searcher = self.index.searcher()
whoosh_results = searcher.search(self.qparser.parse(q))
results = []
for result in whoosh_results:
context = self.extract_context(result['text'])
results.append((result['path'],
result.get('title', ''),
context))
return results<|fim▁end|> | def init_indexing(self, changed=[]): |
<|file_name|>analysis2dSim.cpp<|end_file_name|><|fim▁begin|>/*
* Software License Agreement (New BSD License)
*
* Copyright (c) 2013, Keith Leung, Felipe Inostroza
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Advanced Mining Technology Center (AMTC), the
* Universidad de Chile, nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AMTC, UNIVERSIDAD DE CHILE, OR THE COPYRIGHT
* HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <assert.h>
#include <boost/filesystem.hpp>
#include "GaussianMixture.hpp"
#include "Landmark.hpp"
#include "COLA.hpp"
#include "Particle.hpp"
#include "Pose.hpp"
#include <stdio.h>
#include <string>
#include <vector>
typedef unsigned int uint;
using namespace rfs;
class MM : public Landmark2d{
public:
MM(double x, double y, rfs::TimeStamp t = TimeStamp() ){
x_(0) = x;
x_(1) = y;
this->setTime(t);
}
~MM(){}
double operator-(const MM& other){
rfs::Landmark2d::Vec dx = x_ - other.x_;
return dx.norm();
//return sqrt(mahalanobisDist2( other )); For Mahalanobis distance
}
};
struct COLA_Error{
double error; // combined average error
double loc; // localization error
double card; // cardinality error
TimeStamp t;
};
/**
* \class LogFileReader2dSim
* \brief A class for reading 2d sim log files and for calculating errors
*/
class LogFileReader2dSim
{
public:
typedef Particle<Pose2d, GaussianMixture<Landmark2d> > TParticle;
typedef std::vector< TParticle > TParticleSet;
/** Constructor */
LogFileReader2dSim(const char* logDir){
std::string filename_gtpose( logDir );
std::string filename_gtlmk( logDir );
std::string filename_pose( logDir );
std::string filename_lmk( logDir );
std::string filename_dr( logDir );
filename_gtpose += "gtPose.dat";
filename_gtlmk += "gtLandmark.dat";
filename_pose += "particlePose.dat";
filename_lmk += "landmarkEst.dat";
filename_dr += "deadReckoning.dat";
pGTPoseFile = fopen(filename_gtpose.data(), "r");
pGTLandmarkFile = fopen(filename_gtlmk.data(), "r");
pParticlePoseFile = fopen(filename_pose.data(), "r");
pLandmarkEstFile = fopen(filename_lmk.data(), "r");
pDRFile = fopen(filename_dr.data(), "r");
readLandmarkGroundtruth();
int nread = fscanf(pParticlePoseFile, "%lf %d %lf %lf %lf %lf", &p_t_, &p_id_, &p_x_, &p_y_, &p_z_, &p_w_);
//printf("n = %d\n", nread);
//printf("t = %f [%d] %f %f %f\n", p_t_, p_id_, p_x_, p_y_, p_w_);
nread = fscanf(pLandmarkEstFile, "%lf %d %lf %lf %lf %lf %lf %lf\n",
&lmk_t_, &lmk_pid_, &lmk_x_, &lmk_y_, &lmk_sxx_, &lmk_sxy_, &lmk_syy_, &lmk_w_);
//printf("n = %d\n", nread);
//printf("t = %f [%d] %f %f %f\n", lmk_t_, lmk_pid_, lmk_x_, lmk_y_, lmk_w_);
}
/** Destructor */
~LogFileReader2dSim(){
fclose(pGTPoseFile);
fclose(pGTLandmarkFile);
fclose(pParticlePoseFile);
fclose(pLandmarkEstFile);
fclose(pDRFile);
}
/** Read landmark groundtruth data
* \return number of landmarks
*/
void readLandmarkGroundtruth(){<|fim▁hole|> double x, y, t;
while( fscanf(pGTLandmarkFile, "%lf %lf %lf", &x, &y, &t) == 3){
map_e_M_.push_back( MM( x, y, TimeStamp(t) ) );
}
}
/** Read data for the next timestep
* \return time for which data was read
*/
double readNextStepData(){
if( fscanf(pGTPoseFile, "%lf %lf %lf %lf\n", &t_currentStep_, &rx_, &ry_, &rz_ ) == 4){
// Dead reckoning
int rval = fscanf(pDRFile, "%lf %lf %lf %lf\n", &dr_t_, &dr_x_, &dr_y_, &dr_z_);
// Particles
particles_.clear();
particles_.reserve(200);
w_sum_ = 0;
double w_hi = 0;
while(fabs(p_t_ - t_currentStep_) < 1e-12 ){
// printf("t = %f [%d] %f %f %f\n", p_t_, p_id_, p_x_, p_y_, p_w_);
w_sum_ += p_w_;
if( p_w_ > w_hi ){
i_hi_ = p_id_;
w_hi = p_w_;
}
Pose2d p;
p[0] = p_x_;
p[1] = p_y_;
p[2] = p_z_;
TParticle particle(p_id_, p, p_w_);
particles_.push_back( particle );
particles_[p_id_].setData( TParticle::PtrData( new GaussianMixture<Landmark2d> ));
if( fscanf(pParticlePoseFile, "%lf %d %lf %lf %lf %lf", &p_t_, &p_id_, &p_x_, &p_y_, &p_z_, &p_w_) != 6)
break;
}
// Landmark estimate from highest weighted particle
double const W_THRESHOLD = 0.75;
emap_e_M_.clear();
cardEst_ = 0;
while(fabs(lmk_t_ - t_currentStep_) < 1e-12){
if( lmk_pid_ == i_hi_ ){
if( lmk_w_ >= W_THRESHOLD ){
MM m_e_M(lmk_x_, lmk_y_, lmk_t_);
rfs::Landmark2d::Cov mCov;
mCov << lmk_sxx_, lmk_sxy_, lmk_sxy_, lmk_syy_;
m_e_M.setCov(mCov);
emap_e_M_.push_back(m_e_M);
}
cardEst_ += lmk_w_;
}
if(fscanf(pLandmarkEstFile, "%lf %d %lf %lf %lf %lf %lf %lf\n",
&lmk_t_, &lmk_pid_, &lmk_x_, &lmk_y_, &lmk_sxx_, &lmk_sxy_, &lmk_syy_, &lmk_w_) != 8)
break;
}
return t_currentStep_;
}
return -1;
}
/** Calculate the cardinality error for landmark estimates
* \param[out] nLandmarksObservable the actual number of observed landnmarks up to the current time
* \return cardinality estimate
*/
double getCardinalityEst( int &nLandmarksObservable ){
std::vector<MM> map_e_k_M; // observed groundtruth map storage (for Mahananobis distance calculations)
map_e_k_M.clear();
for(uint i = 0; i < map_e_M_.size(); i++){
if( map_e_M_[i].getTime().getTimeAsDouble() <= t_currentStep_ ){
map_e_k_M.push_back(map_e_M_[i]);
}
}
nLandmarksObservable = map_e_k_M.size();
return cardEst_;
}
/** Caclculate the error for landmark estimates
* \return COLA errors
*/
COLA_Error calcLandmarkError(){
double const cutoff = 0.20; // cola cutoff
double const order = 1.0; // cola order
std::vector<MM> map_e_k_M; // observed groundtruth map storage (for Mahananobis distance calculations)
map_e_k_M.clear();
for(uint i = 0; i < map_e_M_.size(); i++){
if( map_e_M_[i].getTime().getTimeAsDouble() <= t_currentStep_ ){
map_e_k_M.push_back(map_e_M_[i]);
}
}
COLA_Error e_cola;
e_cola.t = t_currentStep_;
COLA<MM> cola(emap_e_M_, map_e_k_M, cutoff, order);
e_cola.error = cola.calcError(&(e_cola.loc), &(e_cola.card));
return e_cola;
}
/** Calculate the dead reckoning error */
void calcDRError(double &err_x, double &err_y, double &err_rot, double &err_dist){
err_x = dr_x_ - rx_;
err_y = dr_y_ - ry_;
err_rot = dr_z_ - rz_;
if(err_rot > PI)
err_rot -= 2*PI;
else if(err_rot < -PI)
err_rot += 2*PI;
err_dist = sqrt(err_x * err_x + err_y * err_y);
}
/** Calculate the error for vehicle pose estimate */
void calcPoseError(double &err_x, double &err_y, double &err_rot, double &err_dist, bool getAverageError = true){
err_x = 0;
err_y = 0;
err_rot = 0;
err_dist = 0;
Pose2d poseEst;
double w = 1;
double ex;
double ey;
double er;
for(int i = 0; i < particles_.size(); i++){
if( !getAverageError && i != i_hi_){
continue;
}
if( getAverageError ){
w = particles_[i].getWeight();
}
poseEst = particles_[i];
ex = poseEst[0] - rx_;
ey = poseEst[1] - ry_;
er = poseEst[2] - rz_;
if(er > PI)
er -= 2 * PI;
else if(er < -PI)
er += 2 * PI;
err_x += ex * w;
err_y += ey * w;
err_rot += er * w;
err_dist += sqrt(ex * ex + ey * ey) * w;
if( !getAverageError && i == i_hi_){
break;
}
}
if( getAverageError ){
err_x /= w_sum_;
err_y /= w_sum_;
err_rot /= w_sum_;
err_dist /= w_sum_;
}
}
private:
FILE* pGTPoseFile; /**< robot pose groundtruth file pointer */
FILE* pGTLandmarkFile; /**< landmark groundtruth file pointer */
FILE* pParticlePoseFile; /**< pose estimate file pointer */
FILE* pLandmarkEstFile; /**< landmark estimate file pointer */
FILE* pMapEstErrorFile; /**< landmark estimate error file pointer */
FILE* pDRFile; /**< Dead-reckoning file */
double mx_; /**< landmark x pos */
double my_; /**< landmark y pos */
double t_currentStep_;
double rx_;
double ry_;
double rz_;
double dr_x_;
double dr_y_;
double dr_z_;
double dr_t_;
double i_hi_; /** highest particle weight index */
double w_sum_; /** particle weight sum */
TParticleSet particles_;
std::vector< Pose2d > pose_gt_;
std::vector<MM> map_e_M_; // groundtruth map storage (for Mahananobis distance calculations)
std::vector<MM> emap_e_M_; // estimated map storage (for Mahananobis distance calculations)
double cardEst_; // cardinality estimate
double p_t_;
int p_id_;
double p_x_;
double p_y_;
double p_z_;
double p_w_;
double lmk_t_;
int lmk_pid_;
double lmk_x_;
double lmk_y_;
double lmk_sxx_;
double lmk_sxy_;
double lmk_syy_;
double lmk_w_;
};
int main(int argc, char* argv[]){
if( argc != 2 ){
printf("Usage: analysis2dSim DATA_DIR/\n");
return 0;
}
const char* logDir = argv[1];
printf("Log directory: %s\n", logDir);
boost::filesystem::path dir(logDir);
if(!exists(dir)){
printf("Log directory %s does not exist\n", logDir);
return 0;
}
std::string filenameLandmarkEstError( logDir );
std::string filenamePoseEstError( logDir );
std::string filenameDREstError( logDir );
filenameLandmarkEstError += "landmarkEstError.dat";
filenamePoseEstError += "poseEstError.dat";
filenameDREstError += "deadReckoningError.dat";
FILE* pMapEstErrorFile = fopen(filenameLandmarkEstError.data(), "w");
FILE* pPoseEstErrorFile = fopen(filenamePoseEstError.data(), "w");
FILE* pDREstErrorFile = fopen(filenameDREstError.data(), "w");
LogFileReader2dSim reader(logDir);
double k = reader.readNextStepData();
while( k != -1){
//printf("Time: %f\n", k);
double ex, ey, er, ed;
reader.calcDRError( ex, ey, er, ed);
fprintf(pDREstErrorFile, "%f %f %f %f %f\n", k, ex, ey, er, ed);
reader.calcPoseError( ex, ey, er, ed, false );
fprintf(pPoseEstErrorFile, "%f %f %f %f %f\n", k, ex, ey, er, ed);
//printf(" error x: %f error y: %f error rot: %f error dist: %f\n", ex, ey, er, ed);
int nLandmarksObserved;
double cardEst = reader.getCardinalityEst( nLandmarksObserved );
COLA_Error colaError = reader.calcLandmarkError();
fprintf(pMapEstErrorFile, "%f %d %f %f\n", k, nLandmarksObserved, cardEst, colaError.error);
//printf(" nLandmarks: %d nLandmarks estimated: %f COLA error: %f\n", nLandmarksObserved, cardEst, colaError.loc + colaError.card);
//printf("--------------------\n");
k = reader.readNextStepData();
}
fclose(pPoseEstErrorFile);
fclose(pMapEstErrorFile);
fclose(pDREstErrorFile);
return 0;
}<|fim▁end|> | |
<|file_name|>plugins.rs<|end_file_name|><|fim▁begin|>use settings;
use indy::ErrorCode;
static INIT_PLUGIN: std::sync::Once = std::sync::Once::new();
pub fn init_plugin(library: &str, initializer: &str) {
settings::set_config_value(settings::CONFIG_PAYMENT_METHOD, settings::DEFAULT_PAYMENT_METHOD);
<|fim▁hole|> if let Ok(init_func) = lib.get(initializer.as_bytes()) {
let init_func: libloading::Symbol<unsafe extern fn() -> ErrorCode> = init_func;
match init_func() {
ErrorCode::Success => {
debug!("Plugin has been loaded: {:?}", library);
}
_ => {
error!("Plugin has not been loaded: {:?}", library);
std::process::exit(123);
}
}
} else {
error!("Init function not found: {:?}", initializer);
std::process::exit(123);
}
}
} else {
error!("Plugin not found: {:?}", library);
std::process::exit(123);
}
});
}
#[cfg(all(unix, test, not(target_os = "android")))]
fn _load_lib(library: &str) -> libloading::Result<libloading::Library> {
libloading::os::unix::Library::open(Some(library), libc::RTLD_NOW | libc::RTLD_NODELETE)
.map(libloading::Library::from)
}
#[cfg(any(not(unix), not(test), target_os = "android"))]
fn _load_lib(library: &str) -> libloading::Result<libloading::Library> {
libloading::Library::new(library)
}<|fim▁end|> | INIT_PLUGIN.call_once(|| {
if let Ok(lib) = _load_lib(library) {
unsafe { |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python<|fim▁hole|># -*- encoding: utf-8 -*-
#
# Copyright (c) 2017 Stephen Bunn (stephen@bunn.io)
# GNU GPLv3 <https://www.gnu.org/licenses/gpl-3.0.en.html>
from ._common import *
from .rethinkdb import RethinkDBPipe
from .mongodb import MongoDBPipe<|fim▁end|> | |
<|file_name|>production.py<|end_file_name|><|fim▁begin|>from .base import *
DEBUG = False
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',#'django.db.backends.postgresql_psycopg2',
'NAME': 'bauth',
'USER': 'postgres',
'ADMINUSER':'postgres',
'PASSWORD': 'C7TS*+dp~-9JHwb*7rzP',
'HOST': '127.0.0.1',
'PORT': '',
}
}
# Add raven to the list of installed apps
INSTALLED_APPS = INSTALLED_APPS + (
# ...
'raven.contrib.django.raven_compat',
)
RAVEN_CONFIG = {<|fim▁hole|>}<|fim▁end|> | 'dsn': 'https://5fa65a7464454dcbadff8a7587d1eaa0:205b12d200e24b39b4c586f7df3965ba@app.getsentry.com/29978', |
<|file_name|>purefa_volume.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2018, Simon Dodsley (simon@purestorage.com)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: purefa_volume
version_added: '2.4'
short_description: Manage volumes on Pure Storage FlashArrays
description:
- Create, delete or extend the capacity of a volume on Pure Storage FlashArray.
author:
- Simon Dodsley (@sdodsley)
options:
name:
description:
- The name of the volume.
required: true
target:
description:
- The name of the target volume, if copying.
state:
description:
- Define whether the volume should exist or not.
default: present
choices: [ absent, present ]
eradicate:
description:
- Define whether to eradicate the volume on delete or leave in trash.
type: bool
default: 'no'
overwrite:
description:
- Define whether to overwrite a target volume if it already exisits.
type: bool
default: 'no'
size:
description:
- Volume size in M, G, T or P units.
extends_documentation_fragment:
- purestorage.fa
'''
EXAMPLES = r'''
- name: Create new volume named foo
purefa_volume:
name: foo
size: 1T
fa_url: 10.10.10.2
api_token: e31060a7-21fc-e277-6240-25983c6c4592
state: present
- name: Extend the size of an existing volume named foo
purefa_volume:
name: foo
size: 2T
fa_url: 10.10.10.2
api_token: e31060a7-21fc-e277-6240-25983c6c4592
state: present
- name: Delete and eradicate volume named foo
purefa_volume:
name: foo
eradicate: yes
fa_url: 10.10.10.2
api_token: e31060a7-21fc-e277-6240-25983c6c4592
state: absent
- name: Create clone of volume bar named foo
purefa_volume:
name: foo
target: bar
fa_url: 10.10.10.2
api_token: e31060a7-21fc-e277-6240-25983c6c4592
state: present
- name: Overwrite volume bar with volume foo
purefa_volume:
name: foo
target: bar
overwrite: yes
fa_url: 10.10.10.2
api_token: e31060a7-21fc-e277-6240-25983c6c4592
state: present
'''
RETURN = r'''
'''
try:
from purestorage import purestorage
HAS_PURESTORAGE = True
except ImportError:
HAS_PURESTORAGE = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pure import get_system, purefa_argument_spec
def human_to_bytes(size):
"""Given a human-readable byte string (e.g. 2G, 30M),
return the number of bytes. Will return 0 if the argument has
unexpected form.
"""
bytes = size[:-1]
unit = size[-1]
if bytes.isdigit():
bytes = int(bytes)
if unit == 'P':
bytes *= 1125899906842624
elif unit == 'T':
bytes *= 1099511627776
elif unit == 'G':
bytes *= 1073741824
elif unit == 'M':
bytes *= 1048576
else:
bytes = 0
else:
bytes = 0
return bytes
def get_volume(module, array):
"""Return Volume or None"""
try:
return array.get_volume(module.params['name'])
except:
return None
def get_target(module, array):
"""Return Volume or None"""
try:
return array.get_volume(module.params['target'])
except:
return None
def create_volume(module, array):
"""Create Volume"""
size = module.params['size']
changed = True
if not module.check_mode:
try:
array.create_volume(module.params['name'], size)
except:
changed = False
module.exit_json(changed=changed)
def copy_from_volume(module, array):
"""Create Volume Clone"""
changed = False
tgt = get_target(module, array)
if tgt is None:
changed = True
if not module.check_mode:
array.copy_volume(module.params['name'],
module.params['target'])
elif tgt is not None and module.params['overwrite']:
changed = True
if not module.check_mode:
array.copy_volume(module.params['name'],
module.params['target'],
overwrite=module.params['overwrite'])
module.exit_json(changed=changed)
def update_volume(module, array):
"""Update Volume"""
changed = True
vol = array.get_volume(module.params['name'])
if human_to_bytes(module.params['size']) > vol['size']:
if not module.check_mode:
array.extend_volume(module.params['name'], module.params['size'])
else:
changed = False
module.exit_json(changed=changed)
def delete_volume(module, array):
""" Delete Volume"""
changed = True
if not module.check_mode:
try:
array.destroy_volume(module.params['name'])
if module.params['eradicate']:
try:
array.eradicate_volume(module.params['name'])
except:
changed = False
except:
changed = False
module.exit_json(changed=True)
def main():
argument_spec = purefa_argument_spec()
argument_spec.update(dict(
name=dict(type='str', required=True),
target=dict(type='str'),
overwrite=dict(type='bool', default=False),
eradicate=dict(type='bool', default=False),
state=dict(type='str', default='present', choices=['absent', 'present']),
size=dict(type='str'),
))
mutually_exclusive = [['size', 'target']]
module = AnsibleModule(argument_spec,
mutually_exclusive=mutually_exclusive,
supports_check_mode=True)
if not HAS_PURESTORAGE:
module.fail_json(msg='purestorage sdk is required for this module in volume')
size = module.params['size']
state = module.params['state']
array = get_system(module)
volume = get_volume(module, array)
target = get_target(module, array)
<|fim▁hole|> elif state == 'present' and volume and size:
update_volume(module, array)
elif state == 'present' and volume and target:
copy_from_volume(module, array)
elif state == 'present' and volume and not target:
copy_from_volume(module, array)
elif state == 'absent' and volume:
delete_volume(module, array)
elif state == 'present' and not volume or not size:
module.exit_json(changed=False)
elif state == 'absent' and not volume:
module.exit_json(changed=False)
if __name__ == '__main__':
main()<|fim▁end|> | if state == 'present' and not volume and size:
create_volume(module, array) |
<|file_name|>20_validators.py<|end_file_name|><|fim▁begin|># coding: utf-8
from smarthumb import SMARTHUMB
from gluon.contrib.imageutils import RESIZE
# Noticias
db.noticias.titulo.requires = [
IS_NOT_EMPTY(error_message=T('Este campo não pode ficar vazio!')),
IS_NOT_IN_DB(db, db.noticias.titulo,
error_message=T('Título deve ser único.')),
IS_LENGTH(128, error_message=T('Tamanho máximo de 128 caracteres.'))
]
db.noticias.resumo.requires = [
IS_NOT_EMPTY(
error_message=T('Este campo não pode ficar vazio!')),
IS_LENGTH(128, error_message=T('Tamanho máximo de 128 caracteres.'))
]
db.noticias.conteudo.requires = [
IS_NOT_EMPTY(
error_message=T('Este campo não pode ficar vazio!')),
IS_LENGTH(5000, error_message=T('Tamanho máximo de 5000 caracteres.'))
]
db.noticias.permalink.compute = lambda registro: IS_SLUG()(registro.titulo)[0]
db.noticias.foto.requires = [
IS_EMPTY_OR(IS_IMAGE(
error_message=T('Arquivo enviado deve ser uma imagem.'))),
IS_LENGTH(100 * 1024, # 100kb
error_message=T('Arquivo muito grande!'
'Tamanho máximo permitido é 100kb'))
]
db.noticias.thumbnail.compute = lambda registro: SMARTHUMB(registro.foto,
(200, 200))
db.noticias.status.requires = IS_IN_SET(
['publicado', 'não publicado'],
error_message=T('Por favor selecione uma das opções')
)
# Membros
db.membros.nome.requires = [
IS_NOT_EMPTY(error_message=T('Este campo não pode ficar vazio!')),
IS_NOT_IN_DB(db, db.membros.nome,
error_message=T('Nome deve ser único.')),
IS_LENGTH(64, error_message=T('Tamanho máximo de 64 caracteres.'))
]
db.membros.foto.requires = [
IS_EMPTY_OR(
IS_IMAGE(error_message=T('Arquivo enviado deve ser uma imagem.'))
),
IS_LENGTH(100 * 1024, # 100kb
error_message=T('Arquivo muito grande!'
'Tamanho máximo permitido é 100kb')),
IS_EMPTY_OR(RESIZE(200, 200))
]
db.membros.email.requires = IS_EMAIL(error_message=T("Entre um email válido"))
# Eventos
db.eventos.nome.requires = [
IS_NOT_EMPTY(error_message=T('Este campo não pode ficar vazio!')),
IS_LENGTH(128, error_message=T('Tamanho máximo de 128 caracteres.'))
]
db.eventos.endereco.requires = [
IS_NOT_EMPTY(error_message=T('Este campo não pode ficar vazio!')),
IS_LENGTH(128, error_message=T('Tamanho máximo de 128 caracteres.'))
]
db.eventos.descricao.requires = [
IS_NOT_EMPTY(error_message=T('Este campo não pode ficar vazio!')),
IS_LENGTH(256, error_message=T('Tamanho máximo de 256 caracteres.'))
]
db.eventos.banner.requires = [
IS_EMPTY_OR(IS_IMAGE(
error_message=T('Arquivo enviado deve ser uma imagem.'))),
IS_LENGTH(100 * 1024, # 100kb
error_message=T('Arquivo muito grande!'
'Tamanho máximo permitido é 100kb'))
]
db.eventos.banner_thumb.compute = lambda registro: SMARTHUMB(registro.foto,
(200, 200))
# Apoiadores
db.apoiadores.nome.requires = [
IS_NOT_EMPTY(error_message=T('Este campo não pode ficar vazio!')),
IS_LENGTH(64, error_message=T('Tamanho máximo de 64 caracteres.'))
]
db.apoiadores.tipo.requires = IS_IN_SET(
['apoiador', 'patrocinador', 'parceiro'],<|fim▁hole|> IS_EMPTY_OR(
IS_IMAGE(error_message=T('Arquivo enviado deve ser uma imagem.'))
),
IS_LENGTH(100 * 1024, # 100kb
error_message=T('Arquivo muito grande!'
'Tamanho máximo permitido é 100kb'))
]
db.apoiadores.logo_thumb.compute = lambda registro: SMARTHUMB(registro.logo,
(200, 200))
db.apoiadores.url.requires = [
IS_NOT_EMPTY(error_message=T('Este campo não pode ficar vazio!')),
IS_LENGTH(256, error_message=T('Tamanho máximo de 256 caracteres.')),
IS_URL()
]
# Produtos
db.produtos.nome.requires = [
IS_NOT_EMPTY(
error_message=T('Este campo não pode ficar vazio!')),
IS_LENGTH(64, error_message=T('Tamanho máximo de 64 caracteres.'))
]
db.produtos.descricao.requires = [
IS_NOT_EMPTY(
error_message=T('Este campo não pode ficar vazio!')),
IS_LENGTH(128, error_message=T('Tamanho máximo de 128 caracteres.'))
]
db.produtos.foto.requires = [
IS_EMPTY_OR(
IS_IMAGE(error_message=T('Arquivo enviado deve ser uma imagem.'))
),
IS_LENGTH(100 * 1024, # 100kb
error_message=T('Arquivo muito grande!'
'Tamanho máximo permitido é 100kb'))
]
db.produtos.thumb.compute = lambda registro: SMARTHUMB(registro.foto,
(200, 200))
db.produtos.preco.requires = IS_EMPTY_OR(IS_FLOAT_IN_RANGE(
minimum=0.1,
dot=',',
error_message=T('Valor inválido para preço. '
'Quando especificado deve ser maior do que 0'
' e no formato 2,50.')
))
# Carousel
db.carousel.nome_aba.requires = [
IS_NOT_EMPTY(
error_message=T('Este campo não pode ficar vazio!')),
IS_LENGTH(16, error_message=T('Tamanho máximo de 16 caracteres.'))
]
db.carousel.descricao_aba.requires = [
IS_NOT_EMPTY(
error_message=T('Este campo não pode ficar vazio!')),
IS_LENGTH(24, error_message=T('Tamanho máximo de 24 caracteres.'))
]
db.carousel.titulo.requires = [
IS_NOT_EMPTY(
error_message=T('Este campo não pode ficar vazio!')),
IS_LENGTH(16, error_message=T('Tamanho máximo de 16 caracteres.'))
]
db.carousel.descricao.requires = [
IS_NOT_EMPTY(
error_message=T('Este campo não pode ficar vazio!')),
IS_LENGTH(256, error_message=T('Tamanho máximo de 256 caracteres.'))
]
db.carousel.imagem.requires = [
IS_EMPTY_OR(
IS_IMAGE(error_message=T('Arquivo enviado deve ser uma imagem.'))
),
IS_LENGTH(100 * 1024, # 100kb
error_message=T('Arquivo muito grande!'
'Tamanho máximo permitido é 100kb')),
IS_EMPTY_OR(RESIZE(1200, 400))
]
db.carousel.url.requires = [
IS_NOT_EMPTY(
error_message=T('Este campo não pode ficar vazio!')),
IS_LENGTH(256, error_message=T('Tamanho máximo de 256 caracteres.')),
IS_URL()
]
db.carousel.status.requires = IS_IN_SET(
['ativo', 'inativo'],
error_message=T('Por favor selecione uma das opções')
)<|fim▁end|> | error_message=T('Por favor selecione uma das opções')
)
db.apoiadores.logo.requires = [ |
<|file_name|>mountedfilesystem_test.go<|end_file_name|><|fim▁begin|>// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2019 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package gadget_test
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
. "gopkg.in/check.v1"
"github.com/snapcore/snapd/gadget"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/testutil"
)
type mountedfilesystemTestSuite struct {
dir string
backup string
}
var _ = Suite(&mountedfilesystemTestSuite{})
func (s *mountedfilesystemTestSuite) SetUpTest(c *C) {
s.dir = c.MkDir()
s.backup = c.MkDir()
}
type gadgetData struct {
name, target, symlinkTo, content string
}
func makeGadgetData(c *C, where string, data []gadgetData) {
for _, en := range data {
if en.name == "" {
continue
}
if strings.HasSuffix(en.name, "/") {
err := os.MkdirAll(filepath.Join(where, en.name), 0755)
c.Check(en.content, HasLen, 0)
c.Assert(err, IsNil)
continue
}
if en.symlinkTo != "" {
err := os.Symlink(en.symlinkTo, filepath.Join(where, en.name))
c.Assert(err, IsNil)
continue
}
makeSizedFile(c, filepath.Join(where, en.name), 0, []byte(en.content))
}
}
func verifyWrittenGadgetData(c *C, where string, data []gadgetData) {
for _, en := range data {
if en.target == "" {
continue
}
if en.symlinkTo != "" {
symlinkTarget, err := os.Readlink(filepath.Join(where, en.target))
c.Assert(err, IsNil)
c.Check(symlinkTarget, Equals, en.symlinkTo)
continue
}
target := filepath.Join(where, en.target)
c.Check(target, testutil.FileContains, en.content)
}
}
func makeExistingData(c *C, where string, data []gadgetData) {
for _, en := range data {
if en.target == "" {
continue
}
if strings.HasSuffix(en.target, "/") {
err := os.MkdirAll(filepath.Join(where, en.target), 0755)
c.Check(en.content, HasLen, 0)
c.Assert(err, IsNil)
continue
}
if en.symlinkTo != "" {
err := os.Symlink(en.symlinkTo, filepath.Join(where, en.target))
c.Assert(err, IsNil)
continue
}
makeSizedFile(c, filepath.Join(where, en.target), 0, []byte(en.content))
}
}
type contentType int
const (
typeFile contentType = iota
typeDir
)
func verifyDirContents(c *C, where string, expected map[string]contentType) {
cleanWhere := filepath.Clean(where)
got := make(map[string]contentType)
filepath.Walk(where, func(name string, fi os.FileInfo, err error) error {
if name == where {
return nil
}
suffixName := name[len(cleanWhere)+1:]
t := typeFile
if fi.IsDir() {
t = typeDir
}
got[suffixName] = t
for prefix := filepath.Dir(name); prefix != where; prefix = filepath.Dir(prefix) {
delete(got, prefix[len(cleanWhere)+1:])
}
return nil
})
c.Assert(got, DeepEquals, expected)
}
func (s *mountedfilesystemTestSuite) TestWriteFile(c *C) {
makeSizedFile(c, filepath.Join(s.dir, "foo"), 0, []byte("foo foo foo"))
outDir := c.MkDir()
// foo -> /foo
err := gadget.WriteFile(filepath.Join(s.dir, "foo"), filepath.Join(outDir, "foo"), nil)
c.Assert(err, IsNil)
c.Check(filepath.Join(outDir, "foo"), testutil.FileEquals, []byte("foo foo foo"))
// foo -> bar/foo
err = gadget.WriteFile(filepath.Join(s.dir, "foo"), filepath.Join(outDir, "bar/foo"), nil)
c.Assert(err, IsNil)
c.Check(filepath.Join(outDir, "bar/foo"), testutil.FileEquals, []byte("foo foo foo"))
// overwrites
makeSizedFile(c, filepath.Join(outDir, "overwrite"), 0, []byte("disappear"))
err = gadget.WriteFile(filepath.Join(s.dir, "foo"), filepath.Join(outDir, "overwrite"), nil)
c.Assert(err, IsNil)
c.Check(filepath.Join(outDir, "overwrite"), testutil.FileEquals, []byte("foo foo foo"))
// unless told to preserve
keepName := filepath.Join(outDir, "keep")
makeSizedFile(c, keepName, 0, []byte("can't touch this"))
err = gadget.WriteFile(filepath.Join(s.dir, "foo"), filepath.Join(outDir, "keep"), []string{keepName})
c.Assert(err, IsNil)
c.Check(filepath.Join(outDir, "keep"), testutil.FileEquals, []byte("can't touch this"))
err = gadget.WriteFile(filepath.Join(s.dir, "not-found"), filepath.Join(outDir, "foo"), nil)
c.Assert(err, ErrorMatches, "cannot copy .*: unable to open .*/not-found: .* no such file or directory")
}
func (s *mountedfilesystemTestSuite) TestWriteDirectoryContents(c *C) {
gd := []gadgetData{
{name: "boot-assets/splash", target: "splash", content: "splash"},
{name: "boot-assets/some-dir/data", target: "some-dir/data", content: "data"},
{name: "boot-assets/some-dir/empty-file", target: "some-dir/empty-file"},
{name: "boot-assets/nested-dir/nested", target: "/nested-dir/nested", content: "nested"},
{name: "boot-assets/nested-dir/more-nested/more", target: "/nested-dir/more-nested/more", content: "more"},
}
makeGadgetData(c, s.dir, gd)
outDir := c.MkDir()
// boot-assets/ -> / (contents of boot assets under /)
err := gadget.WriteDirectory(filepath.Join(s.dir, "boot-assets")+"/", outDir+"/", nil)
c.Assert(err, IsNil)
verifyWrittenGadgetData(c, outDir, gd)
}
func (s *mountedfilesystemTestSuite) TestWriteDirectoryWhole(c *C) {
gd := []gadgetData{
{name: "boot-assets/splash", target: "boot-assets/splash", content: "splash"},
{name: "boot-assets/some-dir/data", target: "boot-assets/some-dir/data", content: "data"},
{name: "boot-assets/some-dir/empty-file", target: "boot-assets/some-dir/empty-file"},
{name: "boot-assets/nested-dir/nested", target: "boot-assets/nested-dir/nested", content: "nested"},
{name: "boot-assets/nested-dir/more-nested/more", target: "boot-assets//nested-dir/more-nested/more", content: "more"},
}
makeGadgetData(c, s.dir, gd)
outDir := c.MkDir()
// boot-assets -> / (boot-assets and children under /)
err := gadget.WriteDirectory(filepath.Join(s.dir, "boot-assets"), outDir+"/", nil)
c.Assert(err, IsNil)
verifyWrittenGadgetData(c, outDir, gd)
}
func (s *mountedfilesystemTestSuite) TestWriteNonDirectory(c *C) {
gd := []gadgetData{
{name: "foo", content: "nested"},
}
makeGadgetData(c, s.dir, gd)
outDir := c.MkDir()
err := gadget.WriteDirectory(filepath.Join(s.dir, "foo")+"/", outDir, nil)
c.Assert(err, ErrorMatches, `cannot specify trailing / for a source which is not a directory`)
err = gadget.WriteDirectory(filepath.Join(s.dir, "foo"), outDir, nil)
c.Assert(err, ErrorMatches, `source is not a directory`)
}
func (s *mountedfilesystemTestSuite) TestMountedWriterHappy(c *C) {
gd := []gadgetData{
{name: "foo", target: "foo-dir/foo", content: "foo foo foo"},
{name: "bar", target: "bar-name", content: "bar bar bar"},
{name: "boot-assets/splash", target: "splash", content: "splash"},
{name: "boot-assets/some-dir/data", target: "some-dir/data", content: "data"},
{name: "boot-assets/some-dir/data", target: "data-copy", content: "data"},
{name: "boot-assets/some-dir/empty-file", target: "some-dir/empty-file"},
{name: "boot-assets/nested-dir/nested", target: "/nested-copy/nested", content: "nested"},
{name: "boot-assets/nested-dir/more-nested/more", target: "/nested-copy/more-nested/more", content: "more"},
}
makeGadgetData(c, s.dir, gd)
err := os.MkdirAll(filepath.Join(s.dir, "boot-assets/empty-dir"), 0755)
c.Assert(err, IsNil)
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
// single file in target directory
Source: "foo",
Target: "/foo-dir/",
}, {
// single file under different name
Source: "bar",
Target: "/bar-name",
}, {
// whole directory contents
Source: "boot-assets/",
Target: "/",
}, {
// single file from nested directory
Source: "boot-assets/some-dir/data",
Target: "/data-copy",
}, {
// contents of nested directory under new target directory
Source: "boot-assets/nested-dir/",
Target: "/nested-copy/",
},
},
},
}
outDir := c.MkDir()
rw, err := gadget.NewMountedFilesystemWriter(s.dir, ps)
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Write(outDir, nil)
c.Assert(err, IsNil)
verifyWrittenGadgetData(c, outDir, gd)
c.Assert(osutil.IsDirectory(filepath.Join(outDir, "empty-dir")), Equals, true)
}
func (s *mountedfilesystemTestSuite) TestMountedWriterNonDirectory(c *C) {
gd := []gadgetData{
{name: "foo", content: "nested"},
}
makeGadgetData(c, s.dir, gd)
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
// contents of nested directory under new target directory
Source: "foo/",
Target: "/nested-copy/",
},
},
},
}
outDir := c.MkDir()
rw, err := gadget.NewMountedFilesystemWriter(s.dir, ps)
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Write(outDir, nil)
c.Assert(err, ErrorMatches, `cannot write filesystem content of source:foo/: cannot specify trailing / for a source which is not a directory`)
}
func (s *mountedfilesystemTestSuite) TestMountedWriterErrorMissingSource(c *C) {
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
// single file in target directory
Source: "foo",
Target: "/foo-dir/",
},
},
},
}
outDir := c.MkDir()
rw, err := gadget.NewMountedFilesystemWriter(s.dir, ps)
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Write(outDir, nil)
c.Assert(err, ErrorMatches, "cannot write filesystem content of source:foo: .*unable to open.*: no such file or directory")
}
func (s *mountedfilesystemTestSuite) TestMountedWriterErrorBadDestination(c *C) {
makeSizedFile(c, filepath.Join(s.dir, "foo"), 0, []byte("foo foo foo"))
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "vfat",
Content: []gadget.VolumeContent{
{
// single file in target directory
Source: "foo",
Target: "/foo-dir/",
},
},
},
}
outDir := c.MkDir()
err := os.Chmod(outDir, 0000)
c.Assert(err, IsNil)
rw, err := gadget.NewMountedFilesystemWriter(s.dir, ps)
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Write(outDir, nil)
c.Assert(err, ErrorMatches, "cannot write filesystem content of source:foo: cannot create .*: mkdir .* permission denied")
}
func (s *mountedfilesystemTestSuite) TestMountedWriterConflictingDestinationDirectoryErrors(c *C) {
makeGadgetData(c, s.dir, []gadgetData{
{name: "foo", content: "foo foo foo"},
{name: "foo-dir", content: "bar bar bar"},
})
psOverwritesDirectoryWithFile := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
// single file in target directory
Source: "foo",
Target: "/foo-dir/",
}, {
// conflicts with /foo-dir directory
Source: "foo-dir",
Target: "/",
},
},
},
}
outDir := c.MkDir()
rw, err := gadget.NewMountedFilesystemWriter(s.dir, psOverwritesDirectoryWithFile)
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
// can't overwrite a directory with a file
err = rw.Write(outDir, nil)
c.Assert(err, ErrorMatches, fmt.Sprintf("cannot write filesystem content of source:foo-dir: cannot copy .*: unable to create %s/foo-dir: .* is a directory", outDir))
}
func (s *mountedfilesystemTestSuite) TestMountedWriterConflictingDestinationFileOk(c *C) {
makeGadgetData(c, s.dir, []gadgetData{
{name: "foo", content: "foo foo foo"},
{name: "bar", content: "bar bar bar"},
})
psOverwritesFile := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "bar",
Target: "/",
}, {
// overwrites data from preceding entry
Source: "foo",
Target: "/bar",
},
},
},
}
outDir := c.MkDir()
rw, err := gadget.NewMountedFilesystemWriter(s.dir, psOverwritesFile)
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Write(outDir, nil)
c.Assert(err, IsNil)
c.Check(osutil.FileExists(filepath.Join(outDir, "foo")), Equals, false)
// overwritten
c.Check(filepath.Join(outDir, "bar"), testutil.FileEquals, "foo foo foo")
}
func (s *mountedfilesystemTestSuite) TestMountedWriterErrorNested(c *C) {
makeGadgetData(c, s.dir, []gadgetData{
{name: "foo/foo-dir", content: "data"},
{name: "foo/bar/baz", content: "data"},
})
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
// single file in target directory
Source: "/",
Target: "/foo-dir/",
},
},
},
}
outDir := c.MkDir()
makeSizedFile(c, filepath.Join(outDir, "/foo-dir/foo/bar"), 0, nil)
rw, err := gadget.NewMountedFilesystemWriter(s.dir, ps)
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Write(outDir, nil)
c.Assert(err, ErrorMatches, "cannot write filesystem content of source:/: .* not a directory")
}
func (s *mountedfilesystemTestSuite) TestMountedWriterPreserve(c *C) {
// some data for the gadget
gdWritten := []gadgetData{
{name: "foo", target: "foo-dir/foo", content: "data"},
{name: "bar", target: "bar-name", content: "data"},
{name: "boot-assets/splash", target: "splash", content: "data"},
{name: "boot-assets/some-dir/data", target: "some-dir/data", content: "data"},
{name: "boot-assets/some-dir/empty-file", target: "some-dir/empty-file", content: "data"},
{name: "boot-assets/nested-dir/more-nested/more", target: "/nested-copy/more-nested/more", content: "data"},
}
gdNotWritten := []gadgetData{
{name: "foo", target: "/foo", content: "data"},
{name: "boot-assets/some-dir/data", target: "data-copy", content: "data"},
{name: "boot-assets/nested-dir/nested", target: "/nested-copy/nested", content: "data"},
}
makeGadgetData(c, s.dir, append(gdWritten, gdNotWritten...))
// these exist in the root directory and are preserved
preserve := []string{
// mix entries with leading / and without
"/foo",
"/data-copy",
"nested-copy/nested",
"not-listed", // not present in 'gadget' contents
}
// these are preserved, but don't exist in the root, so data from gadget
// will be written
preserveButNotPresent := []string{
"/bar-name",
"some-dir/data",
}
outDir := filepath.Join(c.MkDir(), "out-dir")
for _, en := range preserve {
p := filepath.Join(outDir, en)
makeSizedFile(c, p, 0, []byte("can't touch this"))
}
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "foo",
Target: "/foo-dir/",
}, {
// would overwrite /foo
Source: "foo",
Target: "/",
}, {
// preserved, but not present, will be
// written
Source: "bar",
Target: "/bar-name",
}, {
// some-dir/data is preserved, but not
// preset, hence will be written
Source: "boot-assets/",
Target: "/",
}, {
// would overwrite /data-copy
Source: "boot-assets/some-dir/data",
Target: "/data-copy",
}, {
// would overwrite /nested-copy/nested
Source: "boot-assets/nested-dir/",
Target: "/nested-copy/",
},
},
},
}
rw, err := gadget.NewMountedFilesystemWriter(s.dir, ps)
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Write(outDir, append(preserve, preserveButNotPresent...))
c.Assert(err, IsNil)
// files that existed were preserved
for _, en := range preserve {
p := filepath.Join(outDir, en)
c.Check(p, testutil.FileEquals, "can't touch this")
}
// everything else was written
verifyWrittenGadgetData(c, outDir, gdWritten)
}
func (s *mountedfilesystemTestSuite) TestMountedWriterNonFilePreserveError(c *C) {
// some data for the gadget
gd := []gadgetData{
{name: "foo", content: "data"},
}
makeGadgetData(c, s.dir, gd)
preserve := []string{
// this will be a directory
"foo",
}
outDir := filepath.Join(c.MkDir(), "out-dir")
// will conflict with preserve entry
err := os.MkdirAll(filepath.Join(outDir, "foo"), 0755)
c.Assert(err, IsNil)
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "/",
Target: "/",
},
},
},
}
rw, err := gadget.NewMountedFilesystemWriter(s.dir, ps)
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Write(outDir, preserve)
c.Assert(err, ErrorMatches, `cannot map preserve entries for destination ".*/out-dir": preserved entry "foo" cannot be a directory`)
}
func (s *mountedfilesystemTestSuite) TestMountedWriterImplicitDir(c *C) {
gd := []gadgetData{
{name: "boot-assets/nested-dir/nested", target: "/nested-copy/nested-dir/nested", content: "nested"},
{name: "boot-assets/nested-dir/more-nested/more", target: "/nested-copy/nested-dir/more-nested/more", content: "more"},
}
makeGadgetData(c, s.dir, gd)
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
// contents of nested directory under new target directory
Source: "boot-assets/nested-dir",
Target: "/nested-copy/",
},
},
},
}
outDir := c.MkDir()
rw, err := gadget.NewMountedFilesystemWriter(s.dir, ps)
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Write(outDir, nil)
c.Assert(err, IsNil)
verifyWrittenGadgetData(c, outDir, gd)
}
func (s *mountedfilesystemTestSuite) TestMountedWriterNoFs(c *C) {
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
// no filesystem
Content: []gadget.VolumeContent{
{
// single file in target directory
Source: "foo",
Target: "/foo-dir/",
},
},
},
}
rw, err := gadget.NewMountedFilesystemWriter(s.dir, ps)
c.Assert(err, ErrorMatches, "structure #0 has no filesystem")
c.Assert(rw, IsNil)
}
func (s *mountedfilesystemTestSuite) TestMountedWriterTrivialValidation(c *C) {
rw, err := gadget.NewMountedFilesystemWriter(s.dir, nil)
c.Assert(err, ErrorMatches, `internal error: \*LaidOutStructure.*`)
c.Assert(rw, IsNil)
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
// no filesystem
Content: []gadget.VolumeContent{
{
Source: "",
Target: "",
},
},
},
}
rw, err = gadget.NewMountedFilesystemWriter("", ps)
c.Assert(err, ErrorMatches, `internal error: gadget content directory cannot be unset`)
c.Assert(rw, IsNil)
rw, err = gadget.NewMountedFilesystemWriter(s.dir, ps)
c.Assert(err, IsNil)
err = rw.Write("", nil)
c.Assert(err, ErrorMatches, "internal error: destination directory cannot be unset")
d := c.MkDir()
err = rw.Write(d, nil)
c.Assert(err, ErrorMatches, "cannot write filesystem content .* source cannot be unset")
ps.Content[0].Source = "/"
err = rw.Write(d, nil)
c.Assert(err, ErrorMatches, "cannot write filesystem content .* target cannot be unset")
}
func (s *mountedfilesystemTestSuite) TestMountedWriterSymlinks(c *C) {
// some data for the gadget
gd := []gadgetData{
{name: "foo", target: "foo", content: "data"},
{name: "nested/foo", target: "nested/foo", content: "nested-data"},
{name: "link", symlinkTo: "foo"},
{name: "nested-link", symlinkTo: "nested"},
}
makeGadgetData(c, s.dir, gd)
outDir := filepath.Join(c.MkDir(), "out-dir")
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{Source: "/", Target: "/"},
},
},
}
rw, err := gadget.NewMountedFilesystemWriter(s.dir, ps)
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Write(outDir, nil)
c.Assert(err, IsNil)
// everything else was written
verifyWrittenGadgetData(c, outDir, []gadgetData{
{target: "foo", content: "data"},
{target: "link", symlinkTo: "foo"},
{target: "nested/foo", content: "nested-data"},
{target: "nested-link", symlinkTo: "nested"},
// when read via symlink
{target: "nested-link/foo", content: "nested-data"},
})
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterBackupSimple(c *C) {
// some data for the gadget
gdWritten := []gadgetData{
{name: "bar", target: "bar-name", content: "data"},
{name: "foo", target: "foo", content: "data"},
{name: "zed", target: "zed", content: "data"},
{name: "same-data", target: "same", content: "same"},
// not included in volume contents
{name: "not-written", target: "not-written", content: "data"},
}
makeGadgetData(c, s.dir, gdWritten)
outDir := filepath.Join(c.MkDir(), "out-dir")
// these exist in the destination directory and will be backed up
backedUp := []gadgetData{
{target: "foo", content: "can't touch this"},
{target: "nested/foo", content: "can't touch this"},
// listed in preserve
{target: "zed", content: "preserved"},
// same content as the update
{target: "same", content: "same"},
}
makeExistingData(c, outDir, backedUp)
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "bar",
Target: "/bar-name",
}, {
Source: "foo",
Target: "/",
}, {
Source: "foo",
Target: "/nested/",
}, {
Source: "zed",
Target: "/",
}, {
Source: "same-data",
Target: "/same",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
Preserve: []string{"/zed"},
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Backup()
c.Assert(err, IsNil)
// files that existed were backed up
for _, en := range backedUp {
backup := filepath.Join(s.backup, "struct-0", en.target+".backup")
same := filepath.Join(s.backup, "struct-0", en.target+".same")
switch en.content {
case "preserved":
c.Check(osutil.FileExists(backup), Equals, false, Commentf("file: %v", backup))
c.Check(osutil.FileExists(same), Equals, false, Commentf("file: %v", same))
case "same":
c.Check(osutil.FileExists(same), Equals, true, Commentf("file: %v", same))
default:
c.Check(backup, testutil.FileEquals, "can't touch this")
}
}
// running backup again does not error out
err = rw.Backup()
c.Assert(err, IsNil)
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterBackupWithDirectories(c *C) {
// some data for the gadget
gdWritten := []gadgetData{
{name: "bar", content: "data"},
{name: "some-dir/foo", content: "data"},
{name: "empty-dir/"},
}
makeGadgetData(c, s.dir, gdWritten)
outDir := filepath.Join(c.MkDir(), "out-dir")
// these exist in the destination directory and will be backed up
backedUp := []gadgetData{
// overwritten by "bar" -> "/foo"
{target: "foo", content: "can't touch this"},
// overwritten by some-dir/ -> /nested/
{target: "nested/foo", content: "can't touch this"},
// written to by bar -> /this/is/some/nested/
{target: "this/is/some/"},
{target: "lone-dir/"},
}
makeExistingData(c, outDir, backedUp)
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "bar",
Target: "/foo",
}, {
Source: "bar",
Target: "/this/is/some/nested/",
}, {
Source: "some-dir/",
Target: "/nested/",
}, {
Source: "empty-dir/",
Target: "/lone-dir/",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
Preserve: []string{"/zed"},
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Backup()
c.Assert(err, IsNil)
verifyDirContents(c, filepath.Join(s.backup, "struct-0"), map[string]contentType{
"this/is/some.backup": typeFile,
"this/is.backup": typeFile,
"this.backup": typeFile,
"nested/foo.backup": typeFile,
"nested.backup": typeFile,
"foo.backup": typeFile,
"lone-dir.backup": typeFile,
})
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterBackupNonexistent(c *C) {
// some data for the gadget
gd := []gadgetData{
{name: "bar", target: "foo", content: "data"},
{name: "bar", target: "some-dir/foo", content: "data"},
}
makeGadgetData(c, s.dir, gd)
outDir := filepath.Join(c.MkDir(), "out-dir")
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "bar",
Target: "/foo",
}, {
Source: "bar",
Target: "/some-dir/foo",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
// bar not in preserved files
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Backup()
c.Assert(err, IsNil)
backupRoot := filepath.Join(s.backup, "struct-0")
// actually empty
verifyDirContents(c, backupRoot, map[string]contentType{})
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterBackupFailsOnBackupDirErrors(c *C) {
outDir := filepath.Join(c.MkDir(), "out-dir")
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "bar",
Target: "/foo",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = os.Chmod(s.backup, 0555)
c.Assert(err, IsNil)
defer os.Chmod(s.backup, 0755)
err = rw.Backup()
c.Assert(err, ErrorMatches, "cannot create backup directory: .*/struct-0: permission denied")
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterBackupFailsOnDestinationErrors(c *C) {
// some data for the gadget
gd := []gadgetData{
{name: "bar", content: "data"},
}
makeGadgetData(c, s.dir, gd)
outDir := filepath.Join(c.MkDir(), "out-dir")
makeExistingData(c, outDir, []gadgetData{
{target: "foo", content: "same"},
})
err := os.Chmod(filepath.Join(outDir, "foo"), 0000)
c.Assert(err, IsNil)
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "bar",
Target: "/foo",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Backup()
c.Assert(err, ErrorMatches, "cannot backup content: cannot open destination file: open .*/out-dir/foo: permission denied")
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterBackupFailsOnBadSrcComparison(c *C) {
// some data for the gadget
gd := []gadgetData{
{name: "bar", content: "data"},
}
makeGadgetData(c, s.dir, gd)
err := os.Chmod(filepath.Join(s.dir, "bar"), 0000)
c.Assert(err, IsNil)
outDir := filepath.Join(c.MkDir(), "out-dir")
makeExistingData(c, outDir, []gadgetData{
{target: "foo", content: "same"},
})
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "bar",
Target: "/foo",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Backup()
c.Assert(err, ErrorMatches, "cannot backup content: cannot checksum update file: open .*/bar: permission denied")
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterBackupFunnyNamesConflictBackup(c *C) {
gdWritten := []gadgetData{
{name: "bar.backup/foo", content: "data"},
{name: "bar", content: "data"},
{name: "foo.same/foo", content: "same-as-current"},
{name: "foo", content: "same-as-current"},
}
makeGadgetData(c, s.dir, gdWritten)
// backup stamps conflicts with bar.backup
existingUpBar := []gadgetData{
// will be listed first
{target: "bar", content: "can't touch this"},
{target: "bar.backup/foo", content: "can't touch this"},
}
// backup stamps conflicts with foo.same
existingUpFoo := []gadgetData{
// will be listed first
{target: "foo", content: "same-as-current"},
{target: "foo.same/foo", content: "can't touch this"},
}
outDirConflictsBar := filepath.Join(c.MkDir(), "out-dir-bar")
makeExistingData(c, outDirConflictsBar, existingUpBar)
outDirConflictsFoo := filepath.Join(c.MkDir(), "out-dir-foo")
makeExistingData(c, outDirConflictsFoo, existingUpFoo)
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{Source: "/", Target: "/"},
},
Update: gadget.VolumeUpdate{
Edition: 1,
},
},
}
backupBar := filepath.Join(s.backup, "backup-bar")
backupFoo := filepath.Join(s.backup, "backup-foo")
prefix := `cannot backup content: cannot create backup file: cannot create stamp file prefix: `
for _, tc := range []struct {
backupDir string
outDir string
err string
}{
{backupBar, outDirConflictsBar, prefix + `mkdir .*/bar.backup: not a directory`},
{backupFoo, outDirConflictsFoo, prefix + `mkdir .*/foo.same: not a directory`},
} {
err := os.MkdirAll(tc.backupDir, 0755)
c.Assert(err, IsNil)
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, tc.backupDir, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return tc.outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Backup()
c.Assert(err, ErrorMatches, tc.err)
}
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterBackupFunnyNamesOk(c *C) {
gdWritten := []gadgetData{
{name: "bar.backup/foo", target: "bar.backup/foo", content: "data"},
{name: "foo.same/foo.same", target: "foo.same/foo.same", content: "same-as-current"},
{name: "zed.preserve", target: "zed.preserve", content: "this-is-preserved"},
{name: "new-file.same", target: "new-file.same", content: "this-is-new"},
}
makeGadgetData(c, s.dir, gdWritten)
outDir := filepath.Join(c.MkDir(), "out-dir")
// these exist in the destination directory and will be backed up
backedUp := []gadgetData{
// will be listed first
{target: "bar.backup/foo", content: "not-data"},
{target: "foo.same/foo.same", content: "same-as-current"},
{target: "zed.preserve", content: "to-be-preserved"},
}
makeExistingData(c, outDir, backedUp)
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{Source: "/", Target: "/"},
},
Update: gadget.VolumeUpdate{
Edition: 1,
Preserve: []string{
"zed.preserve",
},
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Backup()
c.Assert(err, IsNil)
verifyDirContents(c, filepath.Join(s.backup, "struct-0"), map[string]contentType{
"bar.backup.backup": typeFile,
"bar.backup/foo.backup": typeFile,
"foo.same.backup": typeFile,
"foo.same/foo.same.same": typeFile,
"zed.preserve.preserve": typeFile,
})
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterBackupErrorOnSymlinkFile(c *C) {
gd := []gadgetData{
{name: "bar/data", target: "bar/data", content: "some data"},
{name: "bar/foo", target: "bar/foo", content: "data"},
}
makeGadgetData(c, s.dir, gd)
outDir := filepath.Join(c.MkDir(), "out-dir")
existing := []gadgetData{
{target: "bar/data", content: "some data"},
{target: "bar/foo", symlinkTo: "data"},
}
makeExistingData(c, outDir, existing)
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{Source: "/", Target: "/"},
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Backup()
c.Assert(err, ErrorMatches, "cannot backup content: cannot backup file /bar/foo: symbolic links are not supported")
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterBackupErrorOnSymlinkInPrefixDir(c *C) {
gd := []gadgetData{
{name: "bar/nested/data", target: "bar/data", content: "some data"},
{name: "baz/foo", target: "baz/foo", content: "data"},
}
makeGadgetData(c, s.dir, gd)
outDir := filepath.Join(c.MkDir(), "out-dir")
existing := []gadgetData{
{target: "bar/nested-target/data", content: "some data"},
}
makeExistingData(c, outDir, existing)
// bar/nested-target -> nested
os.Symlink("nested-target", filepath.Join(outDir, "bar/nested"))
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{Source: "/", Target: "/"},
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Backup()
c.Assert(err, ErrorMatches, "cannot backup content: cannot create a checkpoint for directory /bar/nested: symbolic links are not supported")
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterUpdate(c *C) {
// some data for the gadget
gdWritten := []gadgetData{
{name: "foo", target: "foo-dir/foo", content: "data"},
{name: "bar", target: "bar-name", content: "data"},
{name: "boot-assets/splash", target: "splash", content: "data"},
{name: "boot-assets/some-dir/data", target: "some-dir/data", content: "data"},
{name: "boot-assets/some-dir/empty-file", target: "some-dir/empty-file", content: ""},
{name: "boot-assets/nested-dir/more-nested/more", target: "/nested-copy/more-nested/more", content: "data"},
}
// data inside the gadget that will be skipped due to being part of
// 'preserve' list
gdNotWritten := []gadgetData{
{name: "foo", target: "/foo", content: "data"},
{name: "boot-assets/some-dir/data", target: "data-copy", content: "data"},
{name: "boot-assets/nested-dir/nested", target: "/nested-copy/nested", content: "data"},
}
// data inside the gadget that is identical to what is already present in the target
gdIdentical := []gadgetData{
{name: "boot-assets/nested-dir/more-nested/identical", target: "/nested-copy/more-nested/identical", content: "same-as-target"},
{name: "boot-assets/nested-dir/same-as-target-dir/identical", target: "/nested-copy/same-as-target-dir/identical", content: "same-as-target"},
}
gd := append(gdWritten, gdNotWritten...)
gd = append(gd, gdIdentical...)
makeGadgetData(c, s.dir, gd)
// these exist in the root directory and are preserved
preserve := []string{
// mix entries with leading / and without
"/foo",
"/data-copy",
"nested-copy/nested",
"not-listed", // not present in 'gadget' contents
}
// these are preserved, but don't exist in the root, so data from gadget
// will be written
preserveButNotPresent := []string{
"/bar-name",
"some-dir/data",
}
outDir := filepath.Join(c.MkDir(), "out-dir")
for _, en := range preserve {
p := filepath.Join(outDir, en)
makeSizedFile(c, p, 0, []byte("can't touch this"))
}
for _, en := range gdIdentical {
makeSizedFile(c, filepath.Join(outDir, en.target), 0, []byte(en.content))
}
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "foo",
Target: "/foo-dir/",
}, {
// would overwrite /foo
Source: "foo",
Target: "/",
}, {
// preserved, but not present, will be
// written
Source: "bar",
Target: "/bar-name",
}, {
// some-dir/data is preserved, but not
// present, hence will be written
Source: "boot-assets/",
Target: "/",
}, {
// would overwrite /data-copy
Source: "boot-assets/some-dir/data",
Target: "/data-copy",
}, {
// would overwrite /nested-copy/nested
Source: "boot-assets/nested-dir/",
Target: "/nested-copy/",
}, {
Source: "boot-assets",
Target: "/boot-assets-copy/",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
Preserve: append(preserve, preserveButNotPresent...),
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Backup()
c.Assert(err, IsNil)
// identical files were identified as such
for _, en := range gdIdentical {
c.Check(filepath.Join(s.backup, "struct-0", en.target)+".same", testutil.FilePresent)
}
err = rw.Update()
c.Assert(err, IsNil)
// files that existed were preserved
for _, en := range preserve {
p := filepath.Join(outDir, en)
c.Check(p, testutil.FileEquals, "can't touch this")
}
// everything else was written
verifyWrittenGadgetData(c, outDir, append(gdWritten, gdIdentical...))
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterUpdateLookupFails(c *C) {
makeGadgetData(c, s.dir, []gadgetData{
{name: "canary", target: "canary", content: "data"},
})
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "/",
Target: "/",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return "", errors.New("failed")
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Update()
c.Assert(err, ErrorMatches, "cannot find mount location of structure #0: failed")
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterDirContents(c *C) {
// some data for the gadget
gdWritten := []gadgetData{
{name: "bar/foo", target: "/bar-name/foo", content: "data"},
{name: "bar/nested/foo", target: "/bar-name/nested/foo", content: "data"},
{name: "bar/foo", target: "/bar-copy/bar/foo", content: "data"},
{name: "bar/nested/foo", target: "/bar-copy/bar/nested/foo", content: "data"},
{name: "deep-nested", target: "/this/is/some/deep/nesting/deep-nested", content: "data"},
}
makeGadgetData(c, s.dir, gdWritten)
outDir := filepath.Join(c.MkDir(), "out-dir")
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
// contents of bar under /bar-name/
Source: "bar/",
Target: "/bar-name",
}, {
// whole bar under /bar-copy/
Source: "bar",
Target: "/bar-copy/",
}, {
// deep prefix
Source: "deep-nested",
Target: "/this/is/some/deep/nesting/",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Backup()
c.Assert(err, IsNil)
err = rw.Update()
c.Assert(err, IsNil)
verifyWrittenGadgetData(c, outDir, gdWritten)
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterExpectsBackup(c *C) {
// some data for the gadget
gd := []gadgetData{
{name: "bar", target: "foo", content: "update"},
{name: "bar", target: "some-dir/foo", content: "update"},
}
makeGadgetData(c, s.dir, gd)
outDir := filepath.Join(c.MkDir(), "out-dir")
makeExistingData(c, outDir, []gadgetData{
{target: "foo", content: "content"},
{target: "some-dir/foo", content: "content"},
{target: "/preserved", content: "preserve"},
})
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "bar",
Target: "/foo",
}, {
Source: "bar",
Target: "/some-dir/foo",
}, {
Source: "bar",
Target: "/preserved",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
// bar not in preserved files
Preserve: []string{"preserved"},
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Update()
c.Assert(err, ErrorMatches, `cannot update content: missing backup file ".*/struct-0/foo.backup" for /foo`)
// create a mock backup of first file
makeSizedFile(c, filepath.Join(s.backup, "struct-0/foo.backup"), 0, nil)
// try again
err = rw.Update()
c.Assert(err, ErrorMatches, `cannot update content: missing backup file ".*/struct-0/some-dir/foo.backup" for /some-dir/foo`)
// create a mock backup of second entry
makeSizedFile(c, filepath.Join(s.backup, "struct-0/some-dir/foo.backup"), 0, nil)
// try again (preserved files need no backup)
err = rw.Update()
c.Assert(err, IsNil)
verifyWrittenGadgetData(c, outDir, []gadgetData{
{target: "foo", content: "update"},
{target: "some-dir/foo", content: "update"},
{target: "/preserved", content: "preserve"},
})
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterEmptyDir(c *C) {
// some data for the gadget
err := os.MkdirAll(filepath.Join(s.dir, "empty-dir"), 0755)
c.Assert(err, IsNil)
err = os.MkdirAll(filepath.Join(s.dir, "non-empty/empty-dir"), 0755)
c.Assert(err, IsNil)
outDir := filepath.Join(c.MkDir(), "out-dir")
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "/",
Target: "/",
}, {
Source: "/",
Target: "/foo",
}, {
Source: "/non-empty/empty-dir/",
Target: "/contents-of-empty/",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Update()
c.Assert(err, Equals, gadget.ErrNoUpdate)
verifyDirContents(c, outDir, map[string]contentType{
// / -> /
"empty-dir": typeDir,
"non-empty/empty-dir": typeDir,
// / -> /foo
"foo/empty-dir": typeDir,
"foo/non-empty/empty-dir": typeDir,
// /non-empty/empty-dir/ -> /contents-of-empty/
"contents-of-empty": typeDir,
})
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterSameFileSkipped(c *C) {
// some data for the gadget
gd := []gadgetData{
{name: "bar", target: "foo", content: "data"},
{name: "bar", target: "some-dir/foo", content: "data"},
}
makeGadgetData(c, s.dir, gd)
outDir := filepath.Join(c.MkDir(), "out-dir")
makeExistingData(c, outDir, []gadgetData{
{target: "foo", content: "same"},
{target: "some-dir/foo", content: "same"},
})
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "bar",
Target: "/foo",
}, {
Source: "bar",
Target: "/some-dir/foo",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
// pretend a backup pass ran and found the files identical
makeSizedFile(c, filepath.Join(s.backup, "struct-0/foo.same"), 0, nil)
makeSizedFile(c, filepath.Join(s.backup, "struct-0/some-dir/foo.same"), 0, nil)
err = rw.Update()
c.Assert(err, Equals, gadget.ErrNoUpdate)
// files were not modified
verifyWrittenGadgetData(c, outDir, []gadgetData{
{target: "foo", content: "same"},
{target: "some-dir/foo", content: "same"},
})
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterLonePrefix(c *C) {
// some data for the gadget
gd := []gadgetData{
{name: "bar", target: "1/nested/bar", content: "data"},
{name: "bar", target: "2/nested/foo", content: "data"},
{name: "bar", target: "3/nested/bar", content: "data"},
}
makeGadgetData(c, s.dir, gd)
outDir := filepath.Join(c.MkDir(), "out-dir")
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "bar",
Target: "/1/nested/",
}, {
Source: "bar",
Target: "/2/nested/foo",
}, {
Source: "/",
Target: "/3/nested/",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Update()
c.Assert(err, IsNil)
verifyWrittenGadgetData(c, outDir, gd)
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterUpdateErrorOnSymlinkToFile(c *C) {
gdWritten := []gadgetData{
{name: "data", target: "data", content: "some data"},
{name: "foo", symlinkTo: "data"},
}
makeGadgetData(c, s.dir, gdWritten)
outDir := filepath.Join(c.MkDir(), "out-dir")
existing := []gadgetData{
{target: "data", content: "some data"},
}
makeExistingData(c, outDir, existing)
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{Source: "/", Target: "/"},
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
// create a mock backup of first file
makeSizedFile(c, filepath.Join(s.backup, "struct-0/data.backup"), 0, nil)
err = rw.Update()
c.Assert(err, ErrorMatches, "cannot update content: cannot update file /foo: symbolic links are not supported")
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterBackupErrorOnSymlinkToDir(c *C) {
gd := []gadgetData{
{name: "bar/data", target: "bar/data", content: "some data"},
{name: "baz", symlinkTo: "bar"},
}
makeGadgetData(c, s.dir, gd)
outDir := filepath.Join(c.MkDir(), "out-dir")
existing := []gadgetData{
{target: "bar/data", content: "some data"},
}
makeExistingData(c, outDir, existing)
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{Source: "/", Target: "/"},
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
// create a mock backup of first file
makeSizedFile(c, filepath.Join(s.backup, "struct-0/bar/data.backup"), 0, nil)
makeSizedFile(c, filepath.Join(s.backup, "struct-0/bar.backup"), 0, nil)
err = rw.Update()
c.Assert(err, ErrorMatches, "cannot update content: cannot update file /baz: symbolic links are not supported")
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterRollbackFromBackup(c *C) {
// some data for the gadget
gd := []gadgetData{
{name: "bar", target: "foo", content: "data"},
{name: "bar", target: "some-dir/foo", content: "data"},
}
makeGadgetData(c, s.dir, gd)
outDir := filepath.Join(c.MkDir(), "out-dir")
makeExistingData(c, outDir, []gadgetData{
{target: "foo", content: "written"},
{target: "some-dir/foo", content: "written"},
})
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "bar",
Target: "/foo",
}, {
Source: "bar",
Target: "/some-dir/foo",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
// pretend a backup pass ran and created a backup
makeSizedFile(c, filepath.Join(s.backup, "struct-0/foo.backup"), 0, []byte("backup"))
makeSizedFile(c, filepath.Join(s.backup, "struct-0/some-dir/foo.backup"), 0, []byte("backup"))
err = rw.Rollback()
c.Assert(err, IsNil)
// files were restored from backup
verifyWrittenGadgetData(c, outDir, []gadgetData{
{target: "foo", content: "backup"},
{target: "some-dir/foo", content: "backup"},
})
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterRollbackSkipSame(c *C) {
// some data for the gadget
gd := []gadgetData{
{name: "bar", content: "data"},
}
makeGadgetData(c, s.dir, gd)
outDir := filepath.Join(c.MkDir(), "out-dir")
makeExistingData(c, outDir, []gadgetData{
{target: "foo", content: "same"},
})
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "bar",
Target: "/foo",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
// pretend a backup pass ran and created a backup
makeSizedFile(c, filepath.Join(s.backup, "struct-0/foo.same"), 0, nil)
err = rw.Rollback()
c.Assert(err, IsNil)
// files were not modified
verifyWrittenGadgetData(c, outDir, []gadgetData{
{target: "foo", content: "same"},
})
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterRollbackSkipPreserved(c *C) {
// some data for the gadget
gd := []gadgetData{
{name: "bar", content: "data"},
}
makeGadgetData(c, s.dir, gd)
outDir := filepath.Join(c.MkDir(), "out-dir")
makeExistingData(c, outDir, []gadgetData{
{target: "foo", content: "preserved"},<|fim▁hole|> })
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "bar",
Target: "/foo",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
Preserve: []string{"foo"},
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
// preserved files get no backup, but gets a stamp instead
makeSizedFile(c, filepath.Join(s.backup, "struct-0/foo.preserve"), 0, nil)
err = rw.Rollback()
c.Assert(err, IsNil)
// files were not modified
verifyWrittenGadgetData(c, outDir, []gadgetData{
{target: "foo", content: "preserved"},
})
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterRollbackNewFiles(c *C) {
makeGadgetData(c, s.dir, []gadgetData{
{name: "bar", content: "data"},
})
outDir := filepath.Join(c.MkDir(), "out-dir")
makeExistingData(c, outDir, []gadgetData{
{target: "foo", content: "written"},
{target: "some-dir/bar", content: "written"},
{target: "this/is/some/deep/nesting/bar", content: "written"},
})
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "bar",
Target: "/foo",
}, {
Source: "bar",
Target: "some-dir/",
}, {
Source: "bar",
Target: "/this/is/some/deep/nesting/",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
// none of the marker files exists, files are new, will be removed
err = rw.Rollback()
c.Assert(err, IsNil)
// everything was removed
verifyDirContents(c, outDir, map[string]contentType{})
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterRollbackRestoreFails(c *C) {
makeGadgetData(c, s.dir, []gadgetData{
{name: "bar", content: "data"},
})
outDir := filepath.Join(c.MkDir(), "out-dir")
makeExistingData(c, outDir, []gadgetData{
{target: "foo", content: "written"},
{target: "some-dir/foo", content: "written"},
})
// make rollback fail when restoring
err := os.Chmod(filepath.Join(outDir, "foo"), 0000)
c.Assert(err, IsNil)
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "bar",
Target: "/foo",
}, {
Source: "bar",
Target: "/some-dir/foo",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
// one file backed up, the other is new
makeSizedFile(c, filepath.Join(s.backup, "struct-0/foo.backup"), 0, []byte("backup"))
err = rw.Rollback()
c.Assert(err, ErrorMatches, "cannot rollback content: cannot copy .*: unable to create .*/out-dir/foo: permission denied")
// remove offending file
c.Assert(os.Remove(filepath.Join(outDir, "foo")), IsNil)
// make destination dir non-writable
err = os.Chmod(filepath.Join(outDir, "some-dir"), 0555)
c.Assert(err, IsNil)
// restore permissions later, otherwise test suite cleanup complains
defer os.Chmod(filepath.Join(outDir, "some-dir"), 0755)
err = rw.Rollback()
c.Assert(err, ErrorMatches, "cannot rollback content: cannot remove written update: remove .*/out-dir/some-dir/foo: permission denied")
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterRollbackNotWritten(c *C) {
makeGadgetData(c, s.dir, []gadgetData{
{name: "bar", content: "data"},
})
outDir := filepath.Join(c.MkDir(), "out-dir")
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "bar",
Target: "/foo",
}, {
Source: "bar",
Target: "/some-dir/foo",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
// rollback does not error out if files were not written
err = rw.Rollback()
c.Assert(err, IsNil)
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterRollbackDirectory(c *C) {
makeGadgetData(c, s.dir, []gadgetData{
{name: "some-dir/bar", content: "data"},
{name: "some-dir/foo", content: "data"},
{name: "some-dir/nested/nested-foo", content: "data"},
{name: "empty-dir/"},
})
outDir := filepath.Join(c.MkDir(), "out-dir")
makeExistingData(c, outDir, []gadgetData{
// some-dir/ -> /
{target: "foo", content: "written"},
{target: "bar", content: "written"},
{target: "nested/nested-foo", content: "written"},
// some-dir/ -> /other-dir/
{target: "other-dir/foo", content: "written"},
{target: "other-dir/bar", content: "written"},
{target: "other-dir/nested/nested-foo", content: "written"},
// some-dir/nested -> /other-dir/nested/
{target: "other-dir/nested/nested/nested-foo", content: "written"},
// bar -> /this/is/some/deep/nesting/
{target: "this/is/some/deep/nesting/bar", content: "written"},
{target: "lone-dir/"},
})
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "some-dir/",
Target: "/",
}, {
Source: "some-dir/",
Target: "/other-dir/",
}, {
Source: "some-dir/nested",
Target: "/other-dir/nested/",
}, {
Source: "bar",
Target: "/this/is/some/deep/nesting/",
}, {
Source: "empty-dir/",
Target: "/lone-dir/",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
// one file backed up
makeSizedFile(c, filepath.Join(s.backup, "struct-0/foo.backup"), 0, []byte("backup"))
// pretend part of the directory structure existed before
makeSizedFile(c, filepath.Join(s.backup, "struct-0/this/is/some.backup"), 0, nil)
makeSizedFile(c, filepath.Join(s.backup, "struct-0/this/is.backup"), 0, nil)
makeSizedFile(c, filepath.Join(s.backup, "struct-0/this.backup"), 0, nil)
makeSizedFile(c, filepath.Join(s.backup, "struct-0/lone-dir.backup"), 0, nil)
// files without a marker are new, will be removed
err = rw.Rollback()
c.Assert(err, IsNil)
verifyDirContents(c, outDir, map[string]contentType{
"lone-dir": typeDir,
"this/is/some": typeDir,
"foo": typeFile,
})
// this one got restored
c.Check(filepath.Join(outDir, "foo"), testutil.FileEquals, "backup")
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterEndToEndOne(c *C) {
// some data for the gadget
gdWritten := []gadgetData{
{name: "foo", target: "foo-dir/foo", content: "data"},
{name: "bar", target: "bar-name", content: "data"},
{name: "boot-assets/splash", target: "splash", content: "data"},
{name: "boot-assets/some-dir/data", target: "some-dir/data", content: "data"},
{name: "boot-assets/some-dir/empty-file", target: "some-dir/empty-file", content: ""},
{name: "boot-assets/nested-dir/more-nested/more", target: "/nested-copy/more-nested/more", content: "data"},
}
gdNotWritten := []gadgetData{
{name: "foo", target: "/foo", content: "data"},
{name: "boot-assets/some-dir/data", target: "data-copy", content: "data"},
{name: "boot-assets/nested-dir/nested", target: "/nested-copy/nested", content: "data"},
}
makeGadgetData(c, s.dir, append(gdWritten, gdNotWritten...))
err := os.MkdirAll(filepath.Join(s.dir, "boot-assets/empty-dir"), 0755)
c.Assert(err, IsNil)
outDir := filepath.Join(c.MkDir(), "out-dir")
makeExistingData(c, outDir, []gadgetData{
{target: "foo", content: "can't touch this"},
{target: "data-copy-preserved", content: "can't touch this"},
{target: "data-copy", content: "can't touch this"},
{target: "nested-copy/nested", content: "can't touch this"},
{target: "nested-copy/more-nested/"},
{target: "not-listed", content: "can't touch this"},
{target: "unrelated/data/here", content: "unrelated"},
})
// these exist in the root directory and are preserved
preserve := []string{
// mix entries with leading / and without
"/foo",
"/data-copy-preserved",
"nested-copy/nested",
"not-listed", // not present in 'gadget' contents
}
// these are preserved, but don't exist in the root, so data from gadget
// will be written
preserveButNotPresent := []string{
"/bar-name",
"some-dir/data",
}
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{
Source: "foo",
Target: "/foo-dir/",
}, {
// would overwrite /foo
Source: "foo",
Target: "/",
}, {
// preserved, but not present, will be
// written
Source: "bar",
Target: "/bar-name",
}, {
// some-dir/data is preserved, but not
// present, hence will be written
Source: "boot-assets/",
Target: "/",
}, {
// would overwrite /data-copy
Source: "boot-assets/some-dir/data",
Target: "/data-copy-preserved",
}, {
Source: "boot-assets/some-dir/data",
Target: "/data-copy",
}, {
// would overwrite /nested-copy/nested
Source: "boot-assets/nested-dir/",
Target: "/nested-copy/",
}, {
Source: "boot-assets",
Target: "/boot-assets-copy/",
}, {
Source: "/boot-assets/empty-dir/",
Target: "/lone-dir/nested/",
},
},
Update: gadget.VolumeUpdate{
Edition: 1,
Preserve: append(preserve, preserveButNotPresent...),
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
originalState := map[string]contentType{
"foo": typeFile,
"data-copy": typeFile,
"not-listed": typeFile,
"data-copy-preserved": typeFile,
"nested-copy/nested": typeFile,
"nested-copy/more-nested": typeDir,
"unrelated/data/here": typeFile,
}
verifyDirContents(c, outDir, originalState)
// run the backup phase
err = rw.Backup()
c.Assert(err, IsNil)
verifyDirContents(c, filepath.Join(s.backup, "struct-0"), map[string]contentType{
"nested-copy.backup": typeFile,
"nested-copy/nested.preserve": typeFile,
"nested-copy/more-nested.backup": typeFile,
"foo.preserve": typeFile,
"data-copy-preserved.preserve": typeFile,
"data-copy.backup": typeFile,
})
// run the update phase
err = rw.Update()
c.Assert(err, IsNil)
verifyDirContents(c, outDir, map[string]contentType{
"foo": typeFile,
"not-listed": typeFile,
// boot-assets/some-dir/data -> /data-copy
"data-copy": typeFile,
// boot-assets/some-dir/data -> /data-copy-preserved
"data-copy-preserved": typeFile,
// foo -> /foo-dir/
"foo-dir/foo": typeFile,
// bar -> /bar-name
"bar-name": typeFile,
// boot-assets/ -> /
"splash": typeFile,
"some-dir/data": typeFile,
"some-dir/empty-file": typeFile,
"nested-dir/nested": typeFile,
"nested-dir/more-nested/more": typeFile,
"empty-dir": typeDir,
// boot-assets -> /boot-assets-copy/
"boot-assets-copy/boot-assets/splash": typeFile,
"boot-assets-copy/boot-assets/some-dir/data": typeFile,
"boot-assets-copy/boot-assets/some-dir/empty-file": typeFile,
"boot-assets-copy/boot-assets/nested-dir/nested": typeFile,
"boot-assets-copy/boot-assets/nested-dir/more-nested/more": typeFile,
"boot-assets-copy/boot-assets/empty-dir": typeDir,
// boot-assets/nested-dir/ -> /nested-copy/
"nested-copy/nested": typeFile,
"nested-copy/more-nested/more": typeFile,
// data that was not part of the update
"unrelated/data/here": typeFile,
// boot-assets/empty-dir/ -> /lone-dir/nested/
"lone-dir/nested": typeDir,
})
// files that existed were preserved
for _, en := range preserve {
p := filepath.Join(outDir, en)
c.Check(p, testutil.FileEquals, "can't touch this")
}
// everything else was written
verifyWrittenGadgetData(c, outDir, gdWritten)
err = rw.Rollback()
c.Assert(err, IsNil)
// back to square one
verifyDirContents(c, outDir, originalState)
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterTrivialValidation(c *C) {
psNoFs := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
// no filesystem
Content: []gadget.VolumeContent{},
},
}
lookupFail := func(to *gadget.LaidOutStructure) (string, error) {
c.Fatalf("unexpected call")
return "", nil
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, psNoFs, s.backup, lookupFail)
c.Assert(err, ErrorMatches, "structure #0 has no filesystem")
c.Assert(rw, IsNil)
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{},
},
}
rw, err = gadget.NewMountedFilesystemUpdater("", ps, s.backup, lookupFail)
c.Assert(err, ErrorMatches, `internal error: gadget content directory cannot be unset`)
c.Assert(rw, IsNil)
rw, err = gadget.NewMountedFilesystemUpdater(s.dir, ps, "", lookupFail)
c.Assert(err, ErrorMatches, `internal error: backup directory must not be unset`)
c.Assert(rw, IsNil)
rw, err = gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, nil)
c.Assert(err, ErrorMatches, `internal error: mount lookup helper must be provided`)
c.Assert(rw, IsNil)
rw, err = gadget.NewMountedFilesystemUpdater(s.dir, nil, s.backup, lookupFail)
c.Assert(err, ErrorMatches, `internal error: \*LaidOutStructure.*`)
c.Assert(rw, IsNil)
lookupOk := func(to *gadget.LaidOutStructure) (string, error) {
return filepath.Join(s.dir, "foobar"), nil
}
for _, tc := range []struct {
content gadget.VolumeContent
match string
}{
{content: gadget.VolumeContent{Source: "", Target: "/"}, match: "internal error: source cannot be unset"},
{content: gadget.VolumeContent{Source: "/", Target: ""}, match: "internal error: target cannot be unset"},
} {
testPs := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{tc.content},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, testPs, s.backup, lookupOk)
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Update()
c.Assert(err, ErrorMatches, "cannot update content: "+tc.match)
err = rw.Backup()
c.Assert(err, ErrorMatches, "cannot backup content: "+tc.match)
err = rw.Rollback()
c.Assert(err, ErrorMatches, "cannot rollback content: "+tc.match)
}
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterMountLookupFail(c *C) {
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{Source: "/", Target: "/"},
},
},
}
lookupFail := func(to *gadget.LaidOutStructure) (string, error) {
return "", errors.New("fail fail fail")
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, lookupFail)
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Update()
c.Assert(err, ErrorMatches, "cannot find mount location of structure #0: fail fail fail")
err = rw.Backup()
c.Assert(err, ErrorMatches, "cannot find mount location of structure #0: fail fail fail")
err = rw.Rollback()
c.Assert(err, ErrorMatches, "cannot find mount location of structure #0: fail fail fail")
}
func (s *mountedfilesystemTestSuite) TestMountedUpdaterNonFilePreserveError(c *C) {
// some data for the gadget
gd := []gadgetData{
{name: "foo", content: "data"},
}
makeGadgetData(c, s.dir, gd)
outDir := filepath.Join(c.MkDir(), "out-dir")
// will conflict with preserve entry
err := os.MkdirAll(filepath.Join(outDir, "foo"), 0755)
c.Assert(err, IsNil)
ps := &gadget.LaidOutStructure{
VolumeStructure: &gadget.VolumeStructure{
Size: 2048,
Filesystem: "ext4",
Content: []gadget.VolumeContent{
{Source: "/", Target: "/"},
},
Update: gadget.VolumeUpdate{
Preserve: []string{"foo"},
Edition: 1,
},
},
}
rw, err := gadget.NewMountedFilesystemUpdater(s.dir, ps, s.backup, func(to *gadget.LaidOutStructure) (string, error) {
c.Check(to, DeepEquals, ps)
return outDir, nil
})
c.Assert(err, IsNil)
c.Assert(rw, NotNil)
err = rw.Backup()
c.Check(err, ErrorMatches, `cannot map preserve entries for mount location ".*/out-dir": preserved entry "foo" cannot be a directory`)
err = rw.Update()
c.Check(err, ErrorMatches, `cannot map preserve entries for mount location ".*/out-dir": preserved entry "foo" cannot be a directory`)
err = rw.Rollback()
c.Check(err, ErrorMatches, `cannot map preserve entries for mount location ".*/out-dir": preserved entry "foo" cannot be a directory`)
}<|fim▁end|> | |
<|file_name|>dmt_structs.go<|end_file_name|><|fim▁begin|>// Copyright 2013 The Changkong Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package dmt
const VersionNo = "20131207"
/* 图片分类 */
type PictureCategory struct {
Created string `json:"created"`
Modified string `json:"modified"`
ParentId int `json:"parent_id"`
PictureCategoryId int `json:"picture_category_id"`
PictureCategoryName string `json:"picture_category_name"`
Position int `json:"position"`
Type string `json:"type"`
}
/* 图片 */
type Picture struct {
ClientType string `json:"client_type"`
Created string `json:"created"`
Deleted string `json:"deleted"`
Md5 string `json:"md5"`
Modified string `json:"modified"`
PictureCategoryId int `json:"picture_category_id"`
PictureId int `json:"picture_id"`<|fim▁hole|> Pixel string `json:"pixel"`
Referenced bool `json:"referenced"`
Sizes int `json:"sizes"`
Status string `json:"status"`
Title string `json:"title"`
Uid int `json:"uid"`
}
/* 图片空间的用户信息获取,包括订购容量等 */
type UserInfo struct {
AvailableSpace string `json:"available_space"`
FreeSpace string `json:"free_space"`
OrderExpiryDate string `json:"order_expiry_date"`
OrderSpace string `json:"order_space"`
RemainingSpace string `json:"remaining_space"`
UsedSpace string `json:"used_space"`
WaterMark string `json:"water_mark"`
}
/* 搜索返回的结果类 */
type TOPSearchResult struct {
Paginator *TOPPaginator `json:"paginator"`
VideoItems struct {
VideoItem []*VideoItem `json:"video_item"`
} `json:"video_items"`
}
/* 分页信息 */
type TOPPaginator struct {
CurrentPage int `json:"current_page"`
IsLastPage bool `json:"is_last_page"`
PageSize int `json:"page_size"`
TotalResults int `json:"total_results"`
}
/* 视频 */
type VideoItem struct {
CoverUrl string `json:"cover_url"`
Description string `json:"description"`
Duration int `json:"duration"`
IsOpenToOther bool `json:"is_open_to_other"`
State int `json:"state"`
Tags []string `json:"tags"`
Title string `json:"title"`
UploadTime string `json:"upload_time"`
UploaderId int `json:"uploader_id"`
VideoId int `json:"video_id"`
VideoPlayInfo *VideoPlayInfo `json:"video_play_info"`
}
/* 视频播放信息 */
type VideoPlayInfo struct {
AndroidpadUrl string `json:"androidpad_url"`
AndroidpadV23Url *AndroidVlowUrl `json:"androidpad_v23_url"`
AndroidphoneUrl string `json:"androidphone_url"`
AndroidphoneV23Url *AndroidVlowUrl `json:"androidphone_v23_url"`
FlashUrl string `json:"flash_url"`
IpadUrl string `json:"ipad_url"`
IphoneUrl string `json:"iphone_url"`
WebUrl string `json:"web_url"`
}
/* android phone和pad播放的mp4文件类。适用2.3版本的Android。 */
type AndroidVlowUrl struct {
Hd string `json:"hd"`
Ld string `json:"ld"`
Sd string `json:"sd"`
Ud string `json:"ud"`
}<|fim▁end|> | PicturePath string `json:"picture_path"` |
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python<|fim▁hole|>"""Test registry for builders."""
# These need to register plugins so, pylint: disable=unused-import
from grr.lib.builders import signing_test
# pylint: enable=unused-import<|fim▁end|> | |
<|file_name|>cajbook.py<|end_file_name|><|fim▁begin|>"""
Loadable.Loadable subclass
"""
# This file is part of Munin.
# Munin is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# Munin is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Munin; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# This work is Copyright (C)2006 by Andreas Jacobsen
# Individual portions may be copyright by individual contributors, and
# are included in this collective work with permission of the copyright
# owners.
class cajbook(loadable.loadable):
def __init__(self, client, conn, cursor):<|fim▁hole|> self.usage = self.__class__.__name__ + " <x:y:z> (<eta>|<landing tick>)"
def execute(self, nick, username, host, target, prefix, command, user, access):
m = self.commandre.search(command)
if not m:
return 0
m = self.paramre.search(irc_msg.command_parameters)
if not m:
self.client.reply(prefix, nick, target, "Usage: %s" % (self.usage,))
return 0
x = m.group(1)
y = m.group(2)
z = m.group(3)
when = int(m.group(4))
override = m.group(6)
if access < self.level:
self.client.reply(
prefix,
nick,
target,
"You do not have enough access to use this command",
)
return 0
if int(x) != 6 or int(y) != 8:
self.client.reply(
prefix,
nick,
target,
"This command only works for the galaxy 2:5, if you need a normal booking try !book",
)
return 0
p = loadable.planet(x=x, y=y, z=z)
if not p.load_most_recent(self.conn, self.client, self.cursor):
self.client.reply(
prefix, nick, target, "No planet matching '%s:%s:%s' found" % (x, y, z)
)
return 1
else:
i = loadable.intel(pid=p.id)
if not i.load_from_db(self.conn, self.client, self.cursor):
pass
else:
if i and i.alliance and i.alliance.lower() == "ascendancy":
self.client.reply(
prefix,
nick,
target,
"%s:%s:%s is %s in Ascendancy. Quick, launch before they notice the highlight."
% (x, y, z, i.nick or "someone"),
)
return 0
curtick = self.current_tick()
tick = -1
eta = -1
if when < 80:
tick = curtick + when
eta = when
elif when < curtick:
self.client.reply(
prefix,
nick,
target,
"Can not book targets in the past. You wanted tick %s, but current tick is %s."
% (when, curtick),
)
return 1
else:
tick = when
eta = tick - curtick
if tick > 32767:
tick = 32767
args = ()
query = "SELECT t1.id AS id, t1.nick AS nick, t1.pid AS pid, t1.tick AS tick, t1.uid AS uid, t2.pnick AS pnick, t2.userlevel AS userlevel, t3.x AS x, t3.y AS y, t3.z AS z"
query += " FROM target AS t1"
query += " INNER JOIN planet_dump AS t3 ON t1.pid=t3.id"
query += " LEFT JOIN user_list AS t2 ON t1.uid=t2.id"
query += " WHERE"
query += " t1.tick > %s"
query += (
" AND t3.tick = (SELECT MAX(tick) FROM updates) AND t3.x=%s AND t3.y=%s"
)
query += " AND t3.z=%s"
self.cursor.execute(query, (tick, x, y, z))
if self.cursor.rowcount > 0 and not override:
reply = (
"There are already bookings for that target after landing pt %s (eta %s). To see status on this target, do !status %s:%s:%s."
% (tick, eta, x, y, z)
)
reply += (
" To force booking at your desired eta/landing tick, use !book %s:%s:%s %s yes (Bookers:"
% (x, y, z, tick)
)
prev = []
for r in self.cursor.fetchall():
owner = "nick:" + r["nick"]
if r["pnick"]:
owner = "user:" + r["pnick"]
prev.append("(%s %s)" % (r["tick"], owner))
reply += " " + string.join(prev, ", ")
reply += " )"
self.client.reply(prefix, nick, target, reply)
return 1
uid = None
if user:
u = loadable.user(pnick=user)
if u.load_from_db(self.conn, self.client, self.cursor):
uid = u.id
query = "INSERT INTO target (nick,pid,tick,uid) VALUES (%s,%s,%s,%s)"
try:
self.cursor.execute(query, (nick, p.id, tick, uid))
if uid:
reply = "Booked landing on %s:%s:%s tick %s for user %s" % (
p.x,
p.y,
p.z,
tick,
user,
)
else:
reply = "Booked landing on %s:%s:%s tick %s for nick %s" % (
p.x,
p.y,
p.z,
tick,
nick,
)
except psycopg.IntegrityError:
query = "SELECT t1.id AS id, t1.nick AS nick, t1.pid AS pid, t1.tick AS tick, t1.uid AS uid, t2.pnick AS pnick, t2.userlevel AS userlevel "
query += " FROM target AS t1 LEFT JOIN user_list AS t2 ON t1.uid=t2.id "
query += " WHERE t1.pid=%s AND t1.tick=%s"
self.cursor.execute(query, (p.id, tick))
book = self.cursor.fetchone()
if not book:
raise Exception(
"Integrity error? Unable to booking for pid %s and tick %s"
% (p.id, tick)
)
if book["pnick"]:
reply = (
"Target %s:%s:%s is already booked for landing tick %s by user %s"
% (p.x, p.y, p.z, book["tick"], book["pnick"])
)
else:
reply = (
"Target %s:%s:%s is already booked for landing tick %s by nick %s"
% (p.x, p.y, p.z, book["tick"], book["nick"])
)
except:
raise
self.client.reply(prefix, nick, target, reply)
return 1<|fim▁end|> | loadable.loadable.__init__(self, client, conn, cursor, 50)
self.paramre = re.compile(r"^\s*(\d+)[. :-](\d+)[. :-](\d+)\s+(\d+)(\s+(yes))?") |
<|file_name|>day17.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""
http://adventofcode.com/day/17
Part 1
------
The elves bought too much eggnog again - 150 liters this time. To
fit it all into your refrigerator, you'll need to move it into
smaller containers. You take an inventory of the capacities of
the available containers.
For example, suppose you have containers of size 20, 15, 10, 5,
and 5 liters. If you need to store 25 liters, there are four ways
to do it:
- 15 and 10
- 20 and 5 (the first 5)
- 20 and 5 (the second 5)
- 15, 5, and 5
Filling all containers entirely, how many different combinations
of containers can exactly fit all 150 liters of eggnog?
Part 2
------
While playing with all the containers in the kitchen, another load
of eggnog arrives! The shipping and receiving department is
requesting as many containers as you can spare.
Find the minimum number of containers that can exactly fit all
150 liters of eggnog. How many different ways can you fill that
number of containers and still hold exactly 150 litres?
In the example above, the minimum number of containers was two.
There were three ways to use that many containers, and so the
answer there would be 3.
"""
from __future__ import print_function, unicode_literals
from itertools import combinations
import os
import re
import sys
INFILE = 'inputs/input17.txt'
def main():<|fim▁hole|> containers.append(int(line.strip()))
# Part 1
p1count = 0
for s in range(len(containers)):
for c in combinations(containers, s):
if sum(c) == 150:
p1count += 1
# Part 2
p2sizes = dict()
p2min = len(containers)
for i in range(p2min):
p2sizes[i] = 0
for s in range(len(containers)):
for c in combinations(containers, s):
if sum(c) == 150:
if len(c) < p2min:
p2min = len(c)
p2sizes[s] += 1
msg = '[Python] Puzzle 17-1: {}'
print(msg.format(p1count))
msg = '[Python] Puzzle 17-2: {}'
print(msg.format(p2sizes[p2min]))
if __name__ == '__main__':
main()<|fim▁end|> | containers = list()
with open(INFILE) as f:
for line in f: |
<|file_name|>conftest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-<|fim▁hole|> Dummy conftest.py for graph_stix.
If you don't know what this is for, just leave it empty.
Read more about conftest.py under:
https://pytest.org/latest/plugins.html
"""
from __future__ import print_function, absolute_import, division
import pytest<|fim▁end|> | """ |
<|file_name|>type-param-constraints.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
#![allow(dead_code)]
// pretty-expanded FIXME #23616
#![feature(box_syntax)]
fn p_foo<T>(_pinned: T) { }
fn s_foo<T>(_shared: T) { }
fn u_foo<T:Send>(_unique: T) { }
struct r {
i: isize,
}
impl Drop for r {
fn drop(&mut self) {}
}
fn r(i:isize) -> r {
r {
i: i
}
}<|fim▁hole|>pub fn main() {
p_foo(r(10));
p_foo::<Box<_>>(box r(10));
p_foo::<Box<_>>(box 10);
p_foo(10);
s_foo::<Box<_>>(box 10);
s_foo(10);
u_foo::<Box<_>>(box 10);
u_foo(10);
}<|fim▁end|> | |
<|file_name|>n2dp.py<|end_file_name|><|fim▁begin|>"""
===========
N2D+ fitter
===========
Reference for line params:
Dore (priv. comm.) line frequencies in CDMS,
line strength can also be obtained from Splatalogue
L. Dore, P. Caselli, S. Beninati, T. Bourke, P. C. Myers and G. Cazzoli A&A 413, 1177-1181 (2004)
http://adsabs.harvard.edu/abs/2004A%26A...413.1177D
L. Pagani, F. Daniel, and M. L. Dubernet A\%A 494, 719-727 (2009)
DOI: 10.1051/0004-6361:200810570
"""
from . import hyperfine
import astropy.units as u
# line_names = ['J1-0', 'J2-1', 'J3-2',]
# line_names = ['J2-1', 'J3-2',]
freq_dict_cen ={
# 'J1-0': 77109.2697e6,
'J2-1': 154217.1805e6,
'J3-2': 231321.9119e6,
}
voff_lines_dict={
####### J 2-1
'J2-1_01': -5.6031,
'J2-1_02': -5.5332,
'J2-1_03': -5.3617,
'J2-1_04': -5.0993,
'J2-1_05': -4.9677,
'J2-1_06': -4.7052,
'J2-1_07': -3.8195,
'J2-1_08': -3.5571,
'J2-1_09': -2.8342,
'J2-1_10': -2.3388,
'J2-1_11': -1.9449,
'J2-1_12': -1.9002,
'J2-1_13': -1.7733,
'J2-1_14': -1.3965,
'J2-1_15': -1.0025,
'J2-1_16': -0.7968,
'J2-1_17': -0.5740,
'J2-1_18': -0.2311,
'J2-1_19': -0.0085,
'J2-1_20': 0.0000,
'J2-1_21': 0.1351,
'J2-1_22': 0.1457,
'J2-1_23': 0.1886,
'J2-1_24': 0.2538,
'J2-1_25': 0.6165,
'J2-1_26': 0.7541,
'J2-1_27': 0.8789,
'J2-1_28': 2.5594,
'J2-1_29': 3.0143,
'J2-1_30': 3.0632,
'J2-1_31': 3.1579,
'J2-1_32': 3.4572,
'J2-1_33': 3.6394,
'J2-1_34': 3.7234,
'J2-1_35': 3.9567,
'J2-1_36': 4.2049,
'J2-1_37': 4.5817,
'J2-1_38': 4.6054,
'J2-1_39': 8.4164,
'J2-1_40': 9.0414,
####### J 3-2
'J3-2_01': -3.7164,
'J3-2_02': -3.5339,
'J3-2_03': -3.2997,
'J3-2_04': -3.2130,
'J3-2_05': -3.0633,
'J3-2_06': -2.8958,
'J3-2_07': -2.7424,
'J3-2_08': -2.6466,
'J3-2_09': -2.5748,
'J3-2_10': -1.9177,
'J3-2_11': -1.2333,
'J3-2_02': -0.7628,
'J3-2_13': -0.7590,
'J3-2_14': -0.7306,
'J3-2_15': -0.5953,
'J3-2_16': -0.5765,
'J3-2_17': -0.3419,
'J3-2_18': -0.0925,
'J3-2_19': -0.0210,
'J3-2_20': 0.0000,
'J3-2_21': 0.0065,
'J3-2_22': 0.0616,
'J3-2_23': 0.0618,
'J3-2_24': 0.0675,
'J3-2_25': 0.0748,
'J3-2_26': 0.2212,
'J3-2_27': 0.2691,
'J3-2_28': 0.4515,
'J3-2_29': 0.5422,
'J3-2_30': 0.5647,
'J3-2_31': 0.6050,
'J3-2_32': 0.6596,
'J3-2_33': 0.9222,
'J3-2_34': 1.0897,
'J3-2_35': 1.9586,
'J3-2_36': 2.0471,
'J3-2_37': 2.5218,
'J3-2_38': 2.5500,
'J3-2_39': 2.6156,
'J3-2_40': 3.0245,
'J3-2_41': 3.1786,
'J3-2_42': 3.3810,
'J3-2_43': 3.6436,
'J3-2_44': 4.2066,
}<|fim▁hole|>
line_strength_dict = {
####### J 2-1
'J2-1_01': 0.008262,
'J2-1_02': 0.005907,
'J2-1_03': 0.031334,
'J2-1_04': 0.013833,
'J2-1_05': 0.013341,
'J2-1_06': 0.010384,
'J2-1_07': 0.000213,
'J2-1_08': 0.000675,
'J2-1_09': 0.000150,
'J2-1_10': 0.001202,
'J2-1_11': 0.000963,
'J2-1_12': 0.000878,
'J2-1_13': 0.002533,
'J2-1_14': 0.000362,
'J2-1_15': 0.000162,
'J2-1_16': 0.021268,
'J2-1_17': 0.031130,
'J2-1_18': 0.000578,
'J2-1_19': 0.001008,
'J2-1_20': 0.200000,
'J2-1_21': 0.111666,
'J2-1_22': 0.088138,
'J2-1_23': 0.142511,
'J2-1_24': 0.011550,
'J2-1_25': 0.027472,
'J2-1_26': 0.012894,
'J2-1_27': 0.066406,
'J2-1_28': 0.013082,
'J2-1_29': 0.003207,
'J2-1_30': 0.061847,
'J2-1_31': 0.004932,
'J2-1_32': 0.035910,
'J2-1_33': 0.011102,
'J2-1_34': 0.038958,
'J2-1_35': 0.019743,
'J2-1_36': 0.004297,
'J2-1_37': 0.001830,
'J2-1_38': 0.000240,
'J2-1_39': 0.000029,
'J2-1_40': 0.000004,
####### J 3-2
'J3-2_01': 0.001842,
'J3-2_02': 0.001819,
'J3-2_03': 0.003544,
'J3-2_04': 0.014100,
'J3-2_05': 0.011404,
'J3-2_06': 0.000088,
'J3-2_07': 0.002201,
'J3-2_08': 0.002153,
'J3-2_09': 0.000059,
'J3-2_10': 0.000058,
'J3-2_11': 0.000203,
'J3-2_12': 0.000259,
'J3-2_13': 0.000248,
'J3-2_14': 0.000437,
'J3-2_15': 0.010215,
'J3-2_16': 0.000073,
'J3-2_17': 0.007445,
'J3-2_18': 0.000155,
'J3-2_19': 0.000272,
'J3-2_20': 0.174603,
'J3-2_21': 0.018678,
'J3-2_22': 0.100524,
'J3-2_23': 0.135563,
'J3-2_24': 0.124910,
'J3-2_25': 0.060970,
'J3-2_26': 0.088513,
'J3-2_27': 0.001085,
'J3-2_28': 0.094480,
'J3-2_29': 0.013955,
'J3-2_30': 0.007236,
'J3-2_31': 0.022222,
'J3-2_32': 0.047921,
'J3-2_33': 0.015427,
'J3-2_34': 0.000070,
'J3-2_35': 0.000796,
'J3-2_36': 0.001373,
'J3-2_37': 0.007147,
'J3-2_38': 0.016574,
'J3-2_39': 0.009776,
'J3-2_40': 0.000995,
'J3-2_41': 0.000491,
'J3-2_42': 0.000067,
'J3-2_43': 0.000039,
'J3-2_44': 0.000010,
}
# freq_dict = {
# 'J2-1': (voff_lines_dict['J2-1']*u.km/u.s).to(u.GHz, equivalencies=u.doppler_radio(freq_dict_cen['J2-1']*u.Hz)).value,
# 'J3-2': (voff_lines_dict['J3-2']*u.km/u.s).to(u.GHz, equivalencies=u.doppler_radio(freq_dict_cen['J3-2']*u.Hz)).value,
# }
# Get frequency dictionary in Hz based on the offset velocity and rest frequency
conv_J21=u.doppler_radio(freq_dict_cen['J2-1']*u.Hz)
conv_J32=u.doppler_radio(freq_dict_cen['J3-2']*u.Hz)
freq_dict = {
name: ((voff_lines_dict[name]*u.km/u.s).to(u.Hz, equivalencies=conv_J21).value) for name in voff_lines_dict.keys() if "J2-1" in name
}
freq_dict.update({
name: ((voff_lines_dict[name]*u.km/u.s).to(u.Hz, equivalencies=conv_J32).value) for name in voff_lines_dict.keys() if "J3-2" in name
})
# I don't know yet how to use this parameter... in CLASS it does not exist
# Note to Jaime: this is the sum of the degeneracy values for all hyperfines
# for a given line; it gives the relative weights between the J=2-1 and J=3-2
# lines, for example (the hyperfine weights are treated as normalized within
# one rotational transition)
w21 = sum(val for name,val in line_strength_dict.items() if 'J2-1' in name)
w32 = sum(val for name,val in line_strength_dict.items() if 'J3-2' in name)
relative_strength_total_degeneracy = {
name : w21 for name in line_strength_dict.keys() if "J2-1" in name
}
relative_strength_total_degeneracy.update({
name : w32 for name in line_strength_dict.keys() if "J3-2" in name
})
# Get the list of line names from the previous lists
line_names = [name for name in voff_lines_dict.keys()]
# 'J2-1': np.array([1]*len(voff_lines_dict['J2-1'])),
# 'J3-2': np.array([1]*len(voff_lines_dict['J3-2'])),
# }
# aval_dict = {
# # 'J1-0': 10**(-4.90770),
# 'J2-1': 10**(-3.92220),
# 'J3-2': 10**(-3.35866),
# }
n2dp_vtau = hyperfine.hyperfinemodel(line_names, voff_lines_dict, freq_dict,
line_strength_dict,
relative_strength_total_degeneracy)
n2dp_vtau_fitter = n2dp_vtau.fitter
n2dp_vtau_vheight_fitter = n2dp_vtau.vheight_fitter
n2dp_vtau_tbg_fitter = n2dp_vtau.background_fitter<|fim▁end|> | |
<|file_name|>v1beta1_replica_set_spec.py<|end_file_name|><|fim▁begin|># coding: utf-8
"""
OpenAPI spec version:
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from pprint import pformat
from six import iteritems
import re
class V1beta1ReplicaSetSpec(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
operations = [
]
# The key is attribute name
# and the value is attribute type.
swagger_types = {
'replicas': 'int',
'selector': 'V1beta1LabelSelector',
'template': 'V1PodTemplateSpec'
}
# The key is attribute name
# and the value is json key in definition.
attribute_map = {
'replicas': 'replicas',
'selector': 'selector',
'template': 'template'
}
def __init__(self, replicas=None, selector=None, template=None):
"""
V1beta1ReplicaSetSpec - a model defined in Swagger
"""
self._replicas = replicas
self._selector = selector
self._template = template
@property
def replicas(self):
"""
Gets the replicas of this V1beta1ReplicaSetSpec.
Replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. More info: http://releases.k8s.io/release-1.2/docs/user-guide/replication-controller.md#what-is-a-replication-controller
:return: The replicas of this V1beta1ReplicaSetSpec.
:rtype: int
"""
return self._replicas
@replicas.setter
def replicas(self, replicas):
"""
Sets the replicas of this V1beta1ReplicaSetSpec.
Replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. More info: http://releases.k8s.io/release-1.2/docs/user-guide/replication-controller.md#what-is-a-replication-controller
:param replicas: The replicas of this V1beta1ReplicaSetSpec.
:type: int
"""
self._replicas = replicas
@property
def selector(self):
"""
Gets the selector of this V1beta1ReplicaSetSpec.
Selector is a label query over pods that should match the replica count. If the selector is empty, it is defaulted to the labels present on the pod template. Label keys and values that must match in order to be controlled by this replica set. More info: http://releases.k8s.io/release-1.2/docs/user-guide/labels.md#label-selectors
:return: The selector of this V1beta1ReplicaSetSpec.
:rtype: V1beta1LabelSelector
"""
return self._selector
@selector.setter
def selector(self, selector):
"""
Sets the selector of this V1beta1ReplicaSetSpec.
Selector is a label query over pods that should match the replica count. If the selector is empty, it is defaulted to the labels present on the pod template. Label keys and values that must match in order to be controlled by this replica set. More info: http://releases.k8s.io/release-1.2/docs/user-guide/labels.md#label-selectors
:param selector: The selector of this V1beta1ReplicaSetSpec.
:type: V1beta1LabelSelector
"""
self._selector = selector
@property
def template(self):
"""
Gets the template of this V1beta1ReplicaSetSpec.
Template is the object that describes the pod that will be created if insufficient replicas are detected. More info: http://releases.k8s.io/release-1.2/docs/user-guide/replication-controller.md#pod-template
:return: The template of this V1beta1ReplicaSetSpec.
:rtype: V1PodTemplateSpec
"""
return self._template
@template.setter
def template(self, template):
"""
Sets the template of this V1beta1ReplicaSetSpec.
Template is the object that describes the pod that will be created if insufficient replicas are detected. More info: http://releases.k8s.io/release-1.2/docs/user-guide/replication-controller.md#pod-template
:param template: The template of this V1beta1ReplicaSetSpec.
:type: V1PodTemplateSpec
"""
self._template = template
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(V1beta1ReplicaSetSpec.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""<|fim▁hole|> For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other<|fim▁end|> | |
<|file_name|>DataCollector.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python
'''
Saves relevant data fed back from TwitterStream etc next to its PID and timestamp ready for analysis
Needs to do limited analysis to work out which keywords in the tweet stream correspond to which programme
'''
from datetime import datetime
import os
import string
import time as time2
from time import time
from Axon.Ipc import producerFinished
from Axon.Ipc import shutdownMicroprocess
from Axon.ThreadedComponent import threadedcomponent
import MySQLdb
import _mysql_exceptions
import cjson
from dateutil.parser import parse
class DataCollector(threadedcomponent):
Inboxes = {
"inbox" : "Receives data in the format [tweetjson,[pid,pid]]",
"control" : ""
}
Outboxes = {
"outbox" : "",
"signal" : ""
}
def __init__(self,dbuser,dbpass):
super(DataCollector, self).__init__()
self.dbuser = dbuser
self.dbpass = dbpass
def finished(self):
while self.dataReady("control"):
msg = self.recv("control")
if isinstance(msg, producerFinished) or isinstance(msg, shutdownMicroprocess):
self.send(msg, "signal")
return True
return False
def dbConnect(self):
db = MySQLdb.connect(user=self.dbuser,passwd=self.dbpass,db="twitter_bookmarks",use_unicode=True,charset="utf8")
cursor = db.cursor()
return cursor
def main(self):
cursor = self.dbConnect()
while not self.finished():
twitdata = list()
# Collect all current received tweet JSON and their related PIDs into a twitdata list
while self.dataReady("inbox"):
pids = list()
data = self.recv("inbox")
for pid in data[1]:
pids.append(pid)
twitdata.append([data[0],pids])
if len(twitdata) > 0:
# Process the received twitdata
for tweet in twitdata:
tweet[0] = tweet[0].replace("\\/","/") # Fix slashes in links: This may need moving further down the line - ideally it would be handled by cjson
if tweet[0] != "\r\n": # If \r\n is received, this is just a keep alive signal from Twitter every 30 secs
# At this point, each 'tweet' contains tweetdata, and a list of possible pids
newdata = cjson.decode(tweet[0])
if newdata.has_key('delete') or newdata.has_key('scrub_geo') or newdata.has_key('limit'):
# Keep a record of all requests from Twitter for deletions, location removal etc
# As yet none of these have been received, but this code will store them if they are received to enable debugging
filepath = "contentDebug.txt"
if os.path.exists(filepath):
file = open(filepath, 'r')
filecontents = file.read()
else:
filecontents = ""
file = open(filepath, 'w')
file.write(filecontents + "\n" + str(datetime.utcnow()) + " " + cjson.encode(newdata))
file.close()
else:
# This is a real tweet
tweetid = newdata['id']
print "New tweet! @" + newdata['user']['screen_name'] + ": " + newdata['text']
for pid in tweet[1]:
# Cycle through possible pids, grabbing that pid's keywords from the DB
# Then, check this tweet against the keywords and save to DB where appropriate (there may be more than one location)
cursor.execute("""SELECT keyword,type FROM keywords WHERE pid = %s""",(pid))
data = cursor.fetchall()
for row in data:
# Some keywords are stored with a ^. These must be split, and the tweet checked to see if it has both keywords, but not necessarily next to each other
keywords = row[0].split("^")
if len(keywords) == 2:
if string.lower(keywords[0]) in string.lower(newdata['text']) and string.lower(keywords[1]) in string.lower(newdata['text']):
cursor.execute("""SELECT timestamp,timediff FROM programmes WHERE pid = %s ORDER BY timestamp DESC""",(pid))
progdata = cursor.fetchone()
if progdata != None:
# Ensure the user hasn't already tweeted the same text
# Also ensure they haven't tweeted in the past 10 seconds
timestamp = time2.mktime(parse(newdata['created_at']).timetuple())
cursor.execute("""SELECT * FROM rawdata WHERE (pid = %s AND text = %s AND user = %s) OR (pid = %s AND user = %s AND timestamp >= %s AND timestamp < %s)""",(pid,newdata['text'],newdata['user']['screen_name'],pid,newdata['user']['screen_name'],timestamp-10,timestamp+10))
if cursor.fetchone() == None:
print ("Storing tweet for pid " + pid)
# Work out where this tweet really occurred in the programme using timestamps and DVB bridge data
progposition = timestamp - (progdata[0] - progdata[1])
cursor.execute("""INSERT INTO rawdata (tweet_id,pid,timestamp,text,user,programme_position) VALUES (%s,%s,%s,%s,%s,%s)""", (tweetid,pid,timestamp,newdata['text'],newdata['user']['screen_name'],progposition))
break # Break out of this loop and back to check the same tweet against the next programme
else:
print ("Duplicate tweet from user - ignoring")
if string.lower(row[0]) in string.lower(newdata['text']):
cursor.execute("""SELECT timestamp,timediff FROM programmes WHERE pid = %s ORDER BY timestamp DESC""",(pid))
progdata = cursor.fetchone()
if progdata != None:
# Ensure the user hasn't already tweeted the same text for this programme
# Also ensure they haven't tweeted in the past 10 seconds
timestamp = time2.mktime(parse(newdata['created_at']).timetuple())
cursor.execute("""SELECT * FROM rawdata WHERE (pid = %s AND text = %s AND user = %s) OR (pid = %s AND user = %s AND timestamp >= %s AND timestamp < %s)""",(pid,newdata['text'],newdata['user']['screen_name'],pid,newdata['user']['screen_name'],timestamp-10,timestamp+10))
if cursor.fetchone() == None:
print ("Storing tweet for pid " + pid)
# Work out where this tweet really occurred in the programme using timestamps and DVB bridge data
progposition = timestamp - (progdata[0] - progdata[1])
cursor.execute("""INSERT INTO rawdata (tweet_id,pid,timestamp,text,user,programme_position) VALUES (%s,%s,%s,%s,%s,%s)""", (tweetid,pid,timestamp,newdata['text'],newdata['user']['screen_name'],progposition))
break # Break out of this loop and back to check the same tweet against the next programme
else:
print ("Duplicate tweet from user - ignoring")
else:
print "Blank line received from Twitter - no new data"
print ("Done!") # new line to break up display
else:
time2.sleep(0.1)
'''
The raw data collector differs from the plain data collector in that it stores the raw JSON containers for tweets next to their unique IDs, but with no relation to PIDs
This is run concurrent to the other data collector, so the two won't necessarily run at the same rate and could be out of sync
This possible lack of sync must be handled later
'''
class RawDataCollector(threadedcomponent):
Inboxes = {
"inbox" : "Receives data in the format [tweetjson,[pid,pid]]",
"control" : ""
}
Outboxes = {
"outbox" : "",
"signal" : ""
}
def __init__(self,dbuser,dbpass):
super(RawDataCollector, self).__init__()
self.dbuser = dbuser
self.dbpass = dbpass
def finished(self):
while self.dataReady("control"):
msg = self.recv("control")
if isinstance(msg, producerFinished) or isinstance(msg, shutdownMicroprocess):
self.send(msg, "signal")
return True
return False
def dbConnect(self):
db = MySQLdb.connect(user=self.dbuser,passwd=self.dbpass,db="twitter_bookmarks",use_unicode=True,charset="utf8")
cursor = db.cursor()
return cursor
def main(self):
cursor = self.dbConnect()
while not self.finished():
twitdata = list()
# As in the data collector, create a list of all tweets currently received
while self.dataReady("inbox"):
data = self.recv("inbox")
twitdata.append(data[0])
if len(twitdata) > 0:<|fim▁hole|> tweet = tweet.replace("\\/","/") # This may need moving further down the line - ideally it would be handled by cjson
if tweet != "\r\n":
newdata = cjson.decode(tweet)
if newdata.has_key('delete') or newdata.has_key('scrub_geo') or newdata.has_key('limit'):
# It is assumed here that the original data collector has handled the Twitter status message
print "Discarding tweet instruction - captured by other component"
else:
tweetid = newdata['id']
# Capture exactly when this tweet was stored
tweetstamp = time()
tweetsecs = int(tweetstamp)
# Include the fractions of seconds portion of the timestamp in a separate field
tweetfrac = tweetstamp - tweetsecs
# We only have a 16000 VARCHAR field to use in MySQL (through choice) - this should be enough, but if not, the tweet will be written out to file
if len(tweet) < 16000:
try:
cursor.execute("""INSERT INTO rawtweets (tweet_id,tweet_json,tweet_stored_seconds,tweet_stored_fraction) VALUES (%s,%s,%s,%s)""", (tweetid,tweet,tweetsecs,tweetfrac))
except _mysql_exceptions.IntegrityError, e:
# Handle the possibility for Twitter having sent us a duplicate
print "Duplicate tweet ID:", str(e)
else:
print "Discarding tweet - length limit exceeded"
tweetcontents = ""
homedir = os.path.expanduser("~")
if os.path.exists(homedir + "/oversizedtweets.conf"):
try:
file = open(homedir + "/oversizedtweets.conf",'r')
tweetcontents = file.read()
file.close()
except IOError, e:
print ("Failed to load oversized tweet cache - it will be overwritten")
try:
file = open(homedir + "/oversizedtweets.conf",'w')
tweetcontents = tweetcontents + tweet
file.write(tweetcontents)
file.close()
except IOError, e:
print ("Failed to save oversized tweet cache")
else:
time2.sleep(0.1)<|fim▁end|> | # Cycle through the tweets, fixing their URLs as before, and storing them if they aren't a status message
for tweet in twitdata: |
<|file_name|>build.py<|end_file_name|><|fim▁begin|>import os
from os.path import join, getctime, dirname
import glob
import subprocess
import argparse
def newest_file(root):
path = join(root, "*tar.bz2")
newest = max(glob.iglob(path), key=getctime)
return newest
def upload(pkg, user):
cmd = ["binstar", "upload", "--force","-u", user, pkg]
subprocess.check_call(cmd)
def build(recipe, build_path, pythons=[], platforms=[], binstar_user=None):
print (recipe, pythons, platforms)
for p in pythons:
cmd = ["conda", "build", recipe, "--python", p]
subprocess.check_call(cmd)
pkg = newest_file(build_path)
if binstar_user:
upload(pkg, binstar_user)
for plat in platforms:
cmd = ["conda", "convert", "-p", plat, pkg]
subprocess.check_call(cmd)
if binstar_user:
to_upload = newest_file(plat)
upload(to_upload, binstar_user)
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("build_dir")
p.add_argument("--py", action="append", default=[])
p.add_argument("--plat", action="append", default=[])
p.add_argument("-u", "--binstar-user", help="binstar user")
args = p.parse_args()
build_dir = p.add_argument("build_dir")
<|fim▁hole|> python build.py /opt/anaconda/conda-bld/linux-64 --py 27 --py 34 --plat osx-64 --plat win-64 -u hugo
"""<|fim▁end|> | build("conda.recipe", args.build_dir, args.py, args.plat, args.binstar_user)
#build("../into/conda.recipe", args.build_dir, args.py, args.plat, args.binstar_user)
""" |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import urllib.parse
import sys
from ccs import core
from ccs import constants
from . import response
def ticker():
s = __name__.split(".")[1]
r = sys._getframe().f_code.co_name
# complete request
cr = core.request(s, r)
return core.get(core.hostname(s), cr, core.header(s), core.compression(s), core.timeout(s))
def trades():
s = __name__.split(".")[1]
r = sys._getframe().f_code.co_name
# complete request
cr = core.request(s, r)
return core.get(core.hostname(s), cr, core.header(s), core.compression(s), core.timeout(s))
# nejaky problem s kodovanim
# def trades_chart():
# s = __name__.split(".")[1]
# r = sys._getframe().f_code.co_name
#
# # complete request
# cr = core.request(s, r)
#<|fim▁hole|>
def orderbook():
s = __name__.split(".")[1]
r = sys._getframe().f_code.co_name
# complete request
cr = core.request(s, r)
return core.get(core.hostname(s), cr, core.header(s), core.compression(s), core.timeout(s))<|fim▁end|> | # return core.get(core.hostname(s), cr, core.header(s), core.compression(s), core.timeout(s)) |
<|file_name|>rpc_signrawtransaction.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# Copyright (c) 2015-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test transaction signing using the signrawtransaction* RPCs."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_raises_rpc_error
class SignRawTransactionsTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
self.extra_args = [["-deprecatedrpc=signrawtransaction"]]
def successful_signing_test(self):
"""Create and sign a valid raw transaction with one input.
Expected results:
1) The transaction has a complete set of signatures
2) No script verification error occurred"""
privKeys = ['cUeKHd5orzT3mz8P9pxyREHfsWtVfgsfDjiZZBcjUBAaGk1BTj7N', 'cVKpPfVKSJxKqVpE9awvXNWuLHCa5j5tiE7K6zbUSptFpTEtiFrA']
inputs = [
# Valid pay-to-pubkey scripts
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0,
'scriptPubKey': '76a91460baa0f494b38ce3c940dea67f3804dc52d1fb9488ac'},
{'txid': '83a4f6a6b73660e13ee6cb3c6063fa3759c50c9b7521d0536022961898f4fb02', 'vout': 0,
'scriptPubKey': '76a914669b857c03a5ed269d5d85a1ffac9ed5d663072788ac'},
]
outputs = {'mpLQjfK79b7CCV4VMJWEWAj5Mpx8Up5zxB': 0.1}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
rawTxSigned = self.nodes[0].signrawtransactionwithkey(rawTx, privKeys, inputs)
# 1) The transaction has a complete set of signatures
assert rawTxSigned['complete']
# 2) No script verification error occurred
assert 'errors' not in rawTxSigned
# Perform the same test on signrawtransaction
rawTxSigned2 = self.nodes[0].signrawtransaction(rawTx, inputs, privKeys)
assert_equal(rawTxSigned, rawTxSigned2)
def script_verification_error_test(self):
"""Create and sign a raw transaction with valid (vin 0), invalid (vin 1) and one missing (vin 2) input script.
Expected results:
3) The transaction has no complete set of signatures
4) Two script verification errors occurred
5) Script verification errors have certain properties ("txid", "vout", "scriptSig", "sequence", "error")
6) The verification errors refer to the invalid (vin 1) and missing input (vin 2)"""
privKeys = ['cUeKHd5orzT3mz8P9pxyREHfsWtVfgsfDjiZZBcjUBAaGk1BTj7N']
inputs = [
# Valid pay-to-pubkey script
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0},
# Invalid script
{'txid': '5b8673686910442c644b1f4993d8f7753c7c8fcb5c87ee40d56eaeef25204547', 'vout': 7},
# Missing scriptPubKey
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 1},
]
scripts = [
# Valid pay-to-pubkey script
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0,
'scriptPubKey': '76a91460baa0f494b38ce3c940dea67f3804dc52d1fb9488ac'},
# Invalid script
{'txid': '5b8673686910442c644b1f4993d8f7753c7c8fcb5c87ee40d56eaeef25204547', 'vout': 7,
'scriptPubKey': 'badbadbadbad'}
]
outputs = {'mpLQjfK79b7CCV4VMJWEWAj5Mpx8Up5zxB': 0.1}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
<|fim▁hole|> # Make sure decoderawtransaction is at least marginally sane
decodedRawTx = self.nodes[0].decoderawtransaction(rawTx)
for i, inp in enumerate(inputs):
assert_equal(decodedRawTx["vin"][i]["txid"], inp["txid"])
assert_equal(decodedRawTx["vin"][i]["vout"], inp["vout"])
# Make sure decoderawtransaction throws if there is extra data
assert_raises_rpc_error(-22, "TX decode failed", self.nodes[0].decoderawtransaction, rawTx + "00")
rawTxSigned = self.nodes[0].signrawtransactionwithkey(rawTx, privKeys, scripts)
# 3) The transaction has no complete set of signatures
assert not rawTxSigned['complete']
# 4) Two script verification errors occurred
assert 'errors' in rawTxSigned
assert_equal(len(rawTxSigned['errors']), 2)
# 5) Script verification errors have certain properties
assert 'txid' in rawTxSigned['errors'][0]
assert 'vout' in rawTxSigned['errors'][0]
assert 'witness' in rawTxSigned['errors'][0]
assert 'scriptSig' in rawTxSigned['errors'][0]
assert 'sequence' in rawTxSigned['errors'][0]
assert 'error' in rawTxSigned['errors'][0]
# 6) The verification errors refer to the invalid (vin 1) and missing input (vin 2)
assert_equal(rawTxSigned['errors'][0]['txid'], inputs[1]['txid'])
assert_equal(rawTxSigned['errors'][0]['vout'], inputs[1]['vout'])
assert_equal(rawTxSigned['errors'][1]['txid'], inputs[2]['txid'])
assert_equal(rawTxSigned['errors'][1]['vout'], inputs[2]['vout'])
assert not rawTxSigned['errors'][0]['witness']
# Perform same test with signrawtransaction
rawTxSigned2 = self.nodes[0].signrawtransaction(rawTx, scripts, privKeys)
assert_equal(rawTxSigned, rawTxSigned2)
# Now test signing failure for transaction with input witnesses
p2wpkh_raw_tx = "01000000000102fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f00000000494830450221008b9d1dc26ba6a9cb62127b02742fa9d754cd3bebf337f7a55d114c8e5cdd30be022040529b194ba3f9281a99f2b1c0a19c0489bc22ede944ccf4ecbab4cc618ef3ed01eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac000247304402203609e17b84f6a7d30c80bfa610b5b4542f32a8a0d5447a12fb1366d7f01cc44a0220573a954c4518331561406f90300e8f3358f51928d43c212a8caed02de67eebee0121025476c2e83188368da1ff3e292e7acafcdb3566bb0ad253f62fc70f07aeee635711000000"
rawTxSigned = self.nodes[0].signrawtransactionwithwallet(p2wpkh_raw_tx)
# 7) The transaction has no complete set of signatures
assert not rawTxSigned['complete']
# 8) Two script verification errors occurred
assert 'errors' in rawTxSigned
assert_equal(len(rawTxSigned['errors']), 2)
# 9) Script verification errors have certain properties
assert 'txid' in rawTxSigned['errors'][0]
assert 'vout' in rawTxSigned['errors'][0]
assert 'witness' in rawTxSigned['errors'][0]
assert 'scriptSig' in rawTxSigned['errors'][0]
assert 'sequence' in rawTxSigned['errors'][0]
assert 'error' in rawTxSigned['errors'][0]
# Non-empty witness checked here
assert_equal(rawTxSigned['errors'][1]['witness'], ["304402203609e17b84f6a7d30c80bfa610b5b4542f32a8a0d5447a12fb1366d7f01cc44a0220573a954c4518331561406f90300e8f3358f51928d43c212a8caed02de67eebee01", "025476c2e83188368da1ff3e292e7acafcdb3566bb0ad253f62fc70f07aeee6357"])
assert not rawTxSigned['errors'][0]['witness']
# Perform same test with signrawtransaction
rawTxSigned2 = self.nodes[0].signrawtransaction(p2wpkh_raw_tx)
assert_equal(rawTxSigned, rawTxSigned2)
def run_test(self):
self.successful_signing_test()
self.script_verification_error_test()
if __name__ == '__main__':
SignRawTransactionsTest().main()<|fim▁end|> | |
<|file_name|>store_kube_token.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import base64
from cloudify.state import ctx_parameters as inputs
from cloudify.manager import get_rest_client
client = get_rest_client()
client.secrets.create(
'kubernetes_token',
base64.b64decode(inputs['kube_token']),
update_if_exists=True)<|fim▁end|> | |
<|file_name|>126 Word Ladder II.py<|end_file_name|><|fim▁begin|>'''
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
Note:
All words have the same length.
All words contain only lowercase alphabetic characters.
'''
class Solution(object):
def findLadders(self, beginWord, endWord, wordlist):
"""
:type beginWord: str
:type endWord: str
:type wordlist: Set[str]
:rtype: List[List[int]]
"""
def bfs(front_level, end_level, is_forward, word_set, path_dic):
if len(front_level) == 0:
return False
if len(front_level) > len(end_level):
return bfs(end_level, front_level, not is_forward, word_set, path_dic)
for word in (front_level | end_level):
word_set.discard(word)
next_level = set()
done = False
while front_level:
word = front_level.pop()
<|fim▁hole|> done = True
add_path(word, new_word, is_forward, path_dic)
else:
if new_word in word_set:
next_level.add(new_word)
add_path(word, new_word, is_forward, path_dic)
return done or bfs(next_level, end_level, is_forward, word_set, path_dic)
def add_path(word, new_word, is_forward, path_dic):
if is_forward:
path_dic[word] = path_dic.get(word, []) + [new_word]
else:
path_dic[new_word] = path_dic.get(new_word, []) + [word]
def construct_path(word, end_word, path_dic, path, paths):
if word == end_word:
paths.append(path)
return
if word in path_dic:
for item in path_dic[word]:
construct_path(item, end_word, path_dic, path + [item], paths)
front_level, end_level = {beginWord}, {endWord}
path_dic = {}
bfs(front_level, end_level, True, wordlist, path_dic)
path, paths = [beginWord], []
construct_path(beginWord, endWord, path_dic, path, paths)
return paths
if __name__ == "__main__":
assert Solution().findLadders("hit", "cog", {"hot", "dot", "dog", "lot", "log"}) == [
["hit", "hot", "dot", "dog", "cog"],
["hit", "hot", "lot", "log", "cog"]
]<|fim▁end|> | for c in 'abcdefghijklmnopqrstuvwxyz':
for i in range(len(word)):
new_word = word[:i] + c + word[i + 1:]
if new_word in end_level:
|
<|file_name|>viewer-options-spec.js<|end_file_name|><|fim▁begin|>/*
* Copyright 2015 Trim-marks Inc.
*
* This file is part of Vivliostyle UI.
*
* Vivliostyle UI is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Vivliostyle UI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Vivliostyle UI. If not, see <http://www.gnu.org/licenses/>.
*/
import vivliostyle from "../../../src/vivliostyle";
import PageViewMode from "../../../src/models/page-view-mode";
import ViewerOptions from "../../../src/models/viewer-options";
import ZoomOptions from "../../../src/models/zoom-options";
import urlParameters from "../../../src/stores/url-parameters";
import vivliostyleMock from "../../mock/models/vivliostyle";
describe("ViewerOptions", function () {
let history, location;
vivliostyleMock();
beforeEach(function () {
history = urlParameters.history;
urlParameters.history = {};
location = urlParameters.location;
});
afterEach(function () {
urlParameters.history = history;
urlParameters.location = location;
});
describe("constructor", function () {
it("retrieves parameters from URL", function () {
urlParameters.location = { href: "http://example.com#spread=true" };
let options = new ViewerOptions();
expect(options.pageViewMode()).toEqual(PageViewMode.SPREAD);
urlParameters.location = { href: "http://example.com#spread=false" };
options = new ViewerOptions();
expect(options.pageViewMode()).toBe(PageViewMode.SINGLE_PAGE);
urlParameters.location = { href: "http://example.com#spread=auto" };
options = new ViewerOptions();
expect(options.pageViewMode()).toBe(PageViewMode.AUTO_SPREAD);
});
it("copies parameters from the argument", function () {
const other = new ViewerOptions();
other.pageViewMode(PageViewMode.SINGLE_PAGE);
other.fontSize(20);
other.zoom(ZoomOptions.createFromZoomFactor(1.2));
const options = new ViewerOptions(other);
expect(options.pageViewMode()).toBe(PageViewMode.SINGLE_PAGE);
expect(options.fontSize()).toBe(20);
expect(options.zoom().zoom).toBe(1.2);
expect(options.zoom().fitToScreen).toBe(false);
});
});
it("write spread option back to URL when update if it is constructed with no argument", function () {
urlParameters.location = { href: "http://example.com#spread=true" };
let options = new ViewerOptions();
options.pageViewMode(PageViewMode.SINGLE_PAGE);
expect(urlParameters.location.href).toBe("http://example.com#spread=false");
options.pageViewMode(PageViewMode.SPREAD);
expect(urlParameters.location.href).toBe("http://example.com#spread=true");
// options.pageViewMode(PageViewMode.AUTO_SPREAD);
// expect(urlParameters.location.href).toBe("http://example.com#spread=auto");
// not write back if it is constructed with another ViewerOptions
const other = new ViewerOptions();
other.pageViewMode(PageViewMode.SINGLE_PAGE);
other.fontSize(20);
other.zoom(ZoomOptions.createFromZoomFactor(1.2));
options = new ViewerOptions(other);
options.pageViewMode(PageViewMode.SPREAD);
expect(urlParameters.location.href).toBe("http://example.com#spread=false");
});
describe("copyFrom", function () {
it("copies parameters from the argument to itself", function () {
const options = new ViewerOptions();
options.pageViewMode(PageViewMode.SPREAD);
options.fontSize(10);
options.zoom(ZoomOptions.createFromZoomFactor(1.4));
const other = new ViewerOptions();
other.pageViewMode(PageViewMode.SINGLE_PAGE);<|fim▁hole|>
expect(options.pageViewMode()).toBe(PageViewMode.SINGLE_PAGE);
expect(options.fontSize()).toBe(20);
expect(options.zoom().zoom).toBe(1.2);
expect(options.zoom().fitToScreen).toBe(false);
});
});
describe("toObject", function () {
it("converts parameters to an object", function () {
const options = new ViewerOptions();
options.pageViewMode(PageViewMode.SPREAD);
options.fontSize(20);
options.zoom(ZoomOptions.createFromZoomFactor(1.2));
expect(options.toObject()).toEqual({
fontSize: 20,
pageViewMode: vivliostyle.viewer.PageViewMode.SPREAD,
zoom: 1.2,
fitToScreen: false,
renderAllPages: true,
});
});
});
});<|fim▁end|> | other.fontSize(20);
other.zoom(ZoomOptions.createFromZoomFactor(1.2));
options.copyFrom(other); |
<|file_name|>api.py<|end_file_name|><|fim▁begin|># Copyright © 2019 José Alberto Orejuela García (josealberto4444)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License<|fim▁hole|>import json
import os.path
import re
import requests
import youtube_dl
def read_config(section, key):
config = configparser.ConfigParser()
config.read('config.cfg')
return config[section][key]
def is_invalid(date):
try:
datetime.datetime.strptime(date, '%Y-%m-%d')
except ValueError:
return "Incorrect date format, should be YYYY-MM-DD."
else:
return False
class Apod:
def __init__(self, *args):
self.api_key = read_config('NASA_API', 'api_key')
if args:
self.date = args[0]
else:
self.date = ''
self.date = self.ask_api()['date']
self.filename = 'data/' + self.date
self.error = False
self.consult()
if not self.error:
self.title = self.api_response['title']
self.media_type = self.api_response['media_type']
if self.media_type == 'image':
self.hdlink = self.api_response['hdurl']
self.link = self.api_response['url']
self.explanation()
def ask_api(self):
baseurl = 'https://api.nasa.gov/planetary/apod'
payload = {'api_key': self.api_key, 'date': self.date}
r = requests.get(baseurl, params=payload)
return r.json()
def consult(self):
if os.path.exists('data/' + self.date + '.json'):
with open(self.filename + '.json', 'rt') as f:
self.api_response = json.load(f)
else:
self.api_response = self.ask_api()
if 'code' in self.api_response:
if self.api_response['code'] == 400:
self.error = self.api_response['msg']
else:
self.error = self.api_response['code'] + ': ' + self.api_response['msg']
else:
with open(self.filename + '.json', 'wt') as f:
json.dump(self.api_response, f)
def get_userpage(self):
shortdate = self.date.replace('-', '')
shortdate = shortdate[2:]
url = 'https://apod.nasa.gov/apod/ap' + shortdate + '.html'
payload = {}
r = requests.get(url, params=payload)
return r.text
def scrap_explanation(self, pagesource):
re_explanation = re.compile("Explanation: </b>(.*?)<p>", flags=re.DOTALL) # Compile regex for extracting explanation.
explanation = re_explanation.search(pagesource).groups()[0] # Extract explanation.
explanation = explanation.replace('/\n', '/') # Fix split URLs along several lines.
explanation = explanation.replace('\n>', '>') # Fix split HTML tags.
explanation = explanation.replace('<a/>', '</a>') # Fix typos (they seem to write the HTML by hand, yes).
explanation = explanation.replace('\n', ' ') # Delete all newlines.
explanation = re.sub('\s+', ' ', explanation).strip() # Substitute repeated spaces and strips the ones at the beginning and the end of the string.
explanation = re.sub(r'<a([^>]*)href=["\'](?!http)([^"\']*)["\']([^>]*)>', r'<a\1href="https://apod.nasa.gov/apod/\2"\3>', explanation) # Change relative paths to absolute.
return explanation
def save_explanation(self, explanation):
with open(self.filename + '.html', 'wt') as f:
f.write(explanation)
def explanation(self):
filename = self.filename + '.html'
if os.path.exists(filename):
with open(filename, 'rt') as f:
self.explanation = f.read()
self.html = True
else:
try:
userpage = self.get_userpage()
explanation = self.scrap_explanation(userpage)
except:
explanation = self.api_response['explanation']
self.html = False
else:
self.save_explanation(explanation)
self.html = True
self.explanation = explanation
# TO-DO: Check if already downloaded first
# def download_media():
# if self.media_type == 'image':
# link = self.api_response['hdurl']
# r = requests.get(link)
# extension = os.path.splitext(link)[1]
# filename = self.filename + extension
# with open(filename, 'wb') as f:
# for chunk in r.iter_content(chunk_size=128):
# f.write(chunk)
# elif self.media_type == 'video':
# filename = self.filename + '.%(ext)s'
# ydl_opts = {'outtmpl': filename, 'quiet': True}
# with youtube_dl.YoutubeDL(ydl_opts) as ydl:
# ydl.download([api_response['url']])<|fim▁end|> | # along with this program. If not, see <http://www.gnu.org/licenses/>.
import configparser
import datetime |
<|file_name|>consoleauth.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016 Intel, Inc.
# Copyright (c) 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at<|fim▁hole|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_config import cfg
consoleauth_topic_opt = cfg.StrOpt('consoleauth_topic',
default='consoleauth',
help='The topic console auth proxy nodes listen on')
console_token_ttl = cfg.IntOpt('console_token_ttl',
default=600,
help='How many seconds before deleting tokens')
CONSOLEAUTH_OPTS = [consoleauth_topic_opt, console_token_ttl]
def register_opts(conf):
conf.register_opts(CONSOLEAUTH_OPTS)
def list_opts():
return {'DEFAULT': CONSOLEAUTH_OPTS}<|fim▁end|> | |
<|file_name|>max_difference.py<|end_file_name|><|fim▁begin|>import unittest
"""
Given a binary tree, we need to find maximum value we can get by subtracting
value of node B from value of node A, where A and B are two nodes of the binary tree
and A is ancestor of B. Expected time complexity is O(n).
"""
<|fim▁hole|>class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def add_left_child(self, data):
self.left = Node(data)
return self.left
def add_right_child(self, data):
self.right = Node(data)
return self.right
class BinaryTree:
def __init__(self, root):
self.root = root
self.max_difference = -float('inf')
def max_difference_node_and_ancestor(self):
self.max_min_in_subtree(self.root)
return self.max_difference
def max_min_in_subtree(self, node):
if node is None:
return float('inf'), -float('inf')
left_min, left_max = self.max_min_in_subtree(node.left)
right_min, right_max = self.max_min_in_subtree(node.right)
if node.left:
self.max_difference = max(self.max_difference, node.data - left_min, node.data - left_max)
if node.right:
self.max_difference = max(self.max_difference, node.data - right_min, node.data - right_max)
return min(node.data, left_min, right_min), max(node.data, left_max, right_max)
class TestBinaryTree(unittest.TestCase):
def test_max_difference(self):
root = Node(8)
root.left = Node(3)
root.left.left = Node(1)
root.left.right = Node(6)
root.left.right.left = Node(4)
root.left.right.right = Node(7)
root.right = Node(10)
root.right.right = Node(14)
root.right.right.left = Node(13)
binary_tree = BinaryTree(root)
self.assertEqual(binary_tree.max_difference_node_and_ancestor(), 7)<|fim▁end|> | |
<|file_name|>util.js<|end_file_name|><|fim▁begin|>// Utility functions<|fim▁hole|>};
String.prototype.contains = function(it) {
return this.indexOf(it) != -1;
};
if (!String.prototype.trim) {
String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); };
String.prototype.ltrim = function () { return this.replace(/^\s+/, ''); };
String.prototype.rtrim = function () { return this.replace(/\s+$/, ''); };
String.prototype.fulltrim = function () { return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, '').replace(/\s+/g, ' '); };
}
function colorToHex(color) {
if (color.substr(0, 1) === '#') {
return color;
}
var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);
var red = parseInt(digits[2]);
var green = parseInt(digits[3]);
var blue = parseInt(digits[4]);
var rgb = blue | (green << 8) | (red << 16);
return digits[1] + '#' + rgb.toString(16);
};<|fim▁end|> |
String.prototype.endsWith = function (suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1; |
<|file_name|>postcodes.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
crate_anon/preprocess/postcodes.py
===============================================================================
Copyright (C) 2015-2021 Rudolf Cardinal (rudolf@pobox.com).
This file is part of CRATE.
CRATE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CRATE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with CRATE. If not, see <https://www.gnu.org/licenses/>.
===============================================================================
**Fetches UK postcode information and creates a database.**
Code-Point Open, CSV, GB
- https://www.ordnancesurvey.co.uk/business-and-government/products/opendata-products.html
- https://www.ordnancesurvey.co.uk/business-and-government/products/code-point-open.html
- https://www.ordnancesurvey.co.uk/opendatadownload/products.html
- http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/
Office for National Statistics Postcode Database (ONSPD):
- https://geoportal.statistics.gov.uk/geoportal/catalog/content/filelist.page
- e.g. ONSPD_MAY_2016_csv.zip
- http://www.ons.gov.uk/methodology/geography/licences
Background:
- OA = Output Area
- smallest: >=40 households, >=100 people
- 181,408 OAs in England & Wales
- LSOA = Lower Layer Super Output Area
- 34,753 LSOAs in England & Wales
- MSOA = Middle Layer Super Output Area
- 7,201 MSOAs in England & Wales
- WZ = Workplace Zone
- https://www.ons.gov.uk/methodology/geography/ukgeographies/censusgeography#workplace-zone-wz
- https://www.ons.gov.uk/methodology/geography/ukgeographies/censusgeography#output-area-oa
""" # noqa
from abc import ABC, ABCMeta, abstractmethod
import argparse
import csv
import datetime
import logging
import os
import sys
# import textwrap
from typing import (Any, Dict, Generator, Iterable, List, Optional, TextIO,
Tuple)
from cardinal_pythonlib.argparse_func import RawDescriptionArgumentDefaultsHelpFormatter # noqa
from cardinal_pythonlib.dicts import rename_key
from cardinal_pythonlib.extract_text import wordwrap
from cardinal_pythonlib.fileops import find_first
from cardinal_pythonlib.logs import configure_logger_for_colour
import openpyxl
from openpyxl.cell.cell import Cell
import prettytable
from sqlalchemy import (
Column,
create_engine,
Date,
Integer,
Numeric,
String,
)
from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.session import Session
from sqlalchemy.sql.schema import MetaData, Table
# import xlrd
from crate_anon.anonymise.constants import CHARSET, TABLE_KWARGS
from crate_anon.common.constants import EnvVar
log = logging.getLogger(__name__)
metadata = MetaData()
if EnvVar.GENERATING_CRATE_DOCS in os.environ:
DEFAULT_ONSPD_DIR = "/path/to/unzipped/ONSPD/download"
else:
DEFAULT_ONSPD_DIR = os.path.join(
os.path.expanduser("~"), "dev", "ons", "ONSPD_Nov2019"
)
DEFAULT_REPORT_EVERY = 1000
DEFAULT_COMMIT_EVERY = 10000
YEAR_MONTH_FMT = "%Y%m"
CODE_LEN = 9 # many ONSPD codes have this length
NAME_LEN = 80 # seems about right; a bit more than the length of many
# =============================================================================
# Ancillary functions
# =============================================================================
def convert_date(d: Dict[str, Any], key: str) -> None:
"""
Modifies ``d[key]``, if it exists, to convert it to a
:class:`datetime.datetime` or ``None``.
Args:
d: dictionary
key: key
"""
if key not in d:
return
value = d[key]
if value:
d[key] = datetime.datetime.strptime(value,
YEAR_MONTH_FMT)
else:
d[key] = None
def convert_int(d: Dict[str, Any], key: str) -> None:
"""
Modifies ``d[key]``, if it exists, to convert it to an int or ``None``.
Args:
d: dictionary
key: key
"""
if key not in d:
return
value = d[key]
if value is None or (isinstance(value, str) and not value.strip()):
d[key] = None
else:
d[key] = int(value)
def convert_float(d: Dict[str, Any], key: str) -> None:
"""
Modifies ``d[key]``, if it exists, to convert it to a float or ``None``.
Args:
d: dictionary
key: key
"""
if key not in d:
return
value = d[key]
if value is None or (isinstance(value, str) and not value.strip()):
d[key] = None
else:
d[key] = float(value)
def values_from_row(row: Iterable[Cell]) -> List[Any]:
"""
Returns all values from a spreadsheet row.
For the ``openpyxl`` interface to XLSX files.
"""
values = [] # type: List[Any]
for cell in row:
values.append(cell.value)
return values
def commit_and_announce(session: Session) -> None:
"""
Commits an SQLAlchemy ORM session and says so.
"""
log.info("COMMIT")
session.commit()
# =============================================================================
# Extend SQLAlchemy Base class
# =============================================================================
class ExtendedBase(object):
"""
Mixin to extend the SQLAlchemy ORM Base class by specifying table creation
parameters (specifically, for MySQL, to set the character set and
MySQL engine).
Only used in the creation of Base; everything else then inherits from Base
as usual.
See
http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/mixins.html
"""
__table_args__ = TABLE_KWARGS
Base = declarative_base(metadata=metadata, cls=ExtendedBase)
# =============================================================================
# Go to considerable faff to provide type hints for lookup classes
# =============================================================================
class GenericLookupClassMeta(DeclarativeMeta, ABCMeta):
"""
To avoid: "TypeError: metaclass conflict: the metaclass of a derived class
must be a (non-strict) subclass of the metaclasses of all its bases".
We want a class that's a subclass of Base and ABC. So we can work out their
metaclasses:
.. code-block:: python
from abc import ABC
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql.schema import MetaData
class ExtendedBase(object):
__table_args__ = {'mysql_charset': 'utf8', 'mysql_engine': 'InnoDB'}
metadata = MetaData()
Base = declarative_base(metadata=metadata, cls=ExtendedBase)
type(Base) # metaclass of Base: <class: 'sqlalchemy.ext.declarative.api.DeclarativeMeta'>
type(ABC) # metaclass of ABC: <class 'abc.ABCMeta'>
and thus define this class to inherit from those two metaclasses, so it can
be the metaclass we want.
""" # noqa
pass
class GenericLookupClassType(Base, ABC, metaclass=GenericLookupClassMeta):
"""
Type hint for our various simple lookup classes.
Alternatives that don't work: Type[Base], Type[BASETYPE], type(Base).
"""
__abstract__ = True # abstract as seen by SQLAlchemy
# ... avoids SQLAlchemy error: "sqlalchemy.exc.InvalidRequestError: Class
# <class '__main__.GenericLookupClassType'> does not have a __table__ or
# __tablename__ specified and does not inherit from an existing
# table-mapped class."
@abstractmethod
def __call__(self, *args, **kwargs) -> None:
# Represents __init__... not sure I have this quite right, but it
# appeases PyCharm; see populate_generic_lookup_table()
pass
@property
@abstractmethod
def __table__(self) -> Table:
pass
@property
@abstractmethod
def __tablename__(self) -> str:
pass
@property
@abstractmethod
def __filename__(self) -> str:
pass
# =============================================================================
# Models: all postcodes
# =============================================================================
class Postcode(Base):
"""
Maps individual postcodes to... lots of things. Large table.
"""
__tablename__ = 'postcode'
pcd_nospace = Column(
String(8), primary_key=True,
comment="Postcode (no spaces)")
# ... not in original, but simplifies indexing
pcd = Column(
String(7), index=True, unique=True,
comment="Unit postcode (7 characters): 2-4 char outward code, "
"left-aligned; 3-char inward code, right-aligned")
pcd2 = Column(
String(8), index=True, unique=True,
comment="Unit postcode (8 characters): 2-4 char outward code, "
"left-aligned; space; 3-char inward code, right-aligned")
pcds = Column(
String(8), index=True, unique=True,
comment="Unit postcode (variable length): 2-4 char outward "
"code; space; 3-char inward code")
dointr = Column(
Date,
comment="Date of introduction (original format YYYYMM)")
doterm = Column(
Date,
comment="Date of termination (original format YYYYMM) or NULL")
oscty = Column(
String(CODE_LEN),
comment="County code [FK to county_england_2010.county_code]")
oslaua = Column(
String(CODE_LEN),
comment="Local authority district (LUA), unitary authority "
"(UA), metropolitan district (MD), London borough (LB),"
" council area (CA), or district council area (DCA) "
"[FK to lad_local_authority_district_2019.lad_code]")
osward = Column(
String(CODE_LEN),
comment="Electoral ward/division "
"[FK e.g. to electoral_ward_2019.ward_code]")
usertype = Column(
Integer,
comment="Small (0) or large (1) postcode user")
oseast1m = Column(
Integer,
comment="National grid reference Easting, 1m resolution")
osnrth1m = Column(
Integer,
comment="National grid reference Northing, 1m resolution")
osgrdind = Column(
Integer,
comment="Grid reference positional quality indicator")
oshlthau = Column(
String(CODE_LEN),
comment="Former (up to 2013) Strategic Health Authority (SHA), Local "
"Health Board (LHB), Health Board (HB), Health Authority "
"(HA), or Health & Social Care Board (HSCB) [FK to one of: "
"sha_strategic_health_authority_england_2010.sha_code or "
"sha_strategic_health_authority_england_2004.sha_code; "
"hb_health_board_n_ireland_2003.hb_code; "
"hb_health_board_scotland_2014.hb_code; "
"hscb_health_social_care_board_n_ireland_2010.hscb_code; "
"lhb_local_health_board_wales_2014.lhb_code or "
"lhb_local_health_board_wales_2006.lhb_code]")
ctry = Column(
String(CODE_LEN),
comment="Country of the UK [England, Scotland, Wales, "
"Northern Ireland] [FK to country_2012.country_code]")
streg = Column(
Integer,
comment="Standard (Statistical) Region (SSR) [FK to "
"ssr_standard_statistical_region_1995."
"ssr_code]")
pcon = Column(
String(CODE_LEN),
comment="Westminster parliamentary constituency [FK to "
"pcon_westminster_parliamentary_constituency_2014."
"pcon_code]")
eer = Column(
String(CODE_LEN),
comment="European Electoral Region (EER) [FK to "
"eer_european_electoral_region_2010.eer_code]")
teclec = Column(
String(CODE_LEN),
comment="Local Learning and Skills Council (LLSC) / Dept. of "
"Children, Education, Lifelong Learning and Skills (DCELLS) / "
"Enterprise Region (ER) [PROBABLY FK to one of: "
"dcells_dept_children_wales_2010.dcells_code; "
"er_enterprise_region_scotland_2010.er_code; "
"llsc_local_learning_skills_council_england_2010.llsc_code]")
ttwa = Column(
String(CODE_LEN),
comment="Travel to Work Area (TTWA) [FK to "
"ttwa_travel_to_work_area_2011.ttwa_code]")
pct = Column(
String(CODE_LEN),
comment="Primary Care Trust (PCT) / Care Trust / "
"Care Trust Plus (CT) / Local Health Board (LHB) / "
"Community Health Partnership (CHP) / "
"Local Commissioning Group (LCG) / "
"Primary Healthcare Directorate (PHD) [FK to one of: "
"pct_primary_care_trust_2019.pct_code; "
"chp_community_health_partnership_scotland_2012.chp_code; "
"lcg_local_commissioning_group_n_ireland_2010.lcg_code; "
"lhb_local_health_board_wales_2014.lhb_code]")
nuts = Column(
String(10),
comment="LAU2 areas [European Union spatial regions; Local "
"Adminstrative Unit, level 2] / Nomenclature of Units "
"for Territorial Statistics (NUTS) [FK to "
"lau_eu_local_administrative_unit_2019.lau2_code]")
statsward = Column(
String(6),
comment="2005 'statistical' ward [?FK to "
"electoral_ward_2005.ward_code]")
oa01 = Column(
String(10),
comment="2001 Census Output Area (OA). (There are "
"about 222,000, so ~300 population?)")
casward = Column(
String(6),
comment="Census Area Statistics (CAS) ward [PROBABLY FK to "
"cas_ward_2003.cas_ward_code]")
park = Column(
String(CODE_LEN),
comment="National park [FK to "
"park_national_park_2016.park_code]")
lsoa01 = Column(
String(CODE_LEN),
comment="2001 Census Lower Layer Super Output Area (LSOA) [England & "
"Wales, ~1,500 population] / Data Zone (DZ) [Scotland] / "
"Super Output Area (SOA) [FK to one of: "
"lsoa_lower_layer_super_output_area_england_wales_2004.lsoa_code; " # noqa
"lsoa_lower_layer_super_output_area_n_ireland_2005.lsoa_code]")
msoa01 = Column(
String(CODE_LEN),
comment="2001 Census Middle Layer Super Output Area (MSOA) [England & "
"Wales, ~7,200 population] / "
"Intermediate Zone (IZ) [Scotland] [FK to one of: "
"msoa_middle_layer_super_output_area_england_wales_2004.msoa_code; " # noqa
"iz_intermediate_zone_scotland_2005.iz_code]")
ur01ind = Column(
String(1),
comment="2001 Census urban/rural indicator [numeric in "
"England/Wales/Scotland; letters in N. Ireland]")
oac01 = Column(
String(3),
comment="2001 Census Output Area classification (OAC)"
"[POSSIBLY FK to output_area_classification_2011."
"subgroup_code]")
oa11 = Column(
String(CODE_LEN),
comment="2011 Census Output Area (OA) [England, Wales, Scotland;"
" ~100-625 population] / Small Area (SA) [N. Ireland]")
lsoa11 = Column(
String(CODE_LEN),
comment="2011 Census Lower Layer Super Output Area (LSOA) [England & "
"Wales, ~1,500 population] / Data Zone (DZ) [Scotland] / "
"Super Output Area (SOA) [N. Ireland] [FK to one of: "
"lsoa_lower_layer_super_output_area_2011.lsoa_code; " # noqa
" (defunct) dz_datazone_scotland_2011.dz_code]")
msoa11 = Column(
String(CODE_LEN),
comment="2011 Census Middle Layer Super Output Area (MSOA) [England & "
"Wales, ~7,200 population] / "
"Intermediate Zone (IZ) [Scotland] [FK to one of: "
"msoa_middle_layer_super_output_area_2011.msoa_code; " # noqa
"iz_intermediate_zone_scotland_2011.iz_code]")
parish = Column(
String(CODE_LEN),
comment="Parish/community [FK to "
"parish_ncp_england_wales_2018.parish_code]")
wz11 = Column(
String(CODE_LEN),
comment="2011 Census Workplace Zone (WZ)")
ccg = Column(
String(CODE_LEN),
comment="Clinical Commissioning Group (CCG) / Local Health Board "
"(LHB) / Community Health Partnership (CHP) / Local "
"Commissioning Group (LCG) / Primary Healthcare Directorate "
"(PHD) [FK to one of: "
"ccg_clinical_commissioning_group_uk_2019."
"ccg_ons_code, lhb_local_health_board_wales_2014.lhb_code]")
bua11 = Column(
String(CODE_LEN),
comment="Built-up Area (BUA) [FK to "
"bua_built_up_area_uk_2013.bua_code]")
buasd11 = Column(
String(CODE_LEN),
comment="Built-up Area Sub-division (BUASD) [FK to "
"buasd_built_up_area_subdivision_uk_2013.buas_code]")
ru11ind = Column(
String(2),
comment="2011 Census rural-urban classification")
oac11 = Column(
String(3),
comment="2011 Census Output Area classification (OAC) [FK to "
"output_area_classification_2011.subgroup_code]")
lat = Column(
Numeric(precision=9, scale=6),
comment="Latitude (degrees, 6dp)")
long = Column(
Numeric(precision=9, scale=6),
comment="Longitude (degrees, 6dp)")
lep1 = Column(
String(CODE_LEN),
comment="Local Enterprise Partnership (LEP) - first instance [FK to "
"lep_local_enterprise_partnership_england_2017.lep1_code]")
lep2 = Column(
String(CODE_LEN),
comment="Local Enterprise Partnership (LEP) - second instance [FK to "
"lep_local_enterprise_partnership_england_2017.lep1_code]")
pfa = Column(
String(CODE_LEN),
comment="Police Force Area (PFA) [FK to "
"pfa_police_force_area_2015.pfa_code]")
imd = Column(
Integer,
comment="Index of Multiple Deprivation (IMD) [rank of LSOA/DZ, where "<|fim▁hole|> "1 is the most deprived, within each country] [FK to one of: "
"imd_index_multiple_deprivation_england_2015.imd_rank; "
"imd_index_multiple_deprivation_n_ireland_2010.imd_rank; "
"imd_index_multiple_deprivation_scotland_2012.imd_rank; "
"imd_index_multiple_deprivation_wales_2014.imd_rank]")
# New in Nov 2019 ONSPD, relative to 2016 ONSPD:
# ** Not yet implemented:
# calncv
# ced
# nhser
# rgn
# stp
def __init__(self, **kwargs: Any) -> None:
convert_date(kwargs, 'dointr')
convert_date(kwargs, 'doterm')
convert_int(kwargs, 'usertype')
convert_int(kwargs, 'oseast1m')
convert_int(kwargs, 'osnrth1m')
convert_int(kwargs, 'osgrdind')
convert_int(kwargs, 'streg')
convert_int(kwargs, 'edind')
convert_int(kwargs, 'imd')
kwargs['pcd_nospace'] = kwargs['pcd'].replace(" ", "")
super().__init__(**kwargs)
# =============================================================================
# Models: core lookup tables
# =============================================================================
class OAClassification(Base):
"""
Represents 2011 Census Output Area (OA) classification names/codes.
"""
__filename__ = "2011 Census Output Area Classification Names and Codes " \
"UK.xlsx"
__tablename__ = "output_area_classification_2011"
oac11 = Column(String(3), primary_key=True)
supergroup_code = Column(String(1))
supergroup_desc = Column(String(35))
group_code = Column(String(2))
group_desc = Column(String(40))
subgroup_code = Column(String(3))
subgroup_desc = Column(String(60))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'OAC11', 'oac11')
rename_key(kwargs, 'Supergroup', 'supergroup_desc')
rename_key(kwargs, 'Group', 'group_desc')
rename_key(kwargs, 'Subgroup', 'subgroup_desc')
kwargs['supergroup_code'] = kwargs['oac11'][0:1]
kwargs['group_code'] = kwargs['oac11'][0:2]
kwargs['subgroup_code'] = kwargs['oac11']
super().__init__(**kwargs)
class BUA(Base):
"""
Represents England & Wales 2013 build-up area (BUA) codes/names.
"""
__filename__ = "BUA_names and codes UK as at 12_13.xlsx"
__tablename__ = "bua_built_up_area_uk_2013"
bua_code = Column(String(CODE_LEN), primary_key=True)
bua_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'BUA13CD', 'bua_code')
rename_key(kwargs, 'BUA13NM', 'bua_name')
super().__init__(**kwargs)
class BUASD(Base):
"""
Represents built-up area subdivisions (BUASD) in England & Wales 2013.
"""
__filename__ = "BUASD_names and codes UK as at 12_13.xlsx"
__tablename__ = "buasd_built_up_area_subdivision_uk_2013"
buasd_code = Column(String(CODE_LEN), primary_key=True)
buasd_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'BUASD13CD', 'buasd_code')
rename_key(kwargs, 'BUASD13NM', 'buasd_name')
super().__init__(**kwargs)
class CASWard(Base):
"""
Represents censua area statistics (CAS) wards in the UK, 2003.
- https://www.ons.gov.uk/methodology/geography/ukgeographies/censusgeography#statistical-wards-cas-wards-and-st-wards
""" # noqa
__filename__ = "CAS ward names and codes UK as at 01_03.xlsx"
__tablename__ = "cas_ward_2003"
cas_ward_code = Column(String(CODE_LEN), primary_key=True)
cas_ward_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'WDCAS03CD', 'cas_ward_code')
rename_key(kwargs, 'WDCAS03NM', 'cas_ward_name')
super().__init__(**kwargs)
class CCG(Base):
"""
Represents clinical commissioning groups (CCGs), UK 2019.
"""
__filename__ = "CCG names and codes UK as at 04_19.xlsx"
__tablename__ = "ccg_clinical_commissioning_group_uk_2019"
ccg_ons_code = Column(String(CODE_LEN), primary_key=True)
ccg_ccg_code = Column(String(9))
ccg_name = Column(String(NAME_LEN))
ccg_name_welsh = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'CCG19CD', 'ccg_ons_code')
rename_key(kwargs, 'CCG19CDH', 'ccg_ccg_code')
rename_key(kwargs, 'CCG19NM', 'ccg_name')
rename_key(kwargs, 'CCG19NMW', 'ccg_name_welsh')
super().__init__(**kwargs)
class Country(Base):
"""
Represents UK countries, 2012.
This is not a long table.
"""
__filename__ = "Country names and codes UK as at 08_12.xlsx"
__tablename__ = "country_2012"
country_code = Column(String(CODE_LEN), primary_key=True)
country_code_old = Column(Integer) # ?
country_name = Column(String(NAME_LEN))
country_name_welsh = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'CTRY12CD', 'country_code')
rename_key(kwargs, 'CTRY12CDO', 'country_code_old')
rename_key(kwargs, 'CTRY12NM', 'country_name')
rename_key(kwargs, 'CTRY12NMW', 'country_name_welsh')
super().__init__(**kwargs)
class County2019(Base):
"""
Represents counties, UK 2019.
"""
__filename__ = "County names and codes UK as at 04_19.xlsx"
__tablename__ = "county_england_2010"
county_code = Column(String(CODE_LEN), primary_key=True)
county_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'CTY19CD', 'county_code')
rename_key(kwargs, 'CTY19NM', 'county_name')
super().__init__(**kwargs)
class EER(Base):
"""
Represents European electoral regions (EERs), UK 2010.
"""
__filename__ = "EER names and codes UK as at 12_10.xlsx"
__tablename__ = "eer_european_electoral_region_2010"
eer_code = Column(String(CODE_LEN), primary_key=True)
eer_code_old = Column(String(2)) # ?
eer_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'EER10CD', 'eer_code')
rename_key(kwargs, 'EER10CDO', 'eer_code_old')
rename_key(kwargs, 'EER10NM', 'eer_name')
super().__init__(**kwargs)
class IMDLookupEN(Base):
"""
Represents the Index of Multiple Deprivation (IMD), England 2015.
**This is quite an important one to us!** IMDs are mapped to LSOAs; see
e.g. :class:`LSOAEW2011`.
"""
__filename__ = "IMD lookup EN as at 12_15.xlsx"
__tablename__ = "imd_index_multiple_deprivation_england_2015"
lsoa_code = Column(String(CODE_LEN), primary_key=True)
lsoa_name = Column(String(NAME_LEN))
imd_rank = Column(Integer)
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'LSOA11CD', 'lsoa_code')
rename_key(kwargs, 'LSOA11NM', 'lsoa_name')
rename_key(kwargs, 'IMD15', 'imd_rank')
convert_int(kwargs, 'imd_rank')
super().__init__(**kwargs)
class IMDLookupSC(Base):
"""
Represents the Index of Multiple Deprivation (IMD), Scotland 2016.
"""
__filename__ = "IMD lookup SC as at 12_16.xlsx"
__tablename__ = "imd_index_multiple_deprivation_scotland_2016"
dz_code = Column(String(CODE_LEN), primary_key=True)
imd_rank = Column(Integer)
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'DZ11CD', 'dz_code')
rename_key(kwargs, 'IMD16', 'imd_rank')
convert_int(kwargs, 'imd_rank')
super().__init__(**kwargs)
class IMDLookupWA(Base):
"""
Represents the Index of Multiple Deprivation (IMD), Wales 2014.
"""
__filename__ = "IMD lookup WA as at 12_14.xlsx"
__tablename__ = "imd_index_multiple_deprivation_wales_2014"
lsoa_code = Column(String(CODE_LEN), primary_key=True)
lsoa_name = Column(String(NAME_LEN))
imd_rank = Column(Integer)
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'LSOA11CD', 'lsoa_code')
rename_key(kwargs, 'LSOA11NM', 'lsoa_name')
rename_key(kwargs, 'IMD14', 'imd_rank')
convert_int(kwargs, 'imd_rank')
super().__init__(**kwargs)
class LAU(Base):
"""
Represents European Union Local Administrative Units (LAUs), UK 2019.
"""
__filename__ = "LAU2 names and codes UK as at 12_19 (NUTS).xlsx"
__tablename__ = "lau_eu_local_administrative_unit_2019"
lau2_code = Column(String(10), primary_key=True)
lau2_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'LAU219CD', 'lau2_code')
rename_key(kwargs, 'LAU219NM', 'lau2_name')
super().__init__(**kwargs)
class LAD(Base):
"""
Represents local authority districts (LADs), UK 2019.
"""
__filename__ = "LA_UA names and codes UK as at 12_19.xlsx"
__tablename__ = "lad_local_authority_district_2019"
lad_code = Column(String(CODE_LEN), primary_key=True)
lad_name = Column(String(NAME_LEN))
lad_name_welsh = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'LAD19CD', 'lad_code')
rename_key(kwargs, 'LAD19NM', 'lad_name')
rename_key(kwargs, 'LAD19NMW', 'lad_name_welsh')
super().__init__(**kwargs)
class LEP(Base):
"""
Represents Local Enterprise Partnerships (LEPs), England 2017.
"""
__filename__ = "LEP names and codes EN as at 04_17 v2.xlsx"
__tablename__ = "lep_local_enterprise_partnership_england_2017"
# __debug_content__ = True
lep_code = Column(String(CODE_LEN), primary_key=True)
lep_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'LEP17CD', 'lep_code')
rename_key(kwargs, 'LEP17NM', 'lep_name')
super().__init__(**kwargs)
class LSOA2011(Base):
"""
Represents lower layer super output area (LSOAs), UK 2011.
**This is quite an important one.** LSOAs map to IMDs; see
:class:`IMDLookupEN`.
"""
__filename__ = "LSOA (2011) names and codes UK as at 12_12.xlsx"
__tablename__ = "lsoa_lower_layer_super_output_area_2011"
lsoa_code = Column(String(CODE_LEN), primary_key=True)
lsoa_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'LSOA11CD', 'lsoa_code')
rename_key(kwargs, 'LSOA11NM', 'lsoa_name')
super().__init__(**kwargs)
class MSOA2011(Base):
"""
Represents middle layer super output areas (MSOAs), UK 2011.
"""
__filename__ = "MSOA (2011) names and codes UK as at 12_12.xlsx"
__tablename__ = "msoa_middle_layer_super_output_area_2011"
msoa_code = Column(String(CODE_LEN), primary_key=True)
msoa_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'MSOA11CD', 'msoa_code')
rename_key(kwargs, 'MSOA11NM', 'msoa_name')
super().__init__(**kwargs)
class NationalPark(Base):
"""
Represents national parks, Great Britain 2016.
"""
__filename__ = "National Park names and codes GB as at 08_16.xlsx"
__tablename__ = "park_national_park_2016"
park_code = Column(String(CODE_LEN), primary_key=True)
park_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'NPARK16CD', 'park_code')
rename_key(kwargs, 'NPARK16NM', 'park_name')
super().__init__(**kwargs)
class Parish(Base):
"""
Represents parishes, England & Wales 2014.
"""
__filename__ = "Parish_NCP names and codes EW as at 12_18.xlsx"
__tablename__ = "parish_ncp_england_wales_2018"
parish_code = Column(String(CODE_LEN), primary_key=True)
parish_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'PARNCP18CD', 'parish_code')
rename_key(kwargs, 'PARNCP18NM', 'parish_name')
super().__init__(**kwargs)
class PCT2019(Base):
"""
Represents Primary Care Trust (PCT) organizations, UK 2019.
The forerunner of CCGs (q.v.).
"""
__filename__ = "PCT names and codes UK as at 04_19.xlsx"
__tablename__ = "pct_primary_care_trust_2019"
pct_code = Column(String(CODE_LEN), primary_key=True)
pct_code_old = Column(String(5))
pct_name = Column(String(NAME_LEN))
pct_name_welsh = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'PCTCD', 'pct_code')
rename_key(kwargs, 'PCTCDO', 'pct_code_old')
rename_key(kwargs, 'PCTNM', 'pct_name')
rename_key(kwargs, 'PCTNMW', 'pct_name_welsh')
super().__init__(**kwargs)
class PFA(Base):
"""
Represents police force areas (PFAs), Great Britain 2015.
"""
__filename__ = "PFA names and codes GB as at 12_15.xlsx"
__tablename__ = "pfa_police_force_area_2015"
pfa_code = Column(String(CODE_LEN), primary_key=True)
pfa_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'PFA15CD', 'pfa_code')
rename_key(kwargs, 'PFA15NM', 'pfa_name')
super().__init__(**kwargs)
class GOR(Base):
"""
Represents Government Office Regions (GORs), England 2010.
"""
__filename__ = "Region names and codes EN as at 12_10 (RGN).xlsx"
__tablename__ = "gor_govt_office_region_england_2010"
gor_code = Column(String(CODE_LEN), primary_key=True)
gor_code_old = Column(String(1))
gor_name = Column(String(NAME_LEN))
gor_name_welsh = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'GOR10CD', 'gor_code')
rename_key(kwargs, 'GOR10CDO', 'gor_code_old')
rename_key(kwargs, 'GOR10NM', 'gor_name')
rename_key(kwargs, 'GOR10NMW', 'gor_name')
super().__init__(**kwargs)
class SSR(Base):
"""
Represents Standard Statistical Regions (SSRs), UK 2005.
"""
__filename__ = "SSR names and codes UK as at 12_05 (STREG).xlsx"
__tablename__ = "ssr_standard_statistical_region_1995"
ssr_code = Column(Integer, primary_key=True)
ssr_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'SSR95CD', 'ssr_code')
rename_key(kwargs, 'SSR95NM', 'ssr_name')
convert_int(kwargs, 'ssr_code')
super().__init__(**kwargs)
_ = '''
# NOT WORKING 2020-03-03: missing PK somewhere? Also: unimportant.
class Ward2005(Base):
"""
Represents electoral wards, UK 2005.
"""
__filename__ = "Statistical ward names and codes UK as at 2005.xlsx"
__tablename__ = "electoral_ward_2005"
ward_code = Column(String(6), primary_key=True)
ward_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'WDSTL05CD', 'ward_code')
rename_key(kwargs, 'WDSTL05NM', 'ward_name')
super().__init__(**kwargs)
'''
class Ward2019(Base):
"""
Represents electoral wards, UK 2016.
"""
__filename__ = "Ward names and codes UK as at 12_19.xlsx"
__tablename__ = "electoral_ward_2019"
ward_code = Column(String(CODE_LEN), primary_key=True)
ward_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'WD19CD', 'ward_code')
rename_key(kwargs, 'WD19NM', 'ward_name')
super().__init__(**kwargs)
class TTWA(Base):
"""
Represents travel-to-work area (TTWAs), UK 2011.
"""
__filename__ = "TTWA names and codes UK as at 12_11 v5.xlsx"
__tablename__ = "ttwa_travel_to_work_area_2011"
ttwa_code = Column(String(CODE_LEN), primary_key=True)
ttwa_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'TTWA11CD', 'ttwa_code')
rename_key(kwargs, 'TTWA11NM', 'ttwa_name')
super().__init__(**kwargs)
class WestminsterConstituency(Base):
"""
Represents Westminster parliamentary constituencies, UK 2014.
"""
__filename__ = "Westminster Parliamentary Constituency names and codes " \
"UK as at 12_14.xlsx"
__tablename__ = "pcon_westminster_parliamentary_constituency_2014"
pcon_code = Column(String(CODE_LEN), primary_key=True)
pcon_name = Column(String(NAME_LEN))
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'PCON14CD', 'pcon_code')
rename_key(kwargs, 'PCON14NM', 'pcon_name')
super().__init__(**kwargs)
_ = '''
# =============================================================================
# Models: centroids
# =============================================================================
# http://webarchive.nationalarchives.gov.uk/20160105160709/http://www.ons.gov.uk/ons/guide-method/geography/products/census/spatial/centroids/index.html # noqa
#
# Looking at lower_layer_super_output_areas_(e+w)_2011_population_weighted_centroids_v2.zip : # noqa
# - LSOA_2011_EW_PWC.shp -- probably a Shape file;
# ... yes
# ... https://en.wikipedia.org/wiki/Shapefile
# ... ... describes most of the other files
# - LSOA_2011_EW_PWC_COORD_V2.CSV -- LSOA to centroid coordinates
class PopWeightedCentroidsLsoa2011(Base):
"""
Represents a population-weighted centroid of a lower layer super output
area (LSOA).
That is, the geographical centre of the LSOA, weighted by population. (A
first approximation: imagine every person pulling on the centroid
simultaneously and with equal force from their home. Where will it end up?)
""" # noqa
__filename__ = "LSOA_2011_EW_PWC_COORD_V2.CSV"
__tablename__ = "pop_weighted_centroids_lsoa_2011"
# __debug_content__ = True
lsoa_code = Column(String(CODE_LEN), primary_key=True)
lsoa_name = Column(String(NAME_LEN))
bng_north = Column(Integer, comment="British National Grid, North (m)")
bng_east = Column(Integer, comment="British National Grid, East (m)")
# https://en.wikipedia.org/wiki/Ordnance_Survey_National_Grid#All-numeric_grid_references # noqa
latitude = Column(Numeric(precision=13, scale=10),
comment="Latitude (degrees, 10dp)")
longitude = Column(Numeric(precision=13, scale=10),
comment="Longitude (degrees, 10dp)")
# ... there are some with 10dp, e.g. 0.0000570995
# ... (precision - scale) = number of digits before '.'
# ... which can't be more than 3 for any latitude/longitude
def __init__(self, **kwargs: Any) -> None:
rename_key(kwargs, 'LSOA11CD', 'lsoa_code')
rename_key(kwargs, 'LSOA11NM', 'lsoa_name')
rename_key(kwargs, 'BNGNORTH', 'bng_north')
rename_key(kwargs, 'BNGEAST', 'bng_east')
rename_key(kwargs, 'LONGITUDE', 'longitude')
rename_key(kwargs, 'LATITUDE', 'latitude')
# MySQL doesn't care if you pass a string to a numeric field, but
# SQL server does. So:
convert_int(kwargs, 'bng_north')
convert_int(kwargs, 'bng_east')
convert_float(kwargs, 'longitude')
convert_float(kwargs, 'latitude')
super().__init__(**kwargs)
if not self.lsoa_code:
raise ValueError("Can't have a blank lsoa_code")
'''
# =============================================================================
# Files -> table data
# =============================================================================
def populate_postcode_table(filename: str,
session: Session,
replace: bool = False,
startswith: List[str] = None,
reportevery: int = DEFAULT_REPORT_EVERY,
commit: bool = True,
commitevery: int = DEFAULT_COMMIT_EVERY) -> None:
"""
Populates the :class:`Postcode` table, which is very big, from Office of
National Statistics Postcode Database (ONSPD) database that you have
downloaded.
Args:
filename: CSV file to read
session: SQLAlchemy ORM database session
replace: replace tables even if they exist? (Otherwise, skip existing
tables.)
startswith: if specified, restrict to postcodes that start with one of
these strings
reportevery: report to the Python log every *n* rows
commit: COMMIT the session once we've inserted the data?
commitevery: if committing: commit every *n* rows inserted
"""
tablename = Postcode.__tablename__
# noinspection PyUnresolvedReferences
table = Postcode.__table__
if not replace:
engine = session.bind
if engine.has_table(tablename):
log.info(f"Table {tablename} exists; skipping")
return
log.info(f"Dropping/recreating table: {tablename}")
table.drop(checkfirst=True)
table.create(checkfirst=True)
log.info(f"Using ONSPD data file: {filename}")
n = 0
n_inserted = 0
extra_fields = [] # type: List[str]
db_fields = sorted(k for k in table.columns.keys() if k != 'pcd_nospace')
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
n += 1
if n % reportevery == 0:
log.info(f"Processing row {n}: {row['pcds']} "
f"({n_inserted} inserted)")
# log.debug(row)
if n == 1:
file_fields = sorted(row.keys())
missing_fields = sorted(set(db_fields) - set(file_fields))
extra_fields = sorted(set(file_fields) - set(db_fields))
if missing_fields:
log.warning(
f"Fields in database but not file: {missing_fields}")
if extra_fields:
log.warning(
f"Fields in file but not database : {extra_fields}")
for k in extra_fields:
del row[k]
if startswith:
ok = False
for s in startswith:
if row['pcd'].startswith(s):
ok = True
break
if not ok:
continue
obj = Postcode(**row)
session.add(obj)
n_inserted += 1
if commit and n % commitevery == 0:
commit_and_announce(session)
if commit:
commit_and_announce(session)
# BASETYPE = TypeVar('BASETYPE', bound=Base)
# http://mypy.readthedocs.io/en/latest/kinds_of_types.html
# https://docs.python.org/3/library/typing.html
def populate_generic_lookup_table(
sa_class: GenericLookupClassType,
datadir: str,
session: Session,
replace: bool = False,
commit: bool = True,
commitevery: int = DEFAULT_COMMIT_EVERY) -> None:
"""
Populates one of many generic lookup tables with ONSPD data.
We find the data filename from the ``__filename__`` property of the
specific class, hunting for it within ``datadir`` and its subdirectories.
The ``.TXT`` files look at first glance like tab-separated values files,
but in some cases have inconsistent numbers of tabs (e.g. "2011 Census
Output Area Classification Names and Codes UK.txt"). So we'll use the
``.XLSX`` files.
If the headings parameter is passed, those headings are used. Otherwise,
the first row is used for headings.
Args:
sa_class: SQLAlchemy ORM class
datadir: root directory of ONSPD data
session: SQLAlchemy ORM database session
replace: replace tables even if they exist? (Otherwise, skip existing
tables.)
commit: COMMIT the session once we've inserted the data?
commitevery: if committing: commit every *n* rows inserted
"""
tablename = sa_class.__tablename__
filename = find_first(sa_class.__filename__, datadir)
headings = getattr(sa_class, '__headings__', [])
debug = getattr(sa_class, '__debug_content__', False)
n = 0
if not replace:
engine = session.bind
if engine.has_table(tablename):
log.info(f"Table {tablename} exists; skipping")
return
log.info(f"Dropping/recreating table: {tablename}")
sa_class.__table__.drop(checkfirst=True)
sa_class.__table__.create(checkfirst=True)
log.info(f'Processing file "{filename}" -> table "{tablename}"')
ext = os.path.splitext(filename)[1].lower()
type_xlsx = ext in ['.xlsx']
type_csv = ext in ['.csv']
file = None # type: Optional[TextIO]
def dict_from_rows(row_iterator: Iterable[List]) \
-> Generator[Dict, None, None]:
local_headings = headings
first_row = True
for row in row_iterator:
values = values_from_row(row)
if first_row and not local_headings:
local_headings = values
else:
yield dict(zip(local_headings, values))
first_row = False
if type_xlsx:
workbook = openpyxl.load_workbook(filename) # read_only=True
# openpyxl BUG: with read_only=True, cells can have None as their value
# when they're fine if opened in non-read-only mode.
# May be related to this:
# https://bitbucket.org/openpyxl/openpyxl/issues/601/read_only-cell-row-column-attributes-are # noqa
sheet = workbook.active
dict_iterator = dict_from_rows(sheet.iter_rows())
elif type_csv:
file = open(filename, 'r')
csv_reader = csv.DictReader(file)
dict_iterator = csv_reader
else:
raise ValueError("Only XLSX and CSV these days")
# workbook = xlrd.open_workbook(filename)
# sheet = workbook.sheet_by_index(0)
# dict_iterator = dict_from_rows(sheet.get_rows())
for datadict in dict_iterator:
n += 1
if debug:
log.critical(f"{n}: {datadict}")
# filter out blanks:
datadict = {k: v for k, v in datadict.items() if k}
# noinspection PyNoneFunctionAssignment
obj = sa_class(**datadict)
session.add(obj)
if commit and n % commitevery == 0:
commit_and_announce(session)
if commit:
commit_and_announce(session)
log.info(f"... inserted {n} rows")
if file:
file.close()
# =============================================================================
# Docs
# =============================================================================
def show_docs() -> None:
"""
Print the column ``doc`` attributes from the :class:`Postcode` class, in
tabular form, to stdout.
"""
# noinspection PyUnresolvedReferences
table = Postcode.__table__
columns = sorted(table.columns.keys())
pt = prettytable.PrettyTable(
["postcode field", "Description"],
# header=False,
border=True,
hrules=prettytable.ALL,
vrules=prettytable.NONE,
)
pt.align = 'l'
pt.valign = 't'
pt.max_width = 80
for col in columns:
doc = getattr(Postcode, col).doc
doc = wordwrap(doc, width=70)
ptrow = [col, doc]
pt.add_row(ptrow)
print(pt.get_string())
# =============================================================================
# Main
# =============================================================================
def main() -> None:
"""
Command-line entry point. See command-line help.
"""
# noinspection PyTypeChecker
parser = argparse.ArgumentParser(
formatter_class=RawDescriptionArgumentDefaultsHelpFormatter,
description=r"""
- This program reads data from the UK Office of National Statistics Postcode
Database (ONSPD) and inserts it into a database.
- You will need to download the ONSPD from
https://geoportal.statistics.gov.uk/geoportal/catalog/content/filelist.page
e.g. ONSPD_MAY_2016_csv.zip (79 Mb), and unzip it (>1.4 Gb) to a directory.
Tell this program which directory you used.
- Specify your database as an SQLAlchemy connection URL: see
http://docs.sqlalchemy.org/en/latest/core/engines.html
The general format is:
dialect[+driver]://username:password@host[:port]/database[?key=value...]
- If you get an error like:
UnicodeEncodeError: 'latin-1' codec can't encode character '\u2019' in
position 33: ordinal not in range(256)
then try appending "?charset=utf8" to the connection URL.
- ONS POSTCODE DATABASE LICENSE.
Output using this program must add the following attribution statements:
Contains OS data © Crown copyright and database right [year]
Contains Royal Mail data © Royal Mail copyright and database right [year]
Contains National Statistics data © Crown copyright and database right [year]
See http://www.ons.gov.uk/methodology/geography/licences
""") # noqa: E501
parser.add_argument(
"--dir", default=DEFAULT_ONSPD_DIR,
help="Root directory of unzipped ONSPD download")
parser.add_argument(
"--url", help="SQLAlchemy database URL")
parser.add_argument(
"--echo", action="store_true", help="Echo SQL")
parser.add_argument(
"--reportevery", type=int, default=DEFAULT_REPORT_EVERY,
help="Report every n rows")
parser.add_argument(
"--commitevery", type=int, default=DEFAULT_COMMIT_EVERY,
help=(
"Commit every n rows. If you make this too large "
"(relative e.g. to your MySQL max_allowed_packet setting, you may"
" get crashes with errors like 'MySQL has gone away'."))
parser.add_argument(
"--startswith", nargs="+",
help="Restrict to postcodes that start with one of these strings")
parser.add_argument(
"--replace", action="store_true",
help="Replace tables even if they exist (default: skip existing "
"tables)")
parser.add_argument(
"--skiplookup", action="store_true",
help="Skip generation of code lookup tables")
parser.add_argument(
"--specific_lookup_tables", nargs="*",
help="Within the lookup tables, process only specific named tables")
parser.add_argument(
"--list_lookup_tables", action="store_true",
help="List all possible lookup tables, then stop")
parser.add_argument(
"--skippostcodes", action="store_true",
help="Skip generation of main (large) postcode table")
parser.add_argument(
"--docsonly", action="store_true",
help="Show help for postcode table then stop")
parser.add_argument(
"-v", "--verbose", action="store_true", help="Verbose")
args = parser.parse_args()
rootlogger = logging.getLogger()
configure_logger_for_colour(
rootlogger, level=logging.DEBUG if args.verbose else logging.INFO)
log.debug(f"args = {args!r}")
if args.docsonly:
show_docs()
sys.exit(0)
classlist = [
# Core lookup tables:
# In alphabetical order of filename:
OAClassification,
BUA,
BUASD,
CASWard,
CCG,
Country,
County2019,
EER,
IMDLookupEN,
IMDLookupSC,
IMDLookupWA,
LAU,
LAD,
LEP,
LSOA2011,
MSOA2011,
NationalPark,
Parish,
PCT2019,
PFA,
GOR,
SSR,
# Ward2005,
TTWA,
Ward2019,
WestminsterConstituency,
# Centroids:
# PopWeightedCentroidsLsoa2011,
]
if args.list_lookup_tables:
tables_files = [] # type: List[Tuple[str, str]]
for sa_class in classlist:
tables_files.append((sa_class.__tablename__,
sa_class.__filename__))
tables_files.sort(key=lambda x: x[0])
for table, file in tables_files:
print(f"Table {table} from file {file!r}")
return
if not args.url:
print("Must specify URL")
return
engine = create_engine(args.url, echo=args.echo, encoding=CHARSET)
metadata.bind = engine
session = sessionmaker(bind=engine)()
log.info(f"Using directory: {args.dir}")
# lookupdir = os.path.join(args.dir, "Documents")
lookupdir = args.dir
# datadir = os.path.join(args.dir, "Data")
datadir = args.dir
if not args.skiplookup:
for sa_class in classlist:
if (args.specific_lookup_tables and
sa_class.__tablename__ not in args.specific_lookup_tables):
continue
# if (sa_class.__tablename__ ==
# "ccg_clinical_commissioning_group_uk_2019"):
# log.warning("Ignore warning 'Discarded range with reserved "
# "name' below; it works regardless")
populate_generic_lookup_table(
sa_class=sa_class,
datadir=lookupdir,
session=session,
replace=args.replace,
commit=True,
commitevery=args.commitevery
)
if not args.skippostcodes:
populate_postcode_table(
filename=find_first("ONSPD_*.csv", datadir),
session=session,
replace=args.replace,
startswith=args.startswith,
reportevery=args.reportevery,
commit=True,
commitevery=args.commitevery
)
if __name__ == '__main__':
main()<|fim▁end|> | |
<|file_name|>issue-16643.rs<|end_file_name|><|fim▁begin|>#![crate_type = "lib"]
<|fim▁hole|>impl<H> TreeBuilder<H> {
pub fn process_token(&mut self) {
match self {
_ => for _y in self.by_ref() {}
}
}
}
impl<H> Iterator for TreeBuilder<H> {
type Item = H;
fn next(&mut self) -> Option<H> {
None
}
}<|fim▁end|> | pub struct TreeBuilder<H> { pub h: H }
|
<|file_name|>bundle.js<|end_file_name|><|fim▁begin|>var socket = io()
var app = angular.module('alcohol', ['ui.router', 'ui.router.grant', 'ngStorage'])
app.run(['grant', 'authService', function (grant, authService) {
grant.addTest('auth', function () {
console.log(authService.isLoggedIn())
return authService.isLoggedIn()
})
}])
app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('home', {
url: '/',
controller: 'homeController',
templateUrl: 'templates/home.html'
})
.state('about', {
url: '/about',
templateUrl: 'templates/about.html'
})
.state('profile', {
url: '/profile',
controller: 'profileController',
templateUrl: 'templates/profile.html',
resolve: {
auth: function(grant) {
return grant.only({test: 'auth', state: 'nope'});
}
}
})
.state('party', {
url: '/:id',
controller: 'partyController',
templateUrl: 'templates/party.html',
resolve: {
auth: function(grant) {
return grant.only({test: 'auth', state: 'nope'});
}
}
})
.state('nope', {
url: '/nope',
templateUrl: 'templates/nope.html'
})
.state('invalid', {
url: '/404',
templateUrl: 'templates/404.html'
})
$locationProvider.html5Mode(true)
$urlRouterProvider.otherwise('/404')
}])
app.factory('authService', ['$http', '$window', '$localStorage', function ($http, $window, $localStorage) {
var service = {},
user = {},
isLoggedIn = $localStorage.isLoggedIn || false
$http
.get('http://localhost:8080/api/profile')
.then(function (response) {
user.name = response.data.name
user.email = response.data.email
user.id = response.data.facebookId<|fim▁hole|> })
return {
login: function () {
$localStorage.isLoggedIn = true
$window.location.href = 'http://localhost:8080/auth/facebook'
},
getUser: function () {
return user
},
getId: function () {
return user.id
},
isLoggedIn: function () {
return isLoggedIn
},
logout: function () {
$localStorage.isLoggedIn = false
$window.location.href = 'http://localhost:8080/logout'
}
}
}])
app.factory('streamService', ['$http', 'authService', function ($http, authService) {
var partyId
return {
start: function () {
return new Promise(function (resolve, reject) {
$http
.get('/api/start')
.then(function (response) {
partyId = response.data
resolve(response.data)
}, function () {
reject()
})
})
},
join: function (partyId) {
},
getPartyId: function () {
return partyId
}
}
}])
app.controller('homeController', ['$scope', 'authService', function ($scope, authService) {
$scope.pageName = 'Home'
$scope.login = authService.login
}])
app.controller('partyController', ['$scope', 'streamService', function ($scope, streamService) {
$scope.partyId = streamService.getPartyId()
}])
app.controller('profileController', ['$scope', '$state', 'authService', 'streamService', function($scope, $state, authService, streamService) {
$scope.user = authService.getUser()
$scope.logout = authService.logout
$scope.start = function () {
streamService
.start()
.then(function (partyId) {
$state.transitionTo('party', {
id: partyId
})
})
}
$scope.join = streamService.join
}])<|fim▁end|> | |
<|file_name|>TestDrive.java<|end_file_name|><|fim▁begin|>/*****************************************************************************
* Course: CS 27500
* Name: Adam Joseph Cook<|fim▁hole|> * Assignment: 1
*
* The <CODE>TestDrive</CODE> Java application simulates a car being driven
* depending on its provided fuel efficiency and fuel amount.
*
* @author Adam Joseph Cook
* <A HREF="mailto:cook5@purduecal.edu"> (cook5@purduecal.edu) </A>
*****************************************************************************/
import java.util.Scanner;
public class TestDrive
{
public static void main( String[] args ) {
Scanner sc = new Scanner(System.in);
Car car;
boolean mainDone = false;
while (!mainDone) {
System.out.print("Enter fuel efficiency: ");
double fuelEfficiency = sc.nextDouble();
car = new Car(fuelEfficiency);
if (fuelEfficiency == 0) {
// The user entered a fuel efficiency of zero, so terminate the
// program.
System.exit(0);
}
boolean outerDone = false;
while (!outerDone) {
System.out.print("Enter amount of fuel: ");
double fuelAmountToAdd = sc.nextDouble();
if (fuelAmountToAdd == 0) {
// The user entered a zero value for the fuel to add, so
// terminate this outer loop.
outerDone = true;
} else {
// Add provided fuel to the car.
car.addFuel(fuelAmountToAdd);
boolean innerDone = false;
while (!innerDone) {
System.out.print("Enter distance to travel: ");
double distanceToTravel = sc.nextDouble();
if (distanceToTravel == 0) {
// The user entered a zero distance to travel, so
// terminate this inner loop.
innerDone = true;
} else {
// Attempt to travel the distance provided with the
// car.
double distanceTraveled = car.drive(distanceToTravel);
System.out.println(" Distance actually " +
"traveled = " + distanceTraveled);
System.out.println(" Current fuelLevel = " +
car.getFuelLevel());
System.out.println(" Current odometer = " +
car.getOdometer());
}
}
}
}
}
}
}<|fim▁end|> | * Email: cook5@purduecal.edu |
<|file_name|>prevector_tests.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <vector>
#include "prevector.h"
#include "random.h"
#include "serialize.h"
#include "streams.h"
#include "test/test_bitcoin.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(prevector_tests, TestingSetup) // BU harmonize suite name with filename
template<unsigned int N, typename T>
class prevector_tester {
typedef std::vector<T> realtype;
realtype real_vector;
typedef prevector<N, T> pretype;
pretype pre_vector;
typedef typename pretype::size_type Size;
void test() {
const pretype& const_pre_vector = pre_vector;
BOOST_CHECK_EQUAL(real_vector.size(), pre_vector.size());
BOOST_CHECK_EQUAL(real_vector.empty(), pre_vector.empty());
for (Size s = 0; s < real_vector.size(); s++) {
BOOST_CHECK(real_vector[s] == pre_vector[s]);
BOOST_CHECK(&(pre_vector[s]) == &(pre_vector.begin()[s]));
BOOST_CHECK(&(pre_vector[s]) == &*(pre_vector.begin() + s));
BOOST_CHECK(&(pre_vector[s]) == &*((pre_vector.end() + s) - real_vector.size()));
}
// BOOST_CHECK(realtype(pre_vector) == real_vector);
BOOST_CHECK(pretype(real_vector.begin(), real_vector.end()) == pre_vector);
BOOST_CHECK(pretype(pre_vector.begin(), pre_vector.end()) == pre_vector);
size_t pos = 0;
BOOST_FOREACH(const T& v, pre_vector) {
BOOST_CHECK(v == real_vector[pos++]);
}
BOOST_REVERSE_FOREACH(const T& v, pre_vector) {
BOOST_CHECK(v == real_vector[--pos]);
}
BOOST_FOREACH(const T& v, const_pre_vector) {
BOOST_CHECK(v == real_vector[pos++]);
}
BOOST_REVERSE_FOREACH(const T& v, const_pre_vector) {
BOOST_CHECK(v == real_vector[--pos]);
}
CDataStream ss1(SER_DISK, 0);
CDataStream ss2(SER_DISK, 0);
ss1 << real_vector;
ss2 << pre_vector;
BOOST_CHECK_EQUAL(ss1.size(), ss2.size());
for (Size s = 0; s < ss1.size(); s++) {
BOOST_CHECK_EQUAL(ss1[s], ss2[s]);
}
}
public:
void resize(Size s) {
real_vector.resize(s);
BOOST_CHECK_EQUAL(real_vector.size(), s);
pre_vector.resize(s);
BOOST_CHECK_EQUAL(pre_vector.size(), s);
test();
}
void reserve(Size s) {
real_vector.reserve(s);
BOOST_CHECK(real_vector.capacity() >= s);
pre_vector.reserve(s);
BOOST_CHECK(pre_vector.capacity() >= s);
test();
}
void insert(Size position, const T& value) {
real_vector.insert(real_vector.begin() + position, value);
pre_vector.insert(pre_vector.begin() + position, value);
test();
}
void insert(Size position, Size count, const T& value) {
real_vector.insert(real_vector.begin() + position, count, value);
pre_vector.insert(pre_vector.begin() + position, count, value);
test();
}
template<typename I>
void insert_range(Size position, I first, I last) {
real_vector.insert(real_vector.begin() + position, first, last);
pre_vector.insert(pre_vector.begin() + position, first, last);
test();
}
void erase(Size position) {
real_vector.erase(real_vector.begin() + position);
pre_vector.erase(pre_vector.begin() + position);
test();
}
void erase(Size first, Size last) {
real_vector.erase(real_vector.begin() + first, real_vector.begin() + last);
pre_vector.erase(pre_vector.begin() + first, pre_vector.begin() + last);
test();
}
void update(Size pos, const T& value) {
real_vector[pos] = value;
pre_vector[pos] = value;
test();
}
void push_back(const T& value) {
real_vector.push_back(value);
pre_vector.push_back(value);
test();
}
void pop_back() {
real_vector.pop_back();
pre_vector.pop_back();
test();
}
void clear() {
real_vector.clear();
pre_vector.clear();
}
void assign(Size n, const T& value) {
real_vector.assign(n, value);
pre_vector.assign(n, value);
}
Size size() {
return real_vector.size();
}
Size capacity() {
return pre_vector.capacity();
}
<|fim▁hole|> pre_vector.shrink_to_fit();
test();
}
};
BOOST_AUTO_TEST_CASE(PrevectorTestInt)
{
for (int j = 0; j < 64; j++) {
prevector_tester<8, int> test;
for (int i = 0; i < 2048; i++) {
int r = insecure_rand();
if ((r % 4) == 0) {
test.insert(insecure_rand() % (test.size() + 1), insecure_rand());
}
if (test.size() > 0 && ((r >> 2) % 4) == 1) {
test.erase(insecure_rand() % test.size());
}
if (((r >> 4) % 8) == 2) {
int new_size = std::max<int>(0, std::min<int>(30, test.size() + (insecure_rand() % 5) - 2));
test.resize(new_size);
}
if (((r >> 7) % 8) == 3) {
test.insert(insecure_rand() % (test.size() + 1), 1 + (insecure_rand() % 2), insecure_rand());
}
if (((r >> 10) % 8) == 4) {
int del = std::min<int>(test.size(), 1 + (insecure_rand() % 2));
int beg = insecure_rand() % (test.size() + 1 - del);
test.erase(beg, beg + del);
}
if (((r >> 13) % 16) == 5) {
test.push_back(insecure_rand());
}
if (test.size() > 0 && ((r >> 17) % 16) == 6) {
test.pop_back();
}
if (((r >> 21) % 32) == 7) {
int values[4];
int num = 1 + (insecure_rand() % 4);
for (int i = 0; i < num; i++) {
values[i] = insecure_rand();
}
test.insert_range(insecure_rand() % (test.size() + 1), values, values + num);
}
if (((r >> 26) % 32) == 8) {
int del = std::min<int>(test.size(), 1 + (insecure_rand() % 4));
int beg = insecure_rand() % (test.size() + 1 - del);
test.erase(beg, beg + del);
}
r = insecure_rand();
if (r % 32 == 9) {
test.reserve(insecure_rand() % 32);
}
if ((r >> 5) % 64 == 10) {
test.shrink_to_fit();
}
if (test.size() > 0) {
test.update(insecure_rand() % test.size(), insecure_rand());
}
if (((r >> 11) & 1024) == 11) {
test.clear();
}
if (((r >> 21) & 512) == 12) {
test.assign(insecure_rand() % 32, insecure_rand());
}
}
}
}
BOOST_AUTO_TEST_SUITE_END()<|fim▁end|> | void shrink_to_fit() { |
<|file_name|>Zoom.js<|end_file_name|><|fim▁begin|>/**
* @module ol/control/Zoom
*/
import {inherits} from '../index.js';
import {listen} from '../events.js';
import EventType from '../events/EventType.js';
import Control from '../control/Control.js';
import {CLASS_CONTROL, CLASS_UNSELECTABLE} from '../css.js';
import {easeOut} from '../easing.js';
/**
* @typedef {Object} Options
* @property {number} [duration=250] Animation duration in milliseconds.
* @property {string} [className='ol-zoom'] CSS class name.
* @property {string|Element} [zoomInLabel='+'] Text label to use for the zoom-in
* button. Instead of text, also an element (e.g. a `span` element) can be used.
* @property {string|Element} [zoomOutLabel='-'] Text label to use for the zoom-out button.
* Instead of text, also an element (e.g. a `span` element) can be used.
* @property {string} [zoomInTipLabel='Zoom in'] Text label to use for the button tip.
* @property {string} [zoomOutTipLabel='Zoom out'] Text label to use for the button tip.
* @property {number} [delta=1] The zoom delta applied on each click.
* @property {Element|string} [target] Specify a target if you want the control to be
* rendered outside of the map's viewport.
*/
/**
* @classdesc
* A control with 2 buttons, one for zoom in and one for zoom out.
* This control is one of the default controls of a map. To style this control
* use css selectors `.ol-zoom-in` and `.ol-zoom-out`.
*
* @constructor
* @extends {ol.control.Control}
* @param {module:ol/control/Zoom~Options=} opt_options Zoom options.
* @api
*/
const Zoom = function(opt_options) {
const options = opt_options ? opt_options : {};
const className = options.className !== undefined ? options.className : 'ol-zoom';
const delta = options.delta !== undefined ? options.delta : 1;
const zoomInLabel = options.zoomInLabel !== undefined ? options.zoomInLabel : '+';
const zoomOutLabel = options.zoomOutLabel !== undefined ? options.zoomOutLabel : '\u2212';
const zoomInTipLabel = options.zoomInTipLabel !== undefined ?
options.zoomInTipLabel : 'Zoom in';
const zoomOutTipLabel = options.zoomOutTipLabel !== undefined ?
options.zoomOutTipLabel : 'Zoom out';
const inElement = document.createElement('button');
inElement.className = className + '-in';
inElement.setAttribute('type', 'button');
inElement.title = zoomInTipLabel;
inElement.appendChild(
typeof zoomInLabel === 'string' ? document.createTextNode(zoomInLabel) : zoomInLabel
);
listen(inElement, EventType.CLICK,
Zoom.prototype.handleClick_.bind(this, delta));
const outElement = document.createElement('button');
outElement.className = className + '-out';
outElement.setAttribute('type', 'button');
outElement.title = zoomOutTipLabel;
outElement.appendChild(
typeof zoomOutLabel === 'string' ? document.createTextNode(zoomOutLabel) : zoomOutLabel
);
listen(outElement, EventType.CLICK,
Zoom.prototype.handleClick_.bind(this, -delta));
const cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL;
const element = document.createElement('div');
element.className = cssClasses;
element.appendChild(inElement);
element.appendChild(outElement);
Control.call(this, {
element: element,
target: options.target
});
/**
* @type {number}
* @private
*/
this.duration_ = options.duration !== undefined ? options.duration : 250;
};
inherits(Zoom, Control);
/**
* @param {number} delta Zoom delta.<|fim▁hole|>Zoom.prototype.handleClick_ = function(delta, event) {
event.preventDefault();
this.zoomByDelta_(delta);
};
/**
* @param {number} delta Zoom delta.
* @private
*/
Zoom.prototype.zoomByDelta_ = function(delta) {
const map = this.getMap();
const view = map.getView();
if (!view) {
// the map does not have a view, so we can't act
// upon it
return;
}
const currentResolution = view.getResolution();
if (currentResolution) {
const newResolution = view.constrainResolution(currentResolution, delta);
if (this.duration_ > 0) {
if (view.getAnimating()) {
view.cancelAnimations();
}
view.animate({
resolution: newResolution,
duration: this.duration_,
easing: easeOut
});
} else {
view.setResolution(newResolution);
}
}
};
export default Zoom;<|fim▁end|> | * @param {Event} event The event to handle
* @private
*/ |
<|file_name|>htmlstyleelement.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser as CssParser;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLStyleElementBinding;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::Element;
use dom::htmlelement::HTMLElement;
use dom::node::{ChildrenMutation, Node, document_from_node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use script_layout_interface::message::Msg;<|fim▁hole|>use style::stylesheets::{Stylesheet, Origin};
#[dom_struct]
pub struct HTMLStyleElement {
htmlelement: HTMLElement,
#[ignore_heap_size_of = "Arc"]
stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>,
}
impl HTMLStyleElement {
fn new_inherited(local_name: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLStyleElement {
HTMLStyleElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
stylesheet: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLStyleElement> {
Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document),
document,
HTMLStyleElementBinding::Wrap)
}
pub fn parse_own_css(&self) {
let node = self.upcast::<Node>();
let element = self.upcast::<Element>();
assert!(node.is_in_doc());
let win = window_from_node(node);
let url = win.get_url();
let mq_attribute = element.get_attribute(&ns!(), &atom!("media"));
let mq_str = match mq_attribute {
Some(a) => String::from(&**a.value()),
None => String::new(),
};
let data = node.GetTextContent().expect("Element.textContent must be a string");
let mut sheet = Stylesheet::from_str(&data, url, Origin::Author, win.css_error_reporter(),
ParserContextExtraData::default());
let mut css_parser = CssParser::new(&mq_str);
let media = parse_media_query_list(&mut css_parser);
sheet.set_media(Some(media));
let sheet = Arc::new(sheet);
win.layout_chan().send(Msg::AddStylesheet(sheet.clone())).unwrap();
*self.stylesheet.borrow_mut() = Some(sheet);
let doc = document_from_node(self);
doc.invalidate_stylesheets();
}
pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
self.stylesheet.borrow().clone()
}
}
impl VirtualMethods for HTMLStyleElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn children_changed(&self, mutation: &ChildrenMutation) {
if let Some(ref s) = self.super_type() {
s.children_changed(mutation);
}
if self.upcast::<Node>().is_in_doc() {
self.parse_own_css();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
if tree_in_doc {
self.parse_own_css();
}
}
}<|fim▁end|> | use std::sync::Arc;
use string_cache::Atom;
use style::media_queries::parse_media_query_list;
use style::parser::ParserContextExtraData; |
<|file_name|>step5_tco.rs<|end_file_name|><|fim▁begin|>use std::rc::Rc;
//use std::collections::HashMap;<|fim▁hole|>extern crate lazy_static;
extern crate regex;
extern crate itertools;
extern crate fnv;
extern crate rustyline;
use rustyline::error::ReadlineError;
use rustyline::Editor;
#[macro_use]
mod types;
use types::{MalVal,MalArgs,MalRet,MalErr,error,format_error};
use types::MalVal::{Nil,Bool,Sym,List,Vector,Hash,Func,MalFunc};
mod reader;
mod printer;
mod env;
use env::{Env,env_new,env_bind,env_get,env_set,env_sets};
#[macro_use]
mod core;
// read
fn read(str: &str) -> MalRet {
reader::read_str(str.to_string())
}
// eval
fn eval_ast(ast: &MalVal, env: &Env) -> MalRet {
match ast {
Sym(_) => Ok(env_get(&env, &ast)?),
List(v,_) => {
let mut lst: MalArgs = vec![];
for a in v.iter() { lst.push(eval(a.clone(), env.clone())?) }
Ok(list!(lst))
},
Vector(v,_) => {
let mut lst: MalArgs = vec![];
for a in v.iter() { lst.push(eval(a.clone(), env.clone())?) }
Ok(vector!(lst))
},
Hash(hm,_) => {
let mut new_hm: FnvHashMap<String,MalVal> = FnvHashMap::default();
for (k,v) in hm.iter() {
new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
}
Ok(Hash(Rc::new(new_hm),Rc::new(Nil)))
},
_ => Ok(ast.clone()),
}
}
fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
let ret: MalRet;
'tco: loop {
ret = match ast.clone() {
List(l,_) => {
if l.len() == 0 { return Ok(ast); }
let a0 = &l[0];
match a0 {
Sym(ref a0sym) if a0sym == "def!" => {
env_set(&env, l[1].clone(), eval(l[2].clone(), env.clone())?)
},
Sym(ref a0sym) if a0sym == "let*" => {
env = env_new(Some(env.clone()));
let (a1, a2) = (l[1].clone(), l[2].clone());
match a1 {
List(ref binds,_) | Vector(ref binds,_) => {
for (b, e) in binds.iter().tuples() {
match b {
Sym(_) => {
let _ = env_set(&env, b.clone(),
eval(e.clone(), env.clone())?);
},
_ => {
return error("let* with non-Sym binding");
}
}
}
},
_ => {
return error("let* with non-List bindings");
}
};
ast = a2;
continue 'tco;
},
Sym(ref a0sym) if a0sym == "do" => {
match eval_ast(&list!(l[1..l.len()-1].to_vec()), &env)? {
List(_,_) => {
ast = l.last().unwrap_or(&Nil).clone();
continue 'tco;
},
_ => error("invalid do form"),
}
},
Sym(ref a0sym) if a0sym == "if" => {
let cond = eval(l[1].clone(), env.clone())?;
match cond {
Bool(false) | Nil if l.len() >= 4 => {
ast = l[3].clone();
continue 'tco;
},
Bool(false) | Nil => Ok(Nil),
_ if l.len() >= 3 => {
ast = l[2].clone();
continue 'tco;
},
_ => Ok(Nil)
}
},
Sym(ref a0sym) if a0sym == "fn*" => {
let (a1, a2) = (l[1].clone(), l[2].clone());
Ok(MalFunc{eval: eval, ast: Rc::new(a2), env: env,
params: Rc::new(a1), is_macro: false,
meta: Rc::new(Nil)})
},
_ => {
match eval_ast(&ast, &env)? {
List(ref el,_) => {
let ref f = el[0].clone();
let args = el[1..].to_vec();
match f {
Func(_,_) => f.apply(args),
MalFunc{ast: mast, env: menv, params, ..} => {
let a = &**mast;
let p = &**params;
env = env_bind(Some(menv.clone()), p.clone(), args)?;
ast = a.clone();
continue 'tco;
},
_ => error("attempt to call non-function"),
}
},
_ => {
error("expected a list")
}
}
}
}
},
_ => eval_ast(&ast, &env),
};
break;
} // end 'tco loop
ret
}
// print
fn print(ast: &MalVal) -> String {
ast.pr_str(true)
}
fn rep(str: &str, env: &Env) -> Result<String,MalErr> {
let ast = read(str)?;
let exp = eval(ast, env.clone())?;
Ok(print(&exp))
}
fn main() {
// `()` can be used when no completer is required
let mut rl = Editor::<()>::new();
if rl.load_history(".mal-history").is_err() {
println!("No previous history.");
}
// core.rs: defined using rust
let repl_env = env_new(None);
for (k, v) in core::ns() {
env_sets(&repl_env, k, v);
}
// core.mal: defined using the language itself
let _ = rep("(def! not (fn* (a) (if a false true)))", &repl_env);
// main repl loop
loop {
let readline = rl.readline("user> ");
match readline {
Ok(line) => {
rl.add_history_entry(&line);
rl.save_history(".mal-history").unwrap();
if line.len() > 0 {
match rep(&line, &repl_env) {
Ok(out) => println!("{}", out),
Err(e) => println!("Error: {}", format_error(e)),
}
}
},
Err(ReadlineError::Interrupted) => continue,
Err(ReadlineError::Eof) => break,
Err(err) => {
println!("Error: {:?}", err);
break
}
}
}
}
// vim: ts=2:sw=2:expandtab<|fim▁end|> | use fnv::FnvHashMap;
use itertools::Itertools;
#[macro_use] |
<|file_name|>incident-form.ts<|end_file_name|><|fim▁begin|>import { Component } from '@angular/core';
import { NavParams, ViewController, ToastController } from 'ionic-angular';
import { Remote } from '../../app/remote';
import { Incident } from '../../app/incident';
import { notify } from '../../app/utils';
@Component({<|fim▁hole|> public categories = [
'Crash',
'Hazard',
'Maintenance Issue',
'Other'
];
private incident: Incident;
constructor(
private navParams: NavParams,
private viewCtrl: ViewController,
private toastCtrl: ToastController,
private remote: Remote) {
this.incident = new Incident(navParams.data);
}
private closeModal() {
this.viewCtrl.dismiss();
}
public sendIncident() {
this.remote.postIncident(this.incident)
.then(() => notify(this.toastCtrl, 'Report sent successfully!'))
.catch(() => notify(this.toastCtrl,
'Report upload failed. Please try again later.'));
this.closeModal();
}
}<|fim▁end|> | selector: 'page-incident-form',
templateUrl: 'incident-form.html'
})
export class IncidentFormPage { |
<|file_name|>access_flags.go<|end_file_name|><|fim▁begin|>package heap
const (
ACC_PUBLIC = 0x0001
ACC_PRIVATE = 0x0002
ACC_PROTECTED = 0x0004
ACC_STATIC = 0x0008
ACC_FINAL = 0x0010
ACC_SUPER = 0x0020
ACC_SYNCHRONIZED = 0x0020
ACC_VOLATILE = 0x0040
ACC_BRIDGE = 0x0040
ACC_TRANSIENT = 0x0080
ACC_VARARGS = 0x0080<|fim▁hole|> ACC_ABSTRACT = 0x0400
ACC_STRICT = 0x0800
ACC_SYNTHETIC = 0x1000
ACC_ANNOTATION = 0x2000
ACC_ENUM = 0x4000
)<|fim▁end|> | ACC_NATIVE = 0x0100
ACC_INTERFACE = 0x0200 |
<|file_name|>namespaced-enum-glob-import.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.<|fim▁hole|>// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
mod m2 {
pub enum Foo {
A,
B(isize),
C { a: isize },
}
impl Foo {
pub fn foo() {}
}
}
mod m {
pub use m2::Foo::*;
}
fn _f(f: m2::Foo) {
use m2::Foo::*;
match f {
A | B(_) | C { .. } => {}
}
}
fn _f2(f: m2::Foo) {
match f {
m::A | m::B(_) | m::C { .. } => {}
}
}
pub fn main() {}<|fim▁end|> | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
<|file_name|>tunnel_calls.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from neutron.plugins.ml2.drivers.l2pop import rpc as l2pop_rpc
from neutron.plugins.ml2 import managers
from neutron.plugins.ml2 import rpc as rpc
from neutron_lib.agent import topics
class Tunnel_Calls(object):
"""Common tunnel calls for L2 agent."""
def __init__(self):
self._construct_rpc_stuff()
def _construct_rpc_stuff(self):
self.notifier = rpc.AgentNotifierApi(topics.AGENT)
self.type_manager = managers.TypeManager()
self.tunnel_rpc_obj = rpc.RpcCallbacks(self.notifier,
self.type_manager)
def trigger_tunnel_sync(self, context, tunnel_ip):
"""Sends tunnel sync RPC message to the neutron
L2 agent.
"""
tunnel_dict = {'tunnel_ip': tunnel_ip,
'tunnel_type': 'vxlan'}
self.tunnel_rpc_obj.tunnel_sync(context,
**tunnel_dict)
<|fim▁hole|> def trigger_l2pop_sync(self, context, other_fdb_entries):
"""Sends L2pop ADD RPC message to the neutron L2 agent."""
l2pop_rpc.L2populationAgentNotifyAPI(
).add_fdb_entries(context, other_fdb_entries)
def trigger_l2pop_delete(self, context, other_fdb_entries, host=None):
"""Sends L2pop DELETE RPC message to the neutron L2 agent."""
l2pop_rpc.L2populationAgentNotifyAPI(
).remove_fdb_entries(context, other_fdb_entries, host)<|fim▁end|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.