file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
editalgorithmcategory.component.ts | import { Component } from "@angular/core";
import {Router, ActivatedRoute} from "@angular/router";
import {Response} from "@angular/http";
import {SecureComponent} from "../../../../services/secure.component";
import {APIService} from "../../../../services/api.service";
@Component({
selector: 'editalgorithmcategory',
template: require('./editalgorithmcategory.component.html'),
styles: [require('./editalgorithmcategory.component.css')],
})
export class EditAlgorithmCategoryComponent extends SecureComponent {
private category: any;
private id: number;
constructor(router:Router, protected client: APIService, private route: ActivatedRoute){
super(router, client);
this.authorities = ["ROLE_ADMIN"];
}
ngOnInit():void{
super.ngOnInit();
this.route.params.subscribe(params => {
let id = params['id'];
this.id = id;
this.getCategory();
});
}
getCategory(){
this.client.getAlgorithmCategoryByIdWithGET(this.id).subscribe((res:Response)=>{
this.category = JSON.parse(res.text())['category'];
},(err)=>{
this.hasError = true;
this.errorMessage = JSON.parse(err)['message'];
});
}
editAlgorithmCategory(experiment:any)
{
| } | } | random_line_split |
editalgorithmcategory.component.ts | import { Component } from "@angular/core";
import {Router, ActivatedRoute} from "@angular/router";
import {Response} from "@angular/http";
import {SecureComponent} from "../../../../services/secure.component";
import {APIService} from "../../../../services/api.service";
@Component({
selector: 'editalgorithmcategory',
template: require('./editalgorithmcategory.component.html'),
styles: [require('./editalgorithmcategory.component.css')],
})
export class | extends SecureComponent {
private category: any;
private id: number;
constructor(router:Router, protected client: APIService, private route: ActivatedRoute){
super(router, client);
this.authorities = ["ROLE_ADMIN"];
}
ngOnInit():void{
super.ngOnInit();
this.route.params.subscribe(params => {
let id = params['id'];
this.id = id;
this.getCategory();
});
}
getCategory(){
this.client.getAlgorithmCategoryByIdWithGET(this.id).subscribe((res:Response)=>{
this.category = JSON.parse(res.text())['category'];
},(err)=>{
this.hasError = true;
this.errorMessage = JSON.parse(err)['message'];
});
}
editAlgorithmCategory(experiment:any)
{
}
}
| EditAlgorithmCategoryComponent | identifier_name |
views.py | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# 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 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 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/>.
#
#########################################################################
from django.views.generic import View
from django.conf import settings
from geonode.base.enumerations import LINK_TYPES as _LT
# from geonode.base.models import Link
from geonode.utils import json_response
from geonode.geoserver import ows
LINK_TYPES = [L for L in _LT if L.startswith("OGC:")]
class OWSListView(View): | # per-layer links
# for link in Link.objects.filter(link_type__in=LINK_TYPES): # .distinct('url'):
# data.append({'url': link.url, 'type': link.link_type})
data.append({'url': ows._wcs_get_capabilities(), 'type': 'OGC:WCS'})
data.append({'url': ows._wfs_get_capabilities(), 'type': 'OGC:WFS'})
data.append({'url': ows._wms_get_capabilities(), 'type': 'OGC:WMS'})
# catalogue from configuration
for catname, catconf in settings.CATALOGUE.items():
data.append({'url': catconf['URL'], 'type': 'OGC:CSW'})
# main site url
data.append({'url': settings.SITEURL, 'type': 'WWW:LINK'})
return json_response(out)
ows_endpoints = OWSListView.as_view() |
def get(self, request):
out = {'success': True}
data = []
out['data'] = data | random_line_split |
views.py | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# 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 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 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/>.
#
#########################################################################
from django.views.generic import View
from django.conf import settings
from geonode.base.enumerations import LINK_TYPES as _LT
# from geonode.base.models import Link
from geonode.utils import json_response
from geonode.geoserver import ows
LINK_TYPES = [L for L in _LT if L.startswith("OGC:")]
class OWSListView(View):
def get(self, request):
out = {'success': True}
data = []
out['data'] = data
# per-layer links
# for link in Link.objects.filter(link_type__in=LINK_TYPES): # .distinct('url'):
# data.append({'url': link.url, 'type': link.link_type})
data.append({'url': ows._wcs_get_capabilities(), 'type': 'OGC:WCS'})
data.append({'url': ows._wfs_get_capabilities(), 'type': 'OGC:WFS'})
data.append({'url': ows._wms_get_capabilities(), 'type': 'OGC:WMS'})
# catalogue from configuration
for catname, catconf in settings.CATALOGUE.items():
|
# main site url
data.append({'url': settings.SITEURL, 'type': 'WWW:LINK'})
return json_response(out)
ows_endpoints = OWSListView.as_view()
| data.append({'url': catconf['URL'], 'type': 'OGC:CSW'}) | conditional_block |
views.py | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# 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 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 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/>.
#
#########################################################################
from django.views.generic import View
from django.conf import settings
from geonode.base.enumerations import LINK_TYPES as _LT
# from geonode.base.models import Link
from geonode.utils import json_response
from geonode.geoserver import ows
LINK_TYPES = [L for L in _LT if L.startswith("OGC:")]
class OWSListView(View):
def | (self, request):
out = {'success': True}
data = []
out['data'] = data
# per-layer links
# for link in Link.objects.filter(link_type__in=LINK_TYPES): # .distinct('url'):
# data.append({'url': link.url, 'type': link.link_type})
data.append({'url': ows._wcs_get_capabilities(), 'type': 'OGC:WCS'})
data.append({'url': ows._wfs_get_capabilities(), 'type': 'OGC:WFS'})
data.append({'url': ows._wms_get_capabilities(), 'type': 'OGC:WMS'})
# catalogue from configuration
for catname, catconf in settings.CATALOGUE.items():
data.append({'url': catconf['URL'], 'type': 'OGC:CSW'})
# main site url
data.append({'url': settings.SITEURL, 'type': 'WWW:LINK'})
return json_response(out)
ows_endpoints = OWSListView.as_view()
| get | identifier_name |
views.py | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# 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 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 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/>.
#
#########################################################################
from django.views.generic import View
from django.conf import settings
from geonode.base.enumerations import LINK_TYPES as _LT
# from geonode.base.models import Link
from geonode.utils import json_response
from geonode.geoserver import ows
LINK_TYPES = [L for L in _LT if L.startswith("OGC:")]
class OWSListView(View):
def get(self, request):
|
ows_endpoints = OWSListView.as_view()
| out = {'success': True}
data = []
out['data'] = data
# per-layer links
# for link in Link.objects.filter(link_type__in=LINK_TYPES): # .distinct('url'):
# data.append({'url': link.url, 'type': link.link_type})
data.append({'url': ows._wcs_get_capabilities(), 'type': 'OGC:WCS'})
data.append({'url': ows._wfs_get_capabilities(), 'type': 'OGC:WFS'})
data.append({'url': ows._wms_get_capabilities(), 'type': 'OGC:WMS'})
# catalogue from configuration
for catname, catconf in settings.CATALOGUE.items():
data.append({'url': catconf['URL'], 'type': 'OGC:CSW'})
# main site url
data.append({'url': settings.SITEURL, 'type': 'WWW:LINK'})
return json_response(out) | identifier_body |
WidgetLayout.compat.styles.ts | /**
* @author Adam Charron <adam.c@vanillaforums.com>
* @copyright 2009-2021 Vanilla Forums Inc.
* @license gpl-2.0-only
*/
import { injectGlobal } from "@emotion/css";
import { twoColumnClasses } from "@library/layout/types/layout.twoColumns";
import { EMPTY_WIDGET_SECTION } from "@library/layout/WidgetLayout.context";
import { widgetLayoutClasses } from "@library/layout/WidgetLayout.styles";
import { globalVariables } from "@library/styles/globalStyleVars";
import { Mixins } from "@library/styles/Mixins";
export function | () {
const classes = widgetLayoutClasses();
const panelLayoutClasses = twoColumnClasses();
const mainBodySelectors = `
.Content .${EMPTY_WIDGET_SECTION.widgetClass},
.Content .DataList,
.Content .Empty,
.Content .DataTable,
.Content .DataListWrap,
.Trace,
.Content .MessageList`;
injectGlobal({
[`.Frame-body .${EMPTY_WIDGET_SECTION.widgetClass}`]: classes.widgetMixin,
[`.Frame-body .${EMPTY_WIDGET_SECTION.widgetWithContainerClass}`]: classes.widgetWithContainerMixin,
[mainBodySelectors]: panelLayoutClasses.mainPanelWidgetMixin,
[`.pageHeadingBox + .DataList,
.pageHeadingBox + .Empty,
.pageHeadingBox + .DataTable,
.Content h2 + .${EMPTY_WIDGET_SECTION.widgetClass},
.Content h2 + .DataList,
.Content h2 + .DataListWrap,
.Content h2 + .Empty,
.Content h2 + .DataTable`]: {
marginTop: 0,
},
[`.Panel .${EMPTY_WIDGET_SECTION.widgetClass}, .Panel .Box`]: panelLayoutClasses.secondaryPanelWidgetMixin,
[`.Panel .BoxButtons`]: {
...Mixins.margin({
bottom: globalVariables().spacer.panelComponent * 1.5,
}),
},
[`.Frame-row .${EMPTY_WIDGET_SECTION.widgetClass}:first-child`]: {
marginTop: 0,
},
});
}
| widgetLayoutCompactCSS | identifier_name |
WidgetLayout.compat.styles.ts | /**
* @author Adam Charron <adam.c@vanillaforums.com>
* @copyright 2009-2021 Vanilla Forums Inc.
* @license gpl-2.0-only
*/
import { injectGlobal } from "@emotion/css";
import { twoColumnClasses } from "@library/layout/types/layout.twoColumns";
import { EMPTY_WIDGET_SECTION } from "@library/layout/WidgetLayout.context";
import { widgetLayoutClasses } from "@library/layout/WidgetLayout.styles";
import { globalVariables } from "@library/styles/globalStyleVars";
import { Mixins } from "@library/styles/Mixins";
export function widgetLayoutCompactCSS() | {
const classes = widgetLayoutClasses();
const panelLayoutClasses = twoColumnClasses();
const mainBodySelectors = `
.Content .${EMPTY_WIDGET_SECTION.widgetClass},
.Content .DataList,
.Content .Empty,
.Content .DataTable,
.Content .DataListWrap,
.Trace,
.Content .MessageList`;
injectGlobal({
[`.Frame-body .${EMPTY_WIDGET_SECTION.widgetClass}`]: classes.widgetMixin,
[`.Frame-body .${EMPTY_WIDGET_SECTION.widgetWithContainerClass}`]: classes.widgetWithContainerMixin,
[mainBodySelectors]: panelLayoutClasses.mainPanelWidgetMixin,
[`.pageHeadingBox + .DataList,
.pageHeadingBox + .Empty,
.pageHeadingBox + .DataTable,
.Content h2 + .${EMPTY_WIDGET_SECTION.widgetClass},
.Content h2 + .DataList,
.Content h2 + .DataListWrap,
.Content h2 + .Empty,
.Content h2 + .DataTable`]: {
marginTop: 0,
},
[`.Panel .${EMPTY_WIDGET_SECTION.widgetClass}, .Panel .Box`]: panelLayoutClasses.secondaryPanelWidgetMixin,
[`.Panel .BoxButtons`]: {
...Mixins.margin({
bottom: globalVariables().spacer.panelComponent * 1.5,
}),
},
[`.Frame-row .${EMPTY_WIDGET_SECTION.widgetClass}:first-child`]: {
marginTop: 0,
},
});
} | identifier_body | |
WidgetLayout.compat.styles.ts | /**
* @author Adam Charron <adam.c@vanillaforums.com>
* @copyright 2009-2021 Vanilla Forums Inc.
* @license gpl-2.0-only
*/
import { injectGlobal } from "@emotion/css";
import { twoColumnClasses } from "@library/layout/types/layout.twoColumns";
import { EMPTY_WIDGET_SECTION } from "@library/layout/WidgetLayout.context";
import { widgetLayoutClasses } from "@library/layout/WidgetLayout.styles";
import { globalVariables } from "@library/styles/globalStyleVars";
import { Mixins } from "@library/styles/Mixins";
export function widgetLayoutCompactCSS() {
const classes = widgetLayoutClasses();
const panelLayoutClasses = twoColumnClasses();
const mainBodySelectors = `
.Content .${EMPTY_WIDGET_SECTION.widgetClass},
.Content .DataList,
.Content .Empty,
.Content .DataTable,
.Content .DataListWrap,
.Trace,
.Content .MessageList`;
injectGlobal({
[`.Frame-body .${EMPTY_WIDGET_SECTION.widgetClass}`]: classes.widgetMixin,
[`.Frame-body .${EMPTY_WIDGET_SECTION.widgetWithContainerClass}`]: classes.widgetWithContainerMixin,
[mainBodySelectors]: panelLayoutClasses.mainPanelWidgetMixin,
[`.pageHeadingBox + .DataList,
.pageHeadingBox + .Empty,
.pageHeadingBox + .DataTable,
.Content h2 + .${EMPTY_WIDGET_SECTION.widgetClass},
.Content h2 + .DataList,
.Content h2 + .DataListWrap, |
[`.Panel .${EMPTY_WIDGET_SECTION.widgetClass}, .Panel .Box`]: panelLayoutClasses.secondaryPanelWidgetMixin,
[`.Panel .BoxButtons`]: {
...Mixins.margin({
bottom: globalVariables().spacer.panelComponent * 1.5,
}),
},
[`.Frame-row .${EMPTY_WIDGET_SECTION.widgetClass}:first-child`]: {
marginTop: 0,
},
});
} | .Content h2 + .Empty,
.Content h2 + .DataTable`]: {
marginTop: 0,
}, | random_line_split |
0001_initial.py | # Generated by Django 2.2.6 on 2019-10-31 08:31
from django.db import migrations, models
import multiselectfield.db.fields
class Migration(migrations.Migration):
| initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Book',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('categories', multiselectfield.db.fields.MultiSelectField(choices=[(1, 'Handbooks and manuals by discipline'), (2, 'Business books'), (3, 'Books of literary criticism'), (4, 'Books about literary theory'), (5, 'Books about literature')], default=1, max_length=9)),
('tags', multiselectfield.db.fields.MultiSelectField(blank=True, choices=[('sex', 'Sex'), ('work', 'Work'), ('happy', 'Happy'), ('food', 'Food'), ('field', 'Field'), ('boring', 'Boring'), ('interesting', 'Interesting'), ('huge', 'Huge'), ('nice', 'Nice')], max_length=54, null=True)),
('published_in', multiselectfield.db.fields.MultiSelectField(choices=[('Canada - Provinces', (('AB', 'Alberta'), ('BC', 'British Columbia'))), ('USA - States', (('AK', 'Alaska'), ('AL', 'Alabama'), ('AZ', 'Arizona')))], max_length=2, verbose_name='Province or State')),
('chapters', multiselectfield.db.fields.MultiSelectField(choices=[(1, 'Chapter I'), (2, 'Chapter II')], default=1, max_length=3)),
],
),
] | identifier_body | |
0001_initial.py | # Generated by Django 2.2.6 on 2019-10-31 08:31
from django.db import migrations, models
import multiselectfield.db.fields
class Migration(migrations.Migration):
initial = True
dependencies = [ | fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('categories', multiselectfield.db.fields.MultiSelectField(choices=[(1, 'Handbooks and manuals by discipline'), (2, 'Business books'), (3, 'Books of literary criticism'), (4, 'Books about literary theory'), (5, 'Books about literature')], default=1, max_length=9)),
('tags', multiselectfield.db.fields.MultiSelectField(blank=True, choices=[('sex', 'Sex'), ('work', 'Work'), ('happy', 'Happy'), ('food', 'Food'), ('field', 'Field'), ('boring', 'Boring'), ('interesting', 'Interesting'), ('huge', 'Huge'), ('nice', 'Nice')], max_length=54, null=True)),
('published_in', multiselectfield.db.fields.MultiSelectField(choices=[('Canada - Provinces', (('AB', 'Alberta'), ('BC', 'British Columbia'))), ('USA - States', (('AK', 'Alaska'), ('AL', 'Alabama'), ('AZ', 'Arizona')))], max_length=2, verbose_name='Province or State')),
('chapters', multiselectfield.db.fields.MultiSelectField(choices=[(1, 'Chapter I'), (2, 'Chapter II')], default=1, max_length=3)),
],
),
] | ]
operations = [
migrations.CreateModel(
name='Book', | random_line_split |
0001_initial.py | # Generated by Django 2.2.6 on 2019-10-31 08:31
from django.db import migrations, models
import multiselectfield.db.fields
class | (migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Book',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('categories', multiselectfield.db.fields.MultiSelectField(choices=[(1, 'Handbooks and manuals by discipline'), (2, 'Business books'), (3, 'Books of literary criticism'), (4, 'Books about literary theory'), (5, 'Books about literature')], default=1, max_length=9)),
('tags', multiselectfield.db.fields.MultiSelectField(blank=True, choices=[('sex', 'Sex'), ('work', 'Work'), ('happy', 'Happy'), ('food', 'Food'), ('field', 'Field'), ('boring', 'Boring'), ('interesting', 'Interesting'), ('huge', 'Huge'), ('nice', 'Nice')], max_length=54, null=True)),
('published_in', multiselectfield.db.fields.MultiSelectField(choices=[('Canada - Provinces', (('AB', 'Alberta'), ('BC', 'British Columbia'))), ('USA - States', (('AK', 'Alaska'), ('AL', 'Alabama'), ('AZ', 'Arizona')))], max_length=2, verbose_name='Province or State')),
('chapters', multiselectfield.db.fields.MultiSelectField(choices=[(1, 'Chapter I'), (2, 'Chapter II')], default=1, max_length=3)),
],
),
]
| Migration | identifier_name |
typehead.js | /* =============================================================
* bootstrap-typeahead.js v2.3.2
* http://getbootstrap.com/2.3.2/javascript.html#typeahead
* =============================================================
* Copyright 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
!function($){
"use strict";
/* TYPEAHEAD PUBLIC CLASS DEFINITION
* ================================= */
var Typeahead = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, $.fn.typeahead.defaults, options)
this.matcher = this.options.matcher || this.matcher
this.sorter = this.options.sorter || this.sorter
this.highlighter = this.options.highlighter || this.highlighter
this.updater = this.options.updater || this.updater
this.source = this.options.source
this.$menu = $(this.options.menu)
this.shown = false
this.listen()
}
Typeahead.prototype = {
constructor: Typeahead
, select: function () {
var val = this.$menu.find('.active').attr('data-value')
this.$element
.val(this.updater(val)) | return item
}
, show: function () {
var pos = $.extend({}, this.$element.position(), {
height: this.$element[0].offsetHeight
})
this.$menu
.insertAfter(this.$element)
.css({
top: pos.top + pos.height
, left: pos.left
})
.show()
this.shown = true
return this
}
, hide: function () {
this.$menu.hide()
this.shown = false
return this
}
, lookup: function (event) {
var items
this.query = this.$element.val()
if (!this.query || this.query.length < this.options.minLength) {
return this.shown ? this.hide() : this
}
items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source
return items ? this.process(items) : this
}
, process: function (items) {
var that = this
items = $.grep(items, function (item) {
return that.matcher(item)
})
items = this.sorter(items)
if (!items.length) {
return this.shown ? this.hide() : this
}
return this.render(items.slice(0, this.options.items)).show()
}
, matcher: function (item) {
return ~item.toLowerCase().indexOf(this.query.toLowerCase())
}
, sorter: function (items) {
var beginswith = []
, caseSensitive = []
, caseInsensitive = []
, item
while (item = items.shift()) {
if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item)
else if (~item.indexOf(this.query)) caseSensitive.push(item)
else caseInsensitive.push(item)
}
return beginswith.concat(caseSensitive, caseInsensitive)
}
, highlighter: function (item) {
var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>'
})
}
, render: function (items) {
var that = this
items = $(items).map(function (i, item) {
i = $(that.options.item).attr('data-value', item)
i.find('a').html(that.highlighter(item))
return i[0]
})
items.first().addClass('active')
this.$menu.html(items)
return this
}
, next: function (event) {
var active = this.$menu.find('.active').removeClass('active')
, next = active.next()
if (!next.length) {
next = $(this.$menu.find('li')[0])
}
next.addClass('active')
}
, prev: function (event) {
var active = this.$menu.find('.active').removeClass('active')
, prev = active.prev()
if (!prev.length) {
prev = this.$menu.find('li').last()
}
prev.addClass('active')
}
, listen: function () {
this.$element
.on('focus', $.proxy(this.focus, this))
.on('blur', $.proxy(this.blur, this))
.on('keypress', $.proxy(this.keypress, this))
.on('keyup', $.proxy(this.keyup, this))
if (this.eventSupported('keydown')) {
this.$element.on('keydown', $.proxy(this.keydown, this))
}
this.$menu
.on('click', $.proxy(this.click, this))
.on('mouseenter', 'li', $.proxy(this.mouseenter, this))
.on('mouseleave', 'li', $.proxy(this.mouseleave, this))
}
, eventSupported: function(eventName) {
var isSupported = eventName in this.$element
if (!isSupported) {
this.$element.setAttribute(eventName, 'return;')
isSupported = typeof this.$element[eventName] === 'function'
}
return isSupported
}
, move: function (e) {
if (!this.shown) return
switch(e.keyCode) {
case 9: // tab
case 13: // enter
case 27: // escape
e.preventDefault()
break
case 38: // up arrow
e.preventDefault()
this.prev()
break
case 40: // down arrow
e.preventDefault()
this.next()
break
}
e.stopPropagation()
}
, keydown: function (e) {
this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40,38,9,13,27])
this.move(e)
}
, keypress: function (e) {
if (this.suppressKeyPressRepeat) return
this.move(e)
}
, keyup: function (e) {
switch(e.keyCode) {
case 40: // down arrow
case 38: // up arrow
case 16: // shift
case 17: // ctrl
case 18: // alt
break
case 9: // tab
case 13: // enter
if (!this.shown) return
this.select()
break
case 27: // escape
if (!this.shown) return
this.hide()
break
default:
this.lookup()
}
e.stopPropagation()
e.preventDefault()
}
, focus: function (e) {
this.focused = true
}
, blur: function (e) {
this.focused = false
if (!this.mousedover && this.shown) this.hide()
}
, click: function (e) {
e.stopPropagation()
e.preventDefault()
this.select()
this.$element.focus()
}
, mouseenter: function (e) {
this.mousedover = true
this.$menu.find('.active').removeClass('active')
$(e.currentTarget).addClass('active')
}
, mouseleave: function (e) {
this.mousedover = false
if (!this.focused && this.shown) this.hide()
}
}
/* TYPEAHEAD PLUGIN DEFINITION
* =========================== */
var old = $.fn.typeahead
$.fn.typeahead = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('typeahead')
, options = typeof option == 'object' && option
if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.typeahead.defaults = {
source: []
, items: 8
, menu: '<ul class="typeahead dropdown-menu"></ul>'
, item: '<li><a href="#"></a></li>'
, minLength: 1
}
$.fn.typeahead.Constructor = Typeahead
/* TYPEAHEAD NO CONFLICT
* =================== */
$.fn.typeahead.noConflict = function () {
$.fn.typeahead = old
return this
}
/* TYPEAHEAD DATA-API
* ================== */
$(document).on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
var $this = $(this)
if ($this.data('typeahead')) return
$this.typeahead($this.data())
})
}(window.jQuery); | .change()
return this.hide()
}
, updater: function (item) { | random_line_split |
liquidball.js | import React, {Component, PropTypes} from 'react';
import ReactEcharts from 'echarts-for-react';
import 'echarts-liquidfill';
// 用于统计当日金额的组件
class LiquidBall extends Component {
constructor(props) {
super(props);
}
// 初次渲染后执行此方法
componentDidMount() {
setTimeout(() => {
this.refs.liquidBall.getEchartsInstance().resize();
}, 0);
}
render() {
return (
<R | harts ref='liquidBall'
option={this.getOption()}
style={{height: '100%', width: '100%'}}/>
);
}
getOption() {
let {name, value, unit, borderColor, rippleColor = []} = this.props;
var option = {
series: [{
type: 'liquidFill',
name: name,
radius: '90%',
backgroundStyle: {
color: '#0e1e37'
},
data: [{
name: value + unit,
value: 0.8,
itemStyle: {
normal: {
color: rippleColor[0]
}
}
}, {
// name: value + unit,
value: 0.7,
itemStyle: {
normal: {
color: rippleColor[1]
}
}
}],
itemStyle: {
normal: {
shadowBlur: 0
}
},
outline: {
borderDistance: 0,
itemStyle: {
borderWidth: 3,
borderColor: borderColor || '#6176a5',
shadowBlur: 2
}
},
label: {
normal: {
formatter: function (param) {
return param.seriesName + '\n' + '\n'
+ param.name + '\n';
// let str =[
// '<p>'+param.seriesName+'</p>',
// '<p>'+param.name+'</span>',
// ];
//
// return str;
},
// color: 'red',
// insideColor: 'yellow',
textStyle: {
fontSize: 16,
align: 'center',
baseline: 'middle',
fontWeight: 300
},
position: ['50%', '65%']
}
}
}]
};
return option;
}
}
export default LiquidBall; | eactEc | identifier_name |
liquidball.js | import React, {Component, PropTypes} from 'react';
import ReactEcharts from 'echarts-for-react';
import 'echarts-liquidfill';
// 用于统计当日金额的组件
class LiquidBall extends Component {
constructor(props) {
super(props);
}
// 初次渲染后执行此方法
componentDidMount() {
setTimeout(() => {
this.refs.liquidBall.getEchartsInstance().resize();
}, 0);
}
render() {
return (
<ReactEcharts ref='liquidBall'
option={this.getOption()}
style={{height: '100%', width: '100%'}}/>
);
}
getOption() {
let {name, value, unit, borderCo | lor, rippleColor = []} = this.props;
var option = {
series: [{
type: 'liquidFill',
name: name,
radius: '90%',
backgroundStyle: {
color: '#0e1e37'
},
data: [{
name: value + unit,
value: 0.8,
itemStyle: {
normal: {
color: rippleColor[0]
}
}
}, {
// name: value + unit,
value: 0.7,
itemStyle: {
normal: {
color: rippleColor[1]
}
}
}],
itemStyle: {
normal: {
shadowBlur: 0
}
},
outline: {
borderDistance: 0,
itemStyle: {
borderWidth: 3,
borderColor: borderColor || '#6176a5',
shadowBlur: 2
}
},
label: {
normal: {
formatter: function (param) {
return param.seriesName + '\n' + '\n'
+ param.name + '\n';
// let str =[
// '<p>'+param.seriesName+'</p>',
// '<p>'+param.name+'</span>',
// ];
//
// return str;
},
// color: 'red',
// insideColor: 'yellow',
textStyle: {
fontSize: 16,
align: 'center',
baseline: 'middle',
fontWeight: 300
},
position: ['50%', '65%']
}
}
}]
};
return option;
}
}
export default LiquidBall; | identifier_body | |
liquidball.js | import React, {Component, PropTypes} from 'react';
import ReactEcharts from 'echarts-for-react';
import 'echarts-liquidfill';
// 用于统计当日金额的组件
class LiquidBall extends Component {
constructor(props) {
super(props);
}
// 初次渲染后执行此方法
componentDidMount() {
setTimeout(() => {
this.refs.liquidBall.getEchartsInstance().resize();
}, 0);
}
render() {
return (
<ReactEcharts ref='liquidBall'
option={this.getOption()}
style={{height: '100%', width: '100%'}}/>
);
}
getOption() {
let {name, value, unit, borderColor, rippleColor = []} = this.props;
var option = {
series: [{
type: 'liquidFill',
name: name,
radius: '90%',
backgroundStyle: {
color: '#0e1e37'
},
data: [{
name: value + unit,
value: 0.8,
itemStyle: {
normal: {
color: rippleColor[0]
}
}
}, {
// name: value + unit,
value: 0.7,
itemStyle: {
normal: {
color: rippleColor[1]
}
}
}],
itemStyle: {
normal: {
shadowBlur: 0
}
},
outline: {
borderDistance: 0,
itemStyle: {
borderWidth: 3,
borderColor: borderColor || '#6176a5',
shadowBlur: 2
}
},
label: {
normal: {
formatter: function (param) {
return param.seriesName + '\n' + '\n'
+ param.name + '\n';
// let str =[
// '<p>'+param.seriesName+'</p>',
// '<p>'+param.name+'</span>',
// ];
//
// return str;
},
// color: 'red',
// insideColor: 'yellow',
textStyle: {
fontSize: 16,
align: 'center',
baseline: 'middle',
fontWeight: 300
},
position: ['50%', '65%']
}
}
}]
};
return option;
}
}
| export default LiquidBall; | random_line_split | |
main.rs | extern crate crypto;
extern crate itertools;
use std::env;
use crypto::md5::Md5;
use crypto::digest::Digest;
use std::collections::HashMap;
fn main() {
let raw_input = env::args().nth(1).unwrap_or("".to_string());
let input = raw_input.as_bytes();
let mut index : i64 = -1;
let mut hash = Md5::new();
let mut output = String::new();
let mut output2 = HashMap::new();
while {output.len() < 8 || output2.len() < 8} {
let mut temp = [0; 16];
while {
index += 1;
hash.reset();
hash.input(input);
hash.input(index.to_string().as_bytes());
hash.result(&mut temp);
(temp[0] as i32 + temp[1] as i32 + (temp[2] >> 4) as i32) != 0
} {}
let out = format!("{:x}", temp[2] & 0xf);
let out2 = format!("{:x}", temp[3] >> 4);
let pos = (temp[2] & 0x0f) as i32;
if output.len() < 8 |
if pos < 8 && !output2.contains_key(&pos) {
output2.insert(pos, out2);
}
}
println!("P1 {}", output);
let empty = " ".to_string();
let temp = (0..8)
.map(|i| output2.get(&(i as i32)).unwrap_or(&empty))
.cloned()
.collect::<Vec<_>>()
.concat();
println!("P2 {}", temp);
}
| {
output.push_str(&out);
} | conditional_block |
main.rs | extern crate crypto;
extern crate itertools;
use std::env;
use crypto::md5::Md5;
use crypto::digest::Digest;
use std::collections::HashMap;
fn | () {
let raw_input = env::args().nth(1).unwrap_or("".to_string());
let input = raw_input.as_bytes();
let mut index : i64 = -1;
let mut hash = Md5::new();
let mut output = String::new();
let mut output2 = HashMap::new();
while {output.len() < 8 || output2.len() < 8} {
let mut temp = [0; 16];
while {
index += 1;
hash.reset();
hash.input(input);
hash.input(index.to_string().as_bytes());
hash.result(&mut temp);
(temp[0] as i32 + temp[1] as i32 + (temp[2] >> 4) as i32) != 0
} {}
let out = format!("{:x}", temp[2] & 0xf);
let out2 = format!("{:x}", temp[3] >> 4);
let pos = (temp[2] & 0x0f) as i32;
if output.len() < 8 {
output.push_str(&out);
}
if pos < 8 && !output2.contains_key(&pos) {
output2.insert(pos, out2);
}
}
println!("P1 {}", output);
let empty = " ".to_string();
let temp = (0..8)
.map(|i| output2.get(&(i as i32)).unwrap_or(&empty))
.cloned()
.collect::<Vec<_>>()
.concat();
println!("P2 {}", temp);
}
| main | identifier_name |
main.rs | extern crate crypto;
extern crate itertools;
use std::env;
use crypto::md5::Md5;
use crypto::digest::Digest;
use std::collections::HashMap;
fn main() | {
let raw_input = env::args().nth(1).unwrap_or("".to_string());
let input = raw_input.as_bytes();
let mut index : i64 = -1;
let mut hash = Md5::new();
let mut output = String::new();
let mut output2 = HashMap::new();
while {output.len() < 8 || output2.len() < 8} {
let mut temp = [0; 16];
while {
index += 1;
hash.reset();
hash.input(input);
hash.input(index.to_string().as_bytes());
hash.result(&mut temp);
(temp[0] as i32 + temp[1] as i32 + (temp[2] >> 4) as i32) != 0
} {}
let out = format!("{:x}", temp[2] & 0xf);
let out2 = format!("{:x}", temp[3] >> 4);
let pos = (temp[2] & 0x0f) as i32;
if output.len() < 8 {
output.push_str(&out);
}
if pos < 8 && !output2.contains_key(&pos) {
output2.insert(pos, out2);
}
}
println!("P1 {}", output);
let empty = " ".to_string();
let temp = (0..8)
.map(|i| output2.get(&(i as i32)).unwrap_or(&empty))
.cloned()
.collect::<Vec<_>>()
.concat();
println!("P2 {}", temp);
} | identifier_body | |
main.rs | extern crate crypto;
extern crate itertools;
use std::env;
use crypto::md5::Md5;
use crypto::digest::Digest;
use std::collections::HashMap;
fn main() {
let raw_input = env::args().nth(1).unwrap_or("".to_string());
let input = raw_input.as_bytes();
let mut index : i64 = -1;
let mut hash = Md5::new();
let mut output = String::new();
let mut output2 = HashMap::new();
while {output.len() < 8 || output2.len() < 8} {
let mut temp = [0; 16];
while {
index += 1;
hash.reset(); |
hash.input(input);
hash.input(index.to_string().as_bytes());
hash.result(&mut temp);
(temp[0] as i32 + temp[1] as i32 + (temp[2] >> 4) as i32) != 0
} {}
let out = format!("{:x}", temp[2] & 0xf);
let out2 = format!("{:x}", temp[3] >> 4);
let pos = (temp[2] & 0x0f) as i32;
if output.len() < 8 {
output.push_str(&out);
}
if pos < 8 && !output2.contains_key(&pos) {
output2.insert(pos, out2);
}
}
println!("P1 {}", output);
let empty = " ".to_string();
let temp = (0..8)
.map(|i| output2.get(&(i as i32)).unwrap_or(&empty))
.cloned()
.collect::<Vec<_>>()
.concat();
println!("P2 {}", temp);
} | random_line_split | |
2018-09-19_09:49:05__251447ab2060.py | """empty message
Revision ID: 251447ab2060
Revises: 53ac0b4e8891
Create Date: 2018-09-19 09:49:05.552597
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '251447ab2060'
down_revision = '53ac0b4e8891'
branch_labels = None
depends_on = None
def | ():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('transactions', sa.Column('lot_number', sa.String(length=64), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('transactions', 'lot_number')
# ### end Alembic commands ###
| upgrade | identifier_name |
2018-09-19_09:49:05__251447ab2060.py | """empty message
Revision ID: 251447ab2060
Revises: 53ac0b4e8891
Create Date: 2018-09-19 09:49:05.552597
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '251447ab2060' | depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('transactions', sa.Column('lot_number', sa.String(length=64), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('transactions', 'lot_number')
# ### end Alembic commands ### | down_revision = '53ac0b4e8891'
branch_labels = None | random_line_split |
2018-09-19_09:49:05__251447ab2060.py | """empty message
Revision ID: 251447ab2060
Revises: 53ac0b4e8891
Create Date: 2018-09-19 09:49:05.552597
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '251447ab2060'
down_revision = '53ac0b4e8891'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
|
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('transactions', 'lot_number')
# ### end Alembic commands ###
| op.add_column('transactions', sa.Column('lot_number', sa.String(length=64), nullable=True))
# ### end Alembic commands ### | identifier_body |
index.ts | export const PROPERTY_BASED_DESCRIPTORS = !!'3.2.0';
export const EMBER_EXTEND_PROTOTYPES = !!'3.2.0-beta.5';
export const DEPRECATE_OPTIONS_MISSING = !!'2.1.0-beta.1';
export const DEPRECATE_ID_MISSING = !!'2.1.0-beta.1';
export const DEPRECATE_UNTIL_MISSING = !!'2.1.0-beta.1';
export const RUN_SYNC = !!'3.0.0-beta.4';
export const REGISTRY_RESOLVER_AS_FUNCTION = !!'2.3.0-beta.3';
export const LOGGER = !!'3.2.0-beta.1';
export const POSITIONAL_PARAM_CONFLICT = !!'3.1.0-beta.1';
export const DID_INIT_ATTRS = !!'2.6.0-beta.1'; | export const ARRAY_AT_EACH = !!'3.1.0-beta.1';
export const TARGET_OBJECT = !!'2.18.0-beta.1';
export const RENDER_HELPER = !!'2.11.0-beta.1';
export const BINDING_SUPPORT = !!'2.7.0-beta.1'; | export const PROPERTY_WILL_CHANGE = !!'3.1.0-beta.1';
export const PROPERTY_DID_CHANGE = !!'3.1.0-beta.1';
export const ROUTER_ROUTER = !!'3.2.0-beta.1';
export const ORPHAN_OUTLET_RENDER = !!'2.11.0-beta.1'; | random_line_split |
set.js | require('ember-runtime/core');
require('ember-runtime/system/core_object');
require('ember-runtime/mixins/mutable_enumerable');
require('ember-runtime/mixins/copyable');
require('ember-runtime/mixins/freezable');
/**
@module ember
@submodule ember-runtime
*/
var get = Ember.get, set = Ember.set, guidFor = Ember.guidFor, isNone = Ember.isNone, fmt = Ember.String.fmt;
/**
An unordered collection of objects.
A Set works a bit like an array except that its items are not ordered. You
can create a set to efficiently test for membership for an object. You can
also iterate through a set just like an array, even accessing objects by
index, however there is no guarantee as to their order.
All Sets are observable via the Enumerable Observer API - which works
on any enumerable object including both Sets and Arrays.
## Creating a Set
You can create a set like you would most objects using
`new Ember.Set()`. Most new sets you create will be empty, but you can
also initialize the set with some content by passing an array or other
enumerable of objects to the constructor.
Finally, you can pass in an existing set and the set will be copied. You
can also create a copy of a set by calling `Ember.Set#copy()`.
```javascript
// creates a new empty set
var foundNames = new Ember.Set();
// creates a set with four names in it.
var names = new Ember.Set(["Charles", "Tom", "Juan", "Alex"]); // :P
// creates a copy of the names set.
var namesCopy = new Ember.Set(names);
// same as above.
var anotherNamesCopy = names.copy();
```
## Adding/Removing Objects
You generally add or remove objects from a set using `add()` or
`remove()`. You can add any type of object including primitives such as
numbers, strings, and booleans.
Unlike arrays, objects can only exist one time in a set. If you call `add()`
on a set with the same object multiple times, the object will only be added
once. Likewise, calling `remove()` with the same object multiple times will
remove the object the first time and have no effect on future calls until
you add the object to the set again.
NOTE: You cannot add/remove `null` or `undefined` to a set. Any attempt to do
so will be ignored.
In addition to add/remove you can also call `push()`/`pop()`. Push behaves
just like `add()` but `pop()`, unlike `remove()` will pick an arbitrary
object, remove it and return it. This is a good way to use a set as a job
queue when you don't care which order the jobs are executed in.
## Testing for an Object
To test for an object's presence in a set you simply call
`Ember.Set#contains()`.
## Observing changes
When using `Ember.Set`, you can observe the `"[]"` property to be
alerted whenever the content changes. You can also add an enumerable
observer to the set to be notified of specific objects that are added and
removed from the set. See `Ember.Enumerable` for more information on
enumerables.
This is often unhelpful. If you are filtering sets of objects, for instance,
it is very inefficient to re-filter all of the items each time the set
changes. It would be better if you could just adjust the filtered set based
on what was changed on the original set. The same issue applies to merging
sets, as well.
## Other Methods
`Ember.Set` primary implements other mixin APIs. For a complete reference
on the methods you will use with `Ember.Set`, please consult these mixins.
The most useful ones will be `Ember.Enumerable` and
`Ember.MutableEnumerable` which implement most of the common iterator
methods you are used to on Array.
Note that you can also use the `Ember.Copyable` and `Ember.Freezable`
APIs on `Ember.Set` as well. Once a set is frozen it can no longer be
modified. The benefit of this is that when you call `frozenCopy()` on it,
Ember will avoid making copies of the set. This allows you to write
code that can know with certainty when the underlying set data will or
will not be modified.
@class Set
@namespace Ember
@extends Ember.CoreObject
@uses Ember.MutableEnumerable
@uses Ember.Copyable
@uses Ember.Freezable
@since Ember 0.9
*/
Ember.Set = Ember.CoreObject.extend(Ember.MutableEnumerable, Ember.Copyable, Ember.Freezable,
/** @scope Ember.Set.prototype */ {
// ..........................................................
// IMPLEMENT ENUMERABLE APIS
//
/**
This property will change as the number of objects in the set changes.
@property length
@type number
@default 0
*/
length: 0,
/**
Clears the set. This is useful if you want to reuse an existing set
without having to recreate it.
```javascript
var colors = new Ember.Set(["red", "green", "blue"]);
colors.length; // 3
colors.clear();
colors.length; // 0
```
@method clear
@return {Ember.Set} An empty Set
*/
clear: function() {
if (this.isFrozen) { throw new Error(Ember.FROZEN_ERROR); }
var len = get(this, 'length');
if (len === 0) { return this; }
var guid;
this.enumerableContentWillChange(len, 0);
Ember.propertyWillChange(this, 'firstObject');
Ember.propertyWillChange(this, 'lastObject');
for (var i=0; i < len; i++){
guid = guidFor(this[i]);
delete this[guid];
delete this[i];
}
set(this, 'length', 0);
Ember.propertyDidChange(this, 'firstObject');
Ember.propertyDidChange(this, 'lastObject');
this.enumerableContentDidChange(len, 0);
return this;
},
/**
Returns true if the passed object is also an enumerable that contains the
same objects as the receiver.
```javascript
var colors = ["red", "green", "blue"],
same_colors = new Ember.Set(colors);
same_colors.isEqual(colors); // true
same_colors.isEqual(["purple", "brown"]); // false
```
@method isEqual
@param {Ember.Set} obj the other object.
@return {Boolean}
*/
isEqual: function(obj) {
// fail fast
if (!Ember.Enumerable.detect(obj)) return false;
var loc = get(this, 'length');
if (get(obj, 'length') !== loc) return false;
while(--loc >= 0) {
if (!obj.contains(this[loc])) return false;
}
return true;
},
/**
Adds an object to the set. Only non-`null` objects can be added to a set
and those can only be added once. If the object is already in the set or
the passed value is null this method will have no effect.
This is an alias for `Ember.MutableEnumerable.addObject()`.
```javascript
var colors = new Ember.Set();
colors.add("blue"); // ["blue"]
colors.add("blue"); // ["blue"]
colors.add("red"); // ["blue", "red"]
colors.add(null); // ["blue", "red"]
colors.add(undefined); // ["blue", "red"]
```
@method add
@param {Object} obj The object to add.
@return {Ember.Set} The set itself.
*/
add: Ember.aliasMethod('addObject'),
/**
Removes the object from the set if it is found. If you pass a `null` value
or an object that is already not in the set, this method will have no
effect. This is an alias for `Ember.MutableEnumerable.removeObject()`.
```javascript
var colors = new Ember.Set(["red", "green", "blue"]);
colors.remove("red"); // ["blue", "green"]
colors.remove("purple"); // ["blue", "green"]
colors.remove(null); // ["blue", "green"]
```
@method remove
@param {Object} obj The object to remove
@return {Ember.Set} The set itself.
*/
remove: Ember.aliasMethod('removeObject'),
/**
Removes the last element from the set and returns it, or `null` if it's empty.
```javascript
var colors = new Ember.Set(["green", "blue"]);
colors.pop(); // "blue"
colors.pop(); // "green"
colors.pop(); // null
```
@method pop
@return {Object} The removed object from the set or null.
*/
pop: function() {
if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR);
var obj = this.length > 0 ? this[this.length-1] : null;
this.remove(obj);
return obj;
},
/**
Inserts the given object on to the end of the set. It returns
the set itself.
This is an alias for `Ember.MutableEnumerable.addObject()`.
```javascript
var colors = new Ember.Set();
colors.push("red"); // ["red"]
colors.push("green"); // ["red", "green"]
colors.push("blue"); // ["red", "green", "blue"]
```
@method push
@return {Ember.Set} The set itself.
*/
push: Ember.aliasMethod('addObject'),
/**
Removes the last element from the set and returns it, or `null` if it's empty.
This is an alias for `Ember.Set.pop()`.
```javascript
var colors = new Ember.Set(["green", "blue"]);
colors.shift(); // "blue"
colors.shift(); // "green"
colors.shift(); // null
```
@method shift
@return {Object} The removed object from the set or null.
*/
shift: Ember.aliasMethod('pop'),
/**
Inserts the given object on to the end of the set. It returns
the set itself.
This is an alias of `Ember.Set.push()`
```javascript
var colors = new Ember.Set();
colors.unshift("red"); // ["red"]
colors.unshift("green"); // ["red", "green"]
colors.unshift("blue"); // ["red", "green", "blue"]
```
@method unshift
@return {Ember.Set} The set itself.
*/
unshift: Ember.aliasMethod('push'),
/**
Adds each object in the passed enumerable to the set.
This is an alias of `Ember.MutableEnumerable.addObjects()`
```javascript
var colors = new Ember.Set();
colors.addEach(["red", "green", "blue"]); // ["red", "green", "blue"]
```
@method addEach
@param {Ember.Enumerable} objects the objects to add.
@return {Ember.Set} The set itself.
*/
addEach: Ember.aliasMethod('addObjects'),
/**
Removes each object in the passed enumerable to the set.
This is an alias of `Ember.MutableEnumerable.removeObjects()`
```javascript
var colors = new Ember.Set(["red", "green", "blue"]);
colors.removeEach(["red", "blue"]); // ["green"]
```
@method removeEach
@param {Ember.Enumerable} objects the objects to remove.
@return {Ember.Set} The set itself.
*/
removeEach: Ember.aliasMethod('removeObjects'),
// ..........................................................
// PRIVATE ENUMERABLE SUPPORT
//
init: function(items) {
this._super();
if (items) this.addObjects(items);
},
// implement Ember.Enumerable
nextObject: function(idx) {
return this[idx];
},
// more optimized version
firstObject: Ember.computed(function() {
return this.length > 0 ? this[0] : undefined;
}),
// more optimized version
lastObject: Ember.computed(function() {
return this.length > 0 ? this[this.length-1] : undefined;
}),
// implements Ember.MutableEnumerable
addObject: function(obj) {
if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR);
if (isNone(obj)) return this; // nothing to do
var guid = guidFor(obj),
idx = this[guid],
len = get(this, 'length'),
added ;
if (idx>=0 && idx<len && (this[idx] === obj)) return this; // added
added = [obj];
this.enumerableContentWillChange(null, added);
Ember.propertyWillChange(this, 'lastObject');
len = get(this, 'length');
this[guid] = len;
this[len] = obj;
set(this, 'length', len+1);
Ember.propertyDidChange(this, 'lastObject');
this.enumerableContentDidChange(null, added);
return this;
},
// implements Ember.MutableEnumerable
removeObject: function(obj) {
if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR);
if (isNone(obj)) return this; // nothing to do
var guid = guidFor(obj),
idx = this[guid],
len = get(this, 'length'),
isFirst = idx === 0,
isLast = idx === len-1,
last, removed;
if (idx>=0 && idx<len && (this[idx] === obj)) {
removed = [obj];
this.enumerableContentWillChange(removed, null);
if (isFirst) { Ember.propertyWillChange(this, 'firstObject'); }
if (isLast) { Ember.propertyWillChange(this, 'lastObject'); }
// swap items - basically move the item to the end so it can be removed
if (idx < len-1) {
last = this[len-1];
this[idx] = last;
this[guidFor(last)] = idx;
}
delete this[guid];
delete this[len-1];
set(this, 'length', len-1);
if (isFirst) { Ember.propertyDidChange(this, 'firstObject'); }
if (isLast) { Ember.propertyDidChange(this, 'lastObject'); }
this.enumerableContentDidChange(removed, null);
} |
// optimized version
contains: function(obj) {
return this[guidFor(obj)]>=0;
},
copy: function() {
var C = this.constructor, ret = new C(), loc = get(this, 'length');
set(ret, 'length', loc);
while(--loc>=0) {
ret[loc] = this[loc];
ret[guidFor(this[loc])] = loc;
}
return ret;
},
toString: function() {
var len = this.length, idx, array = [];
for(idx = 0; idx < len; idx++) {
array[idx] = this[idx];
}
return fmt("Ember.Set<%@>", [array.join(',')]);
}
}); |
return this;
}, | random_line_split |
set.js | require('ember-runtime/core');
require('ember-runtime/system/core_object');
require('ember-runtime/mixins/mutable_enumerable');
require('ember-runtime/mixins/copyable');
require('ember-runtime/mixins/freezable');
/**
@module ember
@submodule ember-runtime
*/
var get = Ember.get, set = Ember.set, guidFor = Ember.guidFor, isNone = Ember.isNone, fmt = Ember.String.fmt;
/**
An unordered collection of objects.
A Set works a bit like an array except that its items are not ordered. You
can create a set to efficiently test for membership for an object. You can
also iterate through a set just like an array, even accessing objects by
index, however there is no guarantee as to their order.
All Sets are observable via the Enumerable Observer API - which works
on any enumerable object including both Sets and Arrays.
## Creating a Set
You can create a set like you would most objects using
`new Ember.Set()`. Most new sets you create will be empty, but you can
also initialize the set with some content by passing an array or other
enumerable of objects to the constructor.
Finally, you can pass in an existing set and the set will be copied. You
can also create a copy of a set by calling `Ember.Set#copy()`.
```javascript
// creates a new empty set
var foundNames = new Ember.Set();
// creates a set with four names in it.
var names = new Ember.Set(["Charles", "Tom", "Juan", "Alex"]); // :P
// creates a copy of the names set.
var namesCopy = new Ember.Set(names);
// same as above.
var anotherNamesCopy = names.copy();
```
## Adding/Removing Objects
You generally add or remove objects from a set using `add()` or
`remove()`. You can add any type of object including primitives such as
numbers, strings, and booleans.
Unlike arrays, objects can only exist one time in a set. If you call `add()`
on a set with the same object multiple times, the object will only be added
once. Likewise, calling `remove()` with the same object multiple times will
remove the object the first time and have no effect on future calls until
you add the object to the set again.
NOTE: You cannot add/remove `null` or `undefined` to a set. Any attempt to do
so will be ignored.
In addition to add/remove you can also call `push()`/`pop()`. Push behaves
just like `add()` but `pop()`, unlike `remove()` will pick an arbitrary
object, remove it and return it. This is a good way to use a set as a job
queue when you don't care which order the jobs are executed in.
## Testing for an Object
To test for an object's presence in a set you simply call
`Ember.Set#contains()`.
## Observing changes
When using `Ember.Set`, you can observe the `"[]"` property to be
alerted whenever the content changes. You can also add an enumerable
observer to the set to be notified of specific objects that are added and
removed from the set. See `Ember.Enumerable` for more information on
enumerables.
This is often unhelpful. If you are filtering sets of objects, for instance,
it is very inefficient to re-filter all of the items each time the set
changes. It would be better if you could just adjust the filtered set based
on what was changed on the original set. The same issue applies to merging
sets, as well.
## Other Methods
`Ember.Set` primary implements other mixin APIs. For a complete reference
on the methods you will use with `Ember.Set`, please consult these mixins.
The most useful ones will be `Ember.Enumerable` and
`Ember.MutableEnumerable` which implement most of the common iterator
methods you are used to on Array.
Note that you can also use the `Ember.Copyable` and `Ember.Freezable`
APIs on `Ember.Set` as well. Once a set is frozen it can no longer be
modified. The benefit of this is that when you call `frozenCopy()` on it,
Ember will avoid making copies of the set. This allows you to write
code that can know with certainty when the underlying set data will or
will not be modified.
@class Set
@namespace Ember
@extends Ember.CoreObject
@uses Ember.MutableEnumerable
@uses Ember.Copyable
@uses Ember.Freezable
@since Ember 0.9
*/
Ember.Set = Ember.CoreObject.extend(Ember.MutableEnumerable, Ember.Copyable, Ember.Freezable,
/** @scope Ember.Set.prototype */ {
// ..........................................................
// IMPLEMENT ENUMERABLE APIS
//
/**
This property will change as the number of objects in the set changes.
@property length
@type number
@default 0
*/
length: 0,
/**
Clears the set. This is useful if you want to reuse an existing set
without having to recreate it.
```javascript
var colors = new Ember.Set(["red", "green", "blue"]);
colors.length; // 3
colors.clear();
colors.length; // 0
```
@method clear
@return {Ember.Set} An empty Set
*/
clear: function() {
if (this.isFrozen) { throw new Error(Ember.FROZEN_ERROR); }
var len = get(this, 'length');
if (len === 0) { return this; }
var guid;
this.enumerableContentWillChange(len, 0);
Ember.propertyWillChange(this, 'firstObject');
Ember.propertyWillChange(this, 'lastObject');
for (var i=0; i < len; i++){
guid = guidFor(this[i]);
delete this[guid];
delete this[i];
}
set(this, 'length', 0);
Ember.propertyDidChange(this, 'firstObject');
Ember.propertyDidChange(this, 'lastObject');
this.enumerableContentDidChange(len, 0);
return this;
},
/**
Returns true if the passed object is also an enumerable that contains the
same objects as the receiver.
```javascript
var colors = ["red", "green", "blue"],
same_colors = new Ember.Set(colors);
same_colors.isEqual(colors); // true
same_colors.isEqual(["purple", "brown"]); // false
```
@method isEqual
@param {Ember.Set} obj the other object.
@return {Boolean}
*/
isEqual: function(obj) {
// fail fast
if (!Ember.Enumerable.detect(obj)) return false;
var loc = get(this, 'length');
if (get(obj, 'length') !== loc) return false;
while(--loc >= 0) {
if (!obj.contains(this[loc])) return false;
}
return true;
},
/**
Adds an object to the set. Only non-`null` objects can be added to a set
and those can only be added once. If the object is already in the set or
the passed value is null this method will have no effect.
This is an alias for `Ember.MutableEnumerable.addObject()`.
```javascript
var colors = new Ember.Set();
colors.add("blue"); // ["blue"]
colors.add("blue"); // ["blue"]
colors.add("red"); // ["blue", "red"]
colors.add(null); // ["blue", "red"]
colors.add(undefined); // ["blue", "red"]
```
@method add
@param {Object} obj The object to add.
@return {Ember.Set} The set itself.
*/
add: Ember.aliasMethod('addObject'),
/**
Removes the object from the set if it is found. If you pass a `null` value
or an object that is already not in the set, this method will have no
effect. This is an alias for `Ember.MutableEnumerable.removeObject()`.
```javascript
var colors = new Ember.Set(["red", "green", "blue"]);
colors.remove("red"); // ["blue", "green"]
colors.remove("purple"); // ["blue", "green"]
colors.remove(null); // ["blue", "green"]
```
@method remove
@param {Object} obj The object to remove
@return {Ember.Set} The set itself.
*/
remove: Ember.aliasMethod('removeObject'),
/**
Removes the last element from the set and returns it, or `null` if it's empty.
```javascript
var colors = new Ember.Set(["green", "blue"]);
colors.pop(); // "blue"
colors.pop(); // "green"
colors.pop(); // null
```
@method pop
@return {Object} The removed object from the set or null.
*/
pop: function() {
if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR);
var obj = this.length > 0 ? this[this.length-1] : null;
this.remove(obj);
return obj;
},
/**
Inserts the given object on to the end of the set. It returns
the set itself.
This is an alias for `Ember.MutableEnumerable.addObject()`.
```javascript
var colors = new Ember.Set();
colors.push("red"); // ["red"]
colors.push("green"); // ["red", "green"]
colors.push("blue"); // ["red", "green", "blue"]
```
@method push
@return {Ember.Set} The set itself.
*/
push: Ember.aliasMethod('addObject'),
/**
Removes the last element from the set and returns it, or `null` if it's empty.
This is an alias for `Ember.Set.pop()`.
```javascript
var colors = new Ember.Set(["green", "blue"]);
colors.shift(); // "blue"
colors.shift(); // "green"
colors.shift(); // null
```
@method shift
@return {Object} The removed object from the set or null.
*/
shift: Ember.aliasMethod('pop'),
/**
Inserts the given object on to the end of the set. It returns
the set itself.
This is an alias of `Ember.Set.push()`
```javascript
var colors = new Ember.Set();
colors.unshift("red"); // ["red"]
colors.unshift("green"); // ["red", "green"]
colors.unshift("blue"); // ["red", "green", "blue"]
```
@method unshift
@return {Ember.Set} The set itself.
*/
unshift: Ember.aliasMethod('push'),
/**
Adds each object in the passed enumerable to the set.
This is an alias of `Ember.MutableEnumerable.addObjects()`
```javascript
var colors = new Ember.Set();
colors.addEach(["red", "green", "blue"]); // ["red", "green", "blue"]
```
@method addEach
@param {Ember.Enumerable} objects the objects to add.
@return {Ember.Set} The set itself.
*/
addEach: Ember.aliasMethod('addObjects'),
/**
Removes each object in the passed enumerable to the set.
This is an alias of `Ember.MutableEnumerable.removeObjects()`
```javascript
var colors = new Ember.Set(["red", "green", "blue"]);
colors.removeEach(["red", "blue"]); // ["green"]
```
@method removeEach
@param {Ember.Enumerable} objects the objects to remove.
@return {Ember.Set} The set itself.
*/
removeEach: Ember.aliasMethod('removeObjects'),
// ..........................................................
// PRIVATE ENUMERABLE SUPPORT
//
init: function(items) {
this._super();
if (items) this.addObjects(items);
},
// implement Ember.Enumerable
nextObject: function(idx) {
return this[idx];
},
// more optimized version
firstObject: Ember.computed(function() {
return this.length > 0 ? this[0] : undefined;
}),
// more optimized version
lastObject: Ember.computed(function() {
return this.length > 0 ? this[this.length-1] : undefined;
}),
// implements Ember.MutableEnumerable
addObject: function(obj) {
if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR);
if (isNone(obj)) return this; // nothing to do
var guid = guidFor(obj),
idx = this[guid],
len = get(this, 'length'),
added ;
if (idx>=0 && idx<len && (this[idx] === obj)) return this; // added
added = [obj];
this.enumerableContentWillChange(null, added);
Ember.propertyWillChange(this, 'lastObject');
len = get(this, 'length');
this[guid] = len;
this[len] = obj;
set(this, 'length', len+1);
Ember.propertyDidChange(this, 'lastObject');
this.enumerableContentDidChange(null, added);
return this;
},
// implements Ember.MutableEnumerable
removeObject: function(obj) {
if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR);
if (isNone(obj)) return this; // nothing to do
var guid = guidFor(obj),
idx = this[guid],
len = get(this, 'length'),
isFirst = idx === 0,
isLast = idx === len-1,
last, removed;
if (idx>=0 && idx<len && (this[idx] === obj)) {
removed = [obj];
this.enumerableContentWillChange(removed, null);
if (isFirst) |
if (isLast) { Ember.propertyWillChange(this, 'lastObject'); }
// swap items - basically move the item to the end so it can be removed
if (idx < len-1) {
last = this[len-1];
this[idx] = last;
this[guidFor(last)] = idx;
}
delete this[guid];
delete this[len-1];
set(this, 'length', len-1);
if (isFirst) { Ember.propertyDidChange(this, 'firstObject'); }
if (isLast) { Ember.propertyDidChange(this, 'lastObject'); }
this.enumerableContentDidChange(removed, null);
}
return this;
},
// optimized version
contains: function(obj) {
return this[guidFor(obj)]>=0;
},
copy: function() {
var C = this.constructor, ret = new C(), loc = get(this, 'length');
set(ret, 'length', loc);
while(--loc>=0) {
ret[loc] = this[loc];
ret[guidFor(this[loc])] = loc;
}
return ret;
},
toString: function() {
var len = this.length, idx, array = [];
for(idx = 0; idx < len; idx++) {
array[idx] = this[idx];
}
return fmt("Ember.Set<%@>", [array.join(',')]);
}
});
| { Ember.propertyWillChange(this, 'firstObject'); } | conditional_block |
parsers.py | import re
from markdown import Markdown, TextPreprocessor
from smartypants import smartyPants
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name, TextLexer
class CodeBlockPreprocessor(TextPreprocessor):
"""
The Pygments Markdown Preprocessor
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This fragment is a Markdown_ preprocessor that renders source code
to HTML via Pygments. To use it, invoke Markdown like so::
from markdown import Markdown
md = Markdown()
md.textPreprocessors.insert(0, CodeBlockPreprocessor())
html = md.convert(someText)
markdown is then a callable that can be passed to the context of
a template and used in that template, for example.
This uses CSS classes by default, so use
``pygmentize -S <some style> -f html > pygments.css``
to create a stylesheet to be added to the website.
You can then highlight source code in your markdown markup::
@@ lexer
some code
@@ end
.. _Markdown: http://www.freewisdom.org/projects/python-markdown/
:copyright: 2007 by Jochen Kupperschmidt.
:license: BSD, see LICENSE for more details.
"""
pattern = re.compile(r'@@ (.+?)\n(.+?)\n@@ end', re.S)
formatter = HtmlFormatter(noclasses=False)
def run(self, lines):
def repl(m):
try:
lexer = get_lexer_by_name(m.group(1))
except ValueError, instance:
lexer = TextLexer()
code = highlight(m.group(2), lexer, self.formatter)
code = code.replace('\n\n', '\n \n').replace('\n', '<br />')
return '\n\n<div class="code">%s</div>\n\n' % code
return self.pattern.sub(repl, lines)
class SmartyPantsPreprocessor(TextPreprocessor):
"""
A Markdown preprocessor that implements SmartyPants for converting plain
ASCII punctuation characters into typographically correct versions | def run(self, lines):
def repl(m):
return smartyPants(m.group(1)) + m.group(2)
return self.pattern.sub(repl, lines)
def parse_markdown(value):
"""
Parses a value into markdown syntax, using the pygments preprocessor and smartypants
"""
md = Markdown()
md.textPreprocessors.insert(0, SmartyPantsPreprocessor())
md.textPreprocessors.insert(1, CodeBlockPreprocessor())
return md.convert(value) | """
pattern = re.compile(r'(.+?)(@@.+?@@ end|$)', re.S)
| random_line_split |
parsers.py | import re
from markdown import Markdown, TextPreprocessor
from smartypants import smartyPants
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name, TextLexer
class CodeBlockPreprocessor(TextPreprocessor):
"""
The Pygments Markdown Preprocessor
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This fragment is a Markdown_ preprocessor that renders source code
to HTML via Pygments. To use it, invoke Markdown like so::
from markdown import Markdown
md = Markdown()
md.textPreprocessors.insert(0, CodeBlockPreprocessor())
html = md.convert(someText)
markdown is then a callable that can be passed to the context of
a template and used in that template, for example.
This uses CSS classes by default, so use
``pygmentize -S <some style> -f html > pygments.css``
to create a stylesheet to be added to the website.
You can then highlight source code in your markdown markup::
@@ lexer
some code
@@ end
.. _Markdown: http://www.freewisdom.org/projects/python-markdown/
:copyright: 2007 by Jochen Kupperschmidt.
:license: BSD, see LICENSE for more details.
"""
pattern = re.compile(r'@@ (.+?)\n(.+?)\n@@ end', re.S)
formatter = HtmlFormatter(noclasses=False)
def run(self, lines):
def repl(m):
try:
lexer = get_lexer_by_name(m.group(1))
except ValueError, instance:
lexer = TextLexer()
code = highlight(m.group(2), lexer, self.formatter)
code = code.replace('\n\n', '\n \n').replace('\n', '<br />')
return '\n\n<div class="code">%s</div>\n\n' % code
return self.pattern.sub(repl, lines)
class SmartyPantsPreprocessor(TextPreprocessor):
"""
A Markdown preprocessor that implements SmartyPants for converting plain
ASCII punctuation characters into typographically correct versions
"""
pattern = re.compile(r'(.+?)(@@.+?@@ end|$)', re.S)
def run(self, lines):
|
def parse_markdown(value):
"""
Parses a value into markdown syntax, using the pygments preprocessor and smartypants
"""
md = Markdown()
md.textPreprocessors.insert(0, SmartyPantsPreprocessor())
md.textPreprocessors.insert(1, CodeBlockPreprocessor())
return md.convert(value)
| def repl(m):
return smartyPants(m.group(1)) + m.group(2)
return self.pattern.sub(repl, lines) | identifier_body |
parsers.py | import re
from markdown import Markdown, TextPreprocessor
from smartypants import smartyPants
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name, TextLexer
class CodeBlockPreprocessor(TextPreprocessor):
"""
The Pygments Markdown Preprocessor
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This fragment is a Markdown_ preprocessor that renders source code
to HTML via Pygments. To use it, invoke Markdown like so::
from markdown import Markdown
md = Markdown()
md.textPreprocessors.insert(0, CodeBlockPreprocessor())
html = md.convert(someText)
markdown is then a callable that can be passed to the context of
a template and used in that template, for example.
This uses CSS classes by default, so use
``pygmentize -S <some style> -f html > pygments.css``
to create a stylesheet to be added to the website.
You can then highlight source code in your markdown markup::
@@ lexer
some code
@@ end
.. _Markdown: http://www.freewisdom.org/projects/python-markdown/
:copyright: 2007 by Jochen Kupperschmidt.
:license: BSD, see LICENSE for more details.
"""
pattern = re.compile(r'@@ (.+?)\n(.+?)\n@@ end', re.S)
formatter = HtmlFormatter(noclasses=False)
def run(self, lines):
def repl(m):
try:
lexer = get_lexer_by_name(m.group(1))
except ValueError, instance:
lexer = TextLexer()
code = highlight(m.group(2), lexer, self.formatter)
code = code.replace('\n\n', '\n \n').replace('\n', '<br />')
return '\n\n<div class="code">%s</div>\n\n' % code
return self.pattern.sub(repl, lines)
class SmartyPantsPreprocessor(TextPreprocessor):
"""
A Markdown preprocessor that implements SmartyPants for converting plain
ASCII punctuation characters into typographically correct versions
"""
pattern = re.compile(r'(.+?)(@@.+?@@ end|$)', re.S)
def run(self, lines):
def repl(m):
return smartyPants(m.group(1)) + m.group(2)
return self.pattern.sub(repl, lines)
def | (value):
"""
Parses a value into markdown syntax, using the pygments preprocessor and smartypants
"""
md = Markdown()
md.textPreprocessors.insert(0, SmartyPantsPreprocessor())
md.textPreprocessors.insert(1, CodeBlockPreprocessor())
return md.convert(value)
| parse_markdown | identifier_name |
dependency.rs | use std::fmt;
use std::rc::Rc;
use std::str::FromStr;
use semver::VersionReq;
use semver::ReqParseError;
use serde::ser;
use core::{PackageId, SourceId, Summary};
use core::interning::InternedString;
use util::{Cfg, CfgExpr, Config};
use util::errors::{CargoError, CargoResult, CargoResultExt};
/// Information about a dependency requested by a Cargo manifest.
/// Cheap to copy.
#[derive(PartialEq, Eq, Hash, Ord, PartialOrd, Clone, Debug)]
pub struct Dependency {
inner: Rc<Inner>,
}
/// The data underlying a Dependency.
#[derive(PartialEq, Eq, Hash, Ord, PartialOrd, Clone, Debug)]
struct Inner {
name: InternedString,
source_id: SourceId,
registry_id: Option<SourceId>,
req: VersionReq,
specified_req: bool,
kind: Kind,
only_match_name: bool,
rename: Option<String>,
optional: bool,
default_features: bool,
features: Vec<InternedString>,
// This dependency should be used only for this platform.
// `None` means *all platforms*.
platform: Option<Platform>,
}
#[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Clone, Debug)]
pub enum Platform {
Name(String),
Cfg(CfgExpr),
}
#[derive(Serialize)]
struct SerializedDependency<'a> {
name: &'a str,
source: &'a SourceId,
req: String,
kind: Kind,
rename: Option<&'a str>,
optional: bool,
uses_default_features: bool,
features: &'a [String],
target: Option<&'a Platform>,
}
impl ser::Serialize for Dependency {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
let string_features: Vec<_> = self.features().iter().map(|s| s.to_string()).collect();
SerializedDependency {
name: &*self.name(),
source: self.source_id(),
req: self.version_req().to_string(),
kind: self.kind(),
optional: self.is_optional(),
uses_default_features: self.uses_default_features(),
features: &string_features,
target: self.platform(),
rename: self.rename(),
}.serialize(s)
}
}
#[derive(PartialEq, Eq, Hash, Ord, PartialOrd, Clone, Debug, Copy)]
pub enum Kind {
Normal,
Development,
Build,
}
fn parse_req_with_deprecated(
req: &str,
extra: Option<(&PackageId, &Config)>,
) -> CargoResult<VersionReq> {
match VersionReq::parse(req) {
Err(e) => {
let (inside, config) = match extra {
Some(pair) => pair,
None => return Err(e.into()),
};
match e {
ReqParseError::DeprecatedVersionRequirement(requirement) => {
let msg = format!(
"\
parsed version requirement `{}` is no longer valid
Previous versions of Cargo accepted this malformed requirement,
but it is being deprecated. This was found when parsing the manifest
of {} {}, and the correct version requirement is `{}`.
This will soon become a hard error, so it's either recommended to
update to a fixed version or contact the upstream maintainer about
this warning.
",
req,
inside.name(),
inside.version(),
requirement
);
config.shell().warn(&msg)?;
Ok(requirement)
}
e => Err(e.into()),
}
}
Ok(v) => Ok(v),
}
}
impl ser::Serialize for Kind {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
match *self {
Kind::Normal => None,
Kind::Development => Some("dev"),
Kind::Build => Some("build"),
}.serialize(s)
}
}
impl Dependency {
/// Attempt to create a `Dependency` from an entry in the manifest.
pub fn parse(
name: &str,
version: Option<&str>,
source_id: &SourceId,
inside: &PackageId,
config: &Config,
) -> CargoResult<Dependency> {
let arg = Some((inside, config));
let (specified_req, version_req) = match version {
Some(v) => (true, parse_req_with_deprecated(v, arg)?),
None => (false, VersionReq::any()),
};
let mut ret = Dependency::new_override(name, source_id);
{
let ptr = Rc::make_mut(&mut ret.inner);
ptr.only_match_name = false;
ptr.req = version_req;
ptr.specified_req = specified_req;
}
Ok(ret)
}
/// Attempt to create a `Dependency` from an entry in the manifest.
pub fn parse_no_deprecated(
name: &str,
version: Option<&str>,
source_id: &SourceId,
) -> CargoResult<Dependency> {
let (specified_req, version_req) = match version {
Some(v) => (true, parse_req_with_deprecated(v, None)?),
None => (false, VersionReq::any()),
};
let mut ret = Dependency::new_override(name, source_id);
{
let ptr = Rc::make_mut(&mut ret.inner);
ptr.only_match_name = false;
ptr.req = version_req;
ptr.specified_req = specified_req;
}
Ok(ret)
}
pub fn new_override(name: &str, source_id: &SourceId) -> Dependency {
assert!(!name.is_empty());
Dependency {
inner: Rc::new(Inner {
name: InternedString::new(name),
source_id: source_id.clone(),
registry_id: None,
req: VersionReq::any(),
kind: Kind::Normal,
only_match_name: true,
optional: false,
features: Vec::new(),
default_features: true,
specified_req: false,
platform: None,
rename: None,
}),
}
}
pub fn version_req(&self) -> &VersionReq {
&self.inner.req
}
pub fn name(&self) -> InternedString {
self.inner.name
}
pub fn source_id(&self) -> &SourceId {
&self.inner.source_id
}
pub fn registry_id(&self) -> Option<&SourceId> {
self.inner.registry_id.as_ref()
}
pub fn set_registry_id(&mut self, registry_id: &SourceId) -> &mut Dependency {
Rc::make_mut(&mut self.inner).registry_id = Some(registry_id.clone());
self
}
pub fn kind(&self) -> Kind {
self.inner.kind
}
pub fn specified_req(&self) -> bool {
self.inner.specified_req
}
/// If none, this dependencies must be built for all platforms.
/// If some, it must only be built for the specified platform.
pub fn platform(&self) -> Option<&Platform> {
self.inner.platform.as_ref()
}
pub fn | (&self) -> Option<&str> {
self.inner.rename.as_ref().map(|s| &**s)
}
pub fn set_kind(&mut self, kind: Kind) -> &mut Dependency {
Rc::make_mut(&mut self.inner).kind = kind;
self
}
/// Sets the list of features requested for the package.
pub fn set_features(&mut self, features: Vec<String>) -> &mut Dependency {
Rc::make_mut(&mut self.inner).features =
features.iter().map(|s| InternedString::new(s)).collect();
self
}
/// Sets whether the dependency requests default features of the package.
pub fn set_default_features(&mut self, default_features: bool) -> &mut Dependency {
Rc::make_mut(&mut self.inner).default_features = default_features;
self
}
/// Sets whether the dependency is optional.
pub fn set_optional(&mut self, optional: bool) -> &mut Dependency {
Rc::make_mut(&mut self.inner).optional = optional;
self
}
/// Set the source id for this dependency
pub fn set_source_id(&mut self, id: SourceId) -> &mut Dependency {
Rc::make_mut(&mut self.inner).source_id = id;
self
}
/// Set the version requirement for this dependency
pub fn set_version_req(&mut self, req: VersionReq) -> &mut Dependency {
Rc::make_mut(&mut self.inner).req = req;
self
}
pub fn set_platform(&mut self, platform: Option<Platform>) -> &mut Dependency {
Rc::make_mut(&mut self.inner).platform = platform;
self
}
pub fn set_rename(&mut self, rename: &str) -> &mut Dependency {
Rc::make_mut(&mut self.inner).rename = Some(rename.to_string());
self
}
/// Lock this dependency to depending on the specified package id
pub fn lock_to(&mut self, id: &PackageId) -> &mut Dependency {
assert_eq!(self.inner.source_id, *id.source_id());
assert!(self.inner.req.matches(id.version()));
trace!(
"locking dep from `{}` with `{}` at {} to {}",
self.name(),
self.version_req(),
self.source_id(),
id
);
self.set_version_req(VersionReq::exact(id.version()))
.set_source_id(id.source_id().clone())
}
/// Returns whether this is a "locked" dependency, basically whether it has
/// an exact version req.
pub fn is_locked(&self) -> bool {
// Kind of a hack to figure this out, but it works!
self.inner.req.to_string().starts_with('=')
}
/// Returns false if the dependency is only used to build the local package.
pub fn is_transitive(&self) -> bool {
match self.inner.kind {
Kind::Normal | Kind::Build => true,
Kind::Development => false,
}
}
pub fn is_build(&self) -> bool {
match self.inner.kind {
Kind::Build => true,
_ => false,
}
}
pub fn is_optional(&self) -> bool {
self.inner.optional
}
/// Returns true if the default features of the dependency are requested.
pub fn uses_default_features(&self) -> bool {
self.inner.default_features
}
/// Returns the list of features that are requested by the dependency.
pub fn features(&self) -> &[InternedString] {
&self.inner.features
}
/// Returns true if the package (`sum`) can fulfill this dependency request.
pub fn matches(&self, sum: &Summary) -> bool {
self.matches_id(sum.package_id())
}
/// Returns true if the package (`sum`) can fulfill this dependency request.
pub fn matches_ignoring_source(&self, id: &PackageId) -> bool {
self.name() == id.name() && self.version_req().matches(id.version())
}
/// Returns true if the package (`id`) can fulfill this dependency request.
pub fn matches_id(&self, id: &PackageId) -> bool {
self.inner.name == id.name()
&& (self.inner.only_match_name
|| (self.inner.req.matches(id.version())
&& &self.inner.source_id == id.source_id()))
}
pub fn map_source(mut self, to_replace: &SourceId, replace_with: &SourceId) -> Dependency {
if self.source_id() != to_replace {
self
} else {
self.set_source_id(replace_with.clone());
self
}
}
}
impl Platform {
pub fn matches(&self, name: &str, cfg: Option<&[Cfg]>) -> bool {
match *self {
Platform::Name(ref p) => p == name,
Platform::Cfg(ref p) => match cfg {
Some(cfg) => p.matches(cfg),
None => false,
},
}
}
}
impl ser::Serialize for Platform {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
self.to_string().serialize(s)
}
}
impl FromStr for Platform {
type Err = CargoError;
fn from_str(s: &str) -> CargoResult<Platform> {
if s.starts_with("cfg(") && s.ends_with(')') {
let s = &s[4..s.len() - 1];
let p = s.parse()
.map(Platform::Cfg)
.chain_err(|| format_err!("failed to parse `{}` as a cfg expression", s))?;
Ok(p)
} else {
Ok(Platform::Name(s.to_string()))
}
}
}
impl fmt::Display for Platform {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Platform::Name(ref n) => n.fmt(f),
Platform::Cfg(ref e) => write!(f, "cfg({})", e),
}
}
}
| rename | identifier_name |
dependency.rs | use std::fmt;
use std::rc::Rc;
use std::str::FromStr;
use semver::VersionReq;
use semver::ReqParseError;
use serde::ser;
use core::{PackageId, SourceId, Summary};
use core::interning::InternedString;
use util::{Cfg, CfgExpr, Config};
use util::errors::{CargoError, CargoResult, CargoResultExt};
/// Information about a dependency requested by a Cargo manifest.
/// Cheap to copy.
#[derive(PartialEq, Eq, Hash, Ord, PartialOrd, Clone, Debug)]
pub struct Dependency {
inner: Rc<Inner>,
}
/// The data underlying a Dependency.
#[derive(PartialEq, Eq, Hash, Ord, PartialOrd, Clone, Debug)]
struct Inner {
name: InternedString,
source_id: SourceId,
registry_id: Option<SourceId>,
req: VersionReq,
specified_req: bool,
kind: Kind,
only_match_name: bool,
rename: Option<String>,
optional: bool,
default_features: bool,
features: Vec<InternedString>,
// This dependency should be used only for this platform.
// `None` means *all platforms*.
platform: Option<Platform>,
}
#[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Clone, Debug)]
pub enum Platform {
Name(String),
Cfg(CfgExpr),
}
#[derive(Serialize)]
struct SerializedDependency<'a> {
name: &'a str,
source: &'a SourceId,
req: String,
kind: Kind,
rename: Option<&'a str>,
optional: bool,
uses_default_features: bool,
features: &'a [String],
target: Option<&'a Platform>,
}
impl ser::Serialize for Dependency {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
let string_features: Vec<_> = self.features().iter().map(|s| s.to_string()).collect();
SerializedDependency {
name: &*self.name(),
source: self.source_id(),
req: self.version_req().to_string(),
kind: self.kind(),
optional: self.is_optional(),
uses_default_features: self.uses_default_features(),
features: &string_features,
target: self.platform(),
rename: self.rename(),
}.serialize(s)
}
}
#[derive(PartialEq, Eq, Hash, Ord, PartialOrd, Clone, Debug, Copy)]
pub enum Kind {
Normal,
Development,
Build,
}
fn parse_req_with_deprecated(
req: &str,
extra: Option<(&PackageId, &Config)>,
) -> CargoResult<VersionReq> {
match VersionReq::parse(req) {
Err(e) => {
let (inside, config) = match extra {
Some(pair) => pair,
None => return Err(e.into()),
};
match e {
ReqParseError::DeprecatedVersionRequirement(requirement) => {
let msg = format!(
"\
parsed version requirement `{}` is no longer valid
Previous versions of Cargo accepted this malformed requirement,
but it is being deprecated. This was found when parsing the manifest
of {} {}, and the correct version requirement is `{}`.
This will soon become a hard error, so it's either recommended to
update to a fixed version or contact the upstream maintainer about
this warning.
",
req,
inside.name(),
inside.version(),
requirement
);
config.shell().warn(&msg)?;
Ok(requirement)
}
e => Err(e.into()),
}
}
Ok(v) => Ok(v),
}
}
impl ser::Serialize for Kind {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
match *self {
Kind::Normal => None,
Kind::Development => Some("dev"),
Kind::Build => Some("build"),
}.serialize(s)
}
}
impl Dependency {
/// Attempt to create a `Dependency` from an entry in the manifest.
pub fn parse(
name: &str,
version: Option<&str>,
source_id: &SourceId,
inside: &PackageId,
config: &Config,
) -> CargoResult<Dependency> {
let arg = Some((inside, config));
let (specified_req, version_req) = match version {
Some(v) => (true, parse_req_with_deprecated(v, arg)?),
None => (false, VersionReq::any()),
};
let mut ret = Dependency::new_override(name, source_id);
{
let ptr = Rc::make_mut(&mut ret.inner);
ptr.only_match_name = false;
ptr.req = version_req;
ptr.specified_req = specified_req;
}
Ok(ret)
}
/// Attempt to create a `Dependency` from an entry in the manifest.
pub fn parse_no_deprecated(
name: &str,
version: Option<&str>,
source_id: &SourceId,
) -> CargoResult<Dependency> {
let (specified_req, version_req) = match version {
Some(v) => (true, parse_req_with_deprecated(v, None)?),
None => (false, VersionReq::any()),
};
let mut ret = Dependency::new_override(name, source_id);
{
let ptr = Rc::make_mut(&mut ret.inner);
ptr.only_match_name = false;
ptr.req = version_req;
ptr.specified_req = specified_req;
}
Ok(ret)
}
pub fn new_override(name: &str, source_id: &SourceId) -> Dependency {
assert!(!name.is_empty());
Dependency {
inner: Rc::new(Inner {
name: InternedString::new(name),
source_id: source_id.clone(),
registry_id: None,
req: VersionReq::any(),
kind: Kind::Normal,
only_match_name: true,
optional: false,
features: Vec::new(),
default_features: true,
specified_req: false,
platform: None,
rename: None,
}),
}
}
pub fn version_req(&self) -> &VersionReq {
&self.inner.req
}
pub fn name(&self) -> InternedString {
self.inner.name
}
pub fn source_id(&self) -> &SourceId {
&self.inner.source_id
}
pub fn registry_id(&self) -> Option<&SourceId> {
self.inner.registry_id.as_ref()
}
pub fn set_registry_id(&mut self, registry_id: &SourceId) -> &mut Dependency {
Rc::make_mut(&mut self.inner).registry_id = Some(registry_id.clone());
self
}
pub fn kind(&self) -> Kind {
self.inner.kind
}
pub fn specified_req(&self) -> bool {
self.inner.specified_req
}
/// If none, this dependencies must be built for all platforms.
/// If some, it must only be built for the specified platform.
pub fn platform(&self) -> Option<&Platform> {
self.inner.platform.as_ref()
}
pub fn rename(&self) -> Option<&str> {
self.inner.rename.as_ref().map(|s| &**s)
}
pub fn set_kind(&mut self, kind: Kind) -> &mut Dependency {
Rc::make_mut(&mut self.inner).kind = kind;
self
}
/// Sets the list of features requested for the package.
pub fn set_features(&mut self, features: Vec<String>) -> &mut Dependency {
Rc::make_mut(&mut self.inner).features =
features.iter().map(|s| InternedString::new(s)).collect();
self
}
/// Sets whether the dependency requests default features of the package.
pub fn set_default_features(&mut self, default_features: bool) -> &mut Dependency {
Rc::make_mut(&mut self.inner).default_features = default_features;
self
}
/// Sets whether the dependency is optional.
pub fn set_optional(&mut self, optional: bool) -> &mut Dependency {
Rc::make_mut(&mut self.inner).optional = optional;
self
}
/// Set the source id for this dependency
pub fn set_source_id(&mut self, id: SourceId) -> &mut Dependency {
Rc::make_mut(&mut self.inner).source_id = id;
self
}
/// Set the version requirement for this dependency
pub fn set_version_req(&mut self, req: VersionReq) -> &mut Dependency {
Rc::make_mut(&mut self.inner).req = req;
self
}
pub fn set_platform(&mut self, platform: Option<Platform>) -> &mut Dependency {
Rc::make_mut(&mut self.inner).platform = platform;
self
}
pub fn set_rename(&mut self, rename: &str) -> &mut Dependency {
Rc::make_mut(&mut self.inner).rename = Some(rename.to_string());
self
}
/// Lock this dependency to depending on the specified package id
pub fn lock_to(&mut self, id: &PackageId) -> &mut Dependency {
assert_eq!(self.inner.source_id, *id.source_id());
assert!(self.inner.req.matches(id.version()));
trace!(
"locking dep from `{}` with `{}` at {} to {}",
self.name(),
self.version_req(),
self.source_id(),
id
);
self.set_version_req(VersionReq::exact(id.version()))
.set_source_id(id.source_id().clone())
}
/// Returns whether this is a "locked" dependency, basically whether it has
/// an exact version req.
pub fn is_locked(&self) -> bool {
// Kind of a hack to figure this out, but it works!
self.inner.req.to_string().starts_with('=')
}
/// Returns false if the dependency is only used to build the local package.
pub fn is_transitive(&self) -> bool {
match self.inner.kind {
Kind::Normal | Kind::Build => true,
Kind::Development => false,
}
}
pub fn is_build(&self) -> bool {
match self.inner.kind {
Kind::Build => true,
_ => false,
}
}
pub fn is_optional(&self) -> bool {
self.inner.optional
}
/// Returns true if the default features of the dependency are requested.
pub fn uses_default_features(&self) -> bool {
self.inner.default_features
}
/// Returns the list of features that are requested by the dependency.
pub fn features(&self) -> &[InternedString] {
&self.inner.features
}
/// Returns true if the package (`sum`) can fulfill this dependency request.
pub fn matches(&self, sum: &Summary) -> bool {
self.matches_id(sum.package_id())
}
/// Returns true if the package (`sum`) can fulfill this dependency request.
pub fn matches_ignoring_source(&self, id: &PackageId) -> bool {
self.name() == id.name() && self.version_req().matches(id.version())
}
/// Returns true if the package (`id`) can fulfill this dependency request.
pub fn matches_id(&self, id: &PackageId) -> bool {
self.inner.name == id.name()
&& (self.inner.only_match_name
|| (self.inner.req.matches(id.version())
&& &self.inner.source_id == id.source_id()))
}
pub fn map_source(mut self, to_replace: &SourceId, replace_with: &SourceId) -> Dependency {
if self.source_id() != to_replace {
self
} else {
self.set_source_id(replace_with.clone());
self
}
}
}
impl Platform {
pub fn matches(&self, name: &str, cfg: Option<&[Cfg]>) -> bool {
match *self {
Platform::Name(ref p) => p == name,
Platform::Cfg(ref p) => match cfg {
Some(cfg) => p.matches(cfg),
None => false,
},
}
}
}
impl ser::Serialize for Platform {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
self.to_string().serialize(s)
}
}
impl FromStr for Platform {
type Err = CargoError;
fn from_str(s: &str) -> CargoResult<Platform> {
if s.starts_with("cfg(") && s.ends_with(')') {
let s = &s[4..s.len() - 1];
let p = s.parse()
.map(Platform::Cfg)
.chain_err(|| format_err!("failed to parse `{}` as a cfg expression", s))?;
Ok(p)
} else {
Ok(Platform::Name(s.to_string()))
}
}
}
impl fmt::Display for Platform {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Platform::Name(ref n) => n.fmt(f),
Platform::Cfg(ref e) => write!(f, "cfg({})", e),
}
} | } | random_line_split | |
dependency.rs | use std::fmt;
use std::rc::Rc;
use std::str::FromStr;
use semver::VersionReq;
use semver::ReqParseError;
use serde::ser;
use core::{PackageId, SourceId, Summary};
use core::interning::InternedString;
use util::{Cfg, CfgExpr, Config};
use util::errors::{CargoError, CargoResult, CargoResultExt};
/// Information about a dependency requested by a Cargo manifest.
/// Cheap to copy.
#[derive(PartialEq, Eq, Hash, Ord, PartialOrd, Clone, Debug)]
pub struct Dependency {
inner: Rc<Inner>,
}
/// The data underlying a Dependency.
#[derive(PartialEq, Eq, Hash, Ord, PartialOrd, Clone, Debug)]
struct Inner {
name: InternedString,
source_id: SourceId,
registry_id: Option<SourceId>,
req: VersionReq,
specified_req: bool,
kind: Kind,
only_match_name: bool,
rename: Option<String>,
optional: bool,
default_features: bool,
features: Vec<InternedString>,
// This dependency should be used only for this platform.
// `None` means *all platforms*.
platform: Option<Platform>,
}
#[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Clone, Debug)]
pub enum Platform {
Name(String),
Cfg(CfgExpr),
}
#[derive(Serialize)]
struct SerializedDependency<'a> {
name: &'a str,
source: &'a SourceId,
req: String,
kind: Kind,
rename: Option<&'a str>,
optional: bool,
uses_default_features: bool,
features: &'a [String],
target: Option<&'a Platform>,
}
impl ser::Serialize for Dependency {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
let string_features: Vec<_> = self.features().iter().map(|s| s.to_string()).collect();
SerializedDependency {
name: &*self.name(),
source: self.source_id(),
req: self.version_req().to_string(),
kind: self.kind(),
optional: self.is_optional(),
uses_default_features: self.uses_default_features(),
features: &string_features,
target: self.platform(),
rename: self.rename(),
}.serialize(s)
}
}
#[derive(PartialEq, Eq, Hash, Ord, PartialOrd, Clone, Debug, Copy)]
pub enum Kind {
Normal,
Development,
Build,
}
fn parse_req_with_deprecated(
req: &str,
extra: Option<(&PackageId, &Config)>,
) -> CargoResult<VersionReq> {
match VersionReq::parse(req) {
Err(e) => {
let (inside, config) = match extra {
Some(pair) => pair,
None => return Err(e.into()),
};
match e {
ReqParseError::DeprecatedVersionRequirement(requirement) => {
let msg = format!(
"\
parsed version requirement `{}` is no longer valid
Previous versions of Cargo accepted this malformed requirement,
but it is being deprecated. This was found when parsing the manifest
of {} {}, and the correct version requirement is `{}`.
This will soon become a hard error, so it's either recommended to
update to a fixed version or contact the upstream maintainer about
this warning.
",
req,
inside.name(),
inside.version(),
requirement
);
config.shell().warn(&msg)?;
Ok(requirement)
}
e => Err(e.into()),
}
}
Ok(v) => Ok(v),
}
}
impl ser::Serialize for Kind {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
match *self {
Kind::Normal => None,
Kind::Development => Some("dev"),
Kind::Build => Some("build"),
}.serialize(s)
}
}
impl Dependency {
/// Attempt to create a `Dependency` from an entry in the manifest.
pub fn parse(
name: &str,
version: Option<&str>,
source_id: &SourceId,
inside: &PackageId,
config: &Config,
) -> CargoResult<Dependency> {
let arg = Some((inside, config));
let (specified_req, version_req) = match version {
Some(v) => (true, parse_req_with_deprecated(v, arg)?),
None => (false, VersionReq::any()),
};
let mut ret = Dependency::new_override(name, source_id);
{
let ptr = Rc::make_mut(&mut ret.inner);
ptr.only_match_name = false;
ptr.req = version_req;
ptr.specified_req = specified_req;
}
Ok(ret)
}
/// Attempt to create a `Dependency` from an entry in the manifest.
pub fn parse_no_deprecated(
name: &str,
version: Option<&str>,
source_id: &SourceId,
) -> CargoResult<Dependency> {
let (specified_req, version_req) = match version {
Some(v) => (true, parse_req_with_deprecated(v, None)?),
None => (false, VersionReq::any()),
};
let mut ret = Dependency::new_override(name, source_id);
{
let ptr = Rc::make_mut(&mut ret.inner);
ptr.only_match_name = false;
ptr.req = version_req;
ptr.specified_req = specified_req;
}
Ok(ret)
}
pub fn new_override(name: &str, source_id: &SourceId) -> Dependency {
assert!(!name.is_empty());
Dependency {
inner: Rc::new(Inner {
name: InternedString::new(name),
source_id: source_id.clone(),
registry_id: None,
req: VersionReq::any(),
kind: Kind::Normal,
only_match_name: true,
optional: false,
features: Vec::new(),
default_features: true,
specified_req: false,
platform: None,
rename: None,
}),
}
}
pub fn version_req(&self) -> &VersionReq {
&self.inner.req
}
pub fn name(&self) -> InternedString {
self.inner.name
}
pub fn source_id(&self) -> &SourceId {
&self.inner.source_id
}
pub fn registry_id(&self) -> Option<&SourceId> {
self.inner.registry_id.as_ref()
}
pub fn set_registry_id(&mut self, registry_id: &SourceId) -> &mut Dependency {
Rc::make_mut(&mut self.inner).registry_id = Some(registry_id.clone());
self
}
pub fn kind(&self) -> Kind {
self.inner.kind
}
pub fn specified_req(&self) -> bool {
self.inner.specified_req
}
/// If none, this dependencies must be built for all platforms.
/// If some, it must only be built for the specified platform.
pub fn platform(&self) -> Option<&Platform> {
self.inner.platform.as_ref()
}
pub fn rename(&self) -> Option<&str> {
self.inner.rename.as_ref().map(|s| &**s)
}
pub fn set_kind(&mut self, kind: Kind) -> &mut Dependency {
Rc::make_mut(&mut self.inner).kind = kind;
self
}
/// Sets the list of features requested for the package.
pub fn set_features(&mut self, features: Vec<String>) -> &mut Dependency {
Rc::make_mut(&mut self.inner).features =
features.iter().map(|s| InternedString::new(s)).collect();
self
}
/// Sets whether the dependency requests default features of the package.
pub fn set_default_features(&mut self, default_features: bool) -> &mut Dependency {
Rc::make_mut(&mut self.inner).default_features = default_features;
self
}
/// Sets whether the dependency is optional.
pub fn set_optional(&mut self, optional: bool) -> &mut Dependency {
Rc::make_mut(&mut self.inner).optional = optional;
self
}
/// Set the source id for this dependency
pub fn set_source_id(&mut self, id: SourceId) -> &mut Dependency {
Rc::make_mut(&mut self.inner).source_id = id;
self
}
/// Set the version requirement for this dependency
pub fn set_version_req(&mut self, req: VersionReq) -> &mut Dependency {
Rc::make_mut(&mut self.inner).req = req;
self
}
pub fn set_platform(&mut self, platform: Option<Platform>) -> &mut Dependency {
Rc::make_mut(&mut self.inner).platform = platform;
self
}
pub fn set_rename(&mut self, rename: &str) -> &mut Dependency {
Rc::make_mut(&mut self.inner).rename = Some(rename.to_string());
self
}
/// Lock this dependency to depending on the specified package id
pub fn lock_to(&mut self, id: &PackageId) -> &mut Dependency {
assert_eq!(self.inner.source_id, *id.source_id());
assert!(self.inner.req.matches(id.version()));
trace!(
"locking dep from `{}` with `{}` at {} to {}",
self.name(),
self.version_req(),
self.source_id(),
id
);
self.set_version_req(VersionReq::exact(id.version()))
.set_source_id(id.source_id().clone())
}
/// Returns whether this is a "locked" dependency, basically whether it has
/// an exact version req.
pub fn is_locked(&self) -> bool {
// Kind of a hack to figure this out, but it works!
self.inner.req.to_string().starts_with('=')
}
/// Returns false if the dependency is only used to build the local package.
pub fn is_transitive(&self) -> bool {
match self.inner.kind {
Kind::Normal | Kind::Build => true,
Kind::Development => false,
}
}
pub fn is_build(&self) -> bool {
match self.inner.kind {
Kind::Build => true,
_ => false,
}
}
pub fn is_optional(&self) -> bool |
/// Returns true if the default features of the dependency are requested.
pub fn uses_default_features(&self) -> bool {
self.inner.default_features
}
/// Returns the list of features that are requested by the dependency.
pub fn features(&self) -> &[InternedString] {
&self.inner.features
}
/// Returns true if the package (`sum`) can fulfill this dependency request.
pub fn matches(&self, sum: &Summary) -> bool {
self.matches_id(sum.package_id())
}
/// Returns true if the package (`sum`) can fulfill this dependency request.
pub fn matches_ignoring_source(&self, id: &PackageId) -> bool {
self.name() == id.name() && self.version_req().matches(id.version())
}
/// Returns true if the package (`id`) can fulfill this dependency request.
pub fn matches_id(&self, id: &PackageId) -> bool {
self.inner.name == id.name()
&& (self.inner.only_match_name
|| (self.inner.req.matches(id.version())
&& &self.inner.source_id == id.source_id()))
}
pub fn map_source(mut self, to_replace: &SourceId, replace_with: &SourceId) -> Dependency {
if self.source_id() != to_replace {
self
} else {
self.set_source_id(replace_with.clone());
self
}
}
}
impl Platform {
pub fn matches(&self, name: &str, cfg: Option<&[Cfg]>) -> bool {
match *self {
Platform::Name(ref p) => p == name,
Platform::Cfg(ref p) => match cfg {
Some(cfg) => p.matches(cfg),
None => false,
},
}
}
}
impl ser::Serialize for Platform {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
self.to_string().serialize(s)
}
}
impl FromStr for Platform {
type Err = CargoError;
fn from_str(s: &str) -> CargoResult<Platform> {
if s.starts_with("cfg(") && s.ends_with(')') {
let s = &s[4..s.len() - 1];
let p = s.parse()
.map(Platform::Cfg)
.chain_err(|| format_err!("failed to parse `{}` as a cfg expression", s))?;
Ok(p)
} else {
Ok(Platform::Name(s.to_string()))
}
}
}
impl fmt::Display for Platform {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Platform::Name(ref n) => n.fmt(f),
Platform::Cfg(ref e) => write!(f, "cfg({})", e),
}
}
}
| {
self.inner.optional
} | identifier_body |
recipe-137551.py | RegObj.dll is an ActiveX server--and, hence, has an automation interface--that is available with documentation in
the distribution file known as RegObji.exe, from the following page:
http://msdn.microsoft.com/vbasic/downloads/addins.asp
To provide early binding for RegObj use
>>> from win32com.client import gencache
>>> gencache.EnsureModule('{DE10C540-810E-11CF-BBE7-444553540000}', 0, 1, 0)
or the MakePy utility within PythonWin, referring to "Regstration Manipulation Classes (1.0)" (Please notice
the spelling error.)
Sample use, to determine what command is associated with a Python file:
>>> from win32com.client import Dispatch, gencache
>>> from win32con import HKEY_CLASSES_ROOT
>>> gencache.EnsureModule('{DE10C540-810E-11CF-BBE7-444553540000}', 0, 1, 0)
>>> regobj = Dispatch ( 'RegObj.Registry' )
| >>> HKCR = regobj.RegKeyFromHKey ( HKEY_CLASSES_ROOT )
>>> PythonFileKey = HKCR.ParseKeyName('Python.File\Shell\Open\command')
>>> PythonFileKey.Value
u'J:\\Python22\\pythonw.exe "%1" %*' | random_line_split | |
index.js | var map;
window.onload = function() {
var mm = com.modestmaps;
var dmap = document.getElementById('map');
wax.tilejson('https://a.tiles.mapbox.com/v3/examples.map-i86l3621.jsonp',
function(tj) {
map = new com.modestmaps.Map(dmap,
new wax.mm.connector(tj), null, [
easey_handlers.DragHandler(),
easey_handlers.TouchHandler(),
easey_handlers.MouseWheelHandler(),
easey_handlers.DoubleClickHandler()
]);
map.setCenterZoom(new com.modestmaps.Location(-10, 50), 3);
map.addCallback('zoomed', function() {
// console.log(map.getZoom());
});
var pres = document.getElementsByTagName('pre');
for (var i = 0; i < pres.length; i++) {
pres[i].onclick = function() {
eval(this.innerHTML);
};
}
var scrolly = document.getElementById('scrolly');
var positions = [
map.locationCoordinate({ lat: 33.5, lon: 65.6 }).zoomTo(6),
map.locationCoordinate({ lat: 33.1, lon: 44.6 }).zoomTo(6),
map.locationCoordinate({ lat: 28.7, lon: 69.2 }).zoomTo(6)];
var ea = easey().map(map).easing('easeInOut');
function | () {
var pos = scrolly.scrollTop / 200;
ea.from(positions[Math.floor(pos)])
.to(positions[Math.ceil(pos)])
.t(pos - Math.floor(pos));
}
scrolly.addEventListener('scroll', update, false);
});
};
| update | identifier_name |
index.js | var map;
window.onload = function() {
var mm = com.modestmaps;
var dmap = document.getElementById('map');
wax.tilejson('https://a.tiles.mapbox.com/v3/examples.map-i86l3621.jsonp',
function(tj) {
map = new com.modestmaps.Map(dmap, | ]);
map.setCenterZoom(new com.modestmaps.Location(-10, 50), 3);
map.addCallback('zoomed', function() {
// console.log(map.getZoom());
});
var pres = document.getElementsByTagName('pre');
for (var i = 0; i < pres.length; i++) {
pres[i].onclick = function() {
eval(this.innerHTML);
};
}
var scrolly = document.getElementById('scrolly');
var positions = [
map.locationCoordinate({ lat: 33.5, lon: 65.6 }).zoomTo(6),
map.locationCoordinate({ lat: 33.1, lon: 44.6 }).zoomTo(6),
map.locationCoordinate({ lat: 28.7, lon: 69.2 }).zoomTo(6)];
var ea = easey().map(map).easing('easeInOut');
function update() {
var pos = scrolly.scrollTop / 200;
ea.from(positions[Math.floor(pos)])
.to(positions[Math.ceil(pos)])
.t(pos - Math.floor(pos));
}
scrolly.addEventListener('scroll', update, false);
});
}; | new wax.mm.connector(tj), null, [
easey_handlers.DragHandler(),
easey_handlers.TouchHandler(),
easey_handlers.MouseWheelHandler(),
easey_handlers.DoubleClickHandler() | random_line_split |
index.js | var map;
window.onload = function() {
var mm = com.modestmaps;
var dmap = document.getElementById('map');
wax.tilejson('https://a.tiles.mapbox.com/v3/examples.map-i86l3621.jsonp',
function(tj) {
map = new com.modestmaps.Map(dmap,
new wax.mm.connector(tj), null, [
easey_handlers.DragHandler(),
easey_handlers.TouchHandler(),
easey_handlers.MouseWheelHandler(),
easey_handlers.DoubleClickHandler()
]);
map.setCenterZoom(new com.modestmaps.Location(-10, 50), 3);
map.addCallback('zoomed', function() {
// console.log(map.getZoom());
});
var pres = document.getElementsByTagName('pre');
for (var i = 0; i < pres.length; i++) {
pres[i].onclick = function() {
eval(this.innerHTML);
};
}
var scrolly = document.getElementById('scrolly');
var positions = [
map.locationCoordinate({ lat: 33.5, lon: 65.6 }).zoomTo(6),
map.locationCoordinate({ lat: 33.1, lon: 44.6 }).zoomTo(6),
map.locationCoordinate({ lat: 28.7, lon: 69.2 }).zoomTo(6)];
var ea = easey().map(map).easing('easeInOut');
function update() |
scrolly.addEventListener('scroll', update, false);
});
};
| {
var pos = scrolly.scrollTop / 200;
ea.from(positions[Math.floor(pos)])
.to(positions[Math.ceil(pos)])
.t(pos - Math.floor(pos));
} | identifier_body |
index.js | var map;
window.onload = function() {
var mm = com.modestmaps;
var dmap = document.getElementById('map');
wax.tilejson('https://a.tiles.mapbox.com/v3/examples.map-i86l3621.jsonp',
function(tj) {
map = new com.modestmaps.Map(dmap,
new wax.mm.connector(tj), null, [
easey_handlers.DragHandler(),
easey_handlers.TouchHandler(),
easey_handlers.MouseWheelHandler(),
easey_handlers.DoubleClickHandler()
]);
map.setCenterZoom(new com.modestmaps.Location(-10, 50), 3);
map.addCallback('zoomed', function() {
// console.log(map.getZoom());
});
var pres = document.getElementsByTagName('pre');
for (var i = 0; i < pres.length; i++) |
var scrolly = document.getElementById('scrolly');
var positions = [
map.locationCoordinate({ lat: 33.5, lon: 65.6 }).zoomTo(6),
map.locationCoordinate({ lat: 33.1, lon: 44.6 }).zoomTo(6),
map.locationCoordinate({ lat: 28.7, lon: 69.2 }).zoomTo(6)];
var ea = easey().map(map).easing('easeInOut');
function update() {
var pos = scrolly.scrollTop / 200;
ea.from(positions[Math.floor(pos)])
.to(positions[Math.ceil(pos)])
.t(pos - Math.floor(pos));
}
scrolly.addEventListener('scroll', update, false);
});
};
| {
pres[i].onclick = function() {
eval(this.innerHTML);
};
} | conditional_block |
tata.py | # -*- coding: UTF-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##......
# .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######.
# .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........##
# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @Daddy_Blamo wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return. - Muad'Dib
# ----------------------------------------------------------------------------
#######################################################################
# Addon Name: Placenta
# Addon id: plugin.video.placenta
# Addon Provider: Mr.Blamo
import base64
import json
import re
import urllib
import urlparse
from openscrapers.modules import cleantitle
from openscrapers.modules import client
from openscrapers.modules import directstream
from openscrapers.modules import dom_parser
from openscrapers.modules import source_utils
class source:
def __init__(self):
self.priority = 1
self.language = ['de']
self.domains = ['tata.to']
self.base_link = 'http://tata.to'
self.search_link = '/filme?suche=%s&type=alle'
self.ajax_link = '/ajax/stream/%s'
def movie(self, imdb, title, localtitle, aliases, year):
try:
url = self.__search_movie(imdb, year)
return url if url else None
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
try:
url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'localtvshowtitle': localtvshowtitle,
'aliases': aliases, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
try:
if not url:
return
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
tvshowtitle = data['tvshowtitle']
localtvshowtitle = data['localtvshowtitle']
aliases = source_utils.aliases_to_array(eval(data['aliases']))
year = re.findall('(\d{4})', premiered)
year = year[0] if year else data['year']
url = self.__search([localtvshowtitle] + aliases, year, season, episode)
if not url and tvshowtitle != localtvshowtitle:
url = self.__search([tvshowtitle] + aliases, year, season, episode)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
sources = []
try:
if not url:
return sources
ref = urlparse.urljoin(self.base_link, url)
url = urlparse.urljoin(self.base_link, self.ajax_link % re.findall('-(\w+)$', ref)[0])
headers = {'Referer': ref, 'User-Agent': client.randomagent()}
result = client.request(url, headers=headers, post='')
result = base64.decodestring(result)
result = json.loads(result).get('playinfo', [])
if isinstance(result, basestring):
result = result.replace('embed.html', 'index.m3u8')
base_url = re.sub('index\.m3u8\?token=[\w\-]+[^/$]*', '', result)
r = client.request(result, headers=headers)
r = [(i[0], i[1]) for i in
re.findall('#EXT-X-STREAM-INF:.*?RESOLUTION=\d+x(\d+)[^\n]+\n([^\n]+)', r, re.DOTALL) if i]
r = [(source_utils.label_to_quality(i[0]), i[1] + source_utils.append_headers(headers)) for i in r]
r = [{'quality': i[0], 'url': base_url + i[1]} for i in r]
for i in r: sources.append(
{'source': 'CDN', 'quality': i['quality'], 'language': 'de', 'url': i['url'], 'direct': True,
'debridonly': False})
elif result:
result = [i.get('link_mp4') for i in result]
result = [i for i in result if i]
for i in result:
try:
sources.append(
{'source': 'gvideo', 'quality': directstream.googletag(i)[0]['quality'], 'language': 'de',
'url': i, 'direct': True, 'debridonly': False})
except:
pass
return sources
except:
return
def resolve(self, url):
return url
def | (self, imdb, year):
try:
query = urlparse.urljoin(self.base_link, self.search_link % imdb)
y = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1), '0']
r = client.request(query)
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'container'})
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'ml-item-content'})
r = [(dom_parser.parse_dom(i, 'a', attrs={'class': 'ml-image'}, req='href'),
dom_parser.parse_dom(i, 'ul', attrs={'class': 'item-params'})) for i in r]
r = [(i[0][0].attrs['href'], re.findall('calendar.+?>.+?(\d{4})', ''.join([x.content for x in i[1]]))) for i
in r if i[0] and i[1]]
r = [(i[0], i[1][0] if len(i[1]) > 0 else '0') for i in r]
r = sorted(r, key=lambda i: int(i[1]), reverse=True) # with year > no year
r = [i[0] for i in r if i[1] in y][0]
return source_utils.strip_domain(r)
except:
return
def __search(self, titles, year, season=0, episode=False):
try:
query = self.search_link % (urllib.quote_plus(cleantitle.query(titles[0])))
query = urlparse.urljoin(self.base_link, query)
t = [cleantitle.get(i) for i in set(titles) if i]
y = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1), '0']
r = client.request(query)
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'container'})
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'ml-item-content'})
f = []
for i in r:
_url = dom_parser.parse_dom(i, 'a', attrs={'class': 'ml-image'}, req='href')[0].attrs['href']
_title = re.sub('<.+?>|</.+?>', '', dom_parser.parse_dom(i, 'h6')[0].content).strip()
try:
_title = re.search('(.*?)\s(?:staf+el|s)\s*(\d+)', _title, re.I).group(1)
except:
pass
_season = '0'
_year = re.findall('calendar.+?>.+?(\d{4})', ''.join(
[x.content for x in dom_parser.parse_dom(i, 'ul', attrs={'class': 'item-params'})]))
_year = _year[0] if len(_year) > 0 else '0'
if season > 0:
s = dom_parser.parse_dom(i, 'span', attrs={'class': 'season-label'})
s = dom_parser.parse_dom(s, 'span', attrs={'class': 'el-num'})
if s: _season = s[0].content.strip()
if cleantitle.get(_title) in t and _year in y and int(_season) == int(season):
f.append((_url, _year))
r = f
r = sorted(r, key=lambda i: int(i[1]), reverse=True) # with year > no year
r = [i[0] for i in r if r[0]][0]
url = source_utils.strip_domain(r)
if episode:
r = client.request(urlparse.urljoin(self.base_link, url))
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'season-list'})
r = dom_parser.parse_dom(r, 'li')
r = dom_parser.parse_dom(r, 'a', req='href')
r = [(i.attrs['href'], i.content) for i in r]
r = [i[0] for i in r if i[1] and int(i[1]) == int(episode)][0]
url = source_utils.strip_domain(r)
return url
except:
return
| __search_movie | identifier_name |
tata.py | # -*- coding: UTF-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##......
# .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######.
# .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........##
# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @Daddy_Blamo wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return. - Muad'Dib
# ----------------------------------------------------------------------------
#######################################################################
# Addon Name: Placenta
# Addon id: plugin.video.placenta
# Addon Provider: Mr.Blamo
import base64
import json
import re
import urllib
import urlparse
from openscrapers.modules import cleantitle
from openscrapers.modules import client
from openscrapers.modules import directstream
from openscrapers.modules import dom_parser
from openscrapers.modules import source_utils
class source:
def __init__(self):
self.priority = 1
self.language = ['de']
self.domains = ['tata.to']
self.base_link = 'http://tata.to'
self.search_link = '/filme?suche=%s&type=alle'
self.ajax_link = '/ajax/stream/%s'
def movie(self, imdb, title, localtitle, aliases, year):
try:
url = self.__search_movie(imdb, year)
return url if url else None
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
try:
url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'localtvshowtitle': localtvshowtitle,
'aliases': aliases, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
try:
if not url:
return
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
tvshowtitle = data['tvshowtitle']
localtvshowtitle = data['localtvshowtitle']
aliases = source_utils.aliases_to_array(eval(data['aliases']))
year = re.findall('(\d{4})', premiered)
year = year[0] if year else data['year']
url = self.__search([localtvshowtitle] + aliases, year, season, episode)
if not url and tvshowtitle != localtvshowtitle:
url = self.__search([tvshowtitle] + aliases, year, season, episode)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
sources = []
try:
if not url:
return sources
ref = urlparse.urljoin(self.base_link, url)
url = urlparse.urljoin(self.base_link, self.ajax_link % re.findall('-(\w+)$', ref)[0])
headers = {'Referer': ref, 'User-Agent': client.randomagent()}
result = client.request(url, headers=headers, post='')
result = base64.decodestring(result)
result = json.loads(result).get('playinfo', [])
if isinstance(result, basestring):
result = result.replace('embed.html', 'index.m3u8')
base_url = re.sub('index\.m3u8\?token=[\w\-]+[^/$]*', '', result)
r = client.request(result, headers=headers)
r = [(i[0], i[1]) for i in
re.findall('#EXT-X-STREAM-INF:.*?RESOLUTION=\d+x(\d+)[^\n]+\n([^\n]+)', r, re.DOTALL) if i]
r = [(source_utils.label_to_quality(i[0]), i[1] + source_utils.append_headers(headers)) for i in r]
r = [{'quality': i[0], 'url': base_url + i[1]} for i in r]
for i in r: sources.append(
{'source': 'CDN', 'quality': i['quality'], 'language': 'de', 'url': i['url'], 'direct': True,
'debridonly': False})
elif result:
result = [i.get('link_mp4') for i in result]
result = [i for i in result if i]
for i in result:
try:
sources.append(
{'source': 'gvideo', 'quality': directstream.googletag(i)[0]['quality'], 'language': 'de',
'url': i, 'direct': True, 'debridonly': False})
except:
pass
return sources
except:
return
def resolve(self, url):
return url
def __search_movie(self, imdb, year):
try:
query = urlparse.urljoin(self.base_link, self.search_link % imdb)
y = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1), '0']
r = client.request(query)
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'container'})
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'ml-item-content'})
r = [(dom_parser.parse_dom(i, 'a', attrs={'class': 'ml-image'}, req='href'),
dom_parser.parse_dom(i, 'ul', attrs={'class': 'item-params'})) for i in r]
r = [(i[0][0].attrs['href'], re.findall('calendar.+?>.+?(\d{4})', ''.join([x.content for x in i[1]]))) for i
in r if i[0] and i[1]]
r = [(i[0], i[1][0] if len(i[1]) > 0 else '0') for i in r]
r = sorted(r, key=lambda i: int(i[1]), reverse=True) # with year > no year
r = [i[0] for i in r if i[1] in y][0]
return source_utils.strip_domain(r)
except:
return
def __search(self, titles, year, season=0, episode=False):
try:
query = self.search_link % (urllib.quote_plus(cleantitle.query(titles[0])))
query = urlparse.urljoin(self.base_link, query)
t = [cleantitle.get(i) for i in set(titles) if i]
y = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1), '0']
r = client.request(query)
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'container'}) | _url = dom_parser.parse_dom(i, 'a', attrs={'class': 'ml-image'}, req='href')[0].attrs['href']
_title = re.sub('<.+?>|</.+?>', '', dom_parser.parse_dom(i, 'h6')[0].content).strip()
try:
_title = re.search('(.*?)\s(?:staf+el|s)\s*(\d+)', _title, re.I).group(1)
except:
pass
_season = '0'
_year = re.findall('calendar.+?>.+?(\d{4})', ''.join(
[x.content for x in dom_parser.parse_dom(i, 'ul', attrs={'class': 'item-params'})]))
_year = _year[0] if len(_year) > 0 else '0'
if season > 0:
s = dom_parser.parse_dom(i, 'span', attrs={'class': 'season-label'})
s = dom_parser.parse_dom(s, 'span', attrs={'class': 'el-num'})
if s: _season = s[0].content.strip()
if cleantitle.get(_title) in t and _year in y and int(_season) == int(season):
f.append((_url, _year))
r = f
r = sorted(r, key=lambda i: int(i[1]), reverse=True) # with year > no year
r = [i[0] for i in r if r[0]][0]
url = source_utils.strip_domain(r)
if episode:
r = client.request(urlparse.urljoin(self.base_link, url))
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'season-list'})
r = dom_parser.parse_dom(r, 'li')
r = dom_parser.parse_dom(r, 'a', req='href')
r = [(i.attrs['href'], i.content) for i in r]
r = [i[0] for i in r if i[1] and int(i[1]) == int(episode)][0]
url = source_utils.strip_domain(r)
return url
except:
return | r = dom_parser.parse_dom(r, 'div', attrs={'class': 'ml-item-content'})
f = []
for i in r: | random_line_split |
tata.py | # -*- coding: UTF-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##......
# .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######.
# .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........##
# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @Daddy_Blamo wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return. - Muad'Dib
# ----------------------------------------------------------------------------
#######################################################################
# Addon Name: Placenta
# Addon id: plugin.video.placenta
# Addon Provider: Mr.Blamo
import base64
import json
import re
import urllib
import urlparse
from openscrapers.modules import cleantitle
from openscrapers.modules import client
from openscrapers.modules import directstream
from openscrapers.modules import dom_parser
from openscrapers.modules import source_utils
class source:
def __init__(self):
self.priority = 1
self.language = ['de']
self.domains = ['tata.to']
self.base_link = 'http://tata.to'
self.search_link = '/filme?suche=%s&type=alle'
self.ajax_link = '/ajax/stream/%s'
def movie(self, imdb, title, localtitle, aliases, year):
try:
url = self.__search_movie(imdb, year)
return url if url else None
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
try:
url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'localtvshowtitle': localtvshowtitle,
'aliases': aliases, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
try:
if not url:
return
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
tvshowtitle = data['tvshowtitle']
localtvshowtitle = data['localtvshowtitle']
aliases = source_utils.aliases_to_array(eval(data['aliases']))
year = re.findall('(\d{4})', premiered)
year = year[0] if year else data['year']
url = self.__search([localtvshowtitle] + aliases, year, season, episode)
if not url and tvshowtitle != localtvshowtitle:
url = self.__search([tvshowtitle] + aliases, year, season, episode)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
sources = []
try:
if not url:
return sources
ref = urlparse.urljoin(self.base_link, url)
url = urlparse.urljoin(self.base_link, self.ajax_link % re.findall('-(\w+)$', ref)[0])
headers = {'Referer': ref, 'User-Agent': client.randomagent()}
result = client.request(url, headers=headers, post='')
result = base64.decodestring(result)
result = json.loads(result).get('playinfo', [])
if isinstance(result, basestring):
result = result.replace('embed.html', 'index.m3u8')
base_url = re.sub('index\.m3u8\?token=[\w\-]+[^/$]*', '', result)
r = client.request(result, headers=headers)
r = [(i[0], i[1]) for i in
re.findall('#EXT-X-STREAM-INF:.*?RESOLUTION=\d+x(\d+)[^\n]+\n([^\n]+)', r, re.DOTALL) if i]
r = [(source_utils.label_to_quality(i[0]), i[1] + source_utils.append_headers(headers)) for i in r]
r = [{'quality': i[0], 'url': base_url + i[1]} for i in r]
for i in r: sources.append(
{'source': 'CDN', 'quality': i['quality'], 'language': 'de', 'url': i['url'], 'direct': True,
'debridonly': False})
elif result:
result = [i.get('link_mp4') for i in result]
result = [i for i in result if i]
for i in result:
try:
sources.append(
{'source': 'gvideo', 'quality': directstream.googletag(i)[0]['quality'], 'language': 'de',
'url': i, 'direct': True, 'debridonly': False})
except:
pass
return sources
except:
return
def resolve(self, url):
|
def __search_movie(self, imdb, year):
try:
query = urlparse.urljoin(self.base_link, self.search_link % imdb)
y = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1), '0']
r = client.request(query)
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'container'})
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'ml-item-content'})
r = [(dom_parser.parse_dom(i, 'a', attrs={'class': 'ml-image'}, req='href'),
dom_parser.parse_dom(i, 'ul', attrs={'class': 'item-params'})) for i in r]
r = [(i[0][0].attrs['href'], re.findall('calendar.+?>.+?(\d{4})', ''.join([x.content for x in i[1]]))) for i
in r if i[0] and i[1]]
r = [(i[0], i[1][0] if len(i[1]) > 0 else '0') for i in r]
r = sorted(r, key=lambda i: int(i[1]), reverse=True) # with year > no year
r = [i[0] for i in r if i[1] in y][0]
return source_utils.strip_domain(r)
except:
return
def __search(self, titles, year, season=0, episode=False):
try:
query = self.search_link % (urllib.quote_plus(cleantitle.query(titles[0])))
query = urlparse.urljoin(self.base_link, query)
t = [cleantitle.get(i) for i in set(titles) if i]
y = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1), '0']
r = client.request(query)
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'container'})
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'ml-item-content'})
f = []
for i in r:
_url = dom_parser.parse_dom(i, 'a', attrs={'class': 'ml-image'}, req='href')[0].attrs['href']
_title = re.sub('<.+?>|</.+?>', '', dom_parser.parse_dom(i, 'h6')[0].content).strip()
try:
_title = re.search('(.*?)\s(?:staf+el|s)\s*(\d+)', _title, re.I).group(1)
except:
pass
_season = '0'
_year = re.findall('calendar.+?>.+?(\d{4})', ''.join(
[x.content for x in dom_parser.parse_dom(i, 'ul', attrs={'class': 'item-params'})]))
_year = _year[0] if len(_year) > 0 else '0'
if season > 0:
s = dom_parser.parse_dom(i, 'span', attrs={'class': 'season-label'})
s = dom_parser.parse_dom(s, 'span', attrs={'class': 'el-num'})
if s: _season = s[0].content.strip()
if cleantitle.get(_title) in t and _year in y and int(_season) == int(season):
f.append((_url, _year))
r = f
r = sorted(r, key=lambda i: int(i[1]), reverse=True) # with year > no year
r = [i[0] for i in r if r[0]][0]
url = source_utils.strip_domain(r)
if episode:
r = client.request(urlparse.urljoin(self.base_link, url))
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'season-list'})
r = dom_parser.parse_dom(r, 'li')
r = dom_parser.parse_dom(r, 'a', req='href')
r = [(i.attrs['href'], i.content) for i in r]
r = [i[0] for i in r if i[1] and int(i[1]) == int(episode)][0]
url = source_utils.strip_domain(r)
return url
except:
return
| return url | identifier_body |
tata.py | # -*- coding: UTF-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##......
# .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######.
# .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........##
# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @Daddy_Blamo wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return. - Muad'Dib
# ----------------------------------------------------------------------------
#######################################################################
# Addon Name: Placenta
# Addon id: plugin.video.placenta
# Addon Provider: Mr.Blamo
import base64
import json
import re
import urllib
import urlparse
from openscrapers.modules import cleantitle
from openscrapers.modules import client
from openscrapers.modules import directstream
from openscrapers.modules import dom_parser
from openscrapers.modules import source_utils
class source:
def __init__(self):
self.priority = 1
self.language = ['de']
self.domains = ['tata.to']
self.base_link = 'http://tata.to'
self.search_link = '/filme?suche=%s&type=alle'
self.ajax_link = '/ajax/stream/%s'
def movie(self, imdb, title, localtitle, aliases, year):
try:
url = self.__search_movie(imdb, year)
return url if url else None
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
try:
url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'localtvshowtitle': localtvshowtitle,
'aliases': aliases, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
try:
if not url:
return
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
tvshowtitle = data['tvshowtitle']
localtvshowtitle = data['localtvshowtitle']
aliases = source_utils.aliases_to_array(eval(data['aliases']))
year = re.findall('(\d{4})', premiered)
year = year[0] if year else data['year']
url = self.__search([localtvshowtitle] + aliases, year, season, episode)
if not url and tvshowtitle != localtvshowtitle:
url = self.__search([tvshowtitle] + aliases, year, season, episode)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
sources = []
try:
if not url:
return sources
ref = urlparse.urljoin(self.base_link, url)
url = urlparse.urljoin(self.base_link, self.ajax_link % re.findall('-(\w+)$', ref)[0])
headers = {'Referer': ref, 'User-Agent': client.randomagent()}
result = client.request(url, headers=headers, post='')
result = base64.decodestring(result)
result = json.loads(result).get('playinfo', [])
if isinstance(result, basestring):
result = result.replace('embed.html', 'index.m3u8')
base_url = re.sub('index\.m3u8\?token=[\w\-]+[^/$]*', '', result)
r = client.request(result, headers=headers)
r = [(i[0], i[1]) for i in
re.findall('#EXT-X-STREAM-INF:.*?RESOLUTION=\d+x(\d+)[^\n]+\n([^\n]+)', r, re.DOTALL) if i]
r = [(source_utils.label_to_quality(i[0]), i[1] + source_utils.append_headers(headers)) for i in r]
r = [{'quality': i[0], 'url': base_url + i[1]} for i in r]
for i in r: |
elif result:
result = [i.get('link_mp4') for i in result]
result = [i for i in result if i]
for i in result:
try:
sources.append(
{'source': 'gvideo', 'quality': directstream.googletag(i)[0]['quality'], 'language': 'de',
'url': i, 'direct': True, 'debridonly': False})
except:
pass
return sources
except:
return
def resolve(self, url):
return url
def __search_movie(self, imdb, year):
try:
query = urlparse.urljoin(self.base_link, self.search_link % imdb)
y = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1), '0']
r = client.request(query)
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'container'})
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'ml-item-content'})
r = [(dom_parser.parse_dom(i, 'a', attrs={'class': 'ml-image'}, req='href'),
dom_parser.parse_dom(i, 'ul', attrs={'class': 'item-params'})) for i in r]
r = [(i[0][0].attrs['href'], re.findall('calendar.+?>.+?(\d{4})', ''.join([x.content for x in i[1]]))) for i
in r if i[0] and i[1]]
r = [(i[0], i[1][0] if len(i[1]) > 0 else '0') for i in r]
r = sorted(r, key=lambda i: int(i[1]), reverse=True) # with year > no year
r = [i[0] for i in r if i[1] in y][0]
return source_utils.strip_domain(r)
except:
return
def __search(self, titles, year, season=0, episode=False):
try:
query = self.search_link % (urllib.quote_plus(cleantitle.query(titles[0])))
query = urlparse.urljoin(self.base_link, query)
t = [cleantitle.get(i) for i in set(titles) if i]
y = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1), '0']
r = client.request(query)
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'container'})
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'ml-item-content'})
f = []
for i in r:
_url = dom_parser.parse_dom(i, 'a', attrs={'class': 'ml-image'}, req='href')[0].attrs['href']
_title = re.sub('<.+?>|</.+?>', '', dom_parser.parse_dom(i, 'h6')[0].content).strip()
try:
_title = re.search('(.*?)\s(?:staf+el|s)\s*(\d+)', _title, re.I).group(1)
except:
pass
_season = '0'
_year = re.findall('calendar.+?>.+?(\d{4})', ''.join(
[x.content for x in dom_parser.parse_dom(i, 'ul', attrs={'class': 'item-params'})]))
_year = _year[0] if len(_year) > 0 else '0'
if season > 0:
s = dom_parser.parse_dom(i, 'span', attrs={'class': 'season-label'})
s = dom_parser.parse_dom(s, 'span', attrs={'class': 'el-num'})
if s: _season = s[0].content.strip()
if cleantitle.get(_title) in t and _year in y and int(_season) == int(season):
f.append((_url, _year))
r = f
r = sorted(r, key=lambda i: int(i[1]), reverse=True) # with year > no year
r = [i[0] for i in r if r[0]][0]
url = source_utils.strip_domain(r)
if episode:
r = client.request(urlparse.urljoin(self.base_link, url))
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'season-list'})
r = dom_parser.parse_dom(r, 'li')
r = dom_parser.parse_dom(r, 'a', req='href')
r = [(i.attrs['href'], i.content) for i in r]
r = [i[0] for i in r if i[1] and int(i[1]) == int(episode)][0]
url = source_utils.strip_domain(r)
return url
except:
return
| sources.append(
{'source': 'CDN', 'quality': i['quality'], 'language': 'de', 'url': i['url'], 'direct': True,
'debridonly': False}) | conditional_block |
fh_comment.py | # -*- coding: utf-8 -*-
from browser_interface.field.FieldFactory import FieldFactory
from browser_interface.queue.QueueFactory import QueueFactory
from browser_interface.browser.BrowserFactory import BrowserFactory
from browser_interface.log.Logging import Logging
from common import config
import urllib
import json
class Comment(object):
def __init__(self):
# 实例化工厂对象
self.field_factory = FieldFactory(u'凤凰网评论')
self.browser_factory = BrowserFactory()
self.db_factory = QueueFactory()
# 实例化具体对象
self.log = Logging('./log/fenghuang_comment').get_logging()
self.browser = self.browser_factory.create(config.browser_type)
self.db = self.db_factory.create(config.db_type, config.db_table_news_pinglun,
config.db_host, config.db_port, dbname=config.db_table_news_pinglun)
def getcomment(self, news_url, page):
url = 'http://comment.ifeng.com/get.php?&orderby=&docUrl=%s&job=1&p=%d&pageSize=20' % (urllib.quote(news_url), page)
html = self.browser.visit(url, timeout=10, retry=5)
message = json.loads(html)['comments']
field = self.field_factory.create('ping_lun')
for item in message:
# 评论文章url
field.set('news_url', news_url)
# 评论内容
field.set('ping_lun_nei_rong', item["comment_contents"])
# 评论时间
field.set('ping_lun_shi_jian', item["create_time"])
# 回复数
# 点赞数
field.set('dian_zan_shu', item["uptimes"])
# 评论id
field.set('ping_lun_id', item["comment_id"])
# 用户昵称
field.set('yong_hu_ming', item["uname"])
# 性别
# 用户等级
# 用户省份
field.set('yong_hu_sheng_fen', item["ip_from"])
field.set('id', item["comment_id"])
data = field.make()
if data:
self.db.put(data)
print json.dumps(data, ensure_ascii=False, indent=4)
# if __name__ == ' | 9/50071321_0.shtml', 1) | __main__':
# con = Comment()
# con.getcomment('http://news.ifeng.com/a/2016100 | conditional_block |
fh_comment.py | # -*- coding: utf-8 -*-
from browser_interface.field.FieldFactory import FieldFactory
from browser_interface.queue.QueueFactory import QueueFactory
from browser_interface.browser.BrowserFactory import BrowserFactory
from browser_interface.log.Logging import Logging
from common import config
import urllib
import json
class Comment(object):
def __init__(self):
# 实例化工厂对象
self.field_factory = FieldFactory(u'凤凰网评论')
self.browser_factory = BrowserFactory()
self.db_factory = QueueFactory()
# 实例化具体对象
self.log = Logging('./log/fenghuang_comment').get_logging()
self.browser = self.browser_factory.create(config.browser_type)
self.db = self.db_factory.create(config.db_type, config.db_table_news_pinglun,
config.db_host, config.db_port, dbname=config.db_table_news_pinglun)
def getcomment(self, news_url, page):
url = 'http://comment.ifeng.com/get.ph | 9/50071321_0.shtml', 1) | p?&orderby=&docUrl=%s&job=1&p=%d&pageSize=20' % (urllib.quote(news_url), page)
html = self.browser.visit(url, timeout=10, retry=5)
message = json.loads(html)['comments']
field = self.field_factory.create('ping_lun')
for item in message:
# 评论文章url
field.set('news_url', news_url)
# 评论内容
field.set('ping_lun_nei_rong', item["comment_contents"])
# 评论时间
field.set('ping_lun_shi_jian', item["create_time"])
# 回复数
# 点赞数
field.set('dian_zan_shu', item["uptimes"])
# 评论id
field.set('ping_lun_id', item["comment_id"])
# 用户昵称
field.set('yong_hu_ming', item["uname"])
# 性别
# 用户等级
# 用户省份
field.set('yong_hu_sheng_fen', item["ip_from"])
field.set('id', item["comment_id"])
data = field.make()
if data:
self.db.put(data)
print json.dumps(data, ensure_ascii=False, indent=4)
# if __name__ == '__main__':
# con = Comment()
# con.getcomment('http://news.ifeng.com/a/2016100 | identifier_body |
fh_comment.py | # -*- coding: utf-8 -*-
from browser_interface.field.FieldFactory import FieldFactory
from browser_interface.queue.QueueFactory import QueueFactory
from browser_interface.browser.BrowserFactory import BrowserFactory
from browser_interface.log.Logging import Logging
from common import config
import urllib
import json
class Comment(object):
def __init__(self):
# 实例化工厂对象
self.field_factory = FieldFactory(u'凤凰网评论')
self.browser_factory = BrowserFactory()
self.db_factory = QueueFactory()
# 实例化具体对象
self.log = Logging('./log/fenghuang_comment').get_logging()
self.browser = self.browser_factory.create(config.browser_type)
self.db = self.db_factory.create(config.db_type, config.db_table_news_pinglun,
config.db_host, config.db_port, dbname=config.db_table_news_pinglun)
def getcomment(self, news_url, page):
url = 'http://comment.ifeng.com/get.php?&orderby=&docUrl=%s&job=1&p=%d&pageSize=20' % (urllib.quote(news_url), page) | for item in message:
# 评论文章url
field.set('news_url', news_url)
# 评论内容
field.set('ping_lun_nei_rong', item["comment_contents"])
# 评论时间
field.set('ping_lun_shi_jian', item["create_time"])
# 回复数
# 点赞数
field.set('dian_zan_shu', item["uptimes"])
# 评论id
field.set('ping_lun_id', item["comment_id"])
# 用户昵称
field.set('yong_hu_ming', item["uname"])
# 性别
# 用户等级
# 用户省份
field.set('yong_hu_sheng_fen', item["ip_from"])
field.set('id', item["comment_id"])
data = field.make()
if data:
self.db.put(data)
print json.dumps(data, ensure_ascii=False, indent=4)
# if __name__ == '__main__':
# con = Comment()
# con.getcomment('http://news.ifeng.com/a/20161009/50071321_0.shtml', 1) | html = self.browser.visit(url, timeout=10, retry=5)
message = json.loads(html)['comments']
field = self.field_factory.create('ping_lun') | random_line_split |
fh_comment.py | # -*- coding: utf-8 -*-
from browser_interface.field.FieldFactory import FieldFactory
from browser_interface.queue.QueueFactory import QueueFactory
from browser_interface.browser.BrowserFactory import BrowserFactory
from browser_interface.log.Logging import Logging
from common import config
import urllib
import json
class Comment(object):
def __init__(self):
# 实例化工厂对象
self.field_factory = FieldFactory(u'凤凰网评论')
self.browser_factory = BrowserFactory()
self.db_factory = QueueFactory()
# 实例化具体对象
self.log = Logging('./log/fenghuang_comment').get_logging()
self.browser = self.browser_factory.create(config.browser_type)
self.db = self.db_factory.create(config.db_type, config.db_table_news_pinglun,
config.db_host, config.db_port, dbname=config.db_table_news_pinglun)
def getcomment(self, news_url, page):
| 'http://comment.ifeng.com/get.php?&orderby=&docUrl=%s&job=1&p=%d&pageSize=20' % (urllib.quote(news_url), page)
html = self.browser.visit(url, timeout=10, retry=5)
message = json.loads(html)['comments']
field = self.field_factory.create('ping_lun')
for item in message:
# 评论文章url
field.set('news_url', news_url)
# 评论内容
field.set('ping_lun_nei_rong', item["comment_contents"])
# 评论时间
field.set('ping_lun_shi_jian', item["create_time"])
# 回复数
# 点赞数
field.set('dian_zan_shu', item["uptimes"])
# 评论id
field.set('ping_lun_id', item["comment_id"])
# 用户昵称
field.set('yong_hu_ming', item["uname"])
# 性别
# 用户等级
# 用户省份
field.set('yong_hu_sheng_fen', item["ip_from"])
field.set('id', item["comment_id"])
data = field.make()
if data:
self.db.put(data)
print json.dumps(data, ensure_ascii=False, indent=4)
# if __name__ == '__main__':
# con = Comment()
# con.getcomment('http://news.ifeng.com/a/20161009/50071321_0.shtml', 1) | url = | identifier_name |
edit_detail.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
import six
from django.utils.translation import ugettext_lazy as _
from django.views.generic.detail import DetailView
from shoop.core.models import PaymentMethod, ShippingMethod
from shoop.utils.excs import Problem
from shoop.utils.importing import load
class _BaseMethodDetailView(DetailView):
model = None # Overridden below
title = _(u"Edit Details")
def dispatch(self, request, *args, **kwargs):
# This view only dispatches further to the method module's own detail view class
object = self.get_object()
module = object.module
if not module.admin_detail_view_class:
|
if isinstance(module.admin_detail_view_class, six.text_type):
view_class = load(module.admin_detail_view_class)
else:
view_class = module.admin_detail_view_class
kwargs["object"] = object
return view_class(model=self.model).dispatch(request, *args, **kwargs)
class ShippingMethodEditDetailView(_BaseMethodDetailView):
model = ShippingMethod
class PaymentMethodEditDetailView(_BaseMethodDetailView):
model = PaymentMethod
| raise Problem("Module %s has no admin detail view" % module.name) | conditional_block |
edit_detail.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree. | import six
from django.utils.translation import ugettext_lazy as _
from django.views.generic.detail import DetailView
from shoop.core.models import PaymentMethod, ShippingMethod
from shoop.utils.excs import Problem
from shoop.utils.importing import load
class _BaseMethodDetailView(DetailView):
model = None # Overridden below
title = _(u"Edit Details")
def dispatch(self, request, *args, **kwargs):
# This view only dispatches further to the method module's own detail view class
object = self.get_object()
module = object.module
if not module.admin_detail_view_class:
raise Problem("Module %s has no admin detail view" % module.name)
if isinstance(module.admin_detail_view_class, six.text_type):
view_class = load(module.admin_detail_view_class)
else:
view_class = module.admin_detail_view_class
kwargs["object"] = object
return view_class(model=self.model).dispatch(request, *args, **kwargs)
class ShippingMethodEditDetailView(_BaseMethodDetailView):
model = ShippingMethod
class PaymentMethodEditDetailView(_BaseMethodDetailView):
model = PaymentMethod | from __future__ import unicode_literals
| random_line_split |
edit_detail.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
import six
from django.utils.translation import ugettext_lazy as _
from django.views.generic.detail import DetailView
from shoop.core.models import PaymentMethod, ShippingMethod
from shoop.utils.excs import Problem
from shoop.utils.importing import load
class _BaseMethodDetailView(DetailView):
|
class ShippingMethodEditDetailView(_BaseMethodDetailView):
model = ShippingMethod
class PaymentMethodEditDetailView(_BaseMethodDetailView):
model = PaymentMethod
| model = None # Overridden below
title = _(u"Edit Details")
def dispatch(self, request, *args, **kwargs):
# This view only dispatches further to the method module's own detail view class
object = self.get_object()
module = object.module
if not module.admin_detail_view_class:
raise Problem("Module %s has no admin detail view" % module.name)
if isinstance(module.admin_detail_view_class, six.text_type):
view_class = load(module.admin_detail_view_class)
else:
view_class = module.admin_detail_view_class
kwargs["object"] = object
return view_class(model=self.model).dispatch(request, *args, **kwargs) | identifier_body |
edit_detail.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
import six
from django.utils.translation import ugettext_lazy as _
from django.views.generic.detail import DetailView
from shoop.core.models import PaymentMethod, ShippingMethod
from shoop.utils.excs import Problem
from shoop.utils.importing import load
class _BaseMethodDetailView(DetailView):
model = None # Overridden below
title = _(u"Edit Details")
def dispatch(self, request, *args, **kwargs):
# This view only dispatches further to the method module's own detail view class
object = self.get_object()
module = object.module
if not module.admin_detail_view_class:
raise Problem("Module %s has no admin detail view" % module.name)
if isinstance(module.admin_detail_view_class, six.text_type):
view_class = load(module.admin_detail_view_class)
else:
view_class = module.admin_detail_view_class
kwargs["object"] = object
return view_class(model=self.model).dispatch(request, *args, **kwargs)
class ShippingMethodEditDetailView(_BaseMethodDetailView):
model = ShippingMethod
class | (_BaseMethodDetailView):
model = PaymentMethod
| PaymentMethodEditDetailView | identifier_name |
myapp.ts | /* eslint-env browser */
import {IStore, Store} from "../../..";
type ViewpointJson = {
position: string;
};
class Viewpoint {
public position: string;
public constructor(position: string = "0 0 0") {
this.position = position;
}
public toJson(): ViewpointJson |
}
type MapOf<T> = {
[id: string]: T;
};
type ViewpointsState = MapOf<Viewpoint>;
type ViewpointsProps = MapOf<ViewpointJson>;
type SetMessage = Readonly<{
action: "set";
key: string;
value: Viewpoint;
}>;
export function actionSet<ViewpointsState>(message: SetMessage, store: IStore<ViewpointsState, never>): void {
const newItems: any = {};
newItems[message.key] = message.value;
const newState = Object.assign({}, store.state, newItems);
Object.freeze(newState);
store.state = newState;
}
const collection = new Store<ViewpointsState, ViewpointsProps, SetMessage>();
collection.register("set", actionSet);
collection.serialize = (state) => {
const props: ViewpointsProps = {};
for (const id in state) {
props[id] = state[id].toJson();
}
return props;
};
// Subscribe to props
collection.onprops = (props) => {
if ("MOCHA_ON_STORE_PROPS" in window) {
//@ts-ignore
window.MOCHA_ON_STORE_PROPS(JSON.stringify(props)); // eslint-disable-line
} else {
console.log("[PROPS]", props);
}
};
// Initial state
collection.state = {
initial1: new Viewpoint("1 0 0"),
initial2: new Viewpoint("2 0 0"),
initial3: new Viewpoint("3 0 0")
};
// Send actions
collection.schedule({
action: "set",
key: "new1",
value: new Viewpoint("4 0 0")
});
collection.schedule({
action: "set",
key: "new2",
value: new Viewpoint("5 0 0")
});
| {
return {
position: this.position
};
} | identifier_body |
myapp.ts | /* eslint-env browser */
import {IStore, Store} from "../../..";
type ViewpointJson = {
position: string;
};
class Viewpoint {
public position: string;
public constructor(position: string = "0 0 0") {
this.position = position;
}
public toJson(): ViewpointJson {
return {
position: this.position
};
}
}
type MapOf<T> = {
[id: string]: T;
};
type ViewpointsState = MapOf<Viewpoint>;
type ViewpointsProps = MapOf<ViewpointJson>;
type SetMessage = Readonly<{
action: "set";
key: string;
value: Viewpoint;
}>;
export function actionSet<ViewpointsState>(message: SetMessage, store: IStore<ViewpointsState, never>): void {
const newItems: any = {};
newItems[message.key] = message.value;
const newState = Object.assign({}, store.state, newItems);
Object.freeze(newState);
store.state = newState;
}
const collection = new Store<ViewpointsState, ViewpointsProps, SetMessage>();
collection.register("set", actionSet);
collection.serialize = (state) => {
const props: ViewpointsProps = {};
for (const id in state) {
props[id] = state[id].toJson();
}
return props;
};
// Subscribe to props
collection.onprops = (props) => {
if ("MOCHA_ON_STORE_PROPS" in window) | else {
console.log("[PROPS]", props);
}
};
// Initial state
collection.state = {
initial1: new Viewpoint("1 0 0"),
initial2: new Viewpoint("2 0 0"),
initial3: new Viewpoint("3 0 0")
};
// Send actions
collection.schedule({
action: "set",
key: "new1",
value: new Viewpoint("4 0 0")
});
collection.schedule({
action: "set",
key: "new2",
value: new Viewpoint("5 0 0")
});
| {
//@ts-ignore
window.MOCHA_ON_STORE_PROPS(JSON.stringify(props)); // eslint-disable-line
} | conditional_block |
myapp.ts | /* eslint-env browser */
import {IStore, Store} from "../../..";
type ViewpointJson = {
position: string;
};
class Viewpoint {
public position: string;
public constructor(position: string = "0 0 0") {
this.position = position;
}
public toJson(): ViewpointJson {
return {
position: this.position
};
}
}
type MapOf<T> = {
[id: string]: T;
};
type ViewpointsState = MapOf<Viewpoint>;
type ViewpointsProps = MapOf<ViewpointJson>;
type SetMessage = Readonly<{
action: "set";
key: string;
value: Viewpoint;
}>;
export function | <ViewpointsState>(message: SetMessage, store: IStore<ViewpointsState, never>): void {
const newItems: any = {};
newItems[message.key] = message.value;
const newState = Object.assign({}, store.state, newItems);
Object.freeze(newState);
store.state = newState;
}
const collection = new Store<ViewpointsState, ViewpointsProps, SetMessage>();
collection.register("set", actionSet);
collection.serialize = (state) => {
const props: ViewpointsProps = {};
for (const id in state) {
props[id] = state[id].toJson();
}
return props;
};
// Subscribe to props
collection.onprops = (props) => {
if ("MOCHA_ON_STORE_PROPS" in window) {
//@ts-ignore
window.MOCHA_ON_STORE_PROPS(JSON.stringify(props)); // eslint-disable-line
} else {
console.log("[PROPS]", props);
}
};
// Initial state
collection.state = {
initial1: new Viewpoint("1 0 0"),
initial2: new Viewpoint("2 0 0"),
initial3: new Viewpoint("3 0 0")
};
// Send actions
collection.schedule({
action: "set",
key: "new1",
value: new Viewpoint("4 0 0")
});
collection.schedule({
action: "set",
key: "new2",
value: new Viewpoint("5 0 0")
});
| actionSet | identifier_name |
myapp.ts | /* eslint-env browser */
import {IStore, Store} from "../../..";
type ViewpointJson = {
position: string;
};
class Viewpoint {
public position: string;
public constructor(position: string = "0 0 0") {
this.position = position;
}
public toJson(): ViewpointJson {
return {
position: this.position
};
}
}
type MapOf<T> = {
[id: string]: T;
};
type ViewpointsState = MapOf<Viewpoint>;
type ViewpointsProps = MapOf<ViewpointJson>;
type SetMessage = Readonly<{
action: "set";
key: string;
value: Viewpoint;
}>;
export function actionSet<ViewpointsState>(message: SetMessage, store: IStore<ViewpointsState, never>): void {
const newItems: any = {};
newItems[message.key] = message.value;
const newState = Object.assign({}, store.state, newItems);
Object.freeze(newState);
store.state = newState;
}
const collection = new Store<ViewpointsState, ViewpointsProps, SetMessage>();
collection.register("set", actionSet);
collection.serialize = (state) => {
const props: ViewpointsProps = {};
for (const id in state) {
props[id] = state[id].toJson();
}
return props;
};
// Subscribe to props
collection.onprops = (props) => {
if ("MOCHA_ON_STORE_PROPS" in window) {
//@ts-ignore
window.MOCHA_ON_STORE_PROPS(JSON.stringify(props)); // eslint-disable-line
} else {
console.log("[PROPS]", props);
}
};
// Initial state
collection.state = {
initial1: new Viewpoint("1 0 0"),
initial2: new Viewpoint("2 0 0"),
initial3: new Viewpoint("3 0 0")
};
// Send actions
collection.schedule({
action: "set",
key: "new1",
value: new Viewpoint("4 0 0")
});
collection.schedule({ | action: "set",
key: "new2",
value: new Viewpoint("5 0 0")
}); | random_line_split | |
quick_setup_headless.py | #!/usr/bin/python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
# | # 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 argparse
import os
import sys
from cairis.tools.quickSetup import quick_setup
__author__ = 'Shamal Faily'
def main(args=None):
parser = argparse.ArgumentParser(description='CAIRIS quick setup script - headless')
parser.add_argument('--dbHost',dest='dbHost',help='Database host name', default='localhost')
parser.add_argument('--dbPort',dest='dbPort',help='Database port number',default='3306')
parser.add_argument('--dbRootPassword',dest='dbRootPassword',help='Database root password',default='')
parser.add_argument('--tmpDir',dest='tmpDir',help='Temp directory',default='/tmp')
defaultRootDir = os.path.split(os.path.split(os.path.realpath(os.path.dirname(__file__)))[0])[0]
parser.add_argument('--rootDir',dest='rootDir',help='Root directory',default=defaultRootDir + '/cairis')
parser.add_argument('--imageDir',dest='imageDir',help='Default image directory',default='/tmp')
homeDir = os.environ['HOME']
parser.add_argument('--configFile',dest='configFile',help='CAIRIS configuration file name (fully qualified path)',default=homeDir + '/cairis.cnf')
parser.add_argument('--webPort',dest='webPort',help='Web port',default='7071')
parser.add_argument('--logLevel',dest='logLevel',help='Log level',default='warning')
parser.add_argument('--staticDir',dest='staticDir',help='Static directory',default=defaultRootDir + '/cairis/web')
parser.add_argument('--assetDir',dest='assetDir',help='Asset directory',default=defaultRootDir + '/cairis/web/assets')
parser.add_argument('--uploadDir',dest='uploadDir',help='Upload directory',default='/tmp')
parser.add_argument('--user',dest='userName',help='Initial username',default='test')
parser.add_argument('--password',dest='passWd',help='Initial password',default='test')
args = parser.parse_args()
quick_setup(args.dbHost,int(args.dbPort),args.dbRootPassword,args.tmpDir,args.rootDir,args.imageDir,args.configFile,int(args.webPort),args.logLevel,args.staticDir,arg.assetDir,args.uploadDir,args.userName,args.passWd)
if __name__ == '__main__':
try:
from cairis.core.ARM import ARMException
main()
except ARMException as e:
print('Fatal setup error: ' + str(e))
sys.exit(-1) | # http://www.apache.org/licenses/LICENSE-2.0
# | random_line_split |
quick_setup_headless.py | #!/usr/bin/python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import argparse
import os
import sys
from cairis.tools.quickSetup import quick_setup
__author__ = 'Shamal Faily'
def main(args=None):
|
if __name__ == '__main__':
try:
from cairis.core.ARM import ARMException
main()
except ARMException as e:
print('Fatal setup error: ' + str(e))
sys.exit(-1)
| parser = argparse.ArgumentParser(description='CAIRIS quick setup script - headless')
parser.add_argument('--dbHost',dest='dbHost',help='Database host name', default='localhost')
parser.add_argument('--dbPort',dest='dbPort',help='Database port number',default='3306')
parser.add_argument('--dbRootPassword',dest='dbRootPassword',help='Database root password',default='')
parser.add_argument('--tmpDir',dest='tmpDir',help='Temp directory',default='/tmp')
defaultRootDir = os.path.split(os.path.split(os.path.realpath(os.path.dirname(__file__)))[0])[0]
parser.add_argument('--rootDir',dest='rootDir',help='Root directory',default=defaultRootDir + '/cairis')
parser.add_argument('--imageDir',dest='imageDir',help='Default image directory',default='/tmp')
homeDir = os.environ['HOME']
parser.add_argument('--configFile',dest='configFile',help='CAIRIS configuration file name (fully qualified path)',default=homeDir + '/cairis.cnf')
parser.add_argument('--webPort',dest='webPort',help='Web port',default='7071')
parser.add_argument('--logLevel',dest='logLevel',help='Log level',default='warning')
parser.add_argument('--staticDir',dest='staticDir',help='Static directory',default=defaultRootDir + '/cairis/web')
parser.add_argument('--assetDir',dest='assetDir',help='Asset directory',default=defaultRootDir + '/cairis/web/assets')
parser.add_argument('--uploadDir',dest='uploadDir',help='Upload directory',default='/tmp')
parser.add_argument('--user',dest='userName',help='Initial username',default='test')
parser.add_argument('--password',dest='passWd',help='Initial password',default='test')
args = parser.parse_args()
quick_setup(args.dbHost,int(args.dbPort),args.dbRootPassword,args.tmpDir,args.rootDir,args.imageDir,args.configFile,int(args.webPort),args.logLevel,args.staticDir,arg.assetDir,args.uploadDir,args.userName,args.passWd) | identifier_body |
quick_setup_headless.py | #!/usr/bin/python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import argparse
import os
import sys
from cairis.tools.quickSetup import quick_setup
__author__ = 'Shamal Faily'
def main(args=None):
parser = argparse.ArgumentParser(description='CAIRIS quick setup script - headless')
parser.add_argument('--dbHost',dest='dbHost',help='Database host name', default='localhost')
parser.add_argument('--dbPort',dest='dbPort',help='Database port number',default='3306')
parser.add_argument('--dbRootPassword',dest='dbRootPassword',help='Database root password',default='')
parser.add_argument('--tmpDir',dest='tmpDir',help='Temp directory',default='/tmp')
defaultRootDir = os.path.split(os.path.split(os.path.realpath(os.path.dirname(__file__)))[0])[0]
parser.add_argument('--rootDir',dest='rootDir',help='Root directory',default=defaultRootDir + '/cairis')
parser.add_argument('--imageDir',dest='imageDir',help='Default image directory',default='/tmp')
homeDir = os.environ['HOME']
parser.add_argument('--configFile',dest='configFile',help='CAIRIS configuration file name (fully qualified path)',default=homeDir + '/cairis.cnf')
parser.add_argument('--webPort',dest='webPort',help='Web port',default='7071')
parser.add_argument('--logLevel',dest='logLevel',help='Log level',default='warning')
parser.add_argument('--staticDir',dest='staticDir',help='Static directory',default=defaultRootDir + '/cairis/web')
parser.add_argument('--assetDir',dest='assetDir',help='Asset directory',default=defaultRootDir + '/cairis/web/assets')
parser.add_argument('--uploadDir',dest='uploadDir',help='Upload directory',default='/tmp')
parser.add_argument('--user',dest='userName',help='Initial username',default='test')
parser.add_argument('--password',dest='passWd',help='Initial password',default='test')
args = parser.parse_args()
quick_setup(args.dbHost,int(args.dbPort),args.dbRootPassword,args.tmpDir,args.rootDir,args.imageDir,args.configFile,int(args.webPort),args.logLevel,args.staticDir,arg.assetDir,args.uploadDir,args.userName,args.passWd)
if __name__ == '__main__':
| try:
from cairis.core.ARM import ARMException
main()
except ARMException as e:
print('Fatal setup error: ' + str(e))
sys.exit(-1) | conditional_block | |
quick_setup_headless.py | #!/usr/bin/python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import argparse
import os
import sys
from cairis.tools.quickSetup import quick_setup
__author__ = 'Shamal Faily'
def | (args=None):
parser = argparse.ArgumentParser(description='CAIRIS quick setup script - headless')
parser.add_argument('--dbHost',dest='dbHost',help='Database host name', default='localhost')
parser.add_argument('--dbPort',dest='dbPort',help='Database port number',default='3306')
parser.add_argument('--dbRootPassword',dest='dbRootPassword',help='Database root password',default='')
parser.add_argument('--tmpDir',dest='tmpDir',help='Temp directory',default='/tmp')
defaultRootDir = os.path.split(os.path.split(os.path.realpath(os.path.dirname(__file__)))[0])[0]
parser.add_argument('--rootDir',dest='rootDir',help='Root directory',default=defaultRootDir + '/cairis')
parser.add_argument('--imageDir',dest='imageDir',help='Default image directory',default='/tmp')
homeDir = os.environ['HOME']
parser.add_argument('--configFile',dest='configFile',help='CAIRIS configuration file name (fully qualified path)',default=homeDir + '/cairis.cnf')
parser.add_argument('--webPort',dest='webPort',help='Web port',default='7071')
parser.add_argument('--logLevel',dest='logLevel',help='Log level',default='warning')
parser.add_argument('--staticDir',dest='staticDir',help='Static directory',default=defaultRootDir + '/cairis/web')
parser.add_argument('--assetDir',dest='assetDir',help='Asset directory',default=defaultRootDir + '/cairis/web/assets')
parser.add_argument('--uploadDir',dest='uploadDir',help='Upload directory',default='/tmp')
parser.add_argument('--user',dest='userName',help='Initial username',default='test')
parser.add_argument('--password',dest='passWd',help='Initial password',default='test')
args = parser.parse_args()
quick_setup(args.dbHost,int(args.dbPort),args.dbRootPassword,args.tmpDir,args.rootDir,args.imageDir,args.configFile,int(args.webPort),args.logLevel,args.staticDir,arg.assetDir,args.uploadDir,args.userName,args.passWd)
if __name__ == '__main__':
try:
from cairis.core.ARM import ARMException
main()
except ARMException as e:
print('Fatal setup error: ' + str(e))
sys.exit(-1)
| main | identifier_name |
tcp_client.rs | use std::{fmt, io};
use std::sync::Arc;
use std::net::SocketAddr;
use std::marker::PhantomData;
use BindClient;
use tokio_core::reactor::Handle;
use tokio_core::net::{TcpStream, TcpStreamNew};
use futures::{Future, Poll, Async};
// TODO: add configuration, e.g.:
// - connection timeout
// - multiple addresses
// - request timeout
// TODO: consider global event loop handle, so that providing one in the builder
// is optional
/// Builds client connections to external services.
///
/// To connect to a service, you need a *client protocol* implementation; see
/// the crate documentation for guidance. | #[derive(Debug)]
pub struct TcpClient<Kind, P> {
_kind: PhantomData<Kind>,
proto: Arc<P>,
}
/// A future for establishing a client connection.
///
/// Yields a service for interacting with the server.
pub struct Connect<Kind, P> {
_kind: PhantomData<Kind>,
proto: Arc<P>,
socket: TcpStreamNew,
handle: Handle,
}
impl<Kind, P> Future for Connect<Kind, P> where P: BindClient<Kind, TcpStream> {
type Item = P::BindClient;
type Error = io::Error;
fn poll(&mut self) -> Poll<P::BindClient, io::Error> {
let socket = try_ready!(self.socket.poll());
Ok(Async::Ready(self.proto.bind_client(&self.handle, socket)))
}
}
impl<Kind, P> TcpClient<Kind, P> where P: BindClient<Kind, TcpStream> {
/// Create a builder for the given client protocol.
///
/// To connect to a service, you need a *client protocol* implementation;
/// see the crate documentation for guidance.
pub fn new(protocol: P) -> TcpClient<Kind, P> {
TcpClient {
_kind: PhantomData,
proto: Arc::new(protocol)
}
}
/// Establish a connection to the given address.
///
/// # Return value
///
/// Returns a future for the establishment of the connection. When the
/// future completes, it yields an instance of `Service` for interacting
/// with the server.
pub fn connect(&self, addr: &SocketAddr, handle: &Handle) -> Connect<Kind, P> {
Connect {
_kind: PhantomData,
proto: self.proto.clone(),
socket: TcpStream::connect(addr, handle),
handle: handle.clone(),
}
}
}
impl<Kind, P> fmt::Debug for Connect<Kind, P> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Connect {{ ... }}")
}
} | ///
/// At the moment, this builder offers minimal configuration, but more will be
/// added over time. | random_line_split |
tcp_client.rs | use std::{fmt, io};
use std::sync::Arc;
use std::net::SocketAddr;
use std::marker::PhantomData;
use BindClient;
use tokio_core::reactor::Handle;
use tokio_core::net::{TcpStream, TcpStreamNew};
use futures::{Future, Poll, Async};
// TODO: add configuration, e.g.:
// - connection timeout
// - multiple addresses
// - request timeout
// TODO: consider global event loop handle, so that providing one in the builder
// is optional
/// Builds client connections to external services.
///
/// To connect to a service, you need a *client protocol* implementation; see
/// the crate documentation for guidance.
///
/// At the moment, this builder offers minimal configuration, but more will be
/// added over time.
#[derive(Debug)]
pub struct TcpClient<Kind, P> {
_kind: PhantomData<Kind>,
proto: Arc<P>,
}
/// A future for establishing a client connection.
///
/// Yields a service for interacting with the server.
pub struct Connect<Kind, P> {
_kind: PhantomData<Kind>,
proto: Arc<P>,
socket: TcpStreamNew,
handle: Handle,
}
impl<Kind, P> Future for Connect<Kind, P> where P: BindClient<Kind, TcpStream> {
type Item = P::BindClient;
type Error = io::Error;
fn poll(&mut self) -> Poll<P::BindClient, io::Error> {
let socket = try_ready!(self.socket.poll());
Ok(Async::Ready(self.proto.bind_client(&self.handle, socket)))
}
}
impl<Kind, P> TcpClient<Kind, P> where P: BindClient<Kind, TcpStream> {
/// Create a builder for the given client protocol.
///
/// To connect to a service, you need a *client protocol* implementation;
/// see the crate documentation for guidance.
pub fn new(protocol: P) -> TcpClient<Kind, P> {
TcpClient {
_kind: PhantomData,
proto: Arc::new(protocol)
}
}
/// Establish a connection to the given address.
///
/// # Return value
///
/// Returns a future for the establishment of the connection. When the
/// future completes, it yields an instance of `Service` for interacting
/// with the server.
pub fn | (&self, addr: &SocketAddr, handle: &Handle) -> Connect<Kind, P> {
Connect {
_kind: PhantomData,
proto: self.proto.clone(),
socket: TcpStream::connect(addr, handle),
handle: handle.clone(),
}
}
}
impl<Kind, P> fmt::Debug for Connect<Kind, P> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Connect {{ ... }}")
}
}
| connect | identifier_name |
tcp_client.rs | use std::{fmt, io};
use std::sync::Arc;
use std::net::SocketAddr;
use std::marker::PhantomData;
use BindClient;
use tokio_core::reactor::Handle;
use tokio_core::net::{TcpStream, TcpStreamNew};
use futures::{Future, Poll, Async};
// TODO: add configuration, e.g.:
// - connection timeout
// - multiple addresses
// - request timeout
// TODO: consider global event loop handle, so that providing one in the builder
// is optional
/// Builds client connections to external services.
///
/// To connect to a service, you need a *client protocol* implementation; see
/// the crate documentation for guidance.
///
/// At the moment, this builder offers minimal configuration, but more will be
/// added over time.
#[derive(Debug)]
pub struct TcpClient<Kind, P> {
_kind: PhantomData<Kind>,
proto: Arc<P>,
}
/// A future for establishing a client connection.
///
/// Yields a service for interacting with the server.
pub struct Connect<Kind, P> {
_kind: PhantomData<Kind>,
proto: Arc<P>,
socket: TcpStreamNew,
handle: Handle,
}
impl<Kind, P> Future for Connect<Kind, P> where P: BindClient<Kind, TcpStream> {
type Item = P::BindClient;
type Error = io::Error;
fn poll(&mut self) -> Poll<P::BindClient, io::Error> {
let socket = try_ready!(self.socket.poll());
Ok(Async::Ready(self.proto.bind_client(&self.handle, socket)))
}
}
impl<Kind, P> TcpClient<Kind, P> where P: BindClient<Kind, TcpStream> {
/// Create a builder for the given client protocol.
///
/// To connect to a service, you need a *client protocol* implementation;
/// see the crate documentation for guidance.
pub fn new(protocol: P) -> TcpClient<Kind, P> {
TcpClient {
_kind: PhantomData,
proto: Arc::new(protocol)
}
}
/// Establish a connection to the given address.
///
/// # Return value
///
/// Returns a future for the establishment of the connection. When the
/// future completes, it yields an instance of `Service` for interacting
/// with the server.
pub fn connect(&self, addr: &SocketAddr, handle: &Handle) -> Connect<Kind, P> {
Connect {
_kind: PhantomData,
proto: self.proto.clone(),
socket: TcpStream::connect(addr, handle),
handle: handle.clone(),
}
}
}
impl<Kind, P> fmt::Debug for Connect<Kind, P> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
| {
write!(f, "Connect {{ ... }}")
} | identifier_body |
index.native.scroll.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');
var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactNative = require('react-native');
var _warning = require('warning');
var _warning2 = _interopRequireDefault(_warning);
var _checkIndexBounds = require('./utils/checkIndexBounds');
var _checkIndexBounds2 = _interopRequireDefault(_checkIndexBounds);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// weak
/**
* This is an alternative version that use `ScrollView` and `ViewPagerAndroid`.
* I'm not sure what version give the best UX experience.
* I'm keeping the two versions here until we figured out.
*/
var _Dimensions$get = _reactNative.Dimensions.get('window');
var windowWidth = _Dimensions$get.width;
var styles = _reactNative.StyleSheet.create({
root: {
flex: 1,
overflow: 'hidden'
},
container: {
flex: 1
},
slide: {
flex: 1
}
});
var SwipeableViews = function (_Component) {
(0, _inherits3.default)(SwipeableViews, _Component);
function SwipeableViews() {
var _ref;
var _temp, _this, _ret;
(0, _classCallCheck3.default)(this, SwipeableViews);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = SwipeableViews.__proto__ || (0, _getPrototypeOf2.default)(SwipeableViews)).call.apply(_ref, [this].concat(args))), _this), _this.state = {}, _this.handleScroll = function (event) {
if (_this.props.onSwitching) {
_this.props.onSwitching(event.nativeEvent.contentOffset.x / _this.state.viewWidth, 'move');
}
}, _this.handleMomentumScrollEnd = function (event) {
var offset = event.nativeEvent.contentOffset;
var indexNew = offset.x / _this.state.viewWidth;
var indexLatest = _this.state.indexLatest;
_this.setState({
indexLatest: indexNew,
offset: offset
}, function () {
if (_this.props.onSwitching) {
_this.props.onSwitching(indexNew, 'end');
}
if (_this.props.onChangeIndex && indexNew !== indexLatest) {
_this.props.onChangeIndex(indexNew, indexLatest);
}
});
}, _this.handlePageSelected = function (event) {
var indexLatest = _this.state.indexLatest;
var indexNew = event.nativeEvent.position;
_this.setState({
indexLatest: indexNew
}, function () {
if (_this.props.onSwitching) {
_this.props.onSwitching(indexNew, 'end');
}
if (_this.props.onChangeIndex && indexNew !== indexLatest) {
_this.props.onChangeIndex(indexNew, indexLatest);
}
});
}, _this.handlePageScroll = function (event) {
if (_this.props.onSwitching) {
_this.props.onSwitching(event.nativeEvent.offset + event.nativeEvent.position, 'move');
}
}, _this.handleLayout = function (event) {
var width = event.nativeEvent.layout.width;
if (width) |
}, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
}
(0, _createClass3.default)(SwipeableViews, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (process.env.NODE_ENV !== 'production') {
(0, _checkIndexBounds2.default)(this.props);
}
var initState = {
indexLatest: this.props.index,
viewWidth: windowWidth,
offset: {}
};
// android not use offset
if (_reactNative.Platform.OS === 'ios') {
initState.offset = {
x: initState.viewWidth * initState.indexLatest
};
}
this.setState(initState);
process.env.NODE_ENV !== "production" ? (0, _warning2.default)(!this.props.animateHeight, 'react-swipeable-view: The animateHeight property is not implement yet.') : void 0;
process.env.NODE_ENV !== "production" ? (0, _warning2.default)(!this.props.axis, 'react-swipeable-view: The axis property is not implement yet.') : void 0;
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var _this2 = this;
var index = nextProps.index;
if (typeof index === 'number' && index !== this.props.index) {
(0, _checkIndexBounds2.default)(nextProps);
this.setState({
indexLatest: index,
offset: {
x: this.state.viewWidth * index
}
}, function () {
if (_reactNative.Platform.OS === 'android') {
if (_this2.props.animateTransitions) {
_this2.refs.scrollView.setPage(index);
} else {
_this2.refs.scrollView.setPageWithoutAnimation(index);
}
}
});
}
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var resistance = _props.resistance;
var children = _props.children;
var slideStyle = _props.slideStyle;
var style = _props.style;
var containerStyle = _props.containerStyle;
var disabled = _props.disabled;
var other = (0, _objectWithoutProperties3.default)(_props, ['resistance', 'children', 'slideStyle', 'style', 'containerStyle', 'disabled']);
var _state = this.state;
var viewWidth = _state.viewWidth;
var indexLatest = _state.indexLatest;
var offset = _state.offset;
var slideStyleObj = [styles.slide, {
width: viewWidth
}, slideStyle];
var childrenToRender = _react.Children.map(children, function (element, index) {
if (disabled && indexLatest !== index) {
return null;
}
return _react2.default.createElement(
_reactNative.View,
{ style: slideStyleObj },
element
);
});
return _react2.default.createElement(
_reactNative.View,
{
onLayout: this.handleLayout,
style: [styles.root, style]
},
_reactNative.Platform.OS === 'ios' ? _react2.default.createElement(
_reactNative.ScrollView,
(0, _extends3.default)({}, other, {
ref: 'scrollView',
style: [styles.container, containerStyle],
horizontal: true,
pagingEnabled: true,
scrollsToTop: false,
bounces: resistance,
onScroll: this.handleScroll,
scrollEventThrottle: 200,
showsHorizontalScrollIndicator: false,
contentOffset: offset,
onMomentumScrollEnd: this.handleMomentumScrollEnd
}),
childrenToRender
) : _react2.default.createElement(
_reactNative.ViewPagerAndroid,
(0, _extends3.default)({}, other, {
ref: 'scrollView',
style: [styles.container, containerStyle],
initialPage: indexLatest,
onPageSelected: this.handlePageSelected,
onPageScroll: this.handlePageScroll
}),
childrenToRender
)
);
}
}]);
return SwipeableViews;
}(_react.Component);
SwipeableViews.defaultProps = {
animateTransitions: true,
disabled: false,
index: 0,
resistance: false
};
process.env.NODE_ENV !== "production" ? SwipeableViews.propTypes = {
/**
* If `true`, the height of the container will be animated to match the current slide height.
* Animating another style property has a negative impact regarding performance.
*/
animateHeight: _react.PropTypes.bool,
/**
* If `false`, changes to the index prop will not cause an animated transition.
*/
animateTransitions: _react.PropTypes.bool,
/**
* The axis on which the slides will slide.
*/
axis: _react.PropTypes.oneOf(['x', 'x-reverse', 'y', 'y-reverse']),
/**
* Use this property to provide your slides.
*/
children: _react.PropTypes.node,
/**
* This is the inlined style that will be applied
* to each slide container.
*/
containerStyle: _reactNative.ScrollView.propTypes.style,
/**
* If `true`, it will disable touch events.
* This is useful when you want to prohibit the user from changing slides.
*/
disabled: _react.PropTypes.bool,
/**
* This is the index of the slide to show.
* This is useful when you want to change the default slide shown.
* Or when you have tabs linked to each slide.
*/
index: _react.PropTypes.number,
/**
* This is callback prop. It's call by the
* component when the shown slide change after a swipe made by the user.
* This is useful when you have tabs linked to each slide.
*
* @param {integer} index This is the current index of the slide.
* @param {integer} fromIndex This is the oldest index of the slide.
*/
onChangeIndex: _react.PropTypes.func,
/**
* This is callback prop. It's called by the
* component when the slide switching.
* This is useful when you want to implement something corresponding to the current slide position.
*
* @param {integer} index This is the current index of the slide.
* @param {string} type Can be either `move` or `end`.
*/
onSwitching: _react.PropTypes.func,
/**
* If `true`, it will add bounds effect on the edges.
*/
resistance: _react.PropTypes.bool,
/**
* This is the inlined style that will be applied
* on the slide component.
*/
slideStyle: _reactNative.View.propTypes.style,
/**
* This is the inlined style that will be applied
* on the root component.
*/
style: _reactNative.View.propTypes.style
} : void 0;
exports.default = SwipeableViews; | {
_this.setState({
viewWidth: width,
offset: {
x: _this.state.indexLatest * width
}
});
} | conditional_block |
index.native.scroll.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');
var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactNative = require('react-native');
var _warning = require('warning');
var _warning2 = _interopRequireDefault(_warning);
var _checkIndexBounds = require('./utils/checkIndexBounds');
var _checkIndexBounds2 = _interopRequireDefault(_checkIndexBounds);
function _interopRequireDefault(obj) |
// weak
/**
* This is an alternative version that use `ScrollView` and `ViewPagerAndroid`.
* I'm not sure what version give the best UX experience.
* I'm keeping the two versions here until we figured out.
*/
var _Dimensions$get = _reactNative.Dimensions.get('window');
var windowWidth = _Dimensions$get.width;
var styles = _reactNative.StyleSheet.create({
root: {
flex: 1,
overflow: 'hidden'
},
container: {
flex: 1
},
slide: {
flex: 1
}
});
var SwipeableViews = function (_Component) {
(0, _inherits3.default)(SwipeableViews, _Component);
function SwipeableViews() {
var _ref;
var _temp, _this, _ret;
(0, _classCallCheck3.default)(this, SwipeableViews);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = SwipeableViews.__proto__ || (0, _getPrototypeOf2.default)(SwipeableViews)).call.apply(_ref, [this].concat(args))), _this), _this.state = {}, _this.handleScroll = function (event) {
if (_this.props.onSwitching) {
_this.props.onSwitching(event.nativeEvent.contentOffset.x / _this.state.viewWidth, 'move');
}
}, _this.handleMomentumScrollEnd = function (event) {
var offset = event.nativeEvent.contentOffset;
var indexNew = offset.x / _this.state.viewWidth;
var indexLatest = _this.state.indexLatest;
_this.setState({
indexLatest: indexNew,
offset: offset
}, function () {
if (_this.props.onSwitching) {
_this.props.onSwitching(indexNew, 'end');
}
if (_this.props.onChangeIndex && indexNew !== indexLatest) {
_this.props.onChangeIndex(indexNew, indexLatest);
}
});
}, _this.handlePageSelected = function (event) {
var indexLatest = _this.state.indexLatest;
var indexNew = event.nativeEvent.position;
_this.setState({
indexLatest: indexNew
}, function () {
if (_this.props.onSwitching) {
_this.props.onSwitching(indexNew, 'end');
}
if (_this.props.onChangeIndex && indexNew !== indexLatest) {
_this.props.onChangeIndex(indexNew, indexLatest);
}
});
}, _this.handlePageScroll = function (event) {
if (_this.props.onSwitching) {
_this.props.onSwitching(event.nativeEvent.offset + event.nativeEvent.position, 'move');
}
}, _this.handleLayout = function (event) {
var width = event.nativeEvent.layout.width;
if (width) {
_this.setState({
viewWidth: width,
offset: {
x: _this.state.indexLatest * width
}
});
}
}, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
}
(0, _createClass3.default)(SwipeableViews, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (process.env.NODE_ENV !== 'production') {
(0, _checkIndexBounds2.default)(this.props);
}
var initState = {
indexLatest: this.props.index,
viewWidth: windowWidth,
offset: {}
};
// android not use offset
if (_reactNative.Platform.OS === 'ios') {
initState.offset = {
x: initState.viewWidth * initState.indexLatest
};
}
this.setState(initState);
process.env.NODE_ENV !== "production" ? (0, _warning2.default)(!this.props.animateHeight, 'react-swipeable-view: The animateHeight property is not implement yet.') : void 0;
process.env.NODE_ENV !== "production" ? (0, _warning2.default)(!this.props.axis, 'react-swipeable-view: The axis property is not implement yet.') : void 0;
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var _this2 = this;
var index = nextProps.index;
if (typeof index === 'number' && index !== this.props.index) {
(0, _checkIndexBounds2.default)(nextProps);
this.setState({
indexLatest: index,
offset: {
x: this.state.viewWidth * index
}
}, function () {
if (_reactNative.Platform.OS === 'android') {
if (_this2.props.animateTransitions) {
_this2.refs.scrollView.setPage(index);
} else {
_this2.refs.scrollView.setPageWithoutAnimation(index);
}
}
});
}
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var resistance = _props.resistance;
var children = _props.children;
var slideStyle = _props.slideStyle;
var style = _props.style;
var containerStyle = _props.containerStyle;
var disabled = _props.disabled;
var other = (0, _objectWithoutProperties3.default)(_props, ['resistance', 'children', 'slideStyle', 'style', 'containerStyle', 'disabled']);
var _state = this.state;
var viewWidth = _state.viewWidth;
var indexLatest = _state.indexLatest;
var offset = _state.offset;
var slideStyleObj = [styles.slide, {
width: viewWidth
}, slideStyle];
var childrenToRender = _react.Children.map(children, function (element, index) {
if (disabled && indexLatest !== index) {
return null;
}
return _react2.default.createElement(
_reactNative.View,
{ style: slideStyleObj },
element
);
});
return _react2.default.createElement(
_reactNative.View,
{
onLayout: this.handleLayout,
style: [styles.root, style]
},
_reactNative.Platform.OS === 'ios' ? _react2.default.createElement(
_reactNative.ScrollView,
(0, _extends3.default)({}, other, {
ref: 'scrollView',
style: [styles.container, containerStyle],
horizontal: true,
pagingEnabled: true,
scrollsToTop: false,
bounces: resistance,
onScroll: this.handleScroll,
scrollEventThrottle: 200,
showsHorizontalScrollIndicator: false,
contentOffset: offset,
onMomentumScrollEnd: this.handleMomentumScrollEnd
}),
childrenToRender
) : _react2.default.createElement(
_reactNative.ViewPagerAndroid,
(0, _extends3.default)({}, other, {
ref: 'scrollView',
style: [styles.container, containerStyle],
initialPage: indexLatest,
onPageSelected: this.handlePageSelected,
onPageScroll: this.handlePageScroll
}),
childrenToRender
)
);
}
}]);
return SwipeableViews;
}(_react.Component);
SwipeableViews.defaultProps = {
animateTransitions: true,
disabled: false,
index: 0,
resistance: false
};
process.env.NODE_ENV !== "production" ? SwipeableViews.propTypes = {
/**
* If `true`, the height of the container will be animated to match the current slide height.
* Animating another style property has a negative impact regarding performance.
*/
animateHeight: _react.PropTypes.bool,
/**
* If `false`, changes to the index prop will not cause an animated transition.
*/
animateTransitions: _react.PropTypes.bool,
/**
* The axis on which the slides will slide.
*/
axis: _react.PropTypes.oneOf(['x', 'x-reverse', 'y', 'y-reverse']),
/**
* Use this property to provide your slides.
*/
children: _react.PropTypes.node,
/**
* This is the inlined style that will be applied
* to each slide container.
*/
containerStyle: _reactNative.ScrollView.propTypes.style,
/**
* If `true`, it will disable touch events.
* This is useful when you want to prohibit the user from changing slides.
*/
disabled: _react.PropTypes.bool,
/**
* This is the index of the slide to show.
* This is useful when you want to change the default slide shown.
* Or when you have tabs linked to each slide.
*/
index: _react.PropTypes.number,
/**
* This is callback prop. It's call by the
* component when the shown slide change after a swipe made by the user.
* This is useful when you have tabs linked to each slide.
*
* @param {integer} index This is the current index of the slide.
* @param {integer} fromIndex This is the oldest index of the slide.
*/
onChangeIndex: _react.PropTypes.func,
/**
* This is callback prop. It's called by the
* component when the slide switching.
* This is useful when you want to implement something corresponding to the current slide position.
*
* @param {integer} index This is the current index of the slide.
* @param {string} type Can be either `move` or `end`.
*/
onSwitching: _react.PropTypes.func,
/**
* If `true`, it will add bounds effect on the edges.
*/
resistance: _react.PropTypes.bool,
/**
* This is the inlined style that will be applied
* on the slide component.
*/
slideStyle: _reactNative.View.propTypes.style,
/**
* This is the inlined style that will be applied
* on the root component.
*/
style: _reactNative.View.propTypes.style
} : void 0;
exports.default = SwipeableViews; | { return obj && obj.__esModule ? obj : { default: obj }; } | identifier_body |
index.native.scroll.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');
var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactNative = require('react-native');
var _warning = require('warning');
var _warning2 = _interopRequireDefault(_warning);
var _checkIndexBounds = require('./utils/checkIndexBounds');
var _checkIndexBounds2 = _interopRequireDefault(_checkIndexBounds);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// weak
/**
* This is an alternative version that use `ScrollView` and `ViewPagerAndroid`.
* I'm not sure what version give the best UX experience.
* I'm keeping the two versions here until we figured out.
*/
var _Dimensions$get = _reactNative.Dimensions.get('window');
var windowWidth = _Dimensions$get.width;
var styles = _reactNative.StyleSheet.create({
root: {
flex: 1,
overflow: 'hidden'
},
container: {
flex: 1
},
slide: {
flex: 1
}
});
var SwipeableViews = function (_Component) {
(0, _inherits3.default)(SwipeableViews, _Component);
function SwipeableViews() {
var _ref;
var _temp, _this, _ret;
(0, _classCallCheck3.default)(this, SwipeableViews);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = SwipeableViews.__proto__ || (0, _getPrototypeOf2.default)(SwipeableViews)).call.apply(_ref, [this].concat(args))), _this), _this.state = {}, _this.handleScroll = function (event) {
if (_this.props.onSwitching) {
_this.props.onSwitching(event.nativeEvent.contentOffset.x / _this.state.viewWidth, 'move');
}
}, _this.handleMomentumScrollEnd = function (event) {
var offset = event.nativeEvent.contentOffset;
var indexNew = offset.x / _this.state.viewWidth;
var indexLatest = _this.state.indexLatest;
_this.setState({
indexLatest: indexNew,
offset: offset
}, function () {
if (_this.props.onSwitching) {
_this.props.onSwitching(indexNew, 'end');
}
if (_this.props.onChangeIndex && indexNew !== indexLatest) {
_this.props.onChangeIndex(indexNew, indexLatest);
}
});
}, _this.handlePageSelected = function (event) {
var indexLatest = _this.state.indexLatest;
var indexNew = event.nativeEvent.position;
_this.setState({
indexLatest: indexNew
}, function () {
if (_this.props.onSwitching) {
_this.props.onSwitching(indexNew, 'end');
}
if (_this.props.onChangeIndex && indexNew !== indexLatest) {
_this.props.onChangeIndex(indexNew, indexLatest);
}
});
}, _this.handlePageScroll = function (event) {
if (_this.props.onSwitching) {
_this.props.onSwitching(event.nativeEvent.offset + event.nativeEvent.position, 'move');
}
}, _this.handleLayout = function (event) {
var width = event.nativeEvent.layout.width;
if (width) {
_this.setState({
viewWidth: width,
offset: {
x: _this.state.indexLatest * width
}
});
}
}, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
}
(0, _createClass3.default)(SwipeableViews, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (process.env.NODE_ENV !== 'production') {
(0, _checkIndexBounds2.default)(this.props);
}
var initState = {
indexLatest: this.props.index,
viewWidth: windowWidth,
offset: {}
};
// android not use offset
if (_reactNative.Platform.OS === 'ios') {
initState.offset = {
x: initState.viewWidth * initState.indexLatest
};
}
this.setState(initState);
process.env.NODE_ENV !== "production" ? (0, _warning2.default)(!this.props.animateHeight, 'react-swipeable-view: The animateHeight property is not implement yet.') : void 0;
process.env.NODE_ENV !== "production" ? (0, _warning2.default)(!this.props.axis, 'react-swipeable-view: The axis property is not implement yet.') : void 0;
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var _this2 = this;
var index = nextProps.index;
if (typeof index === 'number' && index !== this.props.index) {
(0, _checkIndexBounds2.default)(nextProps);
this.setState({
indexLatest: index,
offset: {
x: this.state.viewWidth * index
}
}, function () {
if (_reactNative.Platform.OS === 'android') {
if (_this2.props.animateTransitions) {
_this2.refs.scrollView.setPage(index);
} else {
_this2.refs.scrollView.setPageWithoutAnimation(index);
}
}
});
}
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var resistance = _props.resistance;
var children = _props.children;
var slideStyle = _props.slideStyle;
var style = _props.style;
var containerStyle = _props.containerStyle;
var disabled = _props.disabled;
var other = (0, _objectWithoutProperties3.default)(_props, ['resistance', 'children', 'slideStyle', 'style', 'containerStyle', 'disabled']); | var viewWidth = _state.viewWidth;
var indexLatest = _state.indexLatest;
var offset = _state.offset;
var slideStyleObj = [styles.slide, {
width: viewWidth
}, slideStyle];
var childrenToRender = _react.Children.map(children, function (element, index) {
if (disabled && indexLatest !== index) {
return null;
}
return _react2.default.createElement(
_reactNative.View,
{ style: slideStyleObj },
element
);
});
return _react2.default.createElement(
_reactNative.View,
{
onLayout: this.handleLayout,
style: [styles.root, style]
},
_reactNative.Platform.OS === 'ios' ? _react2.default.createElement(
_reactNative.ScrollView,
(0, _extends3.default)({}, other, {
ref: 'scrollView',
style: [styles.container, containerStyle],
horizontal: true,
pagingEnabled: true,
scrollsToTop: false,
bounces: resistance,
onScroll: this.handleScroll,
scrollEventThrottle: 200,
showsHorizontalScrollIndicator: false,
contentOffset: offset,
onMomentumScrollEnd: this.handleMomentumScrollEnd
}),
childrenToRender
) : _react2.default.createElement(
_reactNative.ViewPagerAndroid,
(0, _extends3.default)({}, other, {
ref: 'scrollView',
style: [styles.container, containerStyle],
initialPage: indexLatest,
onPageSelected: this.handlePageSelected,
onPageScroll: this.handlePageScroll
}),
childrenToRender
)
);
}
}]);
return SwipeableViews;
}(_react.Component);
SwipeableViews.defaultProps = {
animateTransitions: true,
disabled: false,
index: 0,
resistance: false
};
process.env.NODE_ENV !== "production" ? SwipeableViews.propTypes = {
/**
* If `true`, the height of the container will be animated to match the current slide height.
* Animating another style property has a negative impact regarding performance.
*/
animateHeight: _react.PropTypes.bool,
/**
* If `false`, changes to the index prop will not cause an animated transition.
*/
animateTransitions: _react.PropTypes.bool,
/**
* The axis on which the slides will slide.
*/
axis: _react.PropTypes.oneOf(['x', 'x-reverse', 'y', 'y-reverse']),
/**
* Use this property to provide your slides.
*/
children: _react.PropTypes.node,
/**
* This is the inlined style that will be applied
* to each slide container.
*/
containerStyle: _reactNative.ScrollView.propTypes.style,
/**
* If `true`, it will disable touch events.
* This is useful when you want to prohibit the user from changing slides.
*/
disabled: _react.PropTypes.bool,
/**
* This is the index of the slide to show.
* This is useful when you want to change the default slide shown.
* Or when you have tabs linked to each slide.
*/
index: _react.PropTypes.number,
/**
* This is callback prop. It's call by the
* component when the shown slide change after a swipe made by the user.
* This is useful when you have tabs linked to each slide.
*
* @param {integer} index This is the current index of the slide.
* @param {integer} fromIndex This is the oldest index of the slide.
*/
onChangeIndex: _react.PropTypes.func,
/**
* This is callback prop. It's called by the
* component when the slide switching.
* This is useful when you want to implement something corresponding to the current slide position.
*
* @param {integer} index This is the current index of the slide.
* @param {string} type Can be either `move` or `end`.
*/
onSwitching: _react.PropTypes.func,
/**
* If `true`, it will add bounds effect on the edges.
*/
resistance: _react.PropTypes.bool,
/**
* This is the inlined style that will be applied
* on the slide component.
*/
slideStyle: _reactNative.View.propTypes.style,
/**
* This is the inlined style that will be applied
* on the root component.
*/
style: _reactNative.View.propTypes.style
} : void 0;
exports.default = SwipeableViews; | var _state = this.state; | random_line_split |
index.native.scroll.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');
var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactNative = require('react-native');
var _warning = require('warning');
var _warning2 = _interopRequireDefault(_warning);
var _checkIndexBounds = require('./utils/checkIndexBounds');
var _checkIndexBounds2 = _interopRequireDefault(_checkIndexBounds);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// weak
/**
* This is an alternative version that use `ScrollView` and `ViewPagerAndroid`.
* I'm not sure what version give the best UX experience.
* I'm keeping the two versions here until we figured out.
*/
var _Dimensions$get = _reactNative.Dimensions.get('window');
var windowWidth = _Dimensions$get.width;
var styles = _reactNative.StyleSheet.create({
root: {
flex: 1,
overflow: 'hidden'
},
container: {
flex: 1
},
slide: {
flex: 1
}
});
var SwipeableViews = function (_Component) {
(0, _inherits3.default)(SwipeableViews, _Component);
function | () {
var _ref;
var _temp, _this, _ret;
(0, _classCallCheck3.default)(this, SwipeableViews);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = SwipeableViews.__proto__ || (0, _getPrototypeOf2.default)(SwipeableViews)).call.apply(_ref, [this].concat(args))), _this), _this.state = {}, _this.handleScroll = function (event) {
if (_this.props.onSwitching) {
_this.props.onSwitching(event.nativeEvent.contentOffset.x / _this.state.viewWidth, 'move');
}
}, _this.handleMomentumScrollEnd = function (event) {
var offset = event.nativeEvent.contentOffset;
var indexNew = offset.x / _this.state.viewWidth;
var indexLatest = _this.state.indexLatest;
_this.setState({
indexLatest: indexNew,
offset: offset
}, function () {
if (_this.props.onSwitching) {
_this.props.onSwitching(indexNew, 'end');
}
if (_this.props.onChangeIndex && indexNew !== indexLatest) {
_this.props.onChangeIndex(indexNew, indexLatest);
}
});
}, _this.handlePageSelected = function (event) {
var indexLatest = _this.state.indexLatest;
var indexNew = event.nativeEvent.position;
_this.setState({
indexLatest: indexNew
}, function () {
if (_this.props.onSwitching) {
_this.props.onSwitching(indexNew, 'end');
}
if (_this.props.onChangeIndex && indexNew !== indexLatest) {
_this.props.onChangeIndex(indexNew, indexLatest);
}
});
}, _this.handlePageScroll = function (event) {
if (_this.props.onSwitching) {
_this.props.onSwitching(event.nativeEvent.offset + event.nativeEvent.position, 'move');
}
}, _this.handleLayout = function (event) {
var width = event.nativeEvent.layout.width;
if (width) {
_this.setState({
viewWidth: width,
offset: {
x: _this.state.indexLatest * width
}
});
}
}, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
}
(0, _createClass3.default)(SwipeableViews, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (process.env.NODE_ENV !== 'production') {
(0, _checkIndexBounds2.default)(this.props);
}
var initState = {
indexLatest: this.props.index,
viewWidth: windowWidth,
offset: {}
};
// android not use offset
if (_reactNative.Platform.OS === 'ios') {
initState.offset = {
x: initState.viewWidth * initState.indexLatest
};
}
this.setState(initState);
process.env.NODE_ENV !== "production" ? (0, _warning2.default)(!this.props.animateHeight, 'react-swipeable-view: The animateHeight property is not implement yet.') : void 0;
process.env.NODE_ENV !== "production" ? (0, _warning2.default)(!this.props.axis, 'react-swipeable-view: The axis property is not implement yet.') : void 0;
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var _this2 = this;
var index = nextProps.index;
if (typeof index === 'number' && index !== this.props.index) {
(0, _checkIndexBounds2.default)(nextProps);
this.setState({
indexLatest: index,
offset: {
x: this.state.viewWidth * index
}
}, function () {
if (_reactNative.Platform.OS === 'android') {
if (_this2.props.animateTransitions) {
_this2.refs.scrollView.setPage(index);
} else {
_this2.refs.scrollView.setPageWithoutAnimation(index);
}
}
});
}
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var resistance = _props.resistance;
var children = _props.children;
var slideStyle = _props.slideStyle;
var style = _props.style;
var containerStyle = _props.containerStyle;
var disabled = _props.disabled;
var other = (0, _objectWithoutProperties3.default)(_props, ['resistance', 'children', 'slideStyle', 'style', 'containerStyle', 'disabled']);
var _state = this.state;
var viewWidth = _state.viewWidth;
var indexLatest = _state.indexLatest;
var offset = _state.offset;
var slideStyleObj = [styles.slide, {
width: viewWidth
}, slideStyle];
var childrenToRender = _react.Children.map(children, function (element, index) {
if (disabled && indexLatest !== index) {
return null;
}
return _react2.default.createElement(
_reactNative.View,
{ style: slideStyleObj },
element
);
});
return _react2.default.createElement(
_reactNative.View,
{
onLayout: this.handleLayout,
style: [styles.root, style]
},
_reactNative.Platform.OS === 'ios' ? _react2.default.createElement(
_reactNative.ScrollView,
(0, _extends3.default)({}, other, {
ref: 'scrollView',
style: [styles.container, containerStyle],
horizontal: true,
pagingEnabled: true,
scrollsToTop: false,
bounces: resistance,
onScroll: this.handleScroll,
scrollEventThrottle: 200,
showsHorizontalScrollIndicator: false,
contentOffset: offset,
onMomentumScrollEnd: this.handleMomentumScrollEnd
}),
childrenToRender
) : _react2.default.createElement(
_reactNative.ViewPagerAndroid,
(0, _extends3.default)({}, other, {
ref: 'scrollView',
style: [styles.container, containerStyle],
initialPage: indexLatest,
onPageSelected: this.handlePageSelected,
onPageScroll: this.handlePageScroll
}),
childrenToRender
)
);
}
}]);
return SwipeableViews;
}(_react.Component);
SwipeableViews.defaultProps = {
animateTransitions: true,
disabled: false,
index: 0,
resistance: false
};
process.env.NODE_ENV !== "production" ? SwipeableViews.propTypes = {
/**
* If `true`, the height of the container will be animated to match the current slide height.
* Animating another style property has a negative impact regarding performance.
*/
animateHeight: _react.PropTypes.bool,
/**
* If `false`, changes to the index prop will not cause an animated transition.
*/
animateTransitions: _react.PropTypes.bool,
/**
* The axis on which the slides will slide.
*/
axis: _react.PropTypes.oneOf(['x', 'x-reverse', 'y', 'y-reverse']),
/**
* Use this property to provide your slides.
*/
children: _react.PropTypes.node,
/**
* This is the inlined style that will be applied
* to each slide container.
*/
containerStyle: _reactNative.ScrollView.propTypes.style,
/**
* If `true`, it will disable touch events.
* This is useful when you want to prohibit the user from changing slides.
*/
disabled: _react.PropTypes.bool,
/**
* This is the index of the slide to show.
* This is useful when you want to change the default slide shown.
* Or when you have tabs linked to each slide.
*/
index: _react.PropTypes.number,
/**
* This is callback prop. It's call by the
* component when the shown slide change after a swipe made by the user.
* This is useful when you have tabs linked to each slide.
*
* @param {integer} index This is the current index of the slide.
* @param {integer} fromIndex This is the oldest index of the slide.
*/
onChangeIndex: _react.PropTypes.func,
/**
* This is callback prop. It's called by the
* component when the slide switching.
* This is useful when you want to implement something corresponding to the current slide position.
*
* @param {integer} index This is the current index of the slide.
* @param {string} type Can be either `move` or `end`.
*/
onSwitching: _react.PropTypes.func,
/**
* If `true`, it will add bounds effect on the edges.
*/
resistance: _react.PropTypes.bool,
/**
* This is the inlined style that will be applied
* on the slide component.
*/
slideStyle: _reactNative.View.propTypes.style,
/**
* This is the inlined style that will be applied
* on the root component.
*/
style: _reactNative.View.propTypes.style
} : void 0;
exports.default = SwipeableViews; | SwipeableViews | identifier_name |
Atmosphere.py | from scipy import *
from Reference import *
################################################################################
# DATA
################################################################################
# EARTH FACTS
R = 287.058 # ideal gas constant for earth air, in J/kg*K
r = 6356766 # radius of the earth, in m
g = 9.80665 # gravitational acceleration at sea level, in m/s^2
# ATMOSPHERE FACTS
baseHeights = [0, 11000, 25000, 47000, 53000, 79000, 90000, 105000] # (geopotential) heights for the beginning of each layer, in m
baseTemperatures = [288.16, 216.66, 216.66, 282.66, 282.66, 165.66, 165.66, 225.66] # temperature for the beginning of each layer, in K
tempGradients = [-0.0065, 0, 0.003, 0, -0.0045, 0, 0.004, NaN] # temperature gradients for each layer, in K/m (last one represents no information above that height)
basePressures = [101325.0, 22634.008746132295, 2489.1856086672196, 120.49268001877302, 58.347831704016428, 1.0101781258352585, 0.10452732009352216, nan] # in Pa # precalculated
baseDensities = [1.225, 0.3639451299338376, 0.040025034448687088, 0.0014850787413445172, 0.00071914015402165508, 2.124386216253755e-05, 2.1981905205581133e-06, nan] # in kg/m^3 # precalculated
################################################################################
# CALCULATION FUNCTIONS
################################################################################
def layerIndexForheight(h): # get a reference to the place in the lists where the base information is
return baseHeights.index(next(height for height in reversed(baseHeights) if height <= h))
def | (hg):
return (r * hg) / (r + hg)
def temperatureAtHeight(h):
i = layerIndexForheight(h)
return baseTemperatures[i] + tempGradients[i] * (h - baseHeights[i])
def isothermalLayerPressureAtHeight(h, basePressure, baseHeight, layerTemperature):
return basePressure * exp(-(g * (h - baseHeight) / (R * layerTemperature)))
def isothermalLayerDensityAtHeight(h, baseDensity, basePressure, pressureAtHeight):
return baseDensity * (pressureAtHeight / basePressure)
def gradientLayerPressureAtHeight(h, basePressure, temperatureAtHeight, baseTemperature, layerTemperatureGradient):
return basePressure * (temperatureAtHeight / baseTemperature)**(-(g) / (R * layerTemperatureGradient))
def gradientLayerDensityAtHeight(h, baseDensity, temperatureAtHeight, baseTemperature, layerTemperatureGradient):
return baseDensity * (temperatureAtHeight / baseTemperature)**-(g/(R * layerTemperatureGradient) + 1)
def baseInformation(h):
i = layerIndexForheight(h)
return baseHeights[i], baseTemperatures[i], tempGradients[i], basePressures[i], baseDensities[i]
def informationAtHeight(hg):
"""Takes a Geometric Altitude and Returns the Geometric Altitude, Geopotential
Altitude, Temperature, Pressure and Density at that altitude in that order.
Defined from 0m to 104999m"""
if hg >= 105000 or hg < 0: # if height out of range
raise Exception("Atmosphere values unknown at this altitude ({0}m)".format(hg))
h = geopotentialAltitudeForHeight(hg)
t = temperatureAtHeight(h)
baseHeight, baseTemperature, layerGradient, basePressure, baseDensity = baseInformation(h)
if (layerGradient == 0): # isothermal layer
p = isothermalLayerPressureAtHeight(h, basePressure, baseHeight, baseTemperature)
d = isothermalLayerDensityAtHeight(h, baseDensity, basePressure, p)
else: # gradient layer
p = gradientLayerPressureAtHeight(h, basePressure, t, baseTemperature, layerGradient)
d = gradientLayerDensityAtHeight(h, baseDensity, t, baseTemperature, layerGradient)
return hg, h, t, p, d
################################################################################
# REFERENCE FUNCTIONS
################################################################################
def temperatureAtAltitude(altitude):
return informationAtHeight(altitude)[2]
def pressureAtAltitude(altitude):
return informationAtHeight(altitude)[3]
def densityAtAltitude(altitude):
return informationAtHeight(altitude)[4]
def machAtAltitude(altitude):
return sqrt(airHeatCapacityRatio * airIdealGasConstant * temperatureAtAltitude(altitude))
| geopotentialAltitudeForHeight | identifier_name |
Atmosphere.py | from scipy import *
from Reference import *
################################################################################
# DATA
################################################################################
# EARTH FACTS
R = 287.058 # ideal gas constant for earth air, in J/kg*K
r = 6356766 # radius of the earth, in m
g = 9.80665 # gravitational acceleration at sea level, in m/s^2
# ATMOSPHERE FACTS
baseHeights = [0, 11000, 25000, 47000, 53000, 79000, 90000, 105000] # (geopotential) heights for the beginning of each layer, in m
baseTemperatures = [288.16, 216.66, 216.66, 282.66, 282.66, 165.66, 165.66, 225.66] # temperature for the beginning of each layer, in K
tempGradients = [-0.0065, 0, 0.003, 0, -0.0045, 0, 0.004, NaN] # temperature gradients for each layer, in K/m (last one represents no information above that height)
basePressures = [101325.0, 22634.008746132295, 2489.1856086672196, 120.49268001877302, 58.347831704016428, 1.0101781258352585, 0.10452732009352216, nan] # in Pa # precalculated
baseDensities = [1.225, 0.3639451299338376, 0.040025034448687088, 0.0014850787413445172, 0.00071914015402165508, 2.124386216253755e-05, 2.1981905205581133e-06, nan] # in kg/m^3 # precalculated
################################################################################
# CALCULATION FUNCTIONS
################################################################################
def layerIndexForheight(h): # get a reference to the place in the lists where the base information is
return baseHeights.index(next(height for height in reversed(baseHeights) if height <= h))
def geopotentialAltitudeForHeight(hg):
return (r * hg) / (r + hg)
def temperatureAtHeight(h):
i = layerIndexForheight(h)
return baseTemperatures[i] + tempGradients[i] * (h - baseHeights[i])
def isothermalLayerPressureAtHeight(h, basePressure, baseHeight, layerTemperature):
return basePressure * exp(-(g * (h - baseHeight) / (R * layerTemperature)))
def isothermalLayerDensityAtHeight(h, baseDensity, basePressure, pressureAtHeight):
return baseDensity * (pressureAtHeight / basePressure)
def gradientLayerPressureAtHeight(h, basePressure, temperatureAtHeight, baseTemperature, layerTemperatureGradient):
return basePressure * (temperatureAtHeight / baseTemperature)**(-(g) / (R * layerTemperatureGradient))
def gradientLayerDensityAtHeight(h, baseDensity, temperatureAtHeight, baseTemperature, layerTemperatureGradient):
return baseDensity * (temperatureAtHeight / baseTemperature)**-(g/(R * layerTemperatureGradient) + 1)
def baseInformation(h):
i = layerIndexForheight(h)
return baseHeights[i], baseTemperatures[i], tempGradients[i], basePressures[i], baseDensities[i]
def informationAtHeight(hg):
"""Takes a Geometric Altitude and Returns the Geometric Altitude, Geopotential
Altitude, Temperature, Pressure and Density at that altitude in that order.
Defined from 0m to 104999m"""
if hg >= 105000 or hg < 0: # if height out of range
raise Exception("Atmosphere values unknown at this altitude ({0}m)".format(hg))
h = geopotentialAltitudeForHeight(hg)
t = temperatureAtHeight(h)
baseHeight, baseTemperature, layerGradient, basePressure, baseDensity = baseInformation(h)
if (layerGradient == 0): # isothermal layer
|
else: # gradient layer
p = gradientLayerPressureAtHeight(h, basePressure, t, baseTemperature, layerGradient)
d = gradientLayerDensityAtHeight(h, baseDensity, t, baseTemperature, layerGradient)
return hg, h, t, p, d
################################################################################
# REFERENCE FUNCTIONS
################################################################################
def temperatureAtAltitude(altitude):
return informationAtHeight(altitude)[2]
def pressureAtAltitude(altitude):
return informationAtHeight(altitude)[3]
def densityAtAltitude(altitude):
return informationAtHeight(altitude)[4]
def machAtAltitude(altitude):
return sqrt(airHeatCapacityRatio * airIdealGasConstant * temperatureAtAltitude(altitude))
| p = isothermalLayerPressureAtHeight(h, basePressure, baseHeight, baseTemperature)
d = isothermalLayerDensityAtHeight(h, baseDensity, basePressure, p) | conditional_block |
Atmosphere.py | from scipy import *
from Reference import *
################################################################################
# DATA
################################################################################
# EARTH FACTS
R = 287.058 # ideal gas constant for earth air, in J/kg*K
r = 6356766 # radius of the earth, in m
g = 9.80665 # gravitational acceleration at sea level, in m/s^2
# ATMOSPHERE FACTS
baseHeights = [0, 11000, 25000, 47000, 53000, 79000, 90000, 105000] # (geopotential) heights for the beginning of each layer, in m
baseTemperatures = [288.16, 216.66, 216.66, 282.66, 282.66, 165.66, 165.66, 225.66] # temperature for the beginning of each layer, in K
tempGradients = [-0.0065, 0, 0.003, 0, -0.0045, 0, 0.004, NaN] # temperature gradients for each layer, in K/m (last one represents no information above that height)
basePressures = [101325.0, 22634.008746132295, 2489.1856086672196, 120.49268001877302, 58.347831704016428, 1.0101781258352585, 0.10452732009352216, nan] # in Pa # precalculated
baseDensities = [1.225, 0.3639451299338376, 0.040025034448687088, 0.0014850787413445172, 0.00071914015402165508, 2.124386216253755e-05, 2.1981905205581133e-06, nan] # in kg/m^3 # precalculated
################################################################################
# CALCULATION FUNCTIONS
################################################################################
def layerIndexForheight(h): # get a reference to the place in the lists where the base information is
return baseHeights.index(next(height for height in reversed(baseHeights) if height <= h))
def geopotentialAltitudeForHeight(hg):
return (r * hg) / (r + hg)
def temperatureAtHeight(h):
i = layerIndexForheight(h)
return baseTemperatures[i] + tempGradients[i] * (h - baseHeights[i])
def isothermalLayerPressureAtHeight(h, basePressure, baseHeight, layerTemperature):
return basePressure * exp(-(g * (h - baseHeight) / (R * layerTemperature)))
def isothermalLayerDensityAtHeight(h, baseDensity, basePressure, pressureAtHeight):
return baseDensity * (pressureAtHeight / basePressure)
def gradientLayerPressureAtHeight(h, basePressure, temperatureAtHeight, baseTemperature, layerTemperatureGradient):
return basePressure * (temperatureAtHeight / baseTemperature)**(-(g) / (R * layerTemperatureGradient))
|
def baseInformation(h):
i = layerIndexForheight(h)
return baseHeights[i], baseTemperatures[i], tempGradients[i], basePressures[i], baseDensities[i]
def informationAtHeight(hg):
"""Takes a Geometric Altitude and Returns the Geometric Altitude, Geopotential
Altitude, Temperature, Pressure and Density at that altitude in that order.
Defined from 0m to 104999m"""
if hg >= 105000 or hg < 0: # if height out of range
raise Exception("Atmosphere values unknown at this altitude ({0}m)".format(hg))
h = geopotentialAltitudeForHeight(hg)
t = temperatureAtHeight(h)
baseHeight, baseTemperature, layerGradient, basePressure, baseDensity = baseInformation(h)
if (layerGradient == 0): # isothermal layer
p = isothermalLayerPressureAtHeight(h, basePressure, baseHeight, baseTemperature)
d = isothermalLayerDensityAtHeight(h, baseDensity, basePressure, p)
else: # gradient layer
p = gradientLayerPressureAtHeight(h, basePressure, t, baseTemperature, layerGradient)
d = gradientLayerDensityAtHeight(h, baseDensity, t, baseTemperature, layerGradient)
return hg, h, t, p, d
################################################################################
# REFERENCE FUNCTIONS
################################################################################
def temperatureAtAltitude(altitude):
return informationAtHeight(altitude)[2]
def pressureAtAltitude(altitude):
return informationAtHeight(altitude)[3]
def densityAtAltitude(altitude):
return informationAtHeight(altitude)[4]
def machAtAltitude(altitude):
return sqrt(airHeatCapacityRatio * airIdealGasConstant * temperatureAtAltitude(altitude)) | def gradientLayerDensityAtHeight(h, baseDensity, temperatureAtHeight, baseTemperature, layerTemperatureGradient):
return baseDensity * (temperatureAtHeight / baseTemperature)**-(g/(R * layerTemperatureGradient) + 1) | random_line_split |
Atmosphere.py | from scipy import *
from Reference import *
################################################################################
# DATA
################################################################################
# EARTH FACTS
R = 287.058 # ideal gas constant for earth air, in J/kg*K
r = 6356766 # radius of the earth, in m
g = 9.80665 # gravitational acceleration at sea level, in m/s^2
# ATMOSPHERE FACTS
baseHeights = [0, 11000, 25000, 47000, 53000, 79000, 90000, 105000] # (geopotential) heights for the beginning of each layer, in m
baseTemperatures = [288.16, 216.66, 216.66, 282.66, 282.66, 165.66, 165.66, 225.66] # temperature for the beginning of each layer, in K
tempGradients = [-0.0065, 0, 0.003, 0, -0.0045, 0, 0.004, NaN] # temperature gradients for each layer, in K/m (last one represents no information above that height)
basePressures = [101325.0, 22634.008746132295, 2489.1856086672196, 120.49268001877302, 58.347831704016428, 1.0101781258352585, 0.10452732009352216, nan] # in Pa # precalculated
baseDensities = [1.225, 0.3639451299338376, 0.040025034448687088, 0.0014850787413445172, 0.00071914015402165508, 2.124386216253755e-05, 2.1981905205581133e-06, nan] # in kg/m^3 # precalculated
################################################################################
# CALCULATION FUNCTIONS
################################################################################
def layerIndexForheight(h): # get a reference to the place in the lists where the base information is
return baseHeights.index(next(height for height in reversed(baseHeights) if height <= h))
def geopotentialAltitudeForHeight(hg):
return (r * hg) / (r + hg)
def temperatureAtHeight(h):
|
def isothermalLayerPressureAtHeight(h, basePressure, baseHeight, layerTemperature):
return basePressure * exp(-(g * (h - baseHeight) / (R * layerTemperature)))
def isothermalLayerDensityAtHeight(h, baseDensity, basePressure, pressureAtHeight):
return baseDensity * (pressureAtHeight / basePressure)
def gradientLayerPressureAtHeight(h, basePressure, temperatureAtHeight, baseTemperature, layerTemperatureGradient):
return basePressure * (temperatureAtHeight / baseTemperature)**(-(g) / (R * layerTemperatureGradient))
def gradientLayerDensityAtHeight(h, baseDensity, temperatureAtHeight, baseTemperature, layerTemperatureGradient):
return baseDensity * (temperatureAtHeight / baseTemperature)**-(g/(R * layerTemperatureGradient) + 1)
def baseInformation(h):
i = layerIndexForheight(h)
return baseHeights[i], baseTemperatures[i], tempGradients[i], basePressures[i], baseDensities[i]
def informationAtHeight(hg):
"""Takes a Geometric Altitude and Returns the Geometric Altitude, Geopotential
Altitude, Temperature, Pressure and Density at that altitude in that order.
Defined from 0m to 104999m"""
if hg >= 105000 or hg < 0: # if height out of range
raise Exception("Atmosphere values unknown at this altitude ({0}m)".format(hg))
h = geopotentialAltitudeForHeight(hg)
t = temperatureAtHeight(h)
baseHeight, baseTemperature, layerGradient, basePressure, baseDensity = baseInformation(h)
if (layerGradient == 0): # isothermal layer
p = isothermalLayerPressureAtHeight(h, basePressure, baseHeight, baseTemperature)
d = isothermalLayerDensityAtHeight(h, baseDensity, basePressure, p)
else: # gradient layer
p = gradientLayerPressureAtHeight(h, basePressure, t, baseTemperature, layerGradient)
d = gradientLayerDensityAtHeight(h, baseDensity, t, baseTemperature, layerGradient)
return hg, h, t, p, d
################################################################################
# REFERENCE FUNCTIONS
################################################################################
def temperatureAtAltitude(altitude):
return informationAtHeight(altitude)[2]
def pressureAtAltitude(altitude):
return informationAtHeight(altitude)[3]
def densityAtAltitude(altitude):
return informationAtHeight(altitude)[4]
def machAtAltitude(altitude):
return sqrt(airHeatCapacityRatio * airIdealGasConstant * temperatureAtAltitude(altitude))
| i = layerIndexForheight(h)
return baseTemperatures[i] + tempGradients[i] * (h - baseHeights[i]) | identifier_body |
isScrollable.js | const overflowRegex = /(auto|scroll|hidden)/
function needScroll(el, dir) {
let { scrollTop, scrollLeft, scrollHeight, scrollWidth, clientHeight, clientWidth } = el;
switch (dir) {
case "left":
return scrollLeft > 0
break;
case "right":
return scrollLeft + clientWidth < scrollWidth
break;
case "up":
return scrollTop > 0
break;
case "down":
return scrollTop + clientHeight < scrollHeight
break;
}
return false;
}
function | (el) {
let style = el.currentStyle || window.getComputedStyle(el, null);
if (el === document.scrollingElement) {
return true;
}
if (el === document.body) {
return true;
}
if (el === document.documentElement) {
return true;
}
return overflowRegex.test(style.overflow + style.overflowY + style.overflowX);
}
function isScrollable(el, dir) { // dir: left, right, up, down
return canScroll(el) && needScroll(el, dir);
}
export default isScrollable; | canScroll | identifier_name |
isScrollable.js | const overflowRegex = /(auto|scroll|hidden)/
function needScroll(el, dir) {
let { scrollTop, scrollLeft, scrollHeight, scrollWidth, clientHeight, clientWidth } = el;
switch (dir) {
case "left":
return scrollLeft > 0
break;
case "right":
return scrollLeft + clientWidth < scrollWidth
break;
case "up":
return scrollTop > 0
break;
case "down":
return scrollTop + clientHeight < scrollHeight
break;
} | let style = el.currentStyle || window.getComputedStyle(el, null);
if (el === document.scrollingElement) {
return true;
}
if (el === document.body) {
return true;
}
if (el === document.documentElement) {
return true;
}
return overflowRegex.test(style.overflow + style.overflowY + style.overflowX);
}
function isScrollable(el, dir) { // dir: left, right, up, down
return canScroll(el) && needScroll(el, dir);
}
export default isScrollable; | return false;
}
function canScroll(el) { | random_line_split |
isScrollable.js | const overflowRegex = /(auto|scroll|hidden)/
function needScroll(el, dir) {
let { scrollTop, scrollLeft, scrollHeight, scrollWidth, clientHeight, clientWidth } = el;
switch (dir) {
case "left":
return scrollLeft > 0
break;
case "right":
return scrollLeft + clientWidth < scrollWidth
break;
case "up":
return scrollTop > 0
break;
case "down":
return scrollTop + clientHeight < scrollHeight
break;
}
return false;
}
function canScroll(el) {
let style = el.currentStyle || window.getComputedStyle(el, null);
if (el === document.scrollingElement) |
if (el === document.body) {
return true;
}
if (el === document.documentElement) {
return true;
}
return overflowRegex.test(style.overflow + style.overflowY + style.overflowX);
}
function isScrollable(el, dir) { // dir: left, right, up, down
return canScroll(el) && needScroll(el, dir);
}
export default isScrollable; | {
return true;
} | conditional_block |
isScrollable.js | const overflowRegex = /(auto|scroll|hidden)/
function needScroll(el, dir) {
let { scrollTop, scrollLeft, scrollHeight, scrollWidth, clientHeight, clientWidth } = el;
switch (dir) {
case "left":
return scrollLeft > 0
break;
case "right":
return scrollLeft + clientWidth < scrollWidth
break;
case "up":
return scrollTop > 0
break;
case "down":
return scrollTop + clientHeight < scrollHeight
break;
}
return false;
}
function canScroll(el) |
function isScrollable(el, dir) { // dir: left, right, up, down
return canScroll(el) && needScroll(el, dir);
}
export default isScrollable; | {
let style = el.currentStyle || window.getComputedStyle(el, null);
if (el === document.scrollingElement) {
return true;
}
if (el === document.body) {
return true;
}
if (el === document.documentElement) {
return true;
}
return overflowRegex.test(style.overflow + style.overflowY + style.overflowX);
} | identifier_body |
structure.rs | // Copyright 2016 Dario Domizioli
//
// 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.
use rustc_serialize::json;
use std::io::prelude::*;
use std::fs::File;
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
pub struct Chapter {
title: String,
files: Vec<String>
}
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
pub struct Part {
title: String,
chapters: Vec<Chapter>
}
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
pub struct Structure {
title: String,
author: String,
license: String,
parts: Vec<Part>
}
impl Structure {
pub fn from_json(js: &str) -> Result<Structure, json::DecoderError> {
json::decode::<Structure>(js)
} | pub fn get_title(&self) -> &str { &self.title }
}
#[derive(Clone, PartialEq)]
pub struct Content {
pub chunks: Vec<String>
}
impl Content {
fn build_title_page(st: &Structure) -> Result<String, String> {
let book_header =
r#"<div class="book_cover">"#.to_string() +
r#"<div class="book_author">"# +
&st.author +
r#"</div>"# +
r#"<div class="book_title">"# +
r#"<a id="kos_book_title">"# +
&st.title +
"</a></div>" +
r#"<div class="book_license">(C) "# +
&st.author +
" - " +
&st.license +
"</div></div>\n\n";
Ok(book_header)
}
fn build_toc(st: &Structure) -> Result<String, String> {
let mut toc = String::new();
toc = toc + r#"<div class="toc">"# + "\n\n";
let mut part_index = 1;
for part in st.parts.iter() {
let part_link = format!(
"- **[{0} {1}](#kos_ref_part_{0})**\n\n", part_index, part.title);
toc = toc + &part_link;
let mut chap_index = 1;
for chap in part.chapters.iter() {
let chap_link = format!(
" - *[{0}.{1} {2}](#kos_ref_chap_{0}_{1})*\n\n",
part_index, chap_index, chap.title);
toc = toc + &chap_link;
chap_index += 1;
}
part_index += 1;
}
toc = toc + "</div>\n\n";
Ok(toc)
}
fn build_chunks(st: &Structure) -> Result<Vec<String>, String> {
let mut chunks = Vec::new();
// Book cover first...
match Content::build_title_page(st) {
Ok(tp) => { chunks.push(tp); },
Err(e) => { return Err(e); }
}
// Then TOC...
match Content::build_toc(st) {
Ok(toc) => { chunks.push(toc); },
Err(e) => { return Err(e); }
}
// Then parts and chapters.
let mut part_index = 1;
for part in st.parts.iter() {
let part_header =
r#"<div class="part_"#.to_string() + // Open part div
&format!("{}", part_index) +
r#"">"# + "\n\n" +
r#"<div class="part_title">"# + // Part title div
r#"<a id="kos_ref_part_"# +
&format!("{}", part_index) +
r#"">"# +
&part.title +
"</a></div>\n\n"; // Close part title div
chunks.push(part_header);
let mut chap_index = 1;
for chap in part.chapters.iter() {
let chap_header =
r#"# <a id="kos_ref_chap_"#.to_string() +
&format!("{}", part_index) +
"_" +
&format!("{}", chap_index) +
r#""> "# +
&chap.title +
"</a>\n\n";
chunks.push(chap_header);
for f in chap.files.iter() {
let file_content = match File::open(f) {
Ok(mut fread) => {
let mut res = String::new();
match fread.read_to_string(&mut res) {
Ok(_) => (),
Err(_) => {
return Err(
"Error reading file ".to_string() +
f + "!\n");
}
}
res
},
Err(_) => {
return Err(
"Error reading file ".to_string() + f + "!\n");
}
};
chunks.push(file_content);
}
chap_index += 1;
}
chunks.push("\n\n</div>\n\n".to_string()); // Close part div
part_index += 1;
}
Ok(chunks)
}
pub fn from_structure(st: &Structure) -> Result<Content, String> {
let chunks = Content::build_chunks(st);
Ok(Content {
chunks: match chunks {
Ok(c) => c,
Err(e) => { return Err(e); }
}
})
}
pub fn to_single_string(&self) -> String {
self.chunks.iter().fold(String::new(), |acc, x| {
acc + "\n\n" + &x
})
}
} | random_line_split | |
structure.rs | // Copyright 2016 Dario Domizioli
//
// 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.
use rustc_serialize::json;
use std::io::prelude::*;
use std::fs::File;
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
pub struct Chapter {
title: String,
files: Vec<String>
}
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
pub struct Part {
title: String,
chapters: Vec<Chapter>
}
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
pub struct Structure {
title: String,
author: String,
license: String,
parts: Vec<Part>
}
impl Structure {
pub fn from_json(js: &str) -> Result<Structure, json::DecoderError> {
json::decode::<Structure>(js)
}
pub fn get_title(&self) -> &str { &self.title }
}
#[derive(Clone, PartialEq)]
pub struct Content {
pub chunks: Vec<String>
}
impl Content {
fn build_title_page(st: &Structure) -> Result<String, String> |
fn build_toc(st: &Structure) -> Result<String, String> {
let mut toc = String::new();
toc = toc + r#"<div class="toc">"# + "\n\n";
let mut part_index = 1;
for part in st.parts.iter() {
let part_link = format!(
"- **[{0} {1}](#kos_ref_part_{0})**\n\n", part_index, part.title);
toc = toc + &part_link;
let mut chap_index = 1;
for chap in part.chapters.iter() {
let chap_link = format!(
" - *[{0}.{1} {2}](#kos_ref_chap_{0}_{1})*\n\n",
part_index, chap_index, chap.title);
toc = toc + &chap_link;
chap_index += 1;
}
part_index += 1;
}
toc = toc + "</div>\n\n";
Ok(toc)
}
fn build_chunks(st: &Structure) -> Result<Vec<String>, String> {
let mut chunks = Vec::new();
// Book cover first...
match Content::build_title_page(st) {
Ok(tp) => { chunks.push(tp); },
Err(e) => { return Err(e); }
}
// Then TOC...
match Content::build_toc(st) {
Ok(toc) => { chunks.push(toc); },
Err(e) => { return Err(e); }
}
// Then parts and chapters.
let mut part_index = 1;
for part in st.parts.iter() {
let part_header =
r#"<div class="part_"#.to_string() + // Open part div
&format!("{}", part_index) +
r#"">"# + "\n\n" +
r#"<div class="part_title">"# + // Part title div
r#"<a id="kos_ref_part_"# +
&format!("{}", part_index) +
r#"">"# +
&part.title +
"</a></div>\n\n"; // Close part title div
chunks.push(part_header);
let mut chap_index = 1;
for chap in part.chapters.iter() {
let chap_header =
r#"# <a id="kos_ref_chap_"#.to_string() +
&format!("{}", part_index) +
"_" +
&format!("{}", chap_index) +
r#""> "# +
&chap.title +
"</a>\n\n";
chunks.push(chap_header);
for f in chap.files.iter() {
let file_content = match File::open(f) {
Ok(mut fread) => {
let mut res = String::new();
match fread.read_to_string(&mut res) {
Ok(_) => (),
Err(_) => {
return Err(
"Error reading file ".to_string() +
f + "!\n");
}
}
res
},
Err(_) => {
return Err(
"Error reading file ".to_string() + f + "!\n");
}
};
chunks.push(file_content);
}
chap_index += 1;
}
chunks.push("\n\n</div>\n\n".to_string()); // Close part div
part_index += 1;
}
Ok(chunks)
}
pub fn from_structure(st: &Structure) -> Result<Content, String> {
let chunks = Content::build_chunks(st);
Ok(Content {
chunks: match chunks {
Ok(c) => c,
Err(e) => { return Err(e); }
}
})
}
pub fn to_single_string(&self) -> String {
self.chunks.iter().fold(String::new(), |acc, x| {
acc + "\n\n" + &x
})
}
}
| {
let book_header =
r#"<div class="book_cover">"#.to_string() +
r#"<div class="book_author">"# +
&st.author +
r#"</div>"# +
r#"<div class="book_title">"# +
r#"<a id="kos_book_title">"# +
&st.title +
"</a></div>" +
r#"<div class="book_license">(C) "# +
&st.author +
" - " +
&st.license +
"</div></div>\n\n";
Ok(book_header)
} | identifier_body |
structure.rs | // Copyright 2016 Dario Domizioli
//
// 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.
use rustc_serialize::json;
use std::io::prelude::*;
use std::fs::File;
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
pub struct Chapter {
title: String,
files: Vec<String>
}
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
pub struct Part {
title: String,
chapters: Vec<Chapter>
}
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
pub struct | {
title: String,
author: String,
license: String,
parts: Vec<Part>
}
impl Structure {
pub fn from_json(js: &str) -> Result<Structure, json::DecoderError> {
json::decode::<Structure>(js)
}
pub fn get_title(&self) -> &str { &self.title }
}
#[derive(Clone, PartialEq)]
pub struct Content {
pub chunks: Vec<String>
}
impl Content {
fn build_title_page(st: &Structure) -> Result<String, String> {
let book_header =
r#"<div class="book_cover">"#.to_string() +
r#"<div class="book_author">"# +
&st.author +
r#"</div>"# +
r#"<div class="book_title">"# +
r#"<a id="kos_book_title">"# +
&st.title +
"</a></div>" +
r#"<div class="book_license">(C) "# +
&st.author +
" - " +
&st.license +
"</div></div>\n\n";
Ok(book_header)
}
fn build_toc(st: &Structure) -> Result<String, String> {
let mut toc = String::new();
toc = toc + r#"<div class="toc">"# + "\n\n";
let mut part_index = 1;
for part in st.parts.iter() {
let part_link = format!(
"- **[{0} {1}](#kos_ref_part_{0})**\n\n", part_index, part.title);
toc = toc + &part_link;
let mut chap_index = 1;
for chap in part.chapters.iter() {
let chap_link = format!(
" - *[{0}.{1} {2}](#kos_ref_chap_{0}_{1})*\n\n",
part_index, chap_index, chap.title);
toc = toc + &chap_link;
chap_index += 1;
}
part_index += 1;
}
toc = toc + "</div>\n\n";
Ok(toc)
}
fn build_chunks(st: &Structure) -> Result<Vec<String>, String> {
let mut chunks = Vec::new();
// Book cover first...
match Content::build_title_page(st) {
Ok(tp) => { chunks.push(tp); },
Err(e) => { return Err(e); }
}
// Then TOC...
match Content::build_toc(st) {
Ok(toc) => { chunks.push(toc); },
Err(e) => { return Err(e); }
}
// Then parts and chapters.
let mut part_index = 1;
for part in st.parts.iter() {
let part_header =
r#"<div class="part_"#.to_string() + // Open part div
&format!("{}", part_index) +
r#"">"# + "\n\n" +
r#"<div class="part_title">"# + // Part title div
r#"<a id="kos_ref_part_"# +
&format!("{}", part_index) +
r#"">"# +
&part.title +
"</a></div>\n\n"; // Close part title div
chunks.push(part_header);
let mut chap_index = 1;
for chap in part.chapters.iter() {
let chap_header =
r#"# <a id="kos_ref_chap_"#.to_string() +
&format!("{}", part_index) +
"_" +
&format!("{}", chap_index) +
r#""> "# +
&chap.title +
"</a>\n\n";
chunks.push(chap_header);
for f in chap.files.iter() {
let file_content = match File::open(f) {
Ok(mut fread) => {
let mut res = String::new();
match fread.read_to_string(&mut res) {
Ok(_) => (),
Err(_) => {
return Err(
"Error reading file ".to_string() +
f + "!\n");
}
}
res
},
Err(_) => {
return Err(
"Error reading file ".to_string() + f + "!\n");
}
};
chunks.push(file_content);
}
chap_index += 1;
}
chunks.push("\n\n</div>\n\n".to_string()); // Close part div
part_index += 1;
}
Ok(chunks)
}
pub fn from_structure(st: &Structure) -> Result<Content, String> {
let chunks = Content::build_chunks(st);
Ok(Content {
chunks: match chunks {
Ok(c) => c,
Err(e) => { return Err(e); }
}
})
}
pub fn to_single_string(&self) -> String {
self.chunks.iter().fold(String::new(), |acc, x| {
acc + "\n\n" + &x
})
}
}
| Structure | identifier_name |
cgnv6_nat64_fragmentation_df_bit_transparency.py | from a10sdk.common.A10BaseClass import A10BaseClass
class DfBitTransparency(A10BaseClass):
"""Class Description::
Add an empty IPv6 fragmentation header if IPv4 DF bit is zero (default:disabled).
Class df-bit-transparency supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param df_bit_value: {"optional": true, "enum": ["enable"], "type": "string", "description": "'enable': Add an empty IPv6 fragmentation header if IPv4 DF bit is zero; ", "format": "enum"}
:param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
URL for this object::
`https://<Hostname|Ip address>//axapi/v3/cgnv6/nat64/fragmentation/df-bit-transparency`.
"""
def __init__(self, **kwargs):
| self.ERROR_MSG = ""
self.required=[]
self.b_key = "df-bit-transparency"
self.a10_url="/axapi/v3/cgnv6/nat64/fragmentation/df-bit-transparency"
self.DeviceProxy = ""
self.df_bit_value = ""
self.uuid = ""
for keys, value in kwargs.items():
setattr(self,keys, value) | identifier_body | |
cgnv6_nat64_fragmentation_df_bit_transparency.py | from a10sdk.common.A10BaseClass import A10BaseClass
class DfBitTransparency(A10BaseClass):
"""Class Description::
Add an empty IPv6 fragmentation header if IPv4 DF bit is zero (default:disabled).
Class df-bit-transparency supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param df_bit_value: {"optional": true, "enum": ["enable"], "type": "string", "description": "'enable': Add an empty IPv6 fragmentation header if IPv4 DF bit is zero; ", "format": "enum"}
:param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
URL for this object::
`https://<Hostname|Ip address>//axapi/v3/cgnv6/nat64/fragmentation/df-bit-transparency`.
"""
def | (self, **kwargs):
self.ERROR_MSG = ""
self.required=[]
self.b_key = "df-bit-transparency"
self.a10_url="/axapi/v3/cgnv6/nat64/fragmentation/df-bit-transparency"
self.DeviceProxy = ""
self.df_bit_value = ""
self.uuid = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
| __init__ | identifier_name |
cgnv6_nat64_fragmentation_df_bit_transparency.py | from a10sdk.common.A10BaseClass import A10BaseClass
class DfBitTransparency(A10BaseClass):
"""Class Description::
Add an empty IPv6 fragmentation header if IPv4 DF bit is zero (default:disabled).
Class df-bit-transparency supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param df_bit_value: {"optional": true, "enum": ["enable"], "type": "string", "description": "'enable': Add an empty IPv6 fragmentation header if IPv4 DF bit is zero; ", "format": "enum"}
:param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
URL for this object::
`https://<Hostname|Ip address>//axapi/v3/cgnv6/nat64/fragmentation/df-bit-transparency`.
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.required=[]
self.b_key = "df-bit-transparency"
self.a10_url="/axapi/v3/cgnv6/nat64/fragmentation/df-bit-transparency"
self.DeviceProxy = ""
self.df_bit_value = ""
self.uuid = ""
for keys, value in kwargs.items():
| setattr(self,keys, value) | conditional_block | |
cgnv6_nat64_fragmentation_df_bit_transparency.py | from a10sdk.common.A10BaseClass import A10BaseClass
class DfBitTransparency(A10BaseClass):
"""Class Description::
Add an empty IPv6 fragmentation header if IPv4 DF bit is zero (default:disabled).
Class df-bit-transparency supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param df_bit_value: {"optional": true, "enum": ["enable"], "type": "string", "description": "'enable': Add an empty IPv6 fragmentation header if IPv4 DF bit is zero; ", "format": "enum"}
:param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
URL for this object::
`https://<Hostname|Ip address>//axapi/v3/cgnv6/nat64/fragmentation/df-bit-transparency`.
"""
def __init__(self, **kwargs):
self.ERROR_MSG = "" | self.DeviceProxy = ""
self.df_bit_value = ""
self.uuid = ""
for keys, value in kwargs.items():
setattr(self,keys, value) | self.required=[]
self.b_key = "df-bit-transparency"
self.a10_url="/axapi/v3/cgnv6/nat64/fragmentation/df-bit-transparency" | random_line_split |
CXXII.py | #!/usr/bin/env python3
#----------------------------------------------------------------------------
#
# Copyright (C) 2015 José Flávio de Souza Dias Júnior
#
# This file is part of CXXII - http://www.joseflavio.com/cxxii/
#
# CXXII is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# CXXII 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with CXXII. If not, see http://www.gnu.org/licenses/.
#
#----------------------------------------------------------------------------
#
# Direitos Autorais Reservados (C) 2015 José Flávio de Souza Dias Júnior
#
# Este arquivo é parte de CXXII - http://www.joseflavio.com/cxxii/
#
# CXXII é software livre: você pode redistribuí-lo e/ou modificá-lo
# sob os termos da Licença Pública Menos Geral GNU conforme publicada pela
# Free Software Foundation, tanto a versão 3 da Licença, como
# (a seu critério) qualquer versão posterior.
#
# CXXII é distribuído na expectativa de que seja útil,
# porém, SEM NENHUMA GARANTIA; nem mesmo a garantia implícita de
# COMERCIABILIDADE ou ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a
# Licença Pública Menos Geral do GNU para mais detalhes.
#
# Você deve ter recebido uma cópia da Licença Pública Menos Geral do GNU
# junto com CXXII. Se não, veja http://www.gnu.org/licenses/.
#
#----------------------------------------------------------------------------
# "Não vos conformeis com este mundo,
# mas transformai-vos pela renovação do vosso espírito,
# para que possais discernir qual é a vontade de Deus,
# o que é bom, o que lhe agrada e o que é perfeito."
# (Bíblia Sagrada, Romanos 12:2)
# "Do not conform yourselves to this age
# but be transformed by the renewal of your mind,
# that you may discern what is the will of God,
# what is good and pleasing and perfect."
# (Holy Bible, Romans 12:2)
import sys
if sys.version_info[0] < 3:
print('CXXII exige Python 3 ou mais recente.')
sys.exit(1)
import os
import time
import datetime
import unicodedata
import urllib.request
import tempfile
import zipfile
import re
from xml.etree.ElementTree import ElementTree as CXXII_XML_Arvore
#----------------------------------------------------------------------------
class CXXII_XML_Arquivo:
"""Classe que representa um arquivo XML."""
def __init__(self, endereco):
self.endereco = endereco
self.nome = NomeDoArquivo(endereco)
self.arvore = CXXII_XML_Arvore()
self.arvore.parse(endereco)
def raiz(self):
return self.arvore.getroot()
def CXXII_Baixar( url, destino=None, nome=None, forcar=False ):
"""Download de arquivo."""
if url[-1 | global CXXII_XML_Arquivos
CXXII_XML_Arquivos.append( CXXII_XML_Arquivo(endereco) )
def CXXII_Separadores( endereco ):
"""Substitui os separadores "/" pelo separador real do sistema operacional."""
return endereco.replace('/', os.sep)
def CXXII_Python_Formato( arquivo ):
"""Retorna o valor de "# coding=".
arquivo -- Arquivo ou endereço de arquivo. Pode-se utilizar "/" como separador.
"""
if type(arquivo) is str: arquivo = open( CXXII_Separadores(arquivo), 'r', encoding='iso-8859-1' )
formato = 'utf-8'
arquivo.seek(0)
for i in range(2):
linha = arquivo.readline()
if linha.startswith('# coding='):
formato = linha[9:-1]
break
arquivo.close()
return formato
def CXXII_Abrir_Python( endereco ):
"""Abre um arquivo ".py" respeitando a codificação especificada no cabeçalho "# coding=".
endereco -- Endereço do arquivo. Pode-se utilizar "/" como separador.
"""
endereco = CXXII_Separadores(endereco)
return open( endereco, 'r', encoding=CXXII_Python_Formato(endereco) )
def CXXII_Atual( endereco, modo='w', formato='utf-8' ):
"""Determina o arquivo em geração atual.
endereco -- Endereço do arquivo desejado, relativo ao CXXII_Destino. Pode-se utilizar "/" como separador.
"""
global CXXII_Saida
global CXXII_Destino
endereco = CXXII_Separadores(endereco)
if endereco[0] != os.sep: endereco = os.sep + endereco
if CXXII_Saida != None and CXXII_Saida != sys.stdout: CXXII_Saida.close()
arquivo = CXXII_Texto(CXXII_Destino + endereco)
diretorio = CXXII_Texto(os.path.dirname(arquivo))
if not os.path.exists(diretorio): os.makedirs(diretorio)
CXXII_Saida = open( arquivo, modo, encoding=formato )
def CXXII_Escrever( texto ):
"""Escreve no arquivo em geração atual. Ver CXXII_Atual()."""
global CXXII_Saida
if not CXXII_Saida is None:
CXXII_Saida.write(texto)
def CXXII_ContarIdentacao( linha ):
comprimento = len(linha)
if comprimento == 0: return 0
tamanho = comprimento - len(linha.lstrip())
if linha[0] == ' ': tamanho /= 4
return tamanho
def CXXII_Identar( linha, total=1 ):
espaco = '\t' if len(linha) > 0 and linha[0] == '\t' else ' '
while total > 0:
linha = espaco + linha
total -= 1
return linha
def CXXII_EscreverArquivo( endereco, inicio=1, fim=None, quebraFinal=True, formato='utf-8', dicGlobal=None, dicLocal=None ):
"""Escreve no arquivo em geração atual (CXXII_Atual()) o conteúdo de um arquivo-modelo.
Arquivo-modelo é qualquer conteúdo que contenha instruções CXXII embutidas.
Se o endereço do arquivo for relativo, ele primeiro será buscado em CXXII_Gerador_Diretorio.
endereco -- Endereço do arquivo-modelo. Pode-se utilizar "/" como separador.
inicio -- Número inicial do intervalo de linhas desejado. Padrão: 1
fim -- Número final do intervalo de linhas desejado. Padrão: None (última linha)
quebraFinal -- Quebra de linha na última linha?
dicGlobal -- Ver globals()
dicLocal -- Ver locals()
"""
global CXXII_Saida
if CXXII_Saida is None: return
if dicGlobal is None: dicGlobal = globals()
if dicLocal is None: dicLocal = locals()
endereco = CXXII_Separadores(endereco)
if endereco[0] != os.sep and os.path.exists(CXXII_Gerador_Diretorio + os.sep + endereco):
endereco = CXXII_Gerador_Diretorio + os.sep + endereco
codigo = []
modelo = open( endereco, 'r', encoding=formato )
linhas = list(modelo)
modelo.close()
total = len(linhas)
if inicio != 1 or fim != None:
inicio = inicio - 1 if inicio != None else 0
fim = fim if fim != None else total
linhas = linhas[inicio:fim]
if not quebraFinal and linhas[-1][-1] == '\n': linhas[-1] = linhas[-1][0:-1]
total = len(linhas)
identacao = 0
i = 0
while i < total:
linha = linhas[i]
if linha == '@@@\n':
i += 1
if i < total and identacao > 0 and linhas[i] == '@@@\n':
identacao -= 1
else:
while i < total and linhas[i] != '@@@\n':
linha = linhas[i]
identacao = CXXII_ContarIdentacao(linha)
codigo.append(linha)
linha = linha.strip()
if len(linha) > 0 and linha[-1] == ':':
if linha.startswith('for ') or linha.startswith('while '):
identacao += 1
i += 1
else:
codigo.append(CXXII_Identar('"""~\n', identacao))
finalComQuebra = False
while i < total and linhas[i] != '@@@\n':
linha = linhas[i]
finalComQuebra = linha.endswith('\n')
if not finalComQuebra: linha += '\n'
codigo.append(linha)
i += 1
if finalComQuebra: codigo.append('\n')
codigo.append(CXXII_Identar('"""\n', identacao))
i -= 1
i += 1
CXXII_Executar( CXXII_CompilarPython(codigo), dicGlobal, dicLocal )
def CXXII_Texto( texto, decodificar=False ):
if decodificar and type(texto) is bytes: texto = texto.decode(sys.getfilesystemencoding())
return unicodedata.normalize('NFC', texto)
def CXXII_EscapeParaTexto( texto ):
return texto.replace('\n','\\n').replace('\r','\\r').replace('\t','\\t').replace('\'','\\\'')
def CXXII_TextoParaEscape( texto ):
return texto.replace('\\n','\n').replace('\\r','\r').replace('\\t','\t').replace('\\\'','\'')
def NomeDoArquivo( endereco, extensao=True ):
if endereco[-1] == os.sep: endereco = endereco[0:-1]
nome = endereco[endereco.rfind(os.sep)+1:]
if not extensao:
nome = nome[0:len(nome)-nome.rfind('.')]
return nome
def CXXII_Compilar( endereco ):
"""Compila um arquivo codificado com a linguagem Python.
Se o endereço do arquivo for relativo, ele primeiro será buscado em CXXII_Gerador_Diretorio.
endereco -- Endereço do arquivo ".py". Pode-se utilizar "/" como separador.
"""
endereco = CXXII_Separadores(endereco)
if endereco[0] != os.sep and os.path.exists(CXXII_Gerador_Diretorio + os.sep + endereco):
endereco = CXXII_Gerador_Diretorio + os.sep + endereco
py_arquivo = CXXII_Abrir_Python(endereco)
py = list(py_arquivo)
py_arquivo.close()
return CXXII_CompilarPython(py)
def CXXII_CompilarPython( codigoFonte ):
"""Compila um código fonte codificado com a linguagem Python."""
py = list(codigoFonte) if type(codigoFonte) != list else codigoFonte
if py[0].startswith('# coding='):
py = py[1:]
elif py[1].startswith('# coding='):
py = py[2:]
py[-1] += '\n'
i = 0
total = len(py)
embutido = re.compile('({{{[^{}]*}}})')
while i < total:
linha = py[i]
passo = 1
if linha.endswith('"""~\n'):
desconsiderar = False
tokenstr = None
cpre = None
for c in linha:
if tokenstr != None:
if c == tokenstr and cpre != '\\': tokenstr = None
elif c == '#':
desconsiderar = True
break
elif c == '\'' or c == '\"':
tokenstr = c
cpre = c
if desconsiderar:
i += passo
continue
linha = linha[:-5] + 'CXXII_Escrever(\''
a = i
b = a + 1
while b < total and not py[b].lstrip().startswith('"""'): b += 1
if b >= total: raise Exception('Bloco de escrita não finalizado: linha ' + str(i))
py[b] = py[b][py[b].index('"""')+3:]
passo = b - a
if (b-a) > 1:
primeiro = True
a += 1
while a < b:
linha += ( '\\n' if not primeiro else '' ) + CXXII_EscapeParaTexto( py[a][:-1] )
py[a] = ''
primeiro = False
a += 1
linhapos = 0
while True:
codigo = embutido.search(linha, linhapos)
if not codigo is None:
parte1 = \
linha[0:codigo.start(0)] +\
'\'+' +\
CXXII_TextoParaEscape(codigo.group(0)[3:-3]) +\
'+\''
parte2 = linha[codigo.end(0):]
linha = parte1 + parte2
linhapos = len(parte1)
else:
break
linha += '\');'
py[i] = linha
i += passo
return compile( ''.join(py), 'CXXII_Python', 'exec' )
def CXXII_Executar( python, dicGlobal=None, dicLocal=None ):
"""Executa um código Python pré-compilado com CXXII_Compilar() ou um arquivo Python.
Se o endereço do arquivo for relativo, ele primeiro será buscado em CXXII_Gerador_Diretorio.
python -- Código pré-compilado ou endereço do arquivo. Pode-se utilizar "/" como separador.
dicGlobal -- Ver globals()
dicLocal -- Ver locals()
"""
if dicGlobal is None: dicGlobal = globals()
if dicLocal is None: dicLocal = locals()
exec( CXXII_Compilar(python) if type(python) is str else python, dicGlobal, dicLocal )
#----------------------------------------------------------------------------
CXXII_Repositorio = 'http://www.joseflavio.com/cxxii/'
CXXII_Inicio = datetime.datetime.today()
CXXII_Gerador_Endereco = None
CXXII_Gerador_Diretorio = None
CXXII_Gerador_TempoMaximo = 6*60*60 #6h
CXXII_Gerador_Baixar = False
CXXII_Destino = None
CXXII_XML_Arquivos = []
CXXII_Extensao = 'xml'
CXXII_Saida = sys.stdout
CXXII_Diretorio = CXXII_Texto(os.path.expanduser('~')) + os.sep + 'CXXII'
CXXII_Geradores = CXXII_Diretorio + os.sep + 'Geradores'
if not os.path.exists(CXXII_Geradores): os.makedirs(CXXII_Geradores)
#----------------------------------------------------------------------------
try:
#----------------------------------------------------------------------------
argumentos = CXXII_Texto(' '.join(sys.argv), True)
argumentos = argumentos.replace(' -g', '###g')
argumentos = argumentos.replace(' -f', '###fSIM')
argumentos = argumentos.replace(' -t', '###tSIM')
argumentos = argumentos.replace(' -d', '###d')
argumentos = argumentos.replace(' -e', '###e')
argumentos = argumentos.replace(' -a', '###a')
argumentos = argumentos.split('###')
argumento_g = None
argumento_f = None
argumento_t = None
argumento_d = None
argumento_e = None
argumento_a = None
for argumento in argumentos[1:]:
valor = argumento[1:].strip()
if len(valor) == 0: continue
exec( 'argumento_' + argumento[0] + '=\'' + valor + '\'' )
if argumento_g is None or argumento_a is None:
print('\nCXXII 1.0-A1 : Gerador de arquivos a partir de XML\n')
print('cxxii -g GERADOR [-f] [-t] [-d DESTINO] [-e EXTENSAO] -a ARQUIVOS\n')
print('Argumentos:')
print(' -g URL ou endereço local do gerador a utilizar: .py ou .zip')
print(' Nome sem extensão = ' + CXXII_Repositorio + 'Nome.zip')
print(' -f Forçar download do gerador')
print(' -t Imprimir detalhes do erro que possa ocorrer')
print(' -d Destino dos arquivos gerados')
print(' -e Extensão padrão dos arquivos de entrada: xml')
print(' -a Arquivos XML de entrada ou diretórios que os contenham\n')
sys.exit(1)
#----------------------------------------------------------------------------
if argumento_e != None: CXXII_Extensao = argumento_e.lower()
argumento_a = argumento_a.replace('.' + CXXII_Extensao, '.' + CXXII_Extensao + '###')
argumento_a = argumento_a.split('###')
for xml in argumento_a:
xml = xml.strip()
if len(xml) == 0: continue
xml = CXXII_Texto(os.path.abspath(xml))
if os.path.isdir(xml):
for arquivo in os.listdir(xml):
arquivo = CXXII_Texto(arquivo)
if arquivo.lower().endswith('.' + CXXII_Extensao):
CXXII_XML_Adicionar(xml + os.sep + arquivo)
else:
CXXII_XML_Adicionar(xml)
if len(CXXII_XML_Arquivos) == 0:
sys.exit(0)
#----------------------------------------------------------------------------
try:
CXXII_Gerador_Baixar = not argumento_f is None
gerurl = argumento_g.startswith('http://')
if( gerurl and argumento_g[-1] == '/' ): argumento_g = argumento_g[0:-1]
gernome = argumento_g[argumento_g.rfind('/' if gerurl else os.sep)+1:]
gerpy = gernome.endswith('.py')
gerzip = gernome.endswith('.zip')
if gerurl:
argumento_g = CXXII_Baixar(url=argumento_g, destino=CXXII_Geradores, forcar=CXXII_Gerador_Baixar)
elif gerpy or gerzip:
argumento_g = CXXII_Texto(os.path.abspath(argumento_g))
else:
gerurl = True
gernome += '.zip'
gerzip = True
argumento_g = CXXII_Baixar(url=CXXII_Repositorio + gernome, destino=CXXII_Geradores, forcar=CXXII_Gerador_Baixar)
if gerzip:
destino = argumento_g[0:-4]
if not os.path.exists(destino): os.makedirs(destino)
CXXII_Gerador_Endereco = destino + os.sep + gernome[0:-4] + '.py'
descompactar = not os.path.exists(CXXII_Gerador_Endereco)
if not descompactar:
descompactar = os.path.getmtime(argumento_g) > os.path.getmtime(CXXII_Gerador_Endereco)
if descompactar:
zip = zipfile.ZipFile(argumento_g, 'r')
zip.extractall(destino)
del zip
else:
CXXII_Gerador_Endereco = argumento_g
CXXII_Gerador_Diretorio = CXXII_Texto(os.path.dirname(CXXII_Gerador_Endereco))
except:
raise Exception('Gerador inválido.')
#----------------------------------------------------------------------------
CXXII_Destino = argumento_d if not argumento_d is None else 'CXXII_' + CXXII_Inicio.strftime('%Y%m%d%H%M%S')
CXXII_Destino = CXXII_Texto(os.path.abspath(CXXII_Destino))
if not os.path.exists(CXXII_Destino): os.makedirs(CXXII_Destino)
#----------------------------------------------------------------------------
gerador_nome = ''
gerador_versao = ''
gerador_multiplo = True
cxxii_con = CXXII_Abrir_Python(CXXII_Gerador_Endereco)
cxxii_lin = list(cxxii_con)
cxxii_ini = 0
cxxii_tot = len(cxxii_lin)
while cxxii_ini < cxxii_tot and cxxii_lin[cxxii_ini] != '### CXXII\n': cxxii_ini += 1
if cxxii_ini < cxxii_tot:
fim = cxxii_ini + 1
while fim < cxxii_tot and cxxii_lin[fim] != '###\n': fim += 1
if fim < cxxii_tot: exec(''.join(cxxii_lin[(cxxii_ini+1):fim]))
cxxii_con.close()
del cxxii_con
del cxxii_lin
del cxxii_ini
del cxxii_tot
gerador_nome = gerador_nome if gerador_nome != None and len(gerador_nome) > 0 else NomeDoArquivo(argumento_g)
if gerador_versao == None: gerador_versao = 'Desconhecida'
if not type(gerador_versao) is str: gerador_versao = str(gerador_versao)
print( 'Gerador: ' + gerador_nome )
print( 'Versão: ' + gerador_versao )
#----------------------------------------------------------------------------
CXXII_Gerador_Compilado = CXXII_Compilar( CXXII_Gerador_Endereco )
CXXII_XML = CXXII_XML_Arquivos[0]
if gerador_multiplo:
for xml in CXXII_XML_Arquivos:
print(xml.endereco)
CXXII_XML = xml
CXXII_Executar( CXXII_Gerador_Compilado, globals(), locals() )
else:
CXXII_Executar( CXXII_Gerador_Compilado, globals(), locals() )
#----------------------------------------------------------------------------
except Exception as e:
if not argumento_t is None:
import traceback
traceback.print_exc()
print('Erro: ' + str(e))
#---------------------------------------------------------------------------- | ] == '/' : url = url[0:-1]
if destino is None :
global CXXII_Diretorio
destino = CXXII_Diretorio
if destino[-1] == os.sep : destino = destino[0:-1]
if nome is None : nome = url.replace('/', '_').replace(':', '_')
endereco = destino + os.sep + nome
existe = os.path.exists(endereco)
baixar = forcar or not existe
if not baixar:
global CXXII_Gerador_TempoMaximo
baixar = ( time.time() - os.path.getmtime(endereco) ) > CXXII_Gerador_TempoMaximo
if baixar:
try:
urllib.request.urlretrieve(url, endereco)
except:
raise Exception('Não foi possível baixar o gerador.')
return endereco
def CXXII_XML_Adicionar( endereco ):
| identifier_body |
CXXII.py | #!/usr/bin/env python3
#----------------------------------------------------------------------------
#
# Copyright (C) 2015 José Flávio de Souza Dias Júnior
#
# This file is part of CXXII - http://www.joseflavio.com/cxxii/
#
# CXXII is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# CXXII 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with CXXII. If not, see http://www.gnu.org/licenses/.
#
#----------------------------------------------------------------------------
#
# Direitos Autorais Reservados (C) 2015 José Flávio de Souza Dias Júnior
#
# Este arquivo é parte de CXXII - http://www.joseflavio.com/cxxii/
#
# CXXII é software livre: você pode redistribuí-lo e/ou modificá-lo
# sob os termos da Licença Pública Menos Geral GNU conforme publicada pela
# Free Software Foundation, tanto a versão 3 da Licença, como
# (a seu critério) qualquer versão posterior.
#
# CXXII é distribuído na expectativa de que seja útil,
# porém, SEM NENHUMA GARANTIA; nem mesmo a garantia implícita de
# COMERCIABILIDADE ou ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a
# Licença Pública Menos Geral do GNU para mais detalhes.
#
# Você deve ter recebido uma cópia da Licença Pública Menos Geral do GNU
# junto com CXXII. Se não, veja http://www.gnu.org/licenses/.
#
#----------------------------------------------------------------------------
# "Não vos conformeis com este mundo,
# mas transformai-vos pela renovação do vosso espírito,
# para que possais discernir qual é a vontade de Deus,
# o que é bom, o que lhe agrada e o que é perfeito."
# (Bíblia Sagrada, Romanos 12:2)
# "Do not conform yourselves to this age
# but be transformed by the renewal of your mind,
# that you may discern what is the will of God,
# what is good and pleasing and perfect."
# (Holy Bible, Romans 12:2)
import sys
if sys.version_info[0] < 3:
print('CXXII exige Python 3 ou mais recente.')
sys.exit(1)
import os
import time
import datetime
import unicodedata
import urllib.request
import tempfile
import zipfile
import re
from xml.etree.ElementTree import ElementTree as CXXII_XML_Arvore
#----------------------------------------------------------------------------
class CXXII_XML_Arquivo:
"""Classe que representa um arquivo XML."""
def __init__(self, endereco):
self.endereco = endereco
self.nome = NomeDoArquivo(endereco)
self.arvore = CXXII_XML_Arvore()
self.arvore.parse(endereco)
def raiz(self):
return self.arvore.getroot()
def CXXII_Baixar( url, destino=None, nome=None, forcar=False ):
"""Download de arquivo."""
if url[-1] == '/' : url = url[0:-1]
if destino is None :
global CXXII_Diretorio
destino = CXXII_Diretorio
if destino[-1] == os.sep : destino = destino[0:-1]
if nome is None : nome = url.replace('/', '_').replace(':', '_')
endereco = destino + os.sep + nome
existe = os.path.exists(endereco)
baixar = forcar or not existe
if not baixar:
global CXXII_Gerador_TempoMaximo
baixar = ( time.time() - os.path.getmtime(endereco) ) > CXXII_Gerador_TempoMaximo
if baixar:
try:
urllib.request.urlretrieve(url, endereco)
except:
raise Exception('Não foi possível baixar o gerador.')
return endereco
def CXXII_XML_Adicionar( endereco ):
global CXXII_XML_Arquivos
CXXII_XML_Arquivos.append( CXXII_XML_Arquivo(endereco) )
def CXXII_Separadores( endereco ):
"""Substitui os separadores "/" pelo separador real do sistema operacional."""
return endereco.replace('/', os.sep)
def CXXII_Python_Formato( arquivo ):
"""Retorna o valor de "# coding=".
arquivo -- Arquivo ou endereço de arquivo. Pode-se utilizar "/" como separador.
"""
if type(arquivo) is str: arquivo = open( CXXII_Separadores(arquivo), 'r', encoding='iso-8859-1' )
formato = 'utf-8'
arquivo.seek(0)
for i in range(2):
linha = arquivo.readline()
if linha.startswith('# coding='):
formato = linha[9:-1]
break
arquivo.close()
return formato
def CXXII_Abrir_Python( endereco ):
"""Abre um arquivo ".py" respeitando a codificação especificada no cabeçalho "# coding=".
endereco -- Endereço do arquivo. Pode-se utilizar "/" como separador.
"""
endereco = CXXII_Separadores(endereco)
return open( endereco, 'r', encoding=CXXII_Python_Formato(endereco) )
def CXXII_Atual( endereco, modo='w', formato='utf-8' ):
"""Determina o arquivo em geração atual.
endereco -- Endereço do arquivo desejado, relativo ao CXXII_Destino. Pode-se utilizar "/" como separador.
"""
global CXXII_Saida
global CXXII_Destino
endereco = CXXII_Separadores(endereco)
if endereco[0] != os.sep: endereco = os.sep + endereco
if CXXII_Saida != None and CXXII_Saida != sys.stdout: CXXII_Saida.close()
arquivo = CXXII_Texto(CXXII_Destino + endereco)
diretorio = CXXII_Texto(os.path.dirname(arquivo))
if not os.path.exists(diretorio): os.makedirs(diretorio)
CXXII_Saida = open( arquivo, modo, encoding=formato )
def CXXII_Escrever( texto ):
"""Escreve no arquivo em geração atual. Ver CXXII_Atual()."""
global CXXII_Saida
if not CXXII_Saida is None:
CXXII_Saida.write(texto)
def CXXII_ContarIdentacao( linha ):
comprimento = len(linha)
if comprimento == 0: return 0
tamanho = comprimento - len(linha.lstrip())
if linha[0] == ' ': tamanho /= 4
return tamanho
def CXXII_Identar( linha, total=1 ):
espaco = '\t' if len(linha) > 0 and linha[0] == '\t' else ' '
while total > 0:
linha = espaco + linha
total -= 1
return linha
def CXXII_EscreverArquivo( endereco, inicio=1, fim=None, quebraFinal=True, formato='utf-8', dicGlobal=None, dicLocal=None ):
"""Escreve no arquivo em geração atual (CXXII_Atual()) o conteúdo de um arquivo-modelo.
Arquivo-modelo é qualquer conteúdo que contenha instruções CXXII embutidas.
Se o endereço do arquivo for relativo, ele primeiro será buscado em CXXII_Gerador_Diretorio.
endereco -- Endereço do arquivo-modelo. Pode-se utilizar "/" como separador.
inicio -- Número inicial do intervalo de linhas desejado. Padrão: 1
fim -- Número final do intervalo de linhas desejado. Padrão: None (última linha)
quebraFinal -- Quebra de linha na última linha?
dicGlobal -- Ver globals()
dicLocal -- Ver locals()
"""
global CXXII_Saida
if CXXII_Saida is None: return
if dicGlobal is None: dicGlobal = globals()
if dicLocal is None: dicLocal = locals()
endereco = CXXII_Separadores(endereco)
if endereco[0] != os.sep and os.path.exists(CXXII_Gerador_Diretorio + os.sep + endereco):
endereco = CXXII_Gerador_Diretorio + os.sep + endereco
codigo = []
modelo = open( endereco, 'r', encoding=formato )
linhas = list(modelo)
modelo.close()
total = len(linhas)
if inicio != 1 or fim != None:
inicio = inicio - 1 if inicio != None else 0
fim = fim if fim != None else total
linhas = linhas[inicio:fim]
if not quebraFinal and linhas[-1][-1] == '\n': linhas[-1] = linhas[-1][0:-1]
total = len(linhas)
identacao = 0
i = 0
while i < total:
linha = linhas[i]
if linha == '@@@\n':
i += 1
if i < total and identacao > 0 and linhas[i] == '@@@\n':
identacao -= 1
else:
while i < total and linhas[i] != '@@@\n':
linha = linhas[i]
identacao = CXXII_ContarIdentacao(linha)
codigo.append(linha)
linha = linha.strip()
if len(linha) > 0 and linha[-1] == ':':
if linha.startswith('for ') or linha.startswith('while '):
identacao += 1
i += 1
else:
codigo.append(CXXII_Identar('"""~\n', identacao))
finalComQuebra = False
while i < total and linhas[i] != '@@@\n':
linha = linhas[i]
finalComQuebra = linha.endswith('\n')
if not finalComQuebra: linha += '\n'
codigo.append(linha)
i += 1
if finalComQuebra: codigo.append('\n')
codigo.append(CXXII_Identar('"""\n', identacao))
i -= 1
i += 1
CXXII_Executar( CXXII_CompilarPython(codigo), dicGlobal, dicLocal )
def CXXII_Texto( texto, decodificar=False ):
if decodificar and type(texto) is bytes: texto = texto.decode(sys.getfilesystemencoding())
return unicodedata.normalize('NFC', texto)
def CXXII_EscapeParaTexto( texto ):
return texto.replace('\n','\\n').replace('\r','\\r').replace('\t','\\t').replace('\'','\\\'')
def CXXII_TextoParaEscape( texto ):
return texto.replace('\\n','\n').replace('\\r','\r').replace('\\t','\t').replace('\\\'','\'')
def NomeDoArquivo( endereco, extensao=True ):
if endereco[-1] == os.sep: endereco = endereco[0:-1]
nome = endereco[endereco.rfind(os.sep)+1:]
if not extensao:
nome = nome[0:len(nome)-nome.rfind('.')]
return nome
def CXXII_Compilar( endereco ):
"""Compila um arquivo codificado com a linguagem Python.
Se o endereço do arquivo for relativo, ele primeiro será buscado em CXXII_Gerador_Diretorio.
endereco -- Endereço do arquivo ".py". Pode-se utilizar "/" como separador.
"""
endereco = CXXII_Separadores(endereco)
if endereco[0] != os.sep and os.path.exists(CXXII_Gerador_Diretorio + os.sep + endereco):
endereco = CXXII_Gerador_Diretorio + os.sep + endereco
py_arquivo = CXXII_Abrir_Python(endereco)
py = list(py_arquivo)
py_arquivo.close()
return CXXII_CompilarPython(py)
def CXXII_CompilarPython( codigoFonte ):
"""Compila um código fonte codificado com a linguagem Python."""
py = list(codigoFonte) if type(codigoFonte) != list else codigoFonte
if py[0].startswith('# coding='):
py = py[1:]
elif py[1].startswith('# coding='):
py = py[2:]
py[-1] += '\n'
i = 0
total = len(py)
embutido = re.compile('({{{[^{}]*}}})')
while i < total:
linha = py[i]
passo = 1
if linha.endswith('"""~\n'):
desconsiderar = False
tokenstr = None
cpre = None
for c in linha:
if tokenstr != None:
if c == tokenstr and cpre != '\\': tokenstr = None
elif c == '#':
desconsiderar = True
break
elif c == '\'' or c == '\"':
tokenstr = c
cpre = c
if desconsiderar:
i += passo
continue
linha = linha[:-5] + 'CXXII_Escrever(\''
a = i
b = a + 1
while b < total and not py[b].lstrip().startswith('"""'): b += 1
if b >= total: raise Exception('Bloco de escrita não finalizado: linha ' + str(i))
py[b] = py[b][py[b].index('"""')+3:]
passo = b - a
if (b-a) > 1:
primeiro = True
a += 1
while a < b:
linha += ( '\\n' if not primeiro else '' ) + CXXII_EscapeParaTexto( py[a][:-1] )
py[a] = ''
primeiro = False
a += 1
linhapos = 0
while True:
codigo = embutido.search(linha, linhapos)
if not codigo is None:
parte1 = \
linha[0:codigo.start(0)] +\
'\'+' +\
CXXII_TextoParaEscape(codigo.group(0)[3:-3]) +\
'+\''
parte2 = linha[codigo.end(0):]
linha = parte1 + parte2
linhapos = len(parte1)
else:
break
linha += '\');'
py[i] = linha
i += passo
return compile( ''.join(py), 'CXXII_Python', 'exec' )
def CXXII_Executar( python, dicGlobal=None, dicLocal=None ):
"""Executa um código Python pré-compilado com CXXII_Compilar() ou um arquivo Python.
Se o endereço do arquivo for relativo, ele primeiro será buscado em CXXII_Gerador_Diretorio.
python -- Código pré-compilado ou endereço do arquivo. Pode-se utilizar "/" como separador.
dicGlobal -- Ver globals()
dicLocal -- Ver locals()
"""
if dicGlobal is None: dicGlobal = globals()
if dicLocal is None: dicLocal = locals()
exec( CXXII_Compilar(python) if type(python) is str else python, dicGlobal, dicLocal )
#----------------------------------------------------------------------------
CXXII_Repositorio = 'http://www.joseflavio.com/cxxii/'
CXXII_Inicio = datetime.datetime.today()
CXXII_Gerador_Endereco = None
CXXII_Gerador_Diretorio = None
CXXII_Gerador_TempoMaximo = 6*60*60 #6h
CXXII_Gerador_Baixar = False
CXXII_Destino = None
CXXII_XML_Arquivos = []
CXXII_Extensao = 'xml'
CXXII_Saida = sys.stdout
CXXII_Diretorio = CXXII_Texto(os.path.expanduser('~')) + os.sep + 'CXXII'
CXXII_Geradores = CXXII_Diretorio + os.sep + 'Geradores'
if not os.path.exists(CXXII_Geradores): os.makedirs(CXXII_Geradores)
#----------------------------------------------------------------------------
try:
#----------------------------------------------------------------------------
argumentos = CXXII_Texto(' '.join(sys.argv), True)
argumentos = argumentos.replace(' -g', '###g')
argumentos = argumentos.replace(' -f', '###fSIM')
argumentos = argumentos.replace(' -t', '###tSIM')
argumentos = argumentos.replace(' -d', '###d')
argumentos = argumentos.replace(' -e', '###e')
argumentos = argumentos.replace(' -a', '###a')
argumentos = argumentos.split('###')
argumento_g = None
argumento_f = None
argumento_t = None
argumento_d = None
argumento_e = None
argumento_a = None
for argumento in argumentos[1:]:
valor = argumento[1:].strip()
if len(valor) == 0: continue
exec( 'argumento_' + argumento[0] + '=\'' + valor + '\'' )
if argumento_g is None or argumento_a is None:
print('\nCXXII 1.0-A1 : Gerador de arquivos a partir de XML\n')
print('cxxii -g GERADOR [-f] [-t] [-d DESTINO] [-e EXTENSAO] -a ARQUIVOS\n')
print('Argumentos:')
print(' -g URL ou endereço local do gerador a utilizar: .py ou .zip')
print(' Nome sem extensão = ' + CXXII_Repositorio + 'Nome.zip')
print(' -f Forçar download do gerador')
print(' -t Imprimir detalhes do erro que possa ocorrer')
print(' -d Destino dos arquivos gerados')
print(' -e Extensão padrão dos arquivos de entrada: xml')
print(' -a Arquivos XML de entrada ou diretórios que os contenham\n')
sys.exit(1)
#----------------------------------------------------------------------------
if argumento_e != None: CXXII_Extensao = argumento_e.lower()
argumento_a = argumento_a.replace('.' + CXXII_Extensao, '.' + CXXII_Extensao + '###')
argumento_a = argumento_a.split('###')
for xml in argumento_a:
xml = xml.strip()
if len(xml) == 0: continue
xml = CXXII_Texto(os.path.abspath(xml))
if os.path.isdir(xml):
for arquivo in os.listdir(xml):
arquivo = CXXII_Texto(arquivo)
if arquivo.lower().endswith('.' + CXXII_Extensao):
CXXII_XML_Adicionar(xml + os.sep + arquivo)
else:
CXXII_XML_Adicionar(xml)
if len(CXXII_XML_Arquivos) == 0:
sys.exit(0)
#----------------------------------------------------------------------------
try:
CXXII_Gerador_Baixar = not argumento_f is None
gerurl = argumento_g.startswith('http://')
if( gerurl and argumento_g[-1] == '/' ): argumento_g = argumento_g[0:-1]
gernome = argumento_g[argumento_g.rfind('/' if gerurl else os.sep)+1:] | elif gerpy or gerzip:
argumento_g = CXXII_Texto(os.path.abspath(argumento_g))
else:
gerurl = True
gernome += '.zip'
gerzip = True
argumento_g = CXXII_Baixar(url=CXXII_Repositorio + gernome, destino=CXXII_Geradores, forcar=CXXII_Gerador_Baixar)
if gerzip:
destino = argumento_g[0:-4]
if not os.path.exists(destino): os.makedirs(destino)
CXXII_Gerador_Endereco = destino + os.sep + gernome[0:-4] + '.py'
descompactar = not os.path.exists(CXXII_Gerador_Endereco)
if not descompactar:
descompactar = os.path.getmtime(argumento_g) > os.path.getmtime(CXXII_Gerador_Endereco)
if descompactar:
zip = zipfile.ZipFile(argumento_g, 'r')
zip.extractall(destino)
del zip
else:
CXXII_Gerador_Endereco = argumento_g
CXXII_Gerador_Diretorio = CXXII_Texto(os.path.dirname(CXXII_Gerador_Endereco))
except:
raise Exception('Gerador inválido.')
#----------------------------------------------------------------------------
CXXII_Destino = argumento_d if not argumento_d is None else 'CXXII_' + CXXII_Inicio.strftime('%Y%m%d%H%M%S')
CXXII_Destino = CXXII_Texto(os.path.abspath(CXXII_Destino))
if not os.path.exists(CXXII_Destino): os.makedirs(CXXII_Destino)
#----------------------------------------------------------------------------
gerador_nome = ''
gerador_versao = ''
gerador_multiplo = True
cxxii_con = CXXII_Abrir_Python(CXXII_Gerador_Endereco)
cxxii_lin = list(cxxii_con)
cxxii_ini = 0
cxxii_tot = len(cxxii_lin)
while cxxii_ini < cxxii_tot and cxxii_lin[cxxii_ini] != '### CXXII\n': cxxii_ini += 1
if cxxii_ini < cxxii_tot:
fim = cxxii_ini + 1
while fim < cxxii_tot and cxxii_lin[fim] != '###\n': fim += 1
if fim < cxxii_tot: exec(''.join(cxxii_lin[(cxxii_ini+1):fim]))
cxxii_con.close()
del cxxii_con
del cxxii_lin
del cxxii_ini
del cxxii_tot
gerador_nome = gerador_nome if gerador_nome != None and len(gerador_nome) > 0 else NomeDoArquivo(argumento_g)
if gerador_versao == None: gerador_versao = 'Desconhecida'
if not type(gerador_versao) is str: gerador_versao = str(gerador_versao)
print( 'Gerador: ' + gerador_nome )
print( 'Versão: ' + gerador_versao )
#----------------------------------------------------------------------------
CXXII_Gerador_Compilado = CXXII_Compilar( CXXII_Gerador_Endereco )
CXXII_XML = CXXII_XML_Arquivos[0]
if gerador_multiplo:
for xml in CXXII_XML_Arquivos:
print(xml.endereco)
CXXII_XML = xml
CXXII_Executar( CXXII_Gerador_Compilado, globals(), locals() )
else:
CXXII_Executar( CXXII_Gerador_Compilado, globals(), locals() )
#----------------------------------------------------------------------------
except Exception as e:
if not argumento_t is None:
import traceback
traceback.print_exc()
print('Erro: ' + str(e))
#---------------------------------------------------------------------------- | gerpy = gernome.endswith('.py')
gerzip = gernome.endswith('.zip')
if gerurl:
argumento_g = CXXII_Baixar(url=argumento_g, destino=CXXII_Geradores, forcar=CXXII_Gerador_Baixar) | random_line_split |
CXXII.py | #!/usr/bin/env python3
#----------------------------------------------------------------------------
#
# Copyright (C) 2015 José Flávio de Souza Dias Júnior
#
# This file is part of CXXII - http://www.joseflavio.com/cxxii/
#
# CXXII is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# CXXII 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with CXXII. If not, see http://www.gnu.org/licenses/.
#
#----------------------------------------------------------------------------
#
# Direitos Autorais Reservados (C) 2015 José Flávio de Souza Dias Júnior
#
# Este arquivo é parte de CXXII - http://www.joseflavio.com/cxxii/
#
# CXXII é software livre: você pode redistribuí-lo e/ou modificá-lo
# sob os termos da Licença Pública Menos Geral GNU conforme publicada pela
# Free Software Foundation, tanto a versão 3 da Licença, como
# (a seu critério) qualquer versão posterior.
#
# CXXII é distribuído na expectativa de que seja útil,
# porém, SEM NENHUMA GARANTIA; nem mesmo a garantia implícita de
# COMERCIABILIDADE ou ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a
# Licença Pública Menos Geral do GNU para mais detalhes.
#
# Você deve ter recebido uma cópia da Licença Pública Menos Geral do GNU
# junto com CXXII. Se não, veja http://www.gnu.org/licenses/.
#
#----------------------------------------------------------------------------
# "Não vos conformeis com este mundo,
# mas transformai-vos pela renovação do vosso espírito,
# para que possais discernir qual é a vontade de Deus,
# o que é bom, o que lhe agrada e o que é perfeito."
# (Bíblia Sagrada, Romanos 12:2)
# "Do not conform yourselves to this age
# but be transformed by the renewal of your mind,
# that you may discern what is the will of God,
# what is good and pleasing and perfect."
# (Holy Bible, Romans 12:2)
import sys
if sys.version_info[0] < 3:
print('CXXII exige Python 3 ou mais rece |
import unicodedata
import urllib.request
import tempfile
import zipfile
import re
from xml.etree.ElementTree import ElementTree as CXXII_XML_Arvore
#----------------------------------------------------------------------------
class CXXII_XML_Arquivo:
"""Classe que representa um arquivo XML."""
def __init__(self, endereco):
self.endereco = endereco
self.nome = NomeDoArquivo(endereco)
self.arvore = CXXII_XML_Arvore()
self.arvore.parse(endereco)
def raiz(self):
return self.arvore.getroot()
def CXXII_Baixar( url, destino=None, nome=None, forcar=False ):
"""Download de arquivo."""
if url[-1] == '/' : url = url[0:-1]
if destino is None :
global CXXII_Diretorio
destino = CXXII_Diretorio
if destino[-1] == os.sep : destino = destino[0:-1]
if nome is None : nome = url.replace('/', '_').replace(':', '_')
endereco = destino + os.sep + nome
existe = os.path.exists(endereco)
baixar = forcar or not existe
if not baixar:
global CXXII_Gerador_TempoMaximo
baixar = ( time.time() - os.path.getmtime(endereco) ) > CXXII_Gerador_TempoMaximo
if baixar:
try:
urllib.request.urlretrieve(url, endereco)
except:
raise Exception('Não foi possível baixar o gerador.')
return endereco
def CXXII_XML_Adicionar( endereco ):
global CXXII_XML_Arquivos
CXXII_XML_Arquivos.append( CXXII_XML_Arquivo(endereco) )
def CXXII_Separadores( endereco ):
"""Substitui os separadores "/" pelo separador real do sistema operacional."""
return endereco.replace('/', os.sep)
def CXXII_Python_Formato( arquivo ):
"""Retorna o valor de "# coding=".
arquivo -- Arquivo ou endereço de arquivo. Pode-se utilizar "/" como separador.
"""
if type(arquivo) is str: arquivo = open( CXXII_Separadores(arquivo), 'r', encoding='iso-8859-1' )
formato = 'utf-8'
arquivo.seek(0)
for i in range(2):
linha = arquivo.readline()
if linha.startswith('# coding='):
formato = linha[9:-1]
break
arquivo.close()
return formato
def CXXII_Abrir_Python( endereco ):
"""Abre um arquivo ".py" respeitando a codificação especificada no cabeçalho "# coding=".
endereco -- Endereço do arquivo. Pode-se utilizar "/" como separador.
"""
endereco = CXXII_Separadores(endereco)
return open( endereco, 'r', encoding=CXXII_Python_Formato(endereco) )
def CXXII_Atual( endereco, modo='w', formato='utf-8' ):
"""Determina o arquivo em geração atual.
endereco -- Endereço do arquivo desejado, relativo ao CXXII_Destino. Pode-se utilizar "/" como separador.
"""
global CXXII_Saida
global CXXII_Destino
endereco = CXXII_Separadores(endereco)
if endereco[0] != os.sep: endereco = os.sep + endereco
if CXXII_Saida != None and CXXII_Saida != sys.stdout: CXXII_Saida.close()
arquivo = CXXII_Texto(CXXII_Destino + endereco)
diretorio = CXXII_Texto(os.path.dirname(arquivo))
if not os.path.exists(diretorio): os.makedirs(diretorio)
CXXII_Saida = open( arquivo, modo, encoding=formato )
def CXXII_Escrever( texto ):
"""Escreve no arquivo em geração atual. Ver CXXII_Atual()."""
global CXXII_Saida
if not CXXII_Saida is None:
CXXII_Saida.write(texto)
def CXXII_ContarIdentacao( linha ):
comprimento = len(linha)
if comprimento == 0: return 0
tamanho = comprimento - len(linha.lstrip())
if linha[0] == ' ': tamanho /= 4
return tamanho
def CXXII_Identar( linha, total=1 ):
espaco = '\t' if len(linha) > 0 and linha[0] == '\t' else ' '
while total > 0:
linha = espaco + linha
total -= 1
return linha
def CXXII_EscreverArquivo( endereco, inicio=1, fim=None, quebraFinal=True, formato='utf-8', dicGlobal=None, dicLocal=None ):
"""Escreve no arquivo em geração atual (CXXII_Atual()) o conteúdo de um arquivo-modelo.
Arquivo-modelo é qualquer conteúdo que contenha instruções CXXII embutidas.
Se o endereço do arquivo for relativo, ele primeiro será buscado em CXXII_Gerador_Diretorio.
endereco -- Endereço do arquivo-modelo. Pode-se utilizar "/" como separador.
inicio -- Número inicial do intervalo de linhas desejado. Padrão: 1
fim -- Número final do intervalo de linhas desejado. Padrão: None (última linha)
quebraFinal -- Quebra de linha na última linha?
dicGlobal -- Ver globals()
dicLocal -- Ver locals()
"""
global CXXII_Saida
if CXXII_Saida is None: return
if dicGlobal is None: dicGlobal = globals()
if dicLocal is None: dicLocal = locals()
endereco = CXXII_Separadores(endereco)
if endereco[0] != os.sep and os.path.exists(CXXII_Gerador_Diretorio + os.sep + endereco):
endereco = CXXII_Gerador_Diretorio + os.sep + endereco
codigo = []
modelo = open( endereco, 'r', encoding=formato )
linhas = list(modelo)
modelo.close()
total = len(linhas)
if inicio != 1 or fim != None:
inicio = inicio - 1 if inicio != None else 0
fim = fim if fim != None else total
linhas = linhas[inicio:fim]
if not quebraFinal and linhas[-1][-1] == '\n': linhas[-1] = linhas[-1][0:-1]
total = len(linhas)
identacao = 0
i = 0
while i < total:
linha = linhas[i]
if linha == '@@@\n':
i += 1
if i < total and identacao > 0 and linhas[i] == '@@@\n':
identacao -= 1
else:
while i < total and linhas[i] != '@@@\n':
linha = linhas[i]
identacao = CXXII_ContarIdentacao(linha)
codigo.append(linha)
linha = linha.strip()
if len(linha) > 0 and linha[-1] == ':':
if linha.startswith('for ') or linha.startswith('while '):
identacao += 1
i += 1
else:
codigo.append(CXXII_Identar('"""~\n', identacao))
finalComQuebra = False
while i < total and linhas[i] != '@@@\n':
linha = linhas[i]
finalComQuebra = linha.endswith('\n')
if not finalComQuebra: linha += '\n'
codigo.append(linha)
i += 1
if finalComQuebra: codigo.append('\n')
codigo.append(CXXII_Identar('"""\n', identacao))
i -= 1
i += 1
CXXII_Executar( CXXII_CompilarPython(codigo), dicGlobal, dicLocal )
def CXXII_Texto( texto, decodificar=False ):
if decodificar and type(texto) is bytes: texto = texto.decode(sys.getfilesystemencoding())
return unicodedata.normalize('NFC', texto)
def CXXII_EscapeParaTexto( texto ):
return texto.replace('\n','\\n').replace('\r','\\r').replace('\t','\\t').replace('\'','\\\'')
def CXXII_TextoParaEscape( texto ):
return texto.replace('\\n','\n').replace('\\r','\r').replace('\\t','\t').replace('\\\'','\'')
def NomeDoArquivo( endereco, extensao=True ):
if endereco[-1] == os.sep: endereco = endereco[0:-1]
nome = endereco[endereco.rfind(os.sep)+1:]
if not extensao:
nome = nome[0:len(nome)-nome.rfind('.')]
return nome
def CXXII_Compilar( endereco ):
"""Compila um arquivo codificado com a linguagem Python.
Se o endereço do arquivo for relativo, ele primeiro será buscado em CXXII_Gerador_Diretorio.
endereco -- Endereço do arquivo ".py". Pode-se utilizar "/" como separador.
"""
endereco = CXXII_Separadores(endereco)
if endereco[0] != os.sep and os.path.exists(CXXII_Gerador_Diretorio + os.sep + endereco):
endereco = CXXII_Gerador_Diretorio + os.sep + endereco
py_arquivo = CXXII_Abrir_Python(endereco)
py = list(py_arquivo)
py_arquivo.close()
return CXXII_CompilarPython(py)
def CXXII_CompilarPython( codigoFonte ):
"""Compila um código fonte codificado com a linguagem Python."""
py = list(codigoFonte) if type(codigoFonte) != list else codigoFonte
if py[0].startswith('# coding='):
py = py[1:]
elif py[1].startswith('# coding='):
py = py[2:]
py[-1] += '\n'
i = 0
total = len(py)
embutido = re.compile('({{{[^{}]*}}})')
while i < total:
linha = py[i]
passo = 1
if linha.endswith('"""~\n'):
desconsiderar = False
tokenstr = None
cpre = None
for c in linha:
if tokenstr != None:
if c == tokenstr and cpre != '\\': tokenstr = None
elif c == '#':
desconsiderar = True
break
elif c == '\'' or c == '\"':
tokenstr = c
cpre = c
if desconsiderar:
i += passo
continue
linha = linha[:-5] + 'CXXII_Escrever(\''
a = i
b = a + 1
while b < total and not py[b].lstrip().startswith('"""'): b += 1
if b >= total: raise Exception('Bloco de escrita não finalizado: linha ' + str(i))
py[b] = py[b][py[b].index('"""')+3:]
passo = b - a
if (b-a) > 1:
primeiro = True
a += 1
while a < b:
linha += ( '\\n' if not primeiro else '' ) + CXXII_EscapeParaTexto( py[a][:-1] )
py[a] = ''
primeiro = False
a += 1
linhapos = 0
while True:
codigo = embutido.search(linha, linhapos)
if not codigo is None:
parte1 = \
linha[0:codigo.start(0)] +\
'\'+' +\
CXXII_TextoParaEscape(codigo.group(0)[3:-3]) +\
'+\''
parte2 = linha[codigo.end(0):]
linha = parte1 + parte2
linhapos = len(parte1)
else:
break
linha += '\');'
py[i] = linha
i += passo
return compile( ''.join(py), 'CXXII_Python', 'exec' )
def CXXII_Executar( python, dicGlobal=None, dicLocal=None ):
"""Executa um código Python pré-compilado com CXXII_Compilar() ou um arquivo Python.
Se o endereço do arquivo for relativo, ele primeiro será buscado em CXXII_Gerador_Diretorio.
python -- Código pré-compilado ou endereço do arquivo. Pode-se utilizar "/" como separador.
dicGlobal -- Ver globals()
dicLocal -- Ver locals()
"""
if dicGlobal is None: dicGlobal = globals()
if dicLocal is None: dicLocal = locals()
exec( CXXII_Compilar(python) if type(python) is str else python, dicGlobal, dicLocal )
#----------------------------------------------------------------------------
CXXII_Repositorio = 'http://www.joseflavio.com/cxxii/'
CXXII_Inicio = datetime.datetime.today()
CXXII_Gerador_Endereco = None
CXXII_Gerador_Diretorio = None
CXXII_Gerador_TempoMaximo = 6*60*60 #6h
CXXII_Gerador_Baixar = False
CXXII_Destino = None
CXXII_XML_Arquivos = []
CXXII_Extensao = 'xml'
CXXII_Saida = sys.stdout
CXXII_Diretorio = CXXII_Texto(os.path.expanduser('~')) + os.sep + 'CXXII'
CXXII_Geradores = CXXII_Diretorio + os.sep + 'Geradores'
if not os.path.exists(CXXII_Geradores): os.makedirs(CXXII_Geradores)
#----------------------------------------------------------------------------
try:
#----------------------------------------------------------------------------
argumentos = CXXII_Texto(' '.join(sys.argv), True)
argumentos = argumentos.replace(' -g', '###g')
argumentos = argumentos.replace(' -f', '###fSIM')
argumentos = argumentos.replace(' -t', '###tSIM')
argumentos = argumentos.replace(' -d', '###d')
argumentos = argumentos.replace(' -e', '###e')
argumentos = argumentos.replace(' -a', '###a')
argumentos = argumentos.split('###')
argumento_g = None
argumento_f = None
argumento_t = None
argumento_d = None
argumento_e = None
argumento_a = None
for argumento in argumentos[1:]:
valor = argumento[1:].strip()
if len(valor) == 0: continue
exec( 'argumento_' + argumento[0] + '=\'' + valor + '\'' )
if argumento_g is None or argumento_a is None:
print('\nCXXII 1.0-A1 : Gerador de arquivos a partir de XML\n')
print('cxxii -g GERADOR [-f] [-t] [-d DESTINO] [-e EXTENSAO] -a ARQUIVOS\n')
print('Argumentos:')
print(' -g URL ou endereço local do gerador a utilizar: .py ou .zip')
print(' Nome sem extensão = ' + CXXII_Repositorio + 'Nome.zip')
print(' -f Forçar download do gerador')
print(' -t Imprimir detalhes do erro que possa ocorrer')
print(' -d Destino dos arquivos gerados')
print(' -e Extensão padrão dos arquivos de entrada: xml')
print(' -a Arquivos XML de entrada ou diretórios que os contenham\n')
sys.exit(1)
#----------------------------------------------------------------------------
if argumento_e != None: CXXII_Extensao = argumento_e.lower()
argumento_a = argumento_a.replace('.' + CXXII_Extensao, '.' + CXXII_Extensao + '###')
argumento_a = argumento_a.split('###')
for xml in argumento_a:
xml = xml.strip()
if len(xml) == 0: continue
xml = CXXII_Texto(os.path.abspath(xml))
if os.path.isdir(xml):
for arquivo in os.listdir(xml):
arquivo = CXXII_Texto(arquivo)
if arquivo.lower().endswith('.' + CXXII_Extensao):
CXXII_XML_Adicionar(xml + os.sep + arquivo)
else:
CXXII_XML_Adicionar(xml)
if len(CXXII_XML_Arquivos) == 0:
sys.exit(0)
#----------------------------------------------------------------------------
try:
CXXII_Gerador_Baixar = not argumento_f is None
gerurl = argumento_g.startswith('http://')
if( gerurl and argumento_g[-1] == '/' ): argumento_g = argumento_g[0:-1]
gernome = argumento_g[argumento_g.rfind('/' if gerurl else os.sep)+1:]
gerpy = gernome.endswith('.py')
gerzip = gernome.endswith('.zip')
if gerurl:
argumento_g = CXXII_Baixar(url=argumento_g, destino=CXXII_Geradores, forcar=CXXII_Gerador_Baixar)
elif gerpy or gerzip:
argumento_g = CXXII_Texto(os.path.abspath(argumento_g))
else:
gerurl = True
gernome += '.zip'
gerzip = True
argumento_g = CXXII_Baixar(url=CXXII_Repositorio + gernome, destino=CXXII_Geradores, forcar=CXXII_Gerador_Baixar)
if gerzip:
destino = argumento_g[0:-4]
if not os.path.exists(destino): os.makedirs(destino)
CXXII_Gerador_Endereco = destino + os.sep + gernome[0:-4] + '.py'
descompactar = not os.path.exists(CXXII_Gerador_Endereco)
if not descompactar:
descompactar = os.path.getmtime(argumento_g) > os.path.getmtime(CXXII_Gerador_Endereco)
if descompactar:
zip = zipfile.ZipFile(argumento_g, 'r')
zip.extractall(destino)
del zip
else:
CXXII_Gerador_Endereco = argumento_g
CXXII_Gerador_Diretorio = CXXII_Texto(os.path.dirname(CXXII_Gerador_Endereco))
except:
raise Exception('Gerador inválido.')
#----------------------------------------------------------------------------
CXXII_Destino = argumento_d if not argumento_d is None else 'CXXII_' + CXXII_Inicio.strftime('%Y%m%d%H%M%S')
CXXII_Destino = CXXII_Texto(os.path.abspath(CXXII_Destino))
if not os.path.exists(CXXII_Destino): os.makedirs(CXXII_Destino)
#----------------------------------------------------------------------------
gerador_nome = ''
gerador_versao = ''
gerador_multiplo = True
cxxii_con = CXXII_Abrir_Python(CXXII_Gerador_Endereco)
cxxii_lin = list(cxxii_con)
cxxii_ini = 0
cxxii_tot = len(cxxii_lin)
while cxxii_ini < cxxii_tot and cxxii_lin[cxxii_ini] != '### CXXII\n': cxxii_ini += 1
if cxxii_ini < cxxii_tot:
fim = cxxii_ini + 1
while fim < cxxii_tot and cxxii_lin[fim] != '###\n': fim += 1
if fim < cxxii_tot: exec(''.join(cxxii_lin[(cxxii_ini+1):fim]))
cxxii_con.close()
del cxxii_con
del cxxii_lin
del cxxii_ini
del cxxii_tot
gerador_nome = gerador_nome if gerador_nome != None and len(gerador_nome) > 0 else NomeDoArquivo(argumento_g)
if gerador_versao == None: gerador_versao = 'Desconhecida'
if not type(gerador_versao) is str: gerador_versao = str(gerador_versao)
print( 'Gerador: ' + gerador_nome )
print( 'Versão: ' + gerador_versao )
#----------------------------------------------------------------------------
CXXII_Gerador_Compilado = CXXII_Compilar( CXXII_Gerador_Endereco )
CXXII_XML = CXXII_XML_Arquivos[0]
if gerador_multiplo:
for xml in CXXII_XML_Arquivos:
print(xml.endereco)
CXXII_XML = xml
CXXII_Executar( CXXII_Gerador_Compilado, globals(), locals() )
else:
CXXII_Executar( CXXII_Gerador_Compilado, globals(), locals() )
#----------------------------------------------------------------------------
except Exception as e:
if not argumento_t is None:
import traceback
traceback.print_exc()
print('Erro: ' + str(e))
#---------------------------------------------------------------------------- | nte.')
sys.exit(1)
import os
import time
import datetime | conditional_block |
CXXII.py | #!/usr/bin/env python3
#----------------------------------------------------------------------------
#
# Copyright (C) 2015 José Flávio de Souza Dias Júnior
#
# This file is part of CXXII - http://www.joseflavio.com/cxxii/
#
# CXXII is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# CXXII 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with CXXII. If not, see http://www.gnu.org/licenses/.
#
#----------------------------------------------------------------------------
#
# Direitos Autorais Reservados (C) 2015 José Flávio de Souza Dias Júnior
#
# Este arquivo é parte de CXXII - http://www.joseflavio.com/cxxii/
#
# CXXII é software livre: você pode redistribuí-lo e/ou modificá-lo
# sob os termos da Licença Pública Menos Geral GNU conforme publicada pela
# Free Software Foundation, tanto a versão 3 da Licença, como
# (a seu critério) qualquer versão posterior.
#
# CXXII é distribuído na expectativa de que seja útil,
# porém, SEM NENHUMA GARANTIA; nem mesmo a garantia implícita de
# COMERCIABILIDADE ou ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a
# Licença Pública Menos Geral do GNU para mais detalhes.
#
# Você deve ter recebido uma cópia da Licença Pública Menos Geral do GNU
# junto com CXXII. Se não, veja http://www.gnu.org/licenses/.
#
#----------------------------------------------------------------------------
# "Não vos conformeis com este mundo,
# mas transformai-vos pela renovação do vosso espírito,
# para que possais discernir qual é a vontade de Deus,
# o que é bom, o que lhe agrada e o que é perfeito."
# (Bíblia Sagrada, Romanos 12:2)
# "Do not conform yourselves to this age
# but be transformed by the renewal of your mind,
# that you may discern what is the will of God,
# what is good and pleasing and perfect."
# (Holy Bible, Romans 12:2)
import sys
if sys.version_info[0] < 3:
print('CXXII exige Python 3 ou mais recente.')
sys.exit(1)
import os
import time
import datetime
import unicodedata
import urllib.request
import tempfile
import zipfile
import re
from xml.etree.ElementTree import ElementTree as CXXII_XML_Arvore
#----------------------------------------------------------------------------
class CXXII_XML_Arquivo:
"""Classe que representa um arquivo XML."""
def __init__(self, endereco):
self.endereco = endereco
self.nome = NomeDoArquivo(endereco)
self.arvore = CXXII_XML_Arvore()
self.arvore.parse(endereco)
def raiz(self):
return self.arvore.getroot()
def CXXII_Baixar( url, destino=None, nome=No | alse ):
"""Download de arquivo."""
if url[-1] == '/' : url = url[0:-1]
if destino is None :
global CXXII_Diretorio
destino = CXXII_Diretorio
if destino[-1] == os.sep : destino = destino[0:-1]
if nome is None : nome = url.replace('/', '_').replace(':', '_')
endereco = destino + os.sep + nome
existe = os.path.exists(endereco)
baixar = forcar or not existe
if not baixar:
global CXXII_Gerador_TempoMaximo
baixar = ( time.time() - os.path.getmtime(endereco) ) > CXXII_Gerador_TempoMaximo
if baixar:
try:
urllib.request.urlretrieve(url, endereco)
except:
raise Exception('Não foi possível baixar o gerador.')
return endereco
def CXXII_XML_Adicionar( endereco ):
global CXXII_XML_Arquivos
CXXII_XML_Arquivos.append( CXXII_XML_Arquivo(endereco) )
def CXXII_Separadores( endereco ):
"""Substitui os separadores "/" pelo separador real do sistema operacional."""
return endereco.replace('/', os.sep)
def CXXII_Python_Formato( arquivo ):
"""Retorna o valor de "# coding=".
arquivo -- Arquivo ou endereço de arquivo. Pode-se utilizar "/" como separador.
"""
if type(arquivo) is str: arquivo = open( CXXII_Separadores(arquivo), 'r', encoding='iso-8859-1' )
formato = 'utf-8'
arquivo.seek(0)
for i in range(2):
linha = arquivo.readline()
if linha.startswith('# coding='):
formato = linha[9:-1]
break
arquivo.close()
return formato
def CXXII_Abrir_Python( endereco ):
"""Abre um arquivo ".py" respeitando a codificação especificada no cabeçalho "# coding=".
endereco -- Endereço do arquivo. Pode-se utilizar "/" como separador.
"""
endereco = CXXII_Separadores(endereco)
return open( endereco, 'r', encoding=CXXII_Python_Formato(endereco) )
def CXXII_Atual( endereco, modo='w', formato='utf-8' ):
"""Determina o arquivo em geração atual.
endereco -- Endereço do arquivo desejado, relativo ao CXXII_Destino. Pode-se utilizar "/" como separador.
"""
global CXXII_Saida
global CXXII_Destino
endereco = CXXII_Separadores(endereco)
if endereco[0] != os.sep: endereco = os.sep + endereco
if CXXII_Saida != None and CXXII_Saida != sys.stdout: CXXII_Saida.close()
arquivo = CXXII_Texto(CXXII_Destino + endereco)
diretorio = CXXII_Texto(os.path.dirname(arquivo))
if not os.path.exists(diretorio): os.makedirs(diretorio)
CXXII_Saida = open( arquivo, modo, encoding=formato )
def CXXII_Escrever( texto ):
"""Escreve no arquivo em geração atual. Ver CXXII_Atual()."""
global CXXII_Saida
if not CXXII_Saida is None:
CXXII_Saida.write(texto)
def CXXII_ContarIdentacao( linha ):
comprimento = len(linha)
if comprimento == 0: return 0
tamanho = comprimento - len(linha.lstrip())
if linha[0] == ' ': tamanho /= 4
return tamanho
def CXXII_Identar( linha, total=1 ):
espaco = '\t' if len(linha) > 0 and linha[0] == '\t' else ' '
while total > 0:
linha = espaco + linha
total -= 1
return linha
def CXXII_EscreverArquivo( endereco, inicio=1, fim=None, quebraFinal=True, formato='utf-8', dicGlobal=None, dicLocal=None ):
"""Escreve no arquivo em geração atual (CXXII_Atual()) o conteúdo de um arquivo-modelo.
Arquivo-modelo é qualquer conteúdo que contenha instruções CXXII embutidas.
Se o endereço do arquivo for relativo, ele primeiro será buscado em CXXII_Gerador_Diretorio.
endereco -- Endereço do arquivo-modelo. Pode-se utilizar "/" como separador.
inicio -- Número inicial do intervalo de linhas desejado. Padrão: 1
fim -- Número final do intervalo de linhas desejado. Padrão: None (última linha)
quebraFinal -- Quebra de linha na última linha?
dicGlobal -- Ver globals()
dicLocal -- Ver locals()
"""
global CXXII_Saida
if CXXII_Saida is None: return
if dicGlobal is None: dicGlobal = globals()
if dicLocal is None: dicLocal = locals()
endereco = CXXII_Separadores(endereco)
if endereco[0] != os.sep and os.path.exists(CXXII_Gerador_Diretorio + os.sep + endereco):
endereco = CXXII_Gerador_Diretorio + os.sep + endereco
codigo = []
modelo = open( endereco, 'r', encoding=formato )
linhas = list(modelo)
modelo.close()
total = len(linhas)
if inicio != 1 or fim != None:
inicio = inicio - 1 if inicio != None else 0
fim = fim if fim != None else total
linhas = linhas[inicio:fim]
if not quebraFinal and linhas[-1][-1] == '\n': linhas[-1] = linhas[-1][0:-1]
total = len(linhas)
identacao = 0
i = 0
while i < total:
linha = linhas[i]
if linha == '@@@\n':
i += 1
if i < total and identacao > 0 and linhas[i] == '@@@\n':
identacao -= 1
else:
while i < total and linhas[i] != '@@@\n':
linha = linhas[i]
identacao = CXXII_ContarIdentacao(linha)
codigo.append(linha)
linha = linha.strip()
if len(linha) > 0 and linha[-1] == ':':
if linha.startswith('for ') or linha.startswith('while '):
identacao += 1
i += 1
else:
codigo.append(CXXII_Identar('"""~\n', identacao))
finalComQuebra = False
while i < total and linhas[i] != '@@@\n':
linha = linhas[i]
finalComQuebra = linha.endswith('\n')
if not finalComQuebra: linha += '\n'
codigo.append(linha)
i += 1
if finalComQuebra: codigo.append('\n')
codigo.append(CXXII_Identar('"""\n', identacao))
i -= 1
i += 1
CXXII_Executar( CXXII_CompilarPython(codigo), dicGlobal, dicLocal )
def CXXII_Texto( texto, decodificar=False ):
if decodificar and type(texto) is bytes: texto = texto.decode(sys.getfilesystemencoding())
return unicodedata.normalize('NFC', texto)
def CXXII_EscapeParaTexto( texto ):
return texto.replace('\n','\\n').replace('\r','\\r').replace('\t','\\t').replace('\'','\\\'')
def CXXII_TextoParaEscape( texto ):
return texto.replace('\\n','\n').replace('\\r','\r').replace('\\t','\t').replace('\\\'','\'')
def NomeDoArquivo( endereco, extensao=True ):
if endereco[-1] == os.sep: endereco = endereco[0:-1]
nome = endereco[endereco.rfind(os.sep)+1:]
if not extensao:
nome = nome[0:len(nome)-nome.rfind('.')]
return nome
def CXXII_Compilar( endereco ):
"""Compila um arquivo codificado com a linguagem Python.
Se o endereço do arquivo for relativo, ele primeiro será buscado em CXXII_Gerador_Diretorio.
endereco -- Endereço do arquivo ".py". Pode-se utilizar "/" como separador.
"""
endereco = CXXII_Separadores(endereco)
if endereco[0] != os.sep and os.path.exists(CXXII_Gerador_Diretorio + os.sep + endereco):
endereco = CXXII_Gerador_Diretorio + os.sep + endereco
py_arquivo = CXXII_Abrir_Python(endereco)
py = list(py_arquivo)
py_arquivo.close()
return CXXII_CompilarPython(py)
def CXXII_CompilarPython( codigoFonte ):
"""Compila um código fonte codificado com a linguagem Python."""
py = list(codigoFonte) if type(codigoFonte) != list else codigoFonte
if py[0].startswith('# coding='):
py = py[1:]
elif py[1].startswith('# coding='):
py = py[2:]
py[-1] += '\n'
i = 0
total = len(py)
embutido = re.compile('({{{[^{}]*}}})')
while i < total:
linha = py[i]
passo = 1
if linha.endswith('"""~\n'):
desconsiderar = False
tokenstr = None
cpre = None
for c in linha:
if tokenstr != None:
if c == tokenstr and cpre != '\\': tokenstr = None
elif c == '#':
desconsiderar = True
break
elif c == '\'' or c == '\"':
tokenstr = c
cpre = c
if desconsiderar:
i += passo
continue
linha = linha[:-5] + 'CXXII_Escrever(\''
a = i
b = a + 1
while b < total and not py[b].lstrip().startswith('"""'): b += 1
if b >= total: raise Exception('Bloco de escrita não finalizado: linha ' + str(i))
py[b] = py[b][py[b].index('"""')+3:]
passo = b - a
if (b-a) > 1:
primeiro = True
a += 1
while a < b:
linha += ( '\\n' if not primeiro else '' ) + CXXII_EscapeParaTexto( py[a][:-1] )
py[a] = ''
primeiro = False
a += 1
linhapos = 0
while True:
codigo = embutido.search(linha, linhapos)
if not codigo is None:
parte1 = \
linha[0:codigo.start(0)] +\
'\'+' +\
CXXII_TextoParaEscape(codigo.group(0)[3:-3]) +\
'+\''
parte2 = linha[codigo.end(0):]
linha = parte1 + parte2
linhapos = len(parte1)
else:
break
linha += '\');'
py[i] = linha
i += passo
return compile( ''.join(py), 'CXXII_Python', 'exec' )
def CXXII_Executar( python, dicGlobal=None, dicLocal=None ):
"""Executa um código Python pré-compilado com CXXII_Compilar() ou um arquivo Python.
Se o endereço do arquivo for relativo, ele primeiro será buscado em CXXII_Gerador_Diretorio.
python -- Código pré-compilado ou endereço do arquivo. Pode-se utilizar "/" como separador.
dicGlobal -- Ver globals()
dicLocal -- Ver locals()
"""
if dicGlobal is None: dicGlobal = globals()
if dicLocal is None: dicLocal = locals()
exec( CXXII_Compilar(python) if type(python) is str else python, dicGlobal, dicLocal )
#----------------------------------------------------------------------------
CXXII_Repositorio = 'http://www.joseflavio.com/cxxii/'
CXXII_Inicio = datetime.datetime.today()
CXXII_Gerador_Endereco = None
CXXII_Gerador_Diretorio = None
CXXII_Gerador_TempoMaximo = 6*60*60 #6h
CXXII_Gerador_Baixar = False
CXXII_Destino = None
CXXII_XML_Arquivos = []
CXXII_Extensao = 'xml'
CXXII_Saida = sys.stdout
CXXII_Diretorio = CXXII_Texto(os.path.expanduser('~')) + os.sep + 'CXXII'
CXXII_Geradores = CXXII_Diretorio + os.sep + 'Geradores'
if not os.path.exists(CXXII_Geradores): os.makedirs(CXXII_Geradores)
#----------------------------------------------------------------------------
try:
#----------------------------------------------------------------------------
argumentos = CXXII_Texto(' '.join(sys.argv), True)
argumentos = argumentos.replace(' -g', '###g')
argumentos = argumentos.replace(' -f', '###fSIM')
argumentos = argumentos.replace(' -t', '###tSIM')
argumentos = argumentos.replace(' -d', '###d')
argumentos = argumentos.replace(' -e', '###e')
argumentos = argumentos.replace(' -a', '###a')
argumentos = argumentos.split('###')
argumento_g = None
argumento_f = None
argumento_t = None
argumento_d = None
argumento_e = None
argumento_a = None
for argumento in argumentos[1:]:
valor = argumento[1:].strip()
if len(valor) == 0: continue
exec( 'argumento_' + argumento[0] + '=\'' + valor + '\'' )
if argumento_g is None or argumento_a is None:
print('\nCXXII 1.0-A1 : Gerador de arquivos a partir de XML\n')
print('cxxii -g GERADOR [-f] [-t] [-d DESTINO] [-e EXTENSAO] -a ARQUIVOS\n')
print('Argumentos:')
print(' -g URL ou endereço local do gerador a utilizar: .py ou .zip')
print(' Nome sem extensão = ' + CXXII_Repositorio + 'Nome.zip')
print(' -f Forçar download do gerador')
print(' -t Imprimir detalhes do erro que possa ocorrer')
print(' -d Destino dos arquivos gerados')
print(' -e Extensão padrão dos arquivos de entrada: xml')
print(' -a Arquivos XML de entrada ou diretórios que os contenham\n')
sys.exit(1)
#----------------------------------------------------------------------------
if argumento_e != None: CXXII_Extensao = argumento_e.lower()
argumento_a = argumento_a.replace('.' + CXXII_Extensao, '.' + CXXII_Extensao + '###')
argumento_a = argumento_a.split('###')
for xml in argumento_a:
xml = xml.strip()
if len(xml) == 0: continue
xml = CXXII_Texto(os.path.abspath(xml))
if os.path.isdir(xml):
for arquivo in os.listdir(xml):
arquivo = CXXII_Texto(arquivo)
if arquivo.lower().endswith('.' + CXXII_Extensao):
CXXII_XML_Adicionar(xml + os.sep + arquivo)
else:
CXXII_XML_Adicionar(xml)
if len(CXXII_XML_Arquivos) == 0:
sys.exit(0)
#----------------------------------------------------------------------------
try:
CXXII_Gerador_Baixar = not argumento_f is None
gerurl = argumento_g.startswith('http://')
if( gerurl and argumento_g[-1] == '/' ): argumento_g = argumento_g[0:-1]
gernome = argumento_g[argumento_g.rfind('/' if gerurl else os.sep)+1:]
gerpy = gernome.endswith('.py')
gerzip = gernome.endswith('.zip')
if gerurl:
argumento_g = CXXII_Baixar(url=argumento_g, destino=CXXII_Geradores, forcar=CXXII_Gerador_Baixar)
elif gerpy or gerzip:
argumento_g = CXXII_Texto(os.path.abspath(argumento_g))
else:
gerurl = True
gernome += '.zip'
gerzip = True
argumento_g = CXXII_Baixar(url=CXXII_Repositorio + gernome, destino=CXXII_Geradores, forcar=CXXII_Gerador_Baixar)
if gerzip:
destino = argumento_g[0:-4]
if not os.path.exists(destino): os.makedirs(destino)
CXXII_Gerador_Endereco = destino + os.sep + gernome[0:-4] + '.py'
descompactar = not os.path.exists(CXXII_Gerador_Endereco)
if not descompactar:
descompactar = os.path.getmtime(argumento_g) > os.path.getmtime(CXXII_Gerador_Endereco)
if descompactar:
zip = zipfile.ZipFile(argumento_g, 'r')
zip.extractall(destino)
del zip
else:
CXXII_Gerador_Endereco = argumento_g
CXXII_Gerador_Diretorio = CXXII_Texto(os.path.dirname(CXXII_Gerador_Endereco))
except:
raise Exception('Gerador inválido.')
#----------------------------------------------------------------------------
CXXII_Destino = argumento_d if not argumento_d is None else 'CXXII_' + CXXII_Inicio.strftime('%Y%m%d%H%M%S')
CXXII_Destino = CXXII_Texto(os.path.abspath(CXXII_Destino))
if not os.path.exists(CXXII_Destino): os.makedirs(CXXII_Destino)
#----------------------------------------------------------------------------
gerador_nome = ''
gerador_versao = ''
gerador_multiplo = True
cxxii_con = CXXII_Abrir_Python(CXXII_Gerador_Endereco)
cxxii_lin = list(cxxii_con)
cxxii_ini = 0
cxxii_tot = len(cxxii_lin)
while cxxii_ini < cxxii_tot and cxxii_lin[cxxii_ini] != '### CXXII\n': cxxii_ini += 1
if cxxii_ini < cxxii_tot:
fim = cxxii_ini + 1
while fim < cxxii_tot and cxxii_lin[fim] != '###\n': fim += 1
if fim < cxxii_tot: exec(''.join(cxxii_lin[(cxxii_ini+1):fim]))
cxxii_con.close()
del cxxii_con
del cxxii_lin
del cxxii_ini
del cxxii_tot
gerador_nome = gerador_nome if gerador_nome != None and len(gerador_nome) > 0 else NomeDoArquivo(argumento_g)
if gerador_versao == None: gerador_versao = 'Desconhecida'
if not type(gerador_versao) is str: gerador_versao = str(gerador_versao)
print( 'Gerador: ' + gerador_nome )
print( 'Versão: ' + gerador_versao )
#----------------------------------------------------------------------------
CXXII_Gerador_Compilado = CXXII_Compilar( CXXII_Gerador_Endereco )
CXXII_XML = CXXII_XML_Arquivos[0]
if gerador_multiplo:
for xml in CXXII_XML_Arquivos:
print(xml.endereco)
CXXII_XML = xml
CXXII_Executar( CXXII_Gerador_Compilado, globals(), locals() )
else:
CXXII_Executar( CXXII_Gerador_Compilado, globals(), locals() )
#----------------------------------------------------------------------------
except Exception as e:
if not argumento_t is None:
import traceback
traceback.print_exc()
print('Erro: ' + str(e))
#---------------------------------------------------------------------------- | ne, forcar=F | identifier_name |
TextContent.ts | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of | *
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
/// <reference path="../../Utils.ts" />
namespace mycore.viewer.model {
export interface TextContentModel {
content : Array<TextElement>;
links: Link[];
internLinks: InternLink[];
}
export interface Link {
url: string;
rect: Rect;
}
export interface InternLink {
rect: Rect;
pageNumberResolver(callback: (page: string) => void): void;
}
export interface TextElement {
fromBottomLeft?:boolean;
angle?: number;
size: Size2D;
text: string;
pos: Position2D;
fontFamily?: string;
fontSize?: number;
pageHref: string;
mouseenter?: ()=>void;
mouseleave?: ()=>void;
toString():string;
}
} | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. | random_line_split |
htmltablecolelement.rs | /* 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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::root::DomRoot;
use crate::dom::document::Document;
use crate::dom::htmlelement::HTMLElement;
use crate::dom::node::Node;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
#[dom_struct]
pub struct HTMLTableColElement {
htmlelement: HTMLElement,
}
impl HTMLTableColElement {
fn new_inherited(
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> HTMLTableColElement {
HTMLTableColElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn new(
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document, | )),
document,
);
n.upcast::<Node>().set_weird_parser_insertion_mode();
n
}
} | ) -> DomRoot<HTMLTableColElement> {
let n = Node::reflect_node(
Box::new(HTMLTableColElement::new_inherited(
local_name, prefix, document, | random_line_split |
htmltablecolelement.rs | /* 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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::root::DomRoot;
use crate::dom::document::Document;
use crate::dom::htmlelement::HTMLElement;
use crate::dom::node::Node;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
#[dom_struct]
pub struct HTMLTableColElement {
htmlelement: HTMLElement,
}
impl HTMLTableColElement {
fn new_inherited(
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> HTMLTableColElement {
HTMLTableColElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn new(
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> DomRoot<HTMLTableColElement> |
}
| {
let n = Node::reflect_node(
Box::new(HTMLTableColElement::new_inherited(
local_name, prefix, document,
)),
document,
);
n.upcast::<Node>().set_weird_parser_insertion_mode();
n
} | identifier_body |
htmltablecolelement.rs | /* 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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::root::DomRoot;
use crate::dom::document::Document;
use crate::dom::htmlelement::HTMLElement;
use crate::dom::node::Node;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
#[dom_struct]
pub struct HTMLTableColElement {
htmlelement: HTMLElement,
}
impl HTMLTableColElement {
fn new_inherited(
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> HTMLTableColElement {
HTMLTableColElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn | (
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> DomRoot<HTMLTableColElement> {
let n = Node::reflect_node(
Box::new(HTMLTableColElement::new_inherited(
local_name, prefix, document,
)),
document,
);
n.upcast::<Node>().set_weird_parser_insertion_mode();
n
}
}
| new | identifier_name |
error.rs | use rustc_serialize::json;
use rustc_serialize::Decoder;
use rustc_serialize::Decodable;
use std::str;
use std::fmt;
/// Documentation References:
/// https://developer.github.com/v3/#client-errors
/// `ErrorCode` represents the type of error that was reported
/// as a response on a request to th Github API.
#[derive(Debug)]
pub enum ErrorCode {
/// This means a resource does not exist.
Missing,
/// This means a required field on a resource has not been set.
MissingField,
/// This means the formatting of a field is invalid.
/// The documentation for that resource should be able
/// to give you more specific information.
Invalid,
/// This means another resource has the same value as this field.
/// This can happen in resources that must
/// have some unique key (such as Label names).
AlreadyExists,
/// `Unknown(String)` is used as a last resort when an error code is unknown.
/// This should never happen, please report/resolve the issue when it does happen.
Unknown(String),
}
/// Allowing `ErrorCode` to be printed via `{}`.
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let msg: &str = match *self {
ErrorCode::Missing => "resource does not exist",
ErrorCode::MissingField => "required field on the resource has not been set",
ErrorCode::Invalid => "the formatting of the field is invalid",
ErrorCode::AlreadyExists => "another resource has the same value as this field",
ErrorCode::Unknown(ref s) => &s,
};
write!(f, "{}", msg)
}
}
/// Allowing `ErrorCode` to be decoded from json values.
/// Linked to the `error` key as defind by the `ErrorContext` struct's member.
impl Decodable for ErrorCode {
fn decode<D: Decoder>(d: &mut D) -> Result<ErrorCode, D::Error> {
match d.read_str() {
Ok(code) => Ok(match &*code {
"missing" => ErrorCode::Missing,
"missing_field" => ErrorCode::MissingField,
"invalid" => ErrorCode::Invalid,
"already_exists" => ErrorCode::AlreadyExists,
unknown => ErrorCode::Unknown(unknown.to_string()),
}),
Err(err) => Err(err),
}
}
}
/// When a request was successful.
const STATUS_OK: u32 = 200;
/// There was a problem with the data sent with the request.
const STATUS_BAD_REQUEST: u32 = 400;
/// Given as a response to requests the user has insufficient permissions for.
const STATUS_FORBIDDEN: u32 = 403;
/// Given when the info requested is not found because it
/// either doesn't exist or because you are not authorized.
const STATUS_NOT_FOUND: u32 = 404;
/// Given when a field or resource couldn't be processed properly.
const STATUS_UNPROCCESSABLE_ENTITY: u32 = 422;
/// When a negative status was given as a response to a request,
/// there might be one or several error descriptions embedded in the
/// body to tell more about the details of what was wrong.
/// `ErrorContext` is the representation for each of the errors that are given.
#[derive(RustcDecodable, Debug)]
pub struct ErrorContext {
pub resource: String,
pub field: String,
pub code: ErrorCode,
}
/// Allowing `ErrorContext` to be printed via `{}` in a controlled manner.
impl fmt::Display for ErrorContext {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Error found in {}.{}: {}", self.resource, self.field, self.code)
}
}
/// `ErrorStatus` represents the status code given in the header of a negative response.
/// Look at const definitions such as `STATUS_OK` for more information for each value.
#[derive(Debug)]
pub enum ErrorStatus{
BadRequest,
UnprocessableEntity,
Forbidden,
NotFound,
Unknown(u32),
}
/// Allowing `ErrorStatus` to be printed via `{}` in a controlled manner.
impl fmt::Display for ErrorStatus {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let (code, msg) = match *self {
ErrorStatus::BadRequest => (STATUS_BAD_REQUEST, "Bad Request"),
ErrorStatus::UnprocessableEntity => (STATUS_UNPROCCESSABLE_ENTITY, "Unprocessable Entity"),
ErrorStatus::Forbidden => (STATUS_FORBIDDEN, "Forbidden Request"),
ErrorStatus::NotFound => (STATUS_NOT_FOUND, "Not Found"),
ErrorStatus::Unknown(e) => (e, "Unknown"),
};
write!(f, "status {}: {}", code, msg)
}
}
impl ErrorStatus {
/// Simple way to construct an `ErrorStatus`
/// based on its constant value as defined by the official docs.
pub fn new(code: u32) -> ErrorStatus {
match code {
STATUS_BAD_REQUEST => ErrorStatus::BadRequest,
STATUS_FORBIDDEN => ErrorStatus::Forbidden,
STATUS_UNPROCCESSABLE_ENTITY => ErrorStatus::UnprocessableEntity,
STATUS_NOT_FOUND => ErrorStatus::NotFound,
unknown => ErrorStatus::Unknown(unknown),
}
}
}
/// `RequestError` will be returned as a `Result<T, ClientError>` in case
/// a request responds negatively populated by information from
/// both the header and body.
#[derive(Debug)]
pub struct RequestError {
/// `code` represents the given status code
/// stored in the form of `ErrorStatus`.
pub code: ErrorStatus,
/// In case detailed errors are available
// they will be accessible via `errors`, stored as an `ErrorContext`.
pub errors: Vec<ErrorContext>,
}
impl RequestError {
/// Simple way to construct a `Result<T, ClientError>` based on
/// the status code given in the header and the body in a raw utf8 buffer.
pub fn new<T>(code: u32, buffer: &[u8]) -> Result<T, ClientError> {
Err(ClientError::Http(RequestError {
code: ErrorStatus::new(code),
errors: match str::from_utf8(buffer) {
Err(..) => Vec::new(),
Ok(body) => json::decode(body).unwrap_or(Vec::new()),
},
}))
}
}
/// Allowing `RequestError` to be printed via `{}` in a controlled manner.
impl fmt::Display for RequestError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "HTTP Error: {}. Found {} error description(s)!", self.code, self.errors.len())
}
}
/// `InternalError` will be given in the form of Result<T, ClientError> in
/// case something went wrong within this Client Library.
/// It replaces panics so that you can freely choose the behaviour.
/// Please file an issue and/or resolve the bug yourself when you get this error.
#[derive(Debug)]
pub struct InternalError {
/// `msg` is the actual description of the problem.
/// future versions of this library might store extra info
/// where it would help the debugging of an error.
pub msg: String,
}
impl InternalError {
/// Simple way to construct a `Result<T, ClientError>` based on
/// information known for an internal error.
pub fn new<T>(msg: &str) -> Result<T, ClientError> {
Err(ClientError::Internal(InternalError { msg: msg.to_string() }))
}
}
/// Allowing `InternalError` to be printed via `{}` in a controlled manner.
impl fmt::Display for InternalError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Internal Error: {}", self.msg)
}
}
/// `ClientError` enumerates all the possible errors that a public
/// client (request) function of this library might be given.
#[derive(Debug)]
pub enum ClientError {
/// Read the documentation for `RequestError`
/// for more information on this error.
Http(RequestError),
/// Read the documentation for `InternalError`
/// for more information on this error..
Internal(InternalError)
}
/// Allowing `ClientError` to be printed via `{}` in a controlled manner.
impl fmt::Display for ClientError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&ClientError::Http(ref e) => write!(f, "{}", e),
&ClientError::Internal(ref e) => write!(f, "{}", e),
}
}
}
/// Simplistic function internally used to check
/// if a returned status code is positive.
/// Which means that the request was succesful.
pub fn | (code: u32) -> bool {
code == STATUS_OK
}
| check_status_code | identifier_name |
error.rs | use rustc_serialize::json;
use rustc_serialize::Decoder;
use rustc_serialize::Decodable;
use std::str;
use std::fmt;
/// Documentation References:
/// https://developer.github.com/v3/#client-errors
/// `ErrorCode` represents the type of error that was reported
/// as a response on a request to th Github API.
#[derive(Debug)]
pub enum ErrorCode {
/// This means a resource does not exist.
Missing,
/// This means a required field on a resource has not been set.
MissingField,
/// This means the formatting of a field is invalid.
/// The documentation for that resource should be able
/// to give you more specific information.
Invalid,
/// This means another resource has the same value as this field.
/// This can happen in resources that must
/// have some unique key (such as Label names).
AlreadyExists,
/// `Unknown(String)` is used as a last resort when an error code is unknown.
/// This should never happen, please report/resolve the issue when it does happen. | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let msg: &str = match *self {
ErrorCode::Missing => "resource does not exist",
ErrorCode::MissingField => "required field on the resource has not been set",
ErrorCode::Invalid => "the formatting of the field is invalid",
ErrorCode::AlreadyExists => "another resource has the same value as this field",
ErrorCode::Unknown(ref s) => &s,
};
write!(f, "{}", msg)
}
}
/// Allowing `ErrorCode` to be decoded from json values.
/// Linked to the `error` key as defind by the `ErrorContext` struct's member.
impl Decodable for ErrorCode {
fn decode<D: Decoder>(d: &mut D) -> Result<ErrorCode, D::Error> {
match d.read_str() {
Ok(code) => Ok(match &*code {
"missing" => ErrorCode::Missing,
"missing_field" => ErrorCode::MissingField,
"invalid" => ErrorCode::Invalid,
"already_exists" => ErrorCode::AlreadyExists,
unknown => ErrorCode::Unknown(unknown.to_string()),
}),
Err(err) => Err(err),
}
}
}
/// When a request was successful.
const STATUS_OK: u32 = 200;
/// There was a problem with the data sent with the request.
const STATUS_BAD_REQUEST: u32 = 400;
/// Given as a response to requests the user has insufficient permissions for.
const STATUS_FORBIDDEN: u32 = 403;
/// Given when the info requested is not found because it
/// either doesn't exist or because you are not authorized.
const STATUS_NOT_FOUND: u32 = 404;
/// Given when a field or resource couldn't be processed properly.
const STATUS_UNPROCCESSABLE_ENTITY: u32 = 422;
/// When a negative status was given as a response to a request,
/// there might be one or several error descriptions embedded in the
/// body to tell more about the details of what was wrong.
/// `ErrorContext` is the representation for each of the errors that are given.
#[derive(RustcDecodable, Debug)]
pub struct ErrorContext {
pub resource: String,
pub field: String,
pub code: ErrorCode,
}
/// Allowing `ErrorContext` to be printed via `{}` in a controlled manner.
impl fmt::Display for ErrorContext {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Error found in {}.{}: {}", self.resource, self.field, self.code)
}
}
/// `ErrorStatus` represents the status code given in the header of a negative response.
/// Look at const definitions such as `STATUS_OK` for more information for each value.
#[derive(Debug)]
pub enum ErrorStatus{
BadRequest,
UnprocessableEntity,
Forbidden,
NotFound,
Unknown(u32),
}
/// Allowing `ErrorStatus` to be printed via `{}` in a controlled manner.
impl fmt::Display for ErrorStatus {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let (code, msg) = match *self {
ErrorStatus::BadRequest => (STATUS_BAD_REQUEST, "Bad Request"),
ErrorStatus::UnprocessableEntity => (STATUS_UNPROCCESSABLE_ENTITY, "Unprocessable Entity"),
ErrorStatus::Forbidden => (STATUS_FORBIDDEN, "Forbidden Request"),
ErrorStatus::NotFound => (STATUS_NOT_FOUND, "Not Found"),
ErrorStatus::Unknown(e) => (e, "Unknown"),
};
write!(f, "status {}: {}", code, msg)
}
}
impl ErrorStatus {
/// Simple way to construct an `ErrorStatus`
/// based on its constant value as defined by the official docs.
pub fn new(code: u32) -> ErrorStatus {
match code {
STATUS_BAD_REQUEST => ErrorStatus::BadRequest,
STATUS_FORBIDDEN => ErrorStatus::Forbidden,
STATUS_UNPROCCESSABLE_ENTITY => ErrorStatus::UnprocessableEntity,
STATUS_NOT_FOUND => ErrorStatus::NotFound,
unknown => ErrorStatus::Unknown(unknown),
}
}
}
/// `RequestError` will be returned as a `Result<T, ClientError>` in case
/// a request responds negatively populated by information from
/// both the header and body.
#[derive(Debug)]
pub struct RequestError {
/// `code` represents the given status code
/// stored in the form of `ErrorStatus`.
pub code: ErrorStatus,
/// In case detailed errors are available
// they will be accessible via `errors`, stored as an `ErrorContext`.
pub errors: Vec<ErrorContext>,
}
impl RequestError {
/// Simple way to construct a `Result<T, ClientError>` based on
/// the status code given in the header and the body in a raw utf8 buffer.
pub fn new<T>(code: u32, buffer: &[u8]) -> Result<T, ClientError> {
Err(ClientError::Http(RequestError {
code: ErrorStatus::new(code),
errors: match str::from_utf8(buffer) {
Err(..) => Vec::new(),
Ok(body) => json::decode(body).unwrap_or(Vec::new()),
},
}))
}
}
/// Allowing `RequestError` to be printed via `{}` in a controlled manner.
impl fmt::Display for RequestError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "HTTP Error: {}. Found {} error description(s)!", self.code, self.errors.len())
}
}
/// `InternalError` will be given in the form of Result<T, ClientError> in
/// case something went wrong within this Client Library.
/// It replaces panics so that you can freely choose the behaviour.
/// Please file an issue and/or resolve the bug yourself when you get this error.
#[derive(Debug)]
pub struct InternalError {
/// `msg` is the actual description of the problem.
/// future versions of this library might store extra info
/// where it would help the debugging of an error.
pub msg: String,
}
impl InternalError {
/// Simple way to construct a `Result<T, ClientError>` based on
/// information known for an internal error.
pub fn new<T>(msg: &str) -> Result<T, ClientError> {
Err(ClientError::Internal(InternalError { msg: msg.to_string() }))
}
}
/// Allowing `InternalError` to be printed via `{}` in a controlled manner.
impl fmt::Display for InternalError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Internal Error: {}", self.msg)
}
}
/// `ClientError` enumerates all the possible errors that a public
/// client (request) function of this library might be given.
#[derive(Debug)]
pub enum ClientError {
/// Read the documentation for `RequestError`
/// for more information on this error.
Http(RequestError),
/// Read the documentation for `InternalError`
/// for more information on this error..
Internal(InternalError)
}
/// Allowing `ClientError` to be printed via `{}` in a controlled manner.
impl fmt::Display for ClientError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&ClientError::Http(ref e) => write!(f, "{}", e),
&ClientError::Internal(ref e) => write!(f, "{}", e),
}
}
}
/// Simplistic function internally used to check
/// if a returned status code is positive.
/// Which means that the request was succesful.
pub fn check_status_code(code: u32) -> bool {
code == STATUS_OK
} | Unknown(String),
}
/// Allowing `ErrorCode` to be printed via `{}`.
impl fmt::Display for ErrorCode { | random_line_split |
check_internal.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/gfx/check_internal.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Provides a handy macro to check the outcome
of an OpenGL call for errors -- use it everywhere.
*/
#[cfg(check_gl)]
#[macro_escape] | {
use gl2 = opengles::gl2;
use log::Log;
let err = gl2::get_error();
if err != gl2::NO_ERROR
{
log_error!(func);
log_fail!(util::get_err_str(err));
}
}
#[cfg(not(check_gl))]
pub fn check_gl(_func: &str)
{ }
macro_rules! check
(
($func:expr) =>
({
let ret = $func;
check::check_gl(stringify!($func));
ret
});
)
macro_rules! check_unsafe
(
($func:expr) =>
({
unsafe { check!($func) }
});
) | #[path = "../log/macros.rs"]
mod macros;
#[cfg(check_gl)]
pub fn check_gl(func: &str) | random_line_split |
check_internal.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/gfx/check_internal.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Provides a handy macro to check the outcome
of an OpenGL call for errors -- use it everywhere.
*/
#[cfg(check_gl)]
#[macro_escape]
#[path = "../log/macros.rs"]
mod macros;
#[cfg(check_gl)]
pub fn check_gl(func: &str)
{
use gl2 = opengles::gl2;
use log::Log;
let err = gl2::get_error();
if err != gl2::NO_ERROR
{
log_error!(func);
log_fail!(util::get_err_str(err));
}
}
#[cfg(not(check_gl))]
pub fn | (_func: &str)
{ }
macro_rules! check
(
($func:expr) =>
({
let ret = $func;
check::check_gl(stringify!($func));
ret
});
)
macro_rules! check_unsafe
(
($func:expr) =>
({
unsafe { check!($func) }
});
)
| check_gl | identifier_name |
check_internal.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/gfx/check_internal.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Provides a handy macro to check the outcome
of an OpenGL call for errors -- use it everywhere.
*/
#[cfg(check_gl)]
#[macro_escape]
#[path = "../log/macros.rs"]
mod macros;
#[cfg(check_gl)]
pub fn check_gl(func: &str)
{
use gl2 = opengles::gl2;
use log::Log;
let err = gl2::get_error();
if err != gl2::NO_ERROR
{
log_error!(func);
log_fail!(util::get_err_str(err));
}
}
#[cfg(not(check_gl))]
pub fn check_gl(_func: &str)
|
macro_rules! check
(
($func:expr) =>
({
let ret = $func;
check::check_gl(stringify!($func));
ret
});
)
macro_rules! check_unsafe
(
($func:expr) =>
({
unsafe { check!($func) }
});
)
| { } | identifier_body |
check_internal.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/gfx/check_internal.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Provides a handy macro to check the outcome
of an OpenGL call for errors -- use it everywhere.
*/
#[cfg(check_gl)]
#[macro_escape]
#[path = "../log/macros.rs"]
mod macros;
#[cfg(check_gl)]
pub fn check_gl(func: &str)
{
use gl2 = opengles::gl2;
use log::Log;
let err = gl2::get_error();
if err != gl2::NO_ERROR
|
}
#[cfg(not(check_gl))]
pub fn check_gl(_func: &str)
{ }
macro_rules! check
(
($func:expr) =>
({
let ret = $func;
check::check_gl(stringify!($func));
ret
});
)
macro_rules! check_unsafe
(
($func:expr) =>
({
unsafe { check!($func) }
});
)
| {
log_error!(func);
log_fail!(util::get_err_str(err));
} | conditional_block |
brief_forms.py | from wtforms import IntegerField, SelectMultipleField
from wtforms.validators import NumberRange
from dmutils.forms import DmForm
import flask_featureflags
class BriefSearchForm(DmForm):
| page = IntegerField(default=1, validators=(NumberRange(min=1),))
status = SelectMultipleField("Status", choices=(
("live", "Open",),
("closed", "Closed",)
))
# lot choices expected to be set at runtime
lot = SelectMultipleField("Category")
def __init__(self, *args, **kwargs):
"""
Requires extra keyword arguments:
- `framework` - information on the target framework as returned by the api
- `data_api_client` - a data api client (should be able to remove the need for this arg at some point)
"""
super(BriefSearchForm, self).__init__(*args, **kwargs)
try:
# popping this kwarg so we don't risk it getting fed to wtforms default implementation which might use it
# as a data field if there were a name collision
framework = kwargs.pop("framework")
self._framework_slug = framework["slug"]
self.lot.choices = tuple((lot["slug"], lot["name"],) for lot in framework["lots"] if lot["allowsBrief"])
except KeyError:
raise TypeError("Expected keyword argument 'framework' with framework information")
try:
# data_api_client argument only needed so we can fit in with the current way the tests mock.patch the
# the data_api_client directly on the view. would be nice to able to use the global reference to this
self._data_api_client = kwargs.pop("data_api_client")
except KeyError:
raise TypeError("Expected keyword argument 'data_api_client'")
def get_briefs(self):
if not self.validate():
raise ValueError("Invalid form")
statuses = self.status.data or tuple(id for id, label in self.status.choices)
lots = self.lot.data or tuple(id for id, label in self.lot.choices)
# disable framework filtering when digital marketplace framework is live
kwargs = {} if flask_featureflags.is_active('DM_FRAMEWORK') else {"framework": self._framework_slug}
return self._data_api_client.find_briefs(
status=",".join(statuses),
lot=",".join(lots),
page=self.page.data,
per_page=75,
human=True,
**kwargs
)
def get_filters(self):
"""
generate the same "filters" structure as expected by search page templates
"""
if not self.validate():
raise ValueError("Invalid form")
return [
{
"label": field.label,
"filters": [
{
"label": choice_label,
"name": field.name,
"id": "{}-{}".format(field.id, choice_id),
"value": choice_id,
"checked": field.data and choice_id in field.data,
}
for choice_id, choice_label in field.choices
],
}
for field in (self.lot, self.status,)
]
def filters_applied(self):
"""
returns boolean indicating whether the results are actually filtered at all
"""
if not self.validate():
raise ValueError("Invalid form")
return bool(self.lot.data or self.status.data) | identifier_body | |
brief_forms.py | from wtforms import IntegerField, SelectMultipleField
from wtforms.validators import NumberRange
from dmutils.forms import DmForm
import flask_featureflags
class BriefSearchForm(DmForm):
page = IntegerField(default=1, validators=(NumberRange(min=1),))
status = SelectMultipleField("Status", choices=(
("live", "Open",),
("closed", "Closed",)
))
# lot choices expected to be set at runtime
lot = SelectMultipleField("Category")
def __init__(self, *args, **kwargs):
"""
Requires extra keyword arguments:
- `framework` - information on the target framework as returned by the api
- `data_api_client` - a data api client (should be able to remove the need for this arg at some point)
"""
super(BriefSearchForm, self).__init__(*args, **kwargs)
try:
# popping this kwarg so we don't risk it getting fed to wtforms default implementation which might use it
# as a data field if there were a name collision
framework = kwargs.pop("framework")
self._framework_slug = framework["slug"]
self.lot.choices = tuple((lot["slug"], lot["name"],) for lot in framework["lots"] if lot["allowsBrief"])
except KeyError:
raise TypeError("Expected keyword argument 'framework' with framework information")
try:
# data_api_client argument only needed so we can fit in with the current way the tests mock.patch the
# the data_api_client directly on the view. would be nice to able to use the global reference to this
self._data_api_client = kwargs.pop("data_api_client")
except KeyError:
raise TypeError("Expected keyword argument 'data_api_client'")
def | (self):
if not self.validate():
raise ValueError("Invalid form")
statuses = self.status.data or tuple(id for id, label in self.status.choices)
lots = self.lot.data or tuple(id for id, label in self.lot.choices)
# disable framework filtering when digital marketplace framework is live
kwargs = {} if flask_featureflags.is_active('DM_FRAMEWORK') else {"framework": self._framework_slug}
return self._data_api_client.find_briefs(
status=",".join(statuses),
lot=",".join(lots),
page=self.page.data,
per_page=75,
human=True,
**kwargs
)
def get_filters(self):
"""
generate the same "filters" structure as expected by search page templates
"""
if not self.validate():
raise ValueError("Invalid form")
return [
{
"label": field.label,
"filters": [
{
"label": choice_label,
"name": field.name,
"id": "{}-{}".format(field.id, choice_id),
"value": choice_id,
"checked": field.data and choice_id in field.data,
}
for choice_id, choice_label in field.choices
],
}
for field in (self.lot, self.status,)
]
def filters_applied(self):
"""
returns boolean indicating whether the results are actually filtered at all
"""
if not self.validate():
raise ValueError("Invalid form")
return bool(self.lot.data or self.status.data)
| get_briefs | identifier_name |
brief_forms.py | from wtforms import IntegerField, SelectMultipleField
from wtforms.validators import NumberRange
from dmutils.forms import DmForm
import flask_featureflags
class BriefSearchForm(DmForm):
page = IntegerField(default=1, validators=(NumberRange(min=1),))
status = SelectMultipleField("Status", choices=(
("live", "Open",),
("closed", "Closed",)
))
# lot choices expected to be set at runtime
lot = SelectMultipleField("Category")
def __init__(self, *args, **kwargs):
"""
Requires extra keyword arguments:
- `framework` - information on the target framework as returned by the api
- `data_api_client` - a data api client (should be able to remove the need for this arg at some point)
"""
super(BriefSearchForm, self).__init__(*args, **kwargs)
try:
# popping this kwarg so we don't risk it getting fed to wtforms default implementation which might use it
# as a data field if there were a name collision
framework = kwargs.pop("framework")
self._framework_slug = framework["slug"]
self.lot.choices = tuple((lot["slug"], lot["name"],) for lot in framework["lots"] if lot["allowsBrief"])
except KeyError:
raise TypeError("Expected keyword argument 'framework' with framework information")
try:
# data_api_client argument only needed so we can fit in with the current way the tests mock.patch the
# the data_api_client directly on the view. would be nice to able to use the global reference to this
self._data_api_client = kwargs.pop("data_api_client")
except KeyError:
raise TypeError("Expected keyword argument 'data_api_client'")
def get_briefs(self):
if not self.validate():
raise ValueError("Invalid form")
statuses = self.status.data or tuple(id for id, label in self.status.choices) | return self._data_api_client.find_briefs(
status=",".join(statuses),
lot=",".join(lots),
page=self.page.data,
per_page=75,
human=True,
**kwargs
)
def get_filters(self):
"""
generate the same "filters" structure as expected by search page templates
"""
if not self.validate():
raise ValueError("Invalid form")
return [
{
"label": field.label,
"filters": [
{
"label": choice_label,
"name": field.name,
"id": "{}-{}".format(field.id, choice_id),
"value": choice_id,
"checked": field.data and choice_id in field.data,
}
for choice_id, choice_label in field.choices
],
}
for field in (self.lot, self.status,)
]
def filters_applied(self):
"""
returns boolean indicating whether the results are actually filtered at all
"""
if not self.validate():
raise ValueError("Invalid form")
return bool(self.lot.data or self.status.data) | lots = self.lot.data or tuple(id for id, label in self.lot.choices)
# disable framework filtering when digital marketplace framework is live
kwargs = {} if flask_featureflags.is_active('DM_FRAMEWORK') else {"framework": self._framework_slug}
| random_line_split |
brief_forms.py | from wtforms import IntegerField, SelectMultipleField
from wtforms.validators import NumberRange
from dmutils.forms import DmForm
import flask_featureflags
class BriefSearchForm(DmForm):
page = IntegerField(default=1, validators=(NumberRange(min=1),))
status = SelectMultipleField("Status", choices=(
("live", "Open",),
("closed", "Closed",)
))
# lot choices expected to be set at runtime
lot = SelectMultipleField("Category")
def __init__(self, *args, **kwargs):
"""
Requires extra keyword arguments:
- `framework` - information on the target framework as returned by the api
- `data_api_client` - a data api client (should be able to remove the need for this arg at some point)
"""
super(BriefSearchForm, self).__init__(*args, **kwargs)
try:
# popping this kwarg so we don't risk it getting fed to wtforms default implementation which might use it
# as a data field if there were a name collision
framework = kwargs.pop("framework")
self._framework_slug = framework["slug"]
self.lot.choices = tuple((lot["slug"], lot["name"],) for lot in framework["lots"] if lot["allowsBrief"])
except KeyError:
raise TypeError("Expected keyword argument 'framework' with framework information")
try:
# data_api_client argument only needed so we can fit in with the current way the tests mock.patch the
# the data_api_client directly on the view. would be nice to able to use the global reference to this
self._data_api_client = kwargs.pop("data_api_client")
except KeyError:
raise TypeError("Expected keyword argument 'data_api_client'")
def get_briefs(self):
if not self.validate():
raise ValueError("Invalid form")
statuses = self.status.data or tuple(id for id, label in self.status.choices)
lots = self.lot.data or tuple(id for id, label in self.lot.choices)
# disable framework filtering when digital marketplace framework is live
kwargs = {} if flask_featureflags.is_active('DM_FRAMEWORK') else {"framework": self._framework_slug}
return self._data_api_client.find_briefs(
status=",".join(statuses),
lot=",".join(lots),
page=self.page.data,
per_page=75,
human=True,
**kwargs
)
def get_filters(self):
"""
generate the same "filters" structure as expected by search page templates
"""
if not self.validate():
|
return [
{
"label": field.label,
"filters": [
{
"label": choice_label,
"name": field.name,
"id": "{}-{}".format(field.id, choice_id),
"value": choice_id,
"checked": field.data and choice_id in field.data,
}
for choice_id, choice_label in field.choices
],
}
for field in (self.lot, self.status,)
]
def filters_applied(self):
"""
returns boolean indicating whether the results are actually filtered at all
"""
if not self.validate():
raise ValueError("Invalid form")
return bool(self.lot.data or self.status.data)
| raise ValueError("Invalid form") | conditional_block |
accessibilityHelp.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/css!./accessibilityHelp';
import * as nls from 'vs/nls';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { Disposable } from 'vs/base/common/lifecycle';
import * as strings from 'vs/base/common/strings';
import * as dom from 'vs/base/browser/dom';
import { renderFormattedText } from 'vs/base/browser/htmlContentRenderer';
import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode';
import { Widget } from 'vs/base/browser/ui/widget';
import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { RawContextKey, IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { ICommonCodeEditor, IEditorContribution } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { editorAction, CommonEditorRegistry, EditorAction, EditorCommand } from 'vs/editor/common/editorCommonExtensions';
import { ICodeEditor, IOverlayWidget, IOverlayWidgetPosition } from 'vs/editor/browser/editorBrowser';
import { editorContribution } from 'vs/editor/browser/editorBrowserExtensions';
import { ToggleTabFocusModeAction } from 'vs/editor/contrib/toggleTabFocusMode/common/toggleTabFocusMode';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { editorWidgetBackground, widgetShadow, contrastBorder } from 'vs/platform/theme/common/colorRegistry';
import * as platform from 'vs/base/common/platform';
import { alert } from 'vs/base/browser/ui/aria/aria';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import URI from 'vs/base/common/uri';
import { Selection } from 'vs/editor/common/core/selection';
import * as browser from 'vs/base/browser/browser';
import { IEditorConstructionOptions } from 'vs/editor/standalone/browser/standaloneCodeEditor';
const CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE = new RawContextKey<boolean>('accessibilityHelpWidgetVisible', false);
@editorContribution
class AccessibilityHelpController extends Disposable
implements IEditorContribution {
private static ID = 'editor.contrib.accessibilityHelpController';
public static get(editor: ICommonCodeEditor): AccessibilityHelpController {
return editor.getContribution<AccessibilityHelpController>(
AccessibilityHelpController.ID
);
}
private _editor: ICodeEditor;
private _widget: AccessibilityHelpWidget;
constructor(
editor: ICodeEditor,
@IInstantiationService instantiationService: IInstantiationService
) {
super();
this._editor = editor;
this._widget = this._register(
instantiationService.createInstance(AccessibilityHelpWidget, this._editor)
);
}
public getId(): string {
return AccessibilityHelpController.ID;
}
public | (): void {
this._widget.show();
}
public hide(): void {
this._widget.hide();
}
}
const nlsNoSelection = nls.localize("noSelection", "No selection");
const nlsSingleSelectionRange = nls.localize("singleSelectionRange", "Line {0}, Column {1} ({2} selected)");
const nlsSingleSelection = nls.localize("singleSelection", "Line {0}, Column {1}");
const nlsMultiSelectionRange = nls.localize("multiSelectionRange", "{0} selections ({1} characters selected)");
const nlsMultiSelection = nls.localize("multiSelection", "{0} selections");
function getSelectionLabel(selections: Selection[], charactersSelected: number): string {
if (!selections || selections.length === 0) {
return nlsNoSelection;
}
if (selections.length === 1) {
if (charactersSelected) {
return strings.format(nlsSingleSelectionRange, selections[0].positionLineNumber, selections[0].positionColumn, charactersSelected);
}
return strings.format(nlsSingleSelection, selections[0].positionLineNumber, selections[0].positionColumn);
}
if (charactersSelected) {
return strings.format(nlsMultiSelectionRange, selections.length, charactersSelected);
}
if (selections.length > 0) {
return strings.format(nlsMultiSelection, selections.length);
}
return null;
}
class AccessibilityHelpWidget extends Widget implements IOverlayWidget {
private static ID = 'editor.contrib.accessibilityHelpWidget';
private static WIDTH = 500;
private static HEIGHT = 300;
private _editor: ICodeEditor;
private _domNode: FastDomNode<HTMLElement>;
private _contentDomNode: FastDomNode<HTMLElement>;
private _isVisible: boolean;
private _isVisibleKey: IContextKey<boolean>;
constructor(
editor: ICodeEditor,
@IContextKeyService private _contextKeyService: IContextKeyService,
@IKeybindingService private _keybindingService: IKeybindingService,
@IOpenerService private _openerService: IOpenerService
) {
super();
this._editor = editor;
this._isVisibleKey = CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE.bindTo(
this._contextKeyService
);
this._domNode = createFastDomNode(document.createElement('div'));
this._domNode.setClassName('accessibilityHelpWidget');
this._domNode.setDisplay('none');
this._domNode.setAttribute('role', 'dialog');
this._domNode.setAttribute('aria-hidden', 'true');
this._contentDomNode = createFastDomNode(document.createElement('div'));
this._contentDomNode.setAttribute('role', 'document');
this._domNode.appendChild(this._contentDomNode);
this._isVisible = false;
this._register(this._editor.onDidLayoutChange(() => {
if (this._isVisible) {
this._layout();
}
}));
// Intentionally not configurable!
this._register(dom.addStandardDisposableListener(this._contentDomNode.domNode, 'keydown', (e) => {
if (!this._isVisible) {
return;
}
if (e.equals(KeyMod.CtrlCmd | KeyCode.KEY_E)) {
alert(nls.localize("emergencyConfOn", "Now changing the setting `accessibilitySupport` to 'on'."));
this._editor.updateOptions({
accessibilitySupport: 'on'
});
dom.clearNode(this._contentDomNode.domNode);
this._buildContent();
this._contentDomNode.domNode.focus();
e.preventDefault();
e.stopPropagation();
}
if (e.equals(KeyMod.CtrlCmd | KeyCode.KEY_H)) {
alert(nls.localize("openingDocs", "Now opening the Editor Accessibility documentation page."));
let url = (<IEditorConstructionOptions>this._editor.getRawConfiguration()).accessibilityHelpUrl;
if (typeof url === 'undefined') {
url = 'https://go.microsoft.com/fwlink/?linkid=852450';
}
this._openerService.open(URI.parse(url));
e.preventDefault();
e.stopPropagation();
}
}));
this.onblur(this._contentDomNode.domNode, () => {
this.hide();
});
this._editor.addOverlayWidget(this);
}
public dispose(): void {
this._editor.removeOverlayWidget(this);
super.dispose();
}
public getId(): string {
return AccessibilityHelpWidget.ID;
}
public getDomNode(): HTMLElement {
return this._domNode.domNode;
}
public getPosition(): IOverlayWidgetPosition {
return {
preference: null
};
}
public show(): void {
if (this._isVisible) {
return;
}
this._isVisible = true;
this._isVisibleKey.set(true);
this._layout();
this._domNode.setDisplay('block');
this._domNode.setAttribute('aria-hidden', 'false');
this._contentDomNode.domNode.tabIndex = 0;
this._buildContent();
this._contentDomNode.domNode.focus();
}
private _descriptionForCommand(commandId: string, msg: string, noKbMsg: string): string {
let kb = this._keybindingService.lookupKeybinding(commandId);
if (kb) {
return strings.format(msg, kb.getAriaLabel());
}
return strings.format(noKbMsg, commandId);
}
private _buildContent() {
let opts = this._editor.getConfiguration();
const selections = this._editor.getSelections();
let charactersSelected = 0;
if (selections) {
const model = this._editor.getModel();
if (model) {
selections.forEach((selection) => {
charactersSelected += model.getValueLengthInRange(selection);
});
}
}
let text = getSelectionLabel(selections, charactersSelected);
if (opts.wrappingInfo.inDiffEditor) {
if (opts.readOnly) {
text += nls.localize("readonlyDiffEditor", " in a read-only pane of a diff editor.");
} else {
text += nls.localize("editableDiffEditor", " in a pane of a diff editor.");
}
} else {
if (opts.readOnly) {
text += nls.localize("readonlyEditor", " in a read-only code editor");
} else {
text += nls.localize("editableEditor", " in a code editor");
}
}
switch (opts.accessibilitySupport) {
case platform.AccessibilitySupport.Unknown:
const turnOnMessage = (
platform.isMacintosh
? nls.localize("changeConfigToOnMac", "To configure the editor to be optimized for usage with a Screen Reader press Command+E now.")
: nls.localize("changeConfigToOnWinLinux", "To configure the editor to be optimized for usage with a Screen Reader press Control+E now.")
);
text += '\n\n - ' + turnOnMessage;
break;
case platform.AccessibilitySupport.Enabled:
text += '\n\n - ' + nls.localize("auto_on", "The editor is configured to be optimized for usage with a Screen Reader.");
break;
case platform.AccessibilitySupport.Disabled:
text += '\n\n - ' + nls.localize("auto_off", "The editor is configured to never be optimized for usage with a Screen Reader, which is not the case at this time.");
text += ' ' + turnOnMessage;
break;
}
const NLS_TAB_FOCUS_MODE_ON = nls.localize("tabFocusModeOnMsg", "Pressing Tab in the current editor will move focus to the next focusable element. Toggle this behavior by pressing {0}.");
const NLS_TAB_FOCUS_MODE_ON_NO_KB = nls.localize("tabFocusModeOnMsgNoKb", "Pressing Tab in the current editor will move focus to the next focusable element. The command {0} is currently not triggerable by a keybinding.");
const NLS_TAB_FOCUS_MODE_OFF = nls.localize("tabFocusModeOffMsg", "Pressing Tab in the current editor will insert the tab character. Toggle this behavior by pressing {0}.");
const NLS_TAB_FOCUS_MODE_OFF_NO_KB = nls.localize("tabFocusModeOffMsgNoKb", "Pressing Tab in the current editor will insert the tab character. The command {0} is currently not triggerable by a keybinding.");
if (opts.tabFocusMode) {
text += '\n\n - ' + this._descriptionForCommand(ToggleTabFocusModeAction.ID, NLS_TAB_FOCUS_MODE_ON, NLS_TAB_FOCUS_MODE_ON_NO_KB);
} else {
text += '\n\n - ' + this._descriptionForCommand(ToggleTabFocusModeAction.ID, NLS_TAB_FOCUS_MODE_OFF, NLS_TAB_FOCUS_MODE_OFF_NO_KB);
}
const openDocMessage = (
platform.isMacintosh
? nls.localize("openDocMac", "Press Command+H now to open a browser window with more information related to editor accessibility.")
: nls.localize("openDocWinLinux", "Press Control+H now to open a browser window with more information related to editor accessibility.")
);
text += '\n\n - ' + openDocMessage;
text += '\n\n' + nls.localize("outroMsg", "You can dismiss this tooltip and return to the editor by pressing Escape or Shift+Escape.");
this._contentDomNode.domNode.appendChild(renderFormattedText(text));
// Per https://www.w3.org/TR/wai-aria/roles#document, Authors SHOULD provide a title or label for documents
this._contentDomNode.domNode.setAttribute('aria-label', text);
}
public hide(): void {
if (!this._isVisible) {
return;
}
this._isVisible = false;
this._isVisibleKey.reset();
this._domNode.setDisplay('none');
this._domNode.setAttribute('aria-hidden', 'true');
this._contentDomNode.domNode.tabIndex = -1;
dom.clearNode(this._contentDomNode.domNode);
this._editor.focus();
}
private _layout(): void {
let editorLayout = this._editor.getLayoutInfo();
let w = Math.max(5, Math.min(AccessibilityHelpWidget.WIDTH, editorLayout.width - 40));
let h = Math.max(5, Math.min(AccessibilityHelpWidget.HEIGHT, editorLayout.height - 40));
this._domNode.setWidth(w);
this._domNode.setHeight(h);
let top = Math.round((editorLayout.height - h) / 2);
this._domNode.setTop(top);
let left = Math.round((editorLayout.width - w) / 2);
this._domNode.setLeft(left);
}
}
@editorAction
class ShowAccessibilityHelpAction extends EditorAction {
constructor() {
super({
id: 'editor.action.showAccessibilityHelp',
label: nls.localize("ShowAccessibilityHelpAction", "Show Accessibility Help"),
alias: 'Show Accessibility Help',
precondition: null,
kbOpts: {
kbExpr: EditorContextKeys.focus,
primary: (browser.isIE ? KeyMod.CtrlCmd | KeyCode.F1 : KeyMod.Alt | KeyCode.F1)
}
});
}
public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void {
let controller = AccessibilityHelpController.get(editor);
if (controller) {
controller.show();
}
}
}
const AccessibilityHelpCommand = EditorCommand.bindToContribution<AccessibilityHelpController>(AccessibilityHelpController.get);
CommonEditorRegistry.registerEditorCommand(
new AccessibilityHelpCommand({
id: 'closeAccessibilityHelp',
precondition: CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE,
handler: x => x.hide(),
kbOpts: {
weight: CommonEditorRegistry.commandWeight(100),
kbExpr: EditorContextKeys.focus,
primary: KeyCode.Escape,
secondary: [KeyMod.Shift | KeyCode.Escape]
}
})
);
registerThemingParticipant((theme, collector) => {
let widgetBackground = theme.getColor(editorWidgetBackground);
if (widgetBackground) {
collector.addRule(`.monaco-editor .accessibilityHelpWidget { background-color: ${widgetBackground}; }`);
}
let widgetShadowColor = theme.getColor(widgetShadow);
if (widgetShadowColor) {
collector.addRule(`.monaco-editor .accessibilityHelpWidget { box-shadow: 0 2px 8px ${widgetShadowColor}; }`);
}
let hcBorder = theme.getColor(contrastBorder);
if (hcBorder) {
collector.addRule(`.monaco-editor .accessibilityHelpWidget { border: 2px solid ${hcBorder}; }`);
}
});
| show | identifier_name |
accessibilityHelp.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/css!./accessibilityHelp';
import * as nls from 'vs/nls';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { Disposable } from 'vs/base/common/lifecycle';
import * as strings from 'vs/base/common/strings';
import * as dom from 'vs/base/browser/dom';
import { renderFormattedText } from 'vs/base/browser/htmlContentRenderer';
import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode';
import { Widget } from 'vs/base/browser/ui/widget';
import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { RawContextKey, IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { ICommonCodeEditor, IEditorContribution } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { editorAction, CommonEditorRegistry, EditorAction, EditorCommand } from 'vs/editor/common/editorCommonExtensions';
import { ICodeEditor, IOverlayWidget, IOverlayWidgetPosition } from 'vs/editor/browser/editorBrowser';
import { editorContribution } from 'vs/editor/browser/editorBrowserExtensions';
import { ToggleTabFocusModeAction } from 'vs/editor/contrib/toggleTabFocusMode/common/toggleTabFocusMode';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { editorWidgetBackground, widgetShadow, contrastBorder } from 'vs/platform/theme/common/colorRegistry';
import * as platform from 'vs/base/common/platform';
import { alert } from 'vs/base/browser/ui/aria/aria';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import URI from 'vs/base/common/uri';
import { Selection } from 'vs/editor/common/core/selection';
import * as browser from 'vs/base/browser/browser';
import { IEditorConstructionOptions } from 'vs/editor/standalone/browser/standaloneCodeEditor';
const CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE = new RawContextKey<boolean>('accessibilityHelpWidgetVisible', false);
@editorContribution
class AccessibilityHelpController extends Disposable
implements IEditorContribution {
private static ID = 'editor.contrib.accessibilityHelpController';
public static get(editor: ICommonCodeEditor): AccessibilityHelpController {
return editor.getContribution<AccessibilityHelpController>(
AccessibilityHelpController.ID
);
}
private _editor: ICodeEditor;
private _widget: AccessibilityHelpWidget;
constructor(
editor: ICodeEditor,
@IInstantiationService instantiationService: IInstantiationService
) {
super();
this._editor = editor;
this._widget = this._register(
instantiationService.createInstance(AccessibilityHelpWidget, this._editor)
);
}
public getId(): string {
return AccessibilityHelpController.ID;
}
public show(): void {
this._widget.show();
}
public hide(): void {
this._widget.hide();
}
}
const nlsNoSelection = nls.localize("noSelection", "No selection");
const nlsSingleSelectionRange = nls.localize("singleSelectionRange", "Line {0}, Column {1} ({2} selected)");
const nlsSingleSelection = nls.localize("singleSelection", "Line {0}, Column {1}");
const nlsMultiSelectionRange = nls.localize("multiSelectionRange", "{0} selections ({1} characters selected)");
const nlsMultiSelection = nls.localize("multiSelection", "{0} selections");
function getSelectionLabel(selections: Selection[], charactersSelected: number): string {
if (!selections || selections.length === 0) {
return nlsNoSelection;
}
if (selections.length === 1) {
if (charactersSelected) {
return strings.format(nlsSingleSelectionRange, selections[0].positionLineNumber, selections[0].positionColumn, charactersSelected);
}
return strings.format(nlsSingleSelection, selections[0].positionLineNumber, selections[0].positionColumn);
}
if (charactersSelected) {
return strings.format(nlsMultiSelectionRange, selections.length, charactersSelected);
}
if (selections.length > 0) {
return strings.format(nlsMultiSelection, selections.length);
}
return null;
}
class AccessibilityHelpWidget extends Widget implements IOverlayWidget {
private static ID = 'editor.contrib.accessibilityHelpWidget';
private static WIDTH = 500;
private static HEIGHT = 300;
private _editor: ICodeEditor;
private _domNode: FastDomNode<HTMLElement>;
private _contentDomNode: FastDomNode<HTMLElement>;
private _isVisible: boolean;
private _isVisibleKey: IContextKey<boolean>;
constructor(
editor: ICodeEditor,
@IContextKeyService private _contextKeyService: IContextKeyService,
@IKeybindingService private _keybindingService: IKeybindingService,
@IOpenerService private _openerService: IOpenerService
) {
super();
this._editor = editor;
this._isVisibleKey = CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE.bindTo(
this._contextKeyService
);
this._domNode = createFastDomNode(document.createElement('div'));
this._domNode.setClassName('accessibilityHelpWidget');
this._domNode.setDisplay('none');
this._domNode.setAttribute('role', 'dialog');
this._domNode.setAttribute('aria-hidden', 'true');
this._contentDomNode = createFastDomNode(document.createElement('div'));
this._contentDomNode.setAttribute('role', 'document');
this._domNode.appendChild(this._contentDomNode);
this._isVisible = false;
this._register(this._editor.onDidLayoutChange(() => {
if (this._isVisible) {
this._layout();
}
}));
// Intentionally not configurable!
this._register(dom.addStandardDisposableListener(this._contentDomNode.domNode, 'keydown', (e) => {
if (!this._isVisible) |
if (e.equals(KeyMod.CtrlCmd | KeyCode.KEY_E)) {
alert(nls.localize("emergencyConfOn", "Now changing the setting `accessibilitySupport` to 'on'."));
this._editor.updateOptions({
accessibilitySupport: 'on'
});
dom.clearNode(this._contentDomNode.domNode);
this._buildContent();
this._contentDomNode.domNode.focus();
e.preventDefault();
e.stopPropagation();
}
if (e.equals(KeyMod.CtrlCmd | KeyCode.KEY_H)) {
alert(nls.localize("openingDocs", "Now opening the Editor Accessibility documentation page."));
let url = (<IEditorConstructionOptions>this._editor.getRawConfiguration()).accessibilityHelpUrl;
if (typeof url === 'undefined') {
url = 'https://go.microsoft.com/fwlink/?linkid=852450';
}
this._openerService.open(URI.parse(url));
e.preventDefault();
e.stopPropagation();
}
}));
this.onblur(this._contentDomNode.domNode, () => {
this.hide();
});
this._editor.addOverlayWidget(this);
}
public dispose(): void {
this._editor.removeOverlayWidget(this);
super.dispose();
}
public getId(): string {
return AccessibilityHelpWidget.ID;
}
public getDomNode(): HTMLElement {
return this._domNode.domNode;
}
public getPosition(): IOverlayWidgetPosition {
return {
preference: null
};
}
public show(): void {
if (this._isVisible) {
return;
}
this._isVisible = true;
this._isVisibleKey.set(true);
this._layout();
this._domNode.setDisplay('block');
this._domNode.setAttribute('aria-hidden', 'false');
this._contentDomNode.domNode.tabIndex = 0;
this._buildContent();
this._contentDomNode.domNode.focus();
}
private _descriptionForCommand(commandId: string, msg: string, noKbMsg: string): string {
let kb = this._keybindingService.lookupKeybinding(commandId);
if (kb) {
return strings.format(msg, kb.getAriaLabel());
}
return strings.format(noKbMsg, commandId);
}
private _buildContent() {
let opts = this._editor.getConfiguration();
const selections = this._editor.getSelections();
let charactersSelected = 0;
if (selections) {
const model = this._editor.getModel();
if (model) {
selections.forEach((selection) => {
charactersSelected += model.getValueLengthInRange(selection);
});
}
}
let text = getSelectionLabel(selections, charactersSelected);
if (opts.wrappingInfo.inDiffEditor) {
if (opts.readOnly) {
text += nls.localize("readonlyDiffEditor", " in a read-only pane of a diff editor.");
} else {
text += nls.localize("editableDiffEditor", " in a pane of a diff editor.");
}
} else {
if (opts.readOnly) {
text += nls.localize("readonlyEditor", " in a read-only code editor");
} else {
text += nls.localize("editableEditor", " in a code editor");
}
}
switch (opts.accessibilitySupport) {
case platform.AccessibilitySupport.Unknown:
const turnOnMessage = (
platform.isMacintosh
? nls.localize("changeConfigToOnMac", "To configure the editor to be optimized for usage with a Screen Reader press Command+E now.")
: nls.localize("changeConfigToOnWinLinux", "To configure the editor to be optimized for usage with a Screen Reader press Control+E now.")
);
text += '\n\n - ' + turnOnMessage;
break;
case platform.AccessibilitySupport.Enabled:
text += '\n\n - ' + nls.localize("auto_on", "The editor is configured to be optimized for usage with a Screen Reader.");
break;
case platform.AccessibilitySupport.Disabled:
text += '\n\n - ' + nls.localize("auto_off", "The editor is configured to never be optimized for usage with a Screen Reader, which is not the case at this time.");
text += ' ' + turnOnMessage;
break;
}
const NLS_TAB_FOCUS_MODE_ON = nls.localize("tabFocusModeOnMsg", "Pressing Tab in the current editor will move focus to the next focusable element. Toggle this behavior by pressing {0}.");
const NLS_TAB_FOCUS_MODE_ON_NO_KB = nls.localize("tabFocusModeOnMsgNoKb", "Pressing Tab in the current editor will move focus to the next focusable element. The command {0} is currently not triggerable by a keybinding.");
const NLS_TAB_FOCUS_MODE_OFF = nls.localize("tabFocusModeOffMsg", "Pressing Tab in the current editor will insert the tab character. Toggle this behavior by pressing {0}.");
const NLS_TAB_FOCUS_MODE_OFF_NO_KB = nls.localize("tabFocusModeOffMsgNoKb", "Pressing Tab in the current editor will insert the tab character. The command {0} is currently not triggerable by a keybinding.");
if (opts.tabFocusMode) {
text += '\n\n - ' + this._descriptionForCommand(ToggleTabFocusModeAction.ID, NLS_TAB_FOCUS_MODE_ON, NLS_TAB_FOCUS_MODE_ON_NO_KB);
} else {
text += '\n\n - ' + this._descriptionForCommand(ToggleTabFocusModeAction.ID, NLS_TAB_FOCUS_MODE_OFF, NLS_TAB_FOCUS_MODE_OFF_NO_KB);
}
const openDocMessage = (
platform.isMacintosh
? nls.localize("openDocMac", "Press Command+H now to open a browser window with more information related to editor accessibility.")
: nls.localize("openDocWinLinux", "Press Control+H now to open a browser window with more information related to editor accessibility.")
);
text += '\n\n - ' + openDocMessage;
text += '\n\n' + nls.localize("outroMsg", "You can dismiss this tooltip and return to the editor by pressing Escape or Shift+Escape.");
this._contentDomNode.domNode.appendChild(renderFormattedText(text));
// Per https://www.w3.org/TR/wai-aria/roles#document, Authors SHOULD provide a title or label for documents
this._contentDomNode.domNode.setAttribute('aria-label', text);
}
public hide(): void {
if (!this._isVisible) {
return;
}
this._isVisible = false;
this._isVisibleKey.reset();
this._domNode.setDisplay('none');
this._domNode.setAttribute('aria-hidden', 'true');
this._contentDomNode.domNode.tabIndex = -1;
dom.clearNode(this._contentDomNode.domNode);
this._editor.focus();
}
private _layout(): void {
let editorLayout = this._editor.getLayoutInfo();
let w = Math.max(5, Math.min(AccessibilityHelpWidget.WIDTH, editorLayout.width - 40));
let h = Math.max(5, Math.min(AccessibilityHelpWidget.HEIGHT, editorLayout.height - 40));
this._domNode.setWidth(w);
this._domNode.setHeight(h);
let top = Math.round((editorLayout.height - h) / 2);
this._domNode.setTop(top);
let left = Math.round((editorLayout.width - w) / 2);
this._domNode.setLeft(left);
}
}
@editorAction
class ShowAccessibilityHelpAction extends EditorAction {
constructor() {
super({
id: 'editor.action.showAccessibilityHelp',
label: nls.localize("ShowAccessibilityHelpAction", "Show Accessibility Help"),
alias: 'Show Accessibility Help',
precondition: null,
kbOpts: {
kbExpr: EditorContextKeys.focus,
primary: (browser.isIE ? KeyMod.CtrlCmd | KeyCode.F1 : KeyMod.Alt | KeyCode.F1)
}
});
}
public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void {
let controller = AccessibilityHelpController.get(editor);
if (controller) {
controller.show();
}
}
}
const AccessibilityHelpCommand = EditorCommand.bindToContribution<AccessibilityHelpController>(AccessibilityHelpController.get);
CommonEditorRegistry.registerEditorCommand(
new AccessibilityHelpCommand({
id: 'closeAccessibilityHelp',
precondition: CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE,
handler: x => x.hide(),
kbOpts: {
weight: CommonEditorRegistry.commandWeight(100),
kbExpr: EditorContextKeys.focus,
primary: KeyCode.Escape,
secondary: [KeyMod.Shift | KeyCode.Escape]
}
})
);
registerThemingParticipant((theme, collector) => {
let widgetBackground = theme.getColor(editorWidgetBackground);
if (widgetBackground) {
collector.addRule(`.monaco-editor .accessibilityHelpWidget { background-color: ${widgetBackground}; }`);
}
let widgetShadowColor = theme.getColor(widgetShadow);
if (widgetShadowColor) {
collector.addRule(`.monaco-editor .accessibilityHelpWidget { box-shadow: 0 2px 8px ${widgetShadowColor}; }`);
}
let hcBorder = theme.getColor(contrastBorder);
if (hcBorder) {
collector.addRule(`.monaco-editor .accessibilityHelpWidget { border: 2px solid ${hcBorder}; }`);
}
});
| {
return;
} | conditional_block |
accessibilityHelp.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/css!./accessibilityHelp';
import * as nls from 'vs/nls';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { Disposable } from 'vs/base/common/lifecycle';
import * as strings from 'vs/base/common/strings';
import * as dom from 'vs/base/browser/dom';
import { renderFormattedText } from 'vs/base/browser/htmlContentRenderer';
import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode';
import { Widget } from 'vs/base/browser/ui/widget';
import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { RawContextKey, IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { ICommonCodeEditor, IEditorContribution } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { editorAction, CommonEditorRegistry, EditorAction, EditorCommand } from 'vs/editor/common/editorCommonExtensions';
import { ICodeEditor, IOverlayWidget, IOverlayWidgetPosition } from 'vs/editor/browser/editorBrowser';
import { editorContribution } from 'vs/editor/browser/editorBrowserExtensions';
import { ToggleTabFocusModeAction } from 'vs/editor/contrib/toggleTabFocusMode/common/toggleTabFocusMode';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { editorWidgetBackground, widgetShadow, contrastBorder } from 'vs/platform/theme/common/colorRegistry';
import * as platform from 'vs/base/common/platform';
import { alert } from 'vs/base/browser/ui/aria/aria';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import URI from 'vs/base/common/uri';
import { Selection } from 'vs/editor/common/core/selection';
import * as browser from 'vs/base/browser/browser';
import { IEditorConstructionOptions } from 'vs/editor/standalone/browser/standaloneCodeEditor';
const CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE = new RawContextKey<boolean>('accessibilityHelpWidgetVisible', false);
@editorContribution
class AccessibilityHelpController extends Disposable
implements IEditorContribution {
private static ID = 'editor.contrib.accessibilityHelpController';
public static get(editor: ICommonCodeEditor): AccessibilityHelpController {
return editor.getContribution<AccessibilityHelpController>(
AccessibilityHelpController.ID
);
}
private _editor: ICodeEditor;
private _widget: AccessibilityHelpWidget;
constructor(
editor: ICodeEditor,
@IInstantiationService instantiationService: IInstantiationService
) {
super();
this._editor = editor;
this._widget = this._register(
instantiationService.createInstance(AccessibilityHelpWidget, this._editor)
);
}
public getId(): string {
return AccessibilityHelpController.ID;
}
public show(): void {
this._widget.show();
}
public hide(): void {
this._widget.hide();
}
}
const nlsNoSelection = nls.localize("noSelection", "No selection");
const nlsSingleSelectionRange = nls.localize("singleSelectionRange", "Line {0}, Column {1} ({2} selected)");
const nlsSingleSelection = nls.localize("singleSelection", "Line {0}, Column {1}");
const nlsMultiSelectionRange = nls.localize("multiSelectionRange", "{0} selections ({1} characters selected)");
const nlsMultiSelection = nls.localize("multiSelection", "{0} selections");
function getSelectionLabel(selections: Selection[], charactersSelected: number): string {
if (!selections || selections.length === 0) {
return nlsNoSelection;
}
if (selections.length === 1) {
if (charactersSelected) {
return strings.format(nlsSingleSelectionRange, selections[0].positionLineNumber, selections[0].positionColumn, charactersSelected);
}
return strings.format(nlsSingleSelection, selections[0].positionLineNumber, selections[0].positionColumn);
}
if (charactersSelected) {
return strings.format(nlsMultiSelectionRange, selections.length, charactersSelected);
}
if (selections.length > 0) {
return strings.format(nlsMultiSelection, selections.length);
}
return null;
}
class AccessibilityHelpWidget extends Widget implements IOverlayWidget {
private static ID = 'editor.contrib.accessibilityHelpWidget';
private static WIDTH = 500;
private static HEIGHT = 300;
private _editor: ICodeEditor;
private _domNode: FastDomNode<HTMLElement>;
private _contentDomNode: FastDomNode<HTMLElement>;
private _isVisible: boolean;
private _isVisibleKey: IContextKey<boolean>;
constructor(
editor: ICodeEditor,
@IContextKeyService private _contextKeyService: IContextKeyService,
@IKeybindingService private _keybindingService: IKeybindingService,
@IOpenerService private _openerService: IOpenerService
) {
super();
this._editor = editor;
this._isVisibleKey = CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE.bindTo(
this._contextKeyService
);
this._domNode = createFastDomNode(document.createElement('div'));
this._domNode.setClassName('accessibilityHelpWidget');
this._domNode.setDisplay('none');
this._domNode.setAttribute('role', 'dialog');
this._domNode.setAttribute('aria-hidden', 'true');
this._contentDomNode = createFastDomNode(document.createElement('div'));
this._contentDomNode.setAttribute('role', 'document');
this._domNode.appendChild(this._contentDomNode);
this._isVisible = false;
this._register(this._editor.onDidLayoutChange(() => {
if (this._isVisible) {
this._layout();
}
}));
// Intentionally not configurable!
this._register(dom.addStandardDisposableListener(this._contentDomNode.domNode, 'keydown', (e) => {
if (!this._isVisible) {
return;
}
if (e.equals(KeyMod.CtrlCmd | KeyCode.KEY_E)) {
alert(nls.localize("emergencyConfOn", "Now changing the setting `accessibilitySupport` to 'on'."));
this._editor.updateOptions({
accessibilitySupport: 'on'
});
dom.clearNode(this._contentDomNode.domNode);
this._buildContent();
this._contentDomNode.domNode.focus();
e.preventDefault();
e.stopPropagation();
}
if (e.equals(KeyMod.CtrlCmd | KeyCode.KEY_H)) {
alert(nls.localize("openingDocs", "Now opening the Editor Accessibility documentation page."));
let url = (<IEditorConstructionOptions>this._editor.getRawConfiguration()).accessibilityHelpUrl;
if (typeof url === 'undefined') {
url = 'https://go.microsoft.com/fwlink/?linkid=852450';
}
this._openerService.open(URI.parse(url));
e.preventDefault();
e.stopPropagation();
}
}));
this.onblur(this._contentDomNode.domNode, () => {
this.hide();
});
this._editor.addOverlayWidget(this);
}
public dispose(): void {
this._editor.removeOverlayWidget(this);
super.dispose();
}
public getId(): string {
return AccessibilityHelpWidget.ID;
}
public getDomNode(): HTMLElement {
return this._domNode.domNode;
}
public getPosition(): IOverlayWidgetPosition {
return {
preference: null
};
}
public show(): void {
if (this._isVisible) {
return;
}
this._isVisible = true;
this._isVisibleKey.set(true);
this._layout();
this._domNode.setDisplay('block');
this._domNode.setAttribute('aria-hidden', 'false');
this._contentDomNode.domNode.tabIndex = 0;
this._buildContent();
this._contentDomNode.domNode.focus();
}
private _descriptionForCommand(commandId: string, msg: string, noKbMsg: string): string {
let kb = this._keybindingService.lookupKeybinding(commandId);
if (kb) {
return strings.format(msg, kb.getAriaLabel());
}
return strings.format(noKbMsg, commandId);
}
private _buildContent() {
let opts = this._editor.getConfiguration();
const selections = this._editor.getSelections();
let charactersSelected = 0;
if (selections) {
const model = this._editor.getModel();
if (model) {
selections.forEach((selection) => {
charactersSelected += model.getValueLengthInRange(selection);
});
}
}
let text = getSelectionLabel(selections, charactersSelected);
if (opts.wrappingInfo.inDiffEditor) {
if (opts.readOnly) {
text += nls.localize("readonlyDiffEditor", " in a read-only pane of a diff editor.");
} else {
text += nls.localize("editableDiffEditor", " in a pane of a diff editor.");
}
} else {
if (opts.readOnly) {
text += nls.localize("readonlyEditor", " in a read-only code editor");
} else {
text += nls.localize("editableEditor", " in a code editor");
}
}
switch (opts.accessibilitySupport) {
case platform.AccessibilitySupport.Unknown:
const turnOnMessage = (
platform.isMacintosh
? nls.localize("changeConfigToOnMac", "To configure the editor to be optimized for usage with a Screen Reader press Command+E now.")
: nls.localize("changeConfigToOnWinLinux", "To configure the editor to be optimized for usage with a Screen Reader press Control+E now.")
);
text += '\n\n - ' + turnOnMessage;
break;
case platform.AccessibilitySupport.Enabled:
text += '\n\n - ' + nls.localize("auto_on", "The editor is configured to be optimized for usage with a Screen Reader.");
break;
case platform.AccessibilitySupport.Disabled:
text += '\n\n - ' + nls.localize("auto_off", "The editor is configured to never be optimized for usage with a Screen Reader, which is not the case at this time.");
text += ' ' + turnOnMessage;
break;
}
const NLS_TAB_FOCUS_MODE_ON = nls.localize("tabFocusModeOnMsg", "Pressing Tab in the current editor will move focus to the next focusable element. Toggle this behavior by pressing {0}.");
const NLS_TAB_FOCUS_MODE_ON_NO_KB = nls.localize("tabFocusModeOnMsgNoKb", "Pressing Tab in the current editor will move focus to the next focusable element. The command {0} is currently not triggerable by a keybinding.");
const NLS_TAB_FOCUS_MODE_OFF = nls.localize("tabFocusModeOffMsg", "Pressing Tab in the current editor will insert the tab character. Toggle this behavior by pressing {0}.");
const NLS_TAB_FOCUS_MODE_OFF_NO_KB = nls.localize("tabFocusModeOffMsgNoKb", "Pressing Tab in the current editor will insert the tab character. The command {0} is currently not triggerable by a keybinding.");
if (opts.tabFocusMode) {
text += '\n\n - ' + this._descriptionForCommand(ToggleTabFocusModeAction.ID, NLS_TAB_FOCUS_MODE_ON, NLS_TAB_FOCUS_MODE_ON_NO_KB);
} else {
text += '\n\n - ' + this._descriptionForCommand(ToggleTabFocusModeAction.ID, NLS_TAB_FOCUS_MODE_OFF, NLS_TAB_FOCUS_MODE_OFF_NO_KB);
}
const openDocMessage = (
platform.isMacintosh
? nls.localize("openDocMac", "Press Command+H now to open a browser window with more information related to editor accessibility.")
: nls.localize("openDocWinLinux", "Press Control+H now to open a browser window with more information related to editor accessibility.")
);
text += '\n\n - ' + openDocMessage;
text += '\n\n' + nls.localize("outroMsg", "You can dismiss this tooltip and return to the editor by pressing Escape or Shift+Escape.");
this._contentDomNode.domNode.appendChild(renderFormattedText(text));
// Per https://www.w3.org/TR/wai-aria/roles#document, Authors SHOULD provide a title or label for documents
this._contentDomNode.domNode.setAttribute('aria-label', text);
}
public hide(): void {
if (!this._isVisible) {
return;
}
this._isVisible = false;
this._isVisibleKey.reset();
this._domNode.setDisplay('none');
this._domNode.setAttribute('aria-hidden', 'true');
this._contentDomNode.domNode.tabIndex = -1;
dom.clearNode(this._contentDomNode.domNode);
this._editor.focus();
}
private _layout(): void {
let editorLayout = this._editor.getLayoutInfo();
let w = Math.max(5, Math.min(AccessibilityHelpWidget.WIDTH, editorLayout.width - 40));
let h = Math.max(5, Math.min(AccessibilityHelpWidget.HEIGHT, editorLayout.height - 40));
this._domNode.setWidth(w);
this._domNode.setHeight(h);
let top = Math.round((editorLayout.height - h) / 2);
this._domNode.setTop(top);
let left = Math.round((editorLayout.width - w) / 2);
this._domNode.setLeft(left);
}
}
@editorAction
class ShowAccessibilityHelpAction extends EditorAction {
constructor() |
public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void {
let controller = AccessibilityHelpController.get(editor);
if (controller) {
controller.show();
}
}
}
const AccessibilityHelpCommand = EditorCommand.bindToContribution<AccessibilityHelpController>(AccessibilityHelpController.get);
CommonEditorRegistry.registerEditorCommand(
new AccessibilityHelpCommand({
id: 'closeAccessibilityHelp',
precondition: CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE,
handler: x => x.hide(),
kbOpts: {
weight: CommonEditorRegistry.commandWeight(100),
kbExpr: EditorContextKeys.focus,
primary: KeyCode.Escape,
secondary: [KeyMod.Shift | KeyCode.Escape]
}
})
);
registerThemingParticipant((theme, collector) => {
let widgetBackground = theme.getColor(editorWidgetBackground);
if (widgetBackground) {
collector.addRule(`.monaco-editor .accessibilityHelpWidget { background-color: ${widgetBackground}; }`);
}
let widgetShadowColor = theme.getColor(widgetShadow);
if (widgetShadowColor) {
collector.addRule(`.monaco-editor .accessibilityHelpWidget { box-shadow: 0 2px 8px ${widgetShadowColor}; }`);
}
let hcBorder = theme.getColor(contrastBorder);
if (hcBorder) {
collector.addRule(`.monaco-editor .accessibilityHelpWidget { border: 2px solid ${hcBorder}; }`);
}
});
| {
super({
id: 'editor.action.showAccessibilityHelp',
label: nls.localize("ShowAccessibilityHelpAction", "Show Accessibility Help"),
alias: 'Show Accessibility Help',
precondition: null,
kbOpts: {
kbExpr: EditorContextKeys.focus,
primary: (browser.isIE ? KeyMod.CtrlCmd | KeyCode.F1 : KeyMod.Alt | KeyCode.F1)
}
});
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.