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 |
---|---|---|---|---|
__openerp__.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2014 Didotech SRL (info at didotech.com)
# All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software | {
"name": "Export Customers - Exporting customer's data in .csv file for italian fiscal program.",
'version': '2.0.1.0',
'category': 'Generic Modules/Sales customers',
"description": """Exporting customer's data in .csv file """,
"author": "Didotech SRL",
'website': 'http://www.didotech.com',
"depends": [
"base",
"base_partner_ref",
"sale",
"account",
#"l10n_it",
"l10n_it_base",
"l10n_it_account"
],
"init_xml": [],
"update_xml": [
"security/security.xml",
"export_customers.xml"
],
"demo_xml": [],
"installable": True,
"active": False,
} | # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
############################################################################## | random_line_split |
widgets.py | # -*- coding: utf-8 -*-
from itertools import chain
from django.contrib.sites.models import Site
from django.core.urlresolvers import NoReverseMatch, reverse_lazy
from django.forms.widgets import Select, MultiWidget, TextInput
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from cms.forms.utils import get_site_choices, get_page_choices
from cms.models import Page, PageUser
from cms.templatetags.cms_admin import CMS_ADMIN_ICON_BASE
from cms.utils.compat.dj import force_unicode
class PageSelectWidget(MultiWidget):
"""A widget that allows selecting a page by first selecting a site and then
a page on that site in a two step process.
"""
def __init__(self, site_choices=None, page_choices=None, attrs=None):
if attrs is not None:
self.attrs = attrs.copy()
else:
self.attrs = {}
self.choices = []
super(PageSelectWidget, self).__init__((Select, Select, Select), attrs)
def decompress(self, value):
"""
receives a page_id in value and returns the site_id and page_id
of that page or the current site_id and None if no page_id is given.
"""
if value:
page = Page.objects.get(pk=value)
site = page.site
return [site.pk, page.pk, page.pk]
site = Site.objects.get_current()
return [site.pk,None,None]
def _has_changed(self, initial, data):
# THIS IS A COPY OF django.forms.widgets.Widget._has_changed()
# (except for the first if statement)
"""
Return True if data differs from initial.
"""
# For purposes of seeing whether something has changed, None is
# the same as an empty string, if the data or inital value we get
# is None, replace it w/ u''.
if data is None or (len(data)>=2 and data[1] in [None,'']):
|
else:
data_value = data
if initial is None:
initial_value = u''
else:
initial_value = initial
if force_unicode(initial_value) != force_unicode(data_value):
return True
return False
def render(self, name, value, attrs=None):
# THIS IS A COPY OF django.forms.widgets.MultiWidget.render()
# (except for the last line)
# value is a list of values, each corresponding to a widget
# in self.widgets.
site_choices = get_site_choices()
page_choices = get_page_choices()
self.site_choices = site_choices
self.choices = page_choices
self.widgets = (Select(choices=site_choices ),
Select(choices=[('', '----')]),
Select(choices=self.choices, attrs={'style': "display:none;"} ),
)
if not isinstance(value, list):
value = self.decompress(value)
output = []
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id', None)
for i, widget in enumerate(self.widgets):
try:
widget_value = value[i]
except IndexError:
widget_value = None
if id_:
final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
output.append(r'''<script type="text/javascript">
(function($) {
var handleSiteChange = function(site_name, selected_id) {
$("#id_%(name)s_1 optgroup").remove();
var myOptions = $("#id_%(name)s_2 optgroup[label='" + site_name + "']").clone();
$("#id_%(name)s_1").append(myOptions);
$("#id_%(name)s_1").change();
};
var handlePageChange = function(page_id) {
if (page_id) {
$("#id_%(name)s_2 option").removeAttr('selected');
$("#id_%(name)s_2 option[value=" + page_id + "]").attr('selected','selected');
} else {
$("#id_%(name)s_2 option[value=]").attr('selected','selected');
};
};
$("#id_%(name)s_0").change(function(){
var site_label = $("#id_%(name)s_0").children(":selected").text();
handleSiteChange( site_label );
});
$("#id_%(name)s_1").change(function(){
var page_id = $(this).find('option:selected').val();
handlePageChange( page_id );
});
$(function(){
handleSiteChange( $("#id_%(name)s_0").children(":selected").text() );
$("#add_id_%(name)s").hide();
});
})(django.jQuery);
</script>''' % {'name': name})
return mark_safe(self.format_output(output))
def format_output(self, rendered_widgets):
return u' '.join(rendered_widgets)
class PageSmartLinkWidget(TextInput):
def __init__(self, attrs=None, ajax_view=None):
super(PageSmartLinkWidget, self).__init__(attrs)
self.ajax_url = self.get_ajax_url(ajax_view=ajax_view)
def get_ajax_url(self, ajax_view):
try:
return reverse_lazy(ajax_view)
except NoReverseMatch:
raise Exception(
'You should provide an ajax_view argument that can be reversed to the PageSmartLinkWidget'
)
def render(self, name=None, value=None, attrs=None):
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id', None)
output = [r'''<script type="text/javascript">
(function($){
$(function(){
$("#%(element_id)s").select2({
placeholder: "%(placeholder_text)s",
allowClear: true,
minimumInputLength: 3,
ajax: {
url: "%(ajax_url)s",
dataType: 'json',
data: function (term, page) {
return {
q: term, // search term
language_code: '%(language_code)s'
};
},
results: function (data, page) {
return {
more: false,
results: $.map(data, function(item, i){
return {
'id':item.redirect_url,
'text': item.title + ' (/' + item.path + ')'}
}
)
};
}
},
// Allow creation of new entries
createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} },
multiple: false,
initSelection : function (element, callback) {
var initialValue = element.val()
callback({id:initialValue, text: initialValue});
}
});
})
})(django.jQuery);
</script>''' % {
'element_id': id_,
'placeholder_text': final_attrs.get('placeholder_text', ''),
'language_code': self.language,
'ajax_url': force_unicode(self.ajax_url)
}]
output.append(super(PageSmartLinkWidget, self).render(name, value, attrs))
return mark_safe(u''.join(output))
class Media:
css = {
'all': ('cms/js/select2/select2.css',
'cms/js/select2/select2-bootstrap.css',)
}
js = (#'cms/js/libs/jquery.min.js',
'cms/js/select2/select2.js',)
class UserSelectAdminWidget(Select):
"""Special widget used in page permission inlines, because we have to render
an add user (plus) icon, but point it somewhere else - to special user creation
view, which is accessible only if user haves "add user" permissions.
Current user should be assigned to widget in form constructor as an user
attribute.
"""
def render(self, name, value, attrs=None, choices=()):
output = [super(UserSelectAdminWidget, self).render(name, value, attrs, choices)]
if hasattr(self, 'user') and (self.user.is_superuser or \
self.user.has_perm(PageUser._meta.app_label + '.' + PageUser._meta.get_add_permission())):
# append + icon
add_url = '../../../cms/pageuser/add/'
output.append(u'<a href="%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % \
(add_url, name))
output.append(u'<img src="%sicon_addlink.gif" width="10" height="10" alt="%s"/></a>' % (CMS_ADMIN_ICON_BASE, _('Add Another')))
return mark_safe(u''.join(output))
class AppHookSelect(Select):
"""Special widget used for the App Hook selector in the Advanced Settings
of the Page Admin. It adds support for a data attribute per option and
includes supporting JS into the page.
"""
class Media:
js = ('cms/js/modules/cms.base.js', 'cms/js/modules/cms.app_hook_select.js', )
def __init__(self, attrs=None, choices=(), app_namespaces={}):
self.app_namespaces = app_namespaces
super(AppHookSelect, self).__init__(attrs, choices)
def render_option(self, selected_choices, option_value, option_label):
if option_value is None:
option_value = ''
option_value = force_text(option_value)
if option_value in selected_choices:
selected_html = mark_safe(' selected="selected"')
if not self.allow_multiple_selected:
# Only allow for a single selection.
selected_choices.remove(option_value)
else:
selected_html = ''
if option_value in self.app_namespaces:
data_html = mark_safe(' data-namespace="%s"' % self.app_namespaces[option_value])
else:
data_html = ''
return '<option value="%s"%s%s>%s</option>' % (
option_value,
selected_html,
data_html,
force_text(option_label),
)
def render_options(self, choices, selected_choices):
selected_choices = set(force_text(v) for v in selected_choices)
output = []
for option_value, option_label in chain(self.choices, choices):
output.append(self.render_option(selected_choices, option_value, option_label))
return '\n'.join(output)
| data_value = u'' | conditional_block |
widgets.py | # -*- coding: utf-8 -*-
from itertools import chain
from django.contrib.sites.models import Site
from django.core.urlresolvers import NoReverseMatch, reverse_lazy
from django.forms.widgets import Select, MultiWidget, TextInput
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from cms.forms.utils import get_site_choices, get_page_choices
from cms.models import Page, PageUser
from cms.templatetags.cms_admin import CMS_ADMIN_ICON_BASE
from cms.utils.compat.dj import force_unicode
class PageSelectWidget(MultiWidget):
"""A widget that allows selecting a page by first selecting a site and then
a page on that site in a two step process.
"""
def __init__(self, site_choices=None, page_choices=None, attrs=None):
if attrs is not None:
self.attrs = attrs.copy()
else:
self.attrs = {}
self.choices = []
super(PageSelectWidget, self).__init__((Select, Select, Select), attrs)
def decompress(self, value):
"""
receives a page_id in value and returns the site_id and page_id
of that page or the current site_id and None if no page_id is given.
"""
if value:
page = Page.objects.get(pk=value)
site = page.site
return [site.pk, page.pk, page.pk]
site = Site.objects.get_current()
return [site.pk,None,None]
def _has_changed(self, initial, data):
# THIS IS A COPY OF django.forms.widgets.Widget._has_changed()
# (except for the first if statement)
"""
Return True if data differs from initial.
"""
# For purposes of seeing whether something has changed, None is
# the same as an empty string, if the data or inital value we get
# is None, replace it w/ u''.
if data is None or (len(data)>=2 and data[1] in [None,'']):
data_value = u''
else:
data_value = data
if initial is None:
initial_value = u''
else:
initial_value = initial
if force_unicode(initial_value) != force_unicode(data_value):
return True
return False
def render(self, name, value, attrs=None):
# THIS IS A COPY OF django.forms.widgets.MultiWidget.render()
# (except for the last line)
# value is a list of values, each corresponding to a widget
# in self.widgets.
site_choices = get_site_choices()
page_choices = get_page_choices()
self.site_choices = site_choices
self.choices = page_choices
self.widgets = (Select(choices=site_choices ),
Select(choices=[('', '----')]),
Select(choices=self.choices, attrs={'style': "display:none;"} ),
)
if not isinstance(value, list):
value = self.decompress(value)
output = []
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id', None)
for i, widget in enumerate(self.widgets):
try:
widget_value = value[i]
except IndexError:
widget_value = None
if id_:
final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
output.append(r'''<script type="text/javascript">
(function($) {
var handleSiteChange = function(site_name, selected_id) {
$("#id_%(name)s_1 optgroup").remove();
var myOptions = $("#id_%(name)s_2 optgroup[label='" + site_name + "']").clone();
$("#id_%(name)s_1").append(myOptions);
$("#id_%(name)s_1").change();
};
var handlePageChange = function(page_id) {
if (page_id) {
$("#id_%(name)s_2 option").removeAttr('selected');
$("#id_%(name)s_2 option[value=" + page_id + "]").attr('selected','selected');
} else {
$("#id_%(name)s_2 option[value=]").attr('selected','selected');
};
};
$("#id_%(name)s_0").change(function(){
var site_label = $("#id_%(name)s_0").children(":selected").text();
handleSiteChange( site_label );
});
$("#id_%(name)s_1").change(function(){
var page_id = $(this).find('option:selected').val();
handlePageChange( page_id );
});
$(function(){
handleSiteChange( $("#id_%(name)s_0").children(":selected").text() );
$("#add_id_%(name)s").hide();
});
})(django.jQuery);
</script>''' % {'name': name})
return mark_safe(self.format_output(output))
def format_output(self, rendered_widgets):
return u' '.join(rendered_widgets)
class PageSmartLinkWidget(TextInput):
def __init__(self, attrs=None, ajax_view=None):
super(PageSmartLinkWidget, self).__init__(attrs)
self.ajax_url = self.get_ajax_url(ajax_view=ajax_view)
def get_ajax_url(self, ajax_view):
try:
return reverse_lazy(ajax_view)
except NoReverseMatch:
raise Exception(
'You should provide an ajax_view argument that can be reversed to the PageSmartLinkWidget'
)
def render(self, name=None, value=None, attrs=None):
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id', None)
output = [r'''<script type="text/javascript">
(function($){
$(function(){
$("#%(element_id)s").select2({
placeholder: "%(placeholder_text)s",
allowClear: true,
minimumInputLength: 3,
ajax: {
url: "%(ajax_url)s",
dataType: 'json',
data: function (term, page) {
return {
q: term, // search term
language_code: '%(language_code)s'
};
},
results: function (data, page) {
return {
more: false,
results: $.map(data, function(item, i){
return {
'id':item.redirect_url,
'text': item.title + ' (/' + item.path + ')'}
}
)
};
}
},
// Allow creation of new entries
createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} },
multiple: false,
initSelection : function (element, callback) {
var initialValue = element.val()
callback({id:initialValue, text: initialValue});
}
});
})
})(django.jQuery);
</script>''' % {
'element_id': id_,
'placeholder_text': final_attrs.get('placeholder_text', ''),
'language_code': self.language,
'ajax_url': force_unicode(self.ajax_url)
}]
output.append(super(PageSmartLinkWidget, self).render(name, value, attrs))
return mark_safe(u''.join(output))
class | :
css = {
'all': ('cms/js/select2/select2.css',
'cms/js/select2/select2-bootstrap.css',)
}
js = (#'cms/js/libs/jquery.min.js',
'cms/js/select2/select2.js',)
class UserSelectAdminWidget(Select):
"""Special widget used in page permission inlines, because we have to render
an add user (plus) icon, but point it somewhere else - to special user creation
view, which is accessible only if user haves "add user" permissions.
Current user should be assigned to widget in form constructor as an user
attribute.
"""
def render(self, name, value, attrs=None, choices=()):
output = [super(UserSelectAdminWidget, self).render(name, value, attrs, choices)]
if hasattr(self, 'user') and (self.user.is_superuser or \
self.user.has_perm(PageUser._meta.app_label + '.' + PageUser._meta.get_add_permission())):
# append + icon
add_url = '../../../cms/pageuser/add/'
output.append(u'<a href="%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % \
(add_url, name))
output.append(u'<img src="%sicon_addlink.gif" width="10" height="10" alt="%s"/></a>' % (CMS_ADMIN_ICON_BASE, _('Add Another')))
return mark_safe(u''.join(output))
class AppHookSelect(Select):
"""Special widget used for the App Hook selector in the Advanced Settings
of the Page Admin. It adds support for a data attribute per option and
includes supporting JS into the page.
"""
class Media:
js = ('cms/js/modules/cms.base.js', 'cms/js/modules/cms.app_hook_select.js', )
def __init__(self, attrs=None, choices=(), app_namespaces={}):
self.app_namespaces = app_namespaces
super(AppHookSelect, self).__init__(attrs, choices)
def render_option(self, selected_choices, option_value, option_label):
if option_value is None:
option_value = ''
option_value = force_text(option_value)
if option_value in selected_choices:
selected_html = mark_safe(' selected="selected"')
if not self.allow_multiple_selected:
# Only allow for a single selection.
selected_choices.remove(option_value)
else:
selected_html = ''
if option_value in self.app_namespaces:
data_html = mark_safe(' data-namespace="%s"' % self.app_namespaces[option_value])
else:
data_html = ''
return '<option value="%s"%s%s>%s</option>' % (
option_value,
selected_html,
data_html,
force_text(option_label),
)
def render_options(self, choices, selected_choices):
selected_choices = set(force_text(v) for v in selected_choices)
output = []
for option_value, option_label in chain(self.choices, choices):
output.append(self.render_option(selected_choices, option_value, option_label))
return '\n'.join(output)
| Media | identifier_name |
widgets.py | # -*- coding: utf-8 -*-
from itertools import chain
from django.contrib.sites.models import Site
from django.core.urlresolvers import NoReverseMatch, reverse_lazy
from django.forms.widgets import Select, MultiWidget, TextInput
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from cms.forms.utils import get_site_choices, get_page_choices
from cms.models import Page, PageUser
from cms.templatetags.cms_admin import CMS_ADMIN_ICON_BASE
from cms.utils.compat.dj import force_unicode
class PageSelectWidget(MultiWidget):
"""A widget that allows selecting a page by first selecting a site and then
a page on that site in a two step process.
"""
def __init__(self, site_choices=None, page_choices=None, attrs=None):
if attrs is not None:
self.attrs = attrs.copy()
else:
self.attrs = {}
self.choices = []
super(PageSelectWidget, self).__init__((Select, Select, Select), attrs)
def decompress(self, value):
"""
receives a page_id in value and returns the site_id and page_id
of that page or the current site_id and None if no page_id is given.
"""
if value:
page = Page.objects.get(pk=value)
site = page.site
return [site.pk, page.pk, page.pk]
site = Site.objects.get_current()
return [site.pk,None,None]
def _has_changed(self, initial, data):
# THIS IS A COPY OF django.forms.widgets.Widget._has_changed()
# (except for the first if statement)
"""
Return True if data differs from initial.
"""
# For purposes of seeing whether something has changed, None is
# the same as an empty string, if the data or inital value we get
# is None, replace it w/ u''.
if data is None or (len(data)>=2 and data[1] in [None,'']):
data_value = u''
else:
data_value = data
if initial is None:
initial_value = u''
else:
initial_value = initial
if force_unicode(initial_value) != force_unicode(data_value):
return True
return False
def render(self, name, value, attrs=None):
# THIS IS A COPY OF django.forms.widgets.MultiWidget.render()
# (except for the last line)
# value is a list of values, each corresponding to a widget
# in self.widgets.
site_choices = get_site_choices()
page_choices = get_page_choices()
self.site_choices = site_choices
self.choices = page_choices
self.widgets = (Select(choices=site_choices ),
Select(choices=[('', '----')]),
Select(choices=self.choices, attrs={'style': "display:none;"} ),
)
if not isinstance(value, list):
value = self.decompress(value)
output = []
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id', None)
for i, widget in enumerate(self.widgets):
try:
widget_value = value[i]
except IndexError:
widget_value = None
if id_:
final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
output.append(r'''<script type="text/javascript">
(function($) {
var handleSiteChange = function(site_name, selected_id) {
$("#id_%(name)s_1 optgroup").remove();
var myOptions = $("#id_%(name)s_2 optgroup[label='" + site_name + "']").clone();
$("#id_%(name)s_1").append(myOptions);
$("#id_%(name)s_1").change();
};
var handlePageChange = function(page_id) {
if (page_id) {
$("#id_%(name)s_2 option").removeAttr('selected');
$("#id_%(name)s_2 option[value=" + page_id + "]").attr('selected','selected');
} else {
$("#id_%(name)s_2 option[value=]").attr('selected','selected');
};
};
$("#id_%(name)s_0").change(function(){
var site_label = $("#id_%(name)s_0").children(":selected").text();
handleSiteChange( site_label );
});
$("#id_%(name)s_1").change(function(){
var page_id = $(this).find('option:selected').val();
handlePageChange( page_id );
});
$(function(){
handleSiteChange( $("#id_%(name)s_0").children(":selected").text() );
$("#add_id_%(name)s").hide();
});
})(django.jQuery);
</script>''' % {'name': name})
return mark_safe(self.format_output(output))
def format_output(self, rendered_widgets):
return u' '.join(rendered_widgets)
class PageSmartLinkWidget(TextInput):
def __init__(self, attrs=None, ajax_view=None):
super(PageSmartLinkWidget, self).__init__(attrs)
self.ajax_url = self.get_ajax_url(ajax_view=ajax_view)
| except NoReverseMatch:
raise Exception(
'You should provide an ajax_view argument that can be reversed to the PageSmartLinkWidget'
)
def render(self, name=None, value=None, attrs=None):
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id', None)
output = [r'''<script type="text/javascript">
(function($){
$(function(){
$("#%(element_id)s").select2({
placeholder: "%(placeholder_text)s",
allowClear: true,
minimumInputLength: 3,
ajax: {
url: "%(ajax_url)s",
dataType: 'json',
data: function (term, page) {
return {
q: term, // search term
language_code: '%(language_code)s'
};
},
results: function (data, page) {
return {
more: false,
results: $.map(data, function(item, i){
return {
'id':item.redirect_url,
'text': item.title + ' (/' + item.path + ')'}
}
)
};
}
},
// Allow creation of new entries
createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} },
multiple: false,
initSelection : function (element, callback) {
var initialValue = element.val()
callback({id:initialValue, text: initialValue});
}
});
})
})(django.jQuery);
</script>''' % {
'element_id': id_,
'placeholder_text': final_attrs.get('placeholder_text', ''),
'language_code': self.language,
'ajax_url': force_unicode(self.ajax_url)
}]
output.append(super(PageSmartLinkWidget, self).render(name, value, attrs))
return mark_safe(u''.join(output))
class Media:
css = {
'all': ('cms/js/select2/select2.css',
'cms/js/select2/select2-bootstrap.css',)
}
js = (#'cms/js/libs/jquery.min.js',
'cms/js/select2/select2.js',)
class UserSelectAdminWidget(Select):
"""Special widget used in page permission inlines, because we have to render
an add user (plus) icon, but point it somewhere else - to special user creation
view, which is accessible only if user haves "add user" permissions.
Current user should be assigned to widget in form constructor as an user
attribute.
"""
def render(self, name, value, attrs=None, choices=()):
output = [super(UserSelectAdminWidget, self).render(name, value, attrs, choices)]
if hasattr(self, 'user') and (self.user.is_superuser or \
self.user.has_perm(PageUser._meta.app_label + '.' + PageUser._meta.get_add_permission())):
# append + icon
add_url = '../../../cms/pageuser/add/'
output.append(u'<a href="%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % \
(add_url, name))
output.append(u'<img src="%sicon_addlink.gif" width="10" height="10" alt="%s"/></a>' % (CMS_ADMIN_ICON_BASE, _('Add Another')))
return mark_safe(u''.join(output))
class AppHookSelect(Select):
"""Special widget used for the App Hook selector in the Advanced Settings
of the Page Admin. It adds support for a data attribute per option and
includes supporting JS into the page.
"""
class Media:
js = ('cms/js/modules/cms.base.js', 'cms/js/modules/cms.app_hook_select.js', )
def __init__(self, attrs=None, choices=(), app_namespaces={}):
self.app_namespaces = app_namespaces
super(AppHookSelect, self).__init__(attrs, choices)
def render_option(self, selected_choices, option_value, option_label):
if option_value is None:
option_value = ''
option_value = force_text(option_value)
if option_value in selected_choices:
selected_html = mark_safe(' selected="selected"')
if not self.allow_multiple_selected:
# Only allow for a single selection.
selected_choices.remove(option_value)
else:
selected_html = ''
if option_value in self.app_namespaces:
data_html = mark_safe(' data-namespace="%s"' % self.app_namespaces[option_value])
else:
data_html = ''
return '<option value="%s"%s%s>%s</option>' % (
option_value,
selected_html,
data_html,
force_text(option_label),
)
def render_options(self, choices, selected_choices):
selected_choices = set(force_text(v) for v in selected_choices)
output = []
for option_value, option_label in chain(self.choices, choices):
output.append(self.render_option(selected_choices, option_value, option_label))
return '\n'.join(output) | def get_ajax_url(self, ajax_view):
try:
return reverse_lazy(ajax_view) | random_line_split |
widgets.py | # -*- coding: utf-8 -*-
from itertools import chain
from django.contrib.sites.models import Site
from django.core.urlresolvers import NoReverseMatch, reverse_lazy
from django.forms.widgets import Select, MultiWidget, TextInput
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from cms.forms.utils import get_site_choices, get_page_choices
from cms.models import Page, PageUser
from cms.templatetags.cms_admin import CMS_ADMIN_ICON_BASE
from cms.utils.compat.dj import force_unicode
class PageSelectWidget(MultiWidget):
"""A widget that allows selecting a page by first selecting a site and then
a page on that site in a two step process.
"""
def __init__(self, site_choices=None, page_choices=None, attrs=None):
if attrs is not None:
self.attrs = attrs.copy()
else:
self.attrs = {}
self.choices = []
super(PageSelectWidget, self).__init__((Select, Select, Select), attrs)
def decompress(self, value):
"""
receives a page_id in value and returns the site_id and page_id
of that page or the current site_id and None if no page_id is given.
"""
if value:
page = Page.objects.get(pk=value)
site = page.site
return [site.pk, page.pk, page.pk]
site = Site.objects.get_current()
return [site.pk,None,None]
def _has_changed(self, initial, data):
# THIS IS A COPY OF django.forms.widgets.Widget._has_changed()
# (except for the first if statement)
"""
Return True if data differs from initial.
"""
# For purposes of seeing whether something has changed, None is
# the same as an empty string, if the data or inital value we get
# is None, replace it w/ u''.
if data is None or (len(data)>=2 and data[1] in [None,'']):
data_value = u''
else:
data_value = data
if initial is None:
initial_value = u''
else:
initial_value = initial
if force_unicode(initial_value) != force_unicode(data_value):
return True
return False
def render(self, name, value, attrs=None):
# THIS IS A COPY OF django.forms.widgets.MultiWidget.render()
# (except for the last line)
# value is a list of values, each corresponding to a widget
# in self.widgets.
|
def format_output(self, rendered_widgets):
return u' '.join(rendered_widgets)
class PageSmartLinkWidget(TextInput):
def __init__(self, attrs=None, ajax_view=None):
super(PageSmartLinkWidget, self).__init__(attrs)
self.ajax_url = self.get_ajax_url(ajax_view=ajax_view)
def get_ajax_url(self, ajax_view):
try:
return reverse_lazy(ajax_view)
except NoReverseMatch:
raise Exception(
'You should provide an ajax_view argument that can be reversed to the PageSmartLinkWidget'
)
def render(self, name=None, value=None, attrs=None):
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id', None)
output = [r'''<script type="text/javascript">
(function($){
$(function(){
$("#%(element_id)s").select2({
placeholder: "%(placeholder_text)s",
allowClear: true,
minimumInputLength: 3,
ajax: {
url: "%(ajax_url)s",
dataType: 'json',
data: function (term, page) {
return {
q: term, // search term
language_code: '%(language_code)s'
};
},
results: function (data, page) {
return {
more: false,
results: $.map(data, function(item, i){
return {
'id':item.redirect_url,
'text': item.title + ' (/' + item.path + ')'}
}
)
};
}
},
// Allow creation of new entries
createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} },
multiple: false,
initSelection : function (element, callback) {
var initialValue = element.val()
callback({id:initialValue, text: initialValue});
}
});
})
})(django.jQuery);
</script>''' % {
'element_id': id_,
'placeholder_text': final_attrs.get('placeholder_text', ''),
'language_code': self.language,
'ajax_url': force_unicode(self.ajax_url)
}]
output.append(super(PageSmartLinkWidget, self).render(name, value, attrs))
return mark_safe(u''.join(output))
class Media:
css = {
'all': ('cms/js/select2/select2.css',
'cms/js/select2/select2-bootstrap.css',)
}
js = (#'cms/js/libs/jquery.min.js',
'cms/js/select2/select2.js',)
class UserSelectAdminWidget(Select):
"""Special widget used in page permission inlines, because we have to render
an add user (plus) icon, but point it somewhere else - to special user creation
view, which is accessible only if user haves "add user" permissions.
Current user should be assigned to widget in form constructor as an user
attribute.
"""
def render(self, name, value, attrs=None, choices=()):
output = [super(UserSelectAdminWidget, self).render(name, value, attrs, choices)]
if hasattr(self, 'user') and (self.user.is_superuser or \
self.user.has_perm(PageUser._meta.app_label + '.' + PageUser._meta.get_add_permission())):
# append + icon
add_url = '../../../cms/pageuser/add/'
output.append(u'<a href="%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % \
(add_url, name))
output.append(u'<img src="%sicon_addlink.gif" width="10" height="10" alt="%s"/></a>' % (CMS_ADMIN_ICON_BASE, _('Add Another')))
return mark_safe(u''.join(output))
class AppHookSelect(Select):
"""Special widget used for the App Hook selector in the Advanced Settings
of the Page Admin. It adds support for a data attribute per option and
includes supporting JS into the page.
"""
class Media:
js = ('cms/js/modules/cms.base.js', 'cms/js/modules/cms.app_hook_select.js', )
def __init__(self, attrs=None, choices=(), app_namespaces={}):
self.app_namespaces = app_namespaces
super(AppHookSelect, self).__init__(attrs, choices)
def render_option(self, selected_choices, option_value, option_label):
if option_value is None:
option_value = ''
option_value = force_text(option_value)
if option_value in selected_choices:
selected_html = mark_safe(' selected="selected"')
if not self.allow_multiple_selected:
# Only allow for a single selection.
selected_choices.remove(option_value)
else:
selected_html = ''
if option_value in self.app_namespaces:
data_html = mark_safe(' data-namespace="%s"' % self.app_namespaces[option_value])
else:
data_html = ''
return '<option value="%s"%s%s>%s</option>' % (
option_value,
selected_html,
data_html,
force_text(option_label),
)
def render_options(self, choices, selected_choices):
selected_choices = set(force_text(v) for v in selected_choices)
output = []
for option_value, option_label in chain(self.choices, choices):
output.append(self.render_option(selected_choices, option_value, option_label))
return '\n'.join(output)
| site_choices = get_site_choices()
page_choices = get_page_choices()
self.site_choices = site_choices
self.choices = page_choices
self.widgets = (Select(choices=site_choices ),
Select(choices=[('', '----')]),
Select(choices=self.choices, attrs={'style': "display:none;"} ),
)
if not isinstance(value, list):
value = self.decompress(value)
output = []
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id', None)
for i, widget in enumerate(self.widgets):
try:
widget_value = value[i]
except IndexError:
widget_value = None
if id_:
final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
output.append(r'''<script type="text/javascript">
(function($) {
var handleSiteChange = function(site_name, selected_id) {
$("#id_%(name)s_1 optgroup").remove();
var myOptions = $("#id_%(name)s_2 optgroup[label='" + site_name + "']").clone();
$("#id_%(name)s_1").append(myOptions);
$("#id_%(name)s_1").change();
};
var handlePageChange = function(page_id) {
if (page_id) {
$("#id_%(name)s_2 option").removeAttr('selected');
$("#id_%(name)s_2 option[value=" + page_id + "]").attr('selected','selected');
} else {
$("#id_%(name)s_2 option[value=]").attr('selected','selected');
};
};
$("#id_%(name)s_0").change(function(){
var site_label = $("#id_%(name)s_0").children(":selected").text();
handleSiteChange( site_label );
});
$("#id_%(name)s_1").change(function(){
var page_id = $(this).find('option:selected').val();
handlePageChange( page_id );
});
$(function(){
handleSiteChange( $("#id_%(name)s_0").children(":selected").text() );
$("#add_id_%(name)s").hide();
});
})(django.jQuery);
</script>''' % {'name': name})
return mark_safe(self.format_output(output)) | identifier_body |
type_to_value.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {TypeValueReference} from './host';
/**
* Potentially convert a `ts.TypeNode` to a `TypeValueReference`, which indicates how to use the
* type given in the `ts.TypeNode` in a value position.
*
* This can return `null` if the `typeNode` is `null`, if it does not refer to a symbol with a value
* declaration, or if it is not possible to statically understand.
*/
export function typeToValue(
typeNode: ts.TypeNode | null, checker: ts.TypeChecker): TypeValueReference|null {
// It's not possible to get a value expression if the parameter doesn't even have a type.
if (typeNode === null || !ts.isTypeReferenceNode(typeNode)) {
return null;
}
const symbols = resolveTypeSymbols(typeNode, checker);
if (symbols === null) {
return null;
}
const {local, decl} = symbols;
// It's only valid to convert a type reference to a value reference if the type actually
// has a value declaration associated with it.
if (decl.valueDeclaration === undefined) {
return null;
}
// The type points to a valid value declaration. Rewrite the TypeReference into an
// Expression which references the value pointed to by the TypeReference, if possible.
// Look at the local `ts.Symbol`'s declarations and see if it comes from an import
// statement. If so, extract the module specifier and the name of the imported type.
const firstDecl = local.declarations && local.declarations[0];
if (firstDecl && ts.isImportClause(firstDecl) && firstDecl.name !== undefined) | else if (firstDecl && isImportSource(firstDecl)) {
const origin = extractModuleAndNameFromImport(firstDecl, symbols.importName);
return {local: false, valueDeclaration: decl.valueDeclaration, ...origin};
} else {
const expression = typeNodeToValueExpr(typeNode);
if (expression !== null) {
return {
local: true,
expression,
defaultImportStatement: null,
};
} else {
return null;
}
}
}
/**
* Attempt to extract a `ts.Expression` that's equivalent to a `ts.TypeNode`, as the two have
* different AST shapes but can reference the same symbols.
*
* This will return `null` if an equivalent expression cannot be constructed.
*/
export function typeNodeToValueExpr(node: ts.TypeNode): ts.Expression|null {
if (ts.isTypeReferenceNode(node)) {
return entityNameToValue(node.typeName);
} else {
return null;
}
}
/**
* Resolve a `TypeReference` node to the `ts.Symbol`s for both its declaration and its local source.
*
* In the event that the `TypeReference` refers to a locally declared symbol, these will be the
* same. If the `TypeReference` refers to an imported symbol, then `decl` will be the fully resolved
* `ts.Symbol` of the referenced symbol. `local` will be the `ts.Symbol` of the `ts.Identifer` which
* points to the import statement by which the symbol was imported.
*
* In the event `typeRef` refers to a default import, an `importName` will also be returned to
* give the identifier name within the current file by which the import is known.
*/
function resolveTypeSymbols(typeRef: ts.TypeReferenceNode, checker: ts.TypeChecker):
{local: ts.Symbol, decl: ts.Symbol, importName: string | null}|null {
const typeName = typeRef.typeName;
// typeRefSymbol is the ts.Symbol of the entire type reference.
const typeRefSymbol: ts.Symbol|undefined = checker.getSymbolAtLocation(typeName);
if (typeRefSymbol === undefined) {
return null;
}
// local is the ts.Symbol for the local ts.Identifier for the type.
// If the type is actually locally declared or is imported by name, for example:
// import {Foo} from './foo';
// then it'll be the same as top. If the type is imported via a namespace import, for example:
// import * as foo from './foo';
// and then referenced as:
// constructor(f: foo.Foo)
// then local will be the ts.Symbol of `foo`, whereas top will be the ts.Symbol of `foo.Foo`.
// This allows tracking of the import behind whatever type reference exists.
let local = typeRefSymbol;
let importName: string|null = null;
// TODO(alxhub): this is technically not correct. The user could have any import type with any
// amount of qualification following the imported type:
//
// import * as foo from 'foo'
// constructor(inject: foo.X.Y.Z)
//
// What we really want is the ability to express the arbitrary operation of `.X.Y.Z` on top of
// whatever import we generate for 'foo'. This logic is sufficient for now, though.
if (ts.isQualifiedName(typeName) && ts.isIdentifier(typeName.left) &&
ts.isIdentifier(typeName.right)) {
const localTmp = checker.getSymbolAtLocation(typeName.left);
if (localTmp !== undefined) {
local = localTmp;
importName = typeName.right.text;
}
}
// De-alias the top-level type reference symbol to get the symbol of the actual declaration.
let decl = typeRefSymbol;
if (typeRefSymbol.flags & ts.SymbolFlags.Alias) {
decl = checker.getAliasedSymbol(typeRefSymbol);
}
return {local, decl, importName};
}
function entityNameToValue(node: ts.EntityName): ts.Expression|null {
if (ts.isQualifiedName(node)) {
const left = entityNameToValue(node.left);
return left !== null ? ts.createPropertyAccess(left, node.right) : null;
} else if (ts.isIdentifier(node)) {
return ts.getMutableClone(node);
} else {
return null;
}
}
function isImportSource(node: ts.Declaration): node is(ts.ImportSpecifier | ts.NamespaceImport) {
return ts.isImportSpecifier(node) || ts.isNamespaceImport(node);
}
function extractModuleAndNameFromImport(
node: ts.ImportSpecifier | ts.NamespaceImport | ts.ImportClause,
localName: string | null): {name: string, moduleName: string} {
let name: string;
let moduleSpecifier: ts.Expression;
switch (node.kind) {
case ts.SyntaxKind.ImportSpecifier:
// The symbol was imported by name, in a ts.ImportSpecifier.
name = (node.propertyName || node.name).text;
moduleSpecifier = node.parent.parent.parent.moduleSpecifier;
break;
case ts.SyntaxKind.NamespaceImport:
// The symbol was imported via a namespace import. In this case, the name to use when
// importing it was extracted by resolveTypeSymbols.
if (localName === null) {
// resolveTypeSymbols() should have extracted the correct local name for the import.
throw new Error(`Debug failure: no local name provided for NamespaceImport`);
}
name = localName;
moduleSpecifier = node.parent.parent.moduleSpecifier;
break;
default:
throw new Error(`Unreachable: ${ts.SyntaxKind[(node as ts.Node).kind]}`);
}
if (!ts.isStringLiteral(moduleSpecifier)) {
throw new Error('not a module specifier');
}
const moduleName = moduleSpecifier.text;
return {moduleName, name};
}
| {
// This is a default import.
return {
local: true,
// Copying the name here ensures the generated references will be correctly transformed along
// with the import.
expression: ts.updateIdentifier(firstDecl.name),
defaultImportStatement: firstDecl.parent,
};
} | conditional_block |
type_to_value.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {TypeValueReference} from './host';
/**
* Potentially convert a `ts.TypeNode` to a `TypeValueReference`, which indicates how to use the
* type given in the `ts.TypeNode` in a value position.
*
* This can return `null` if the `typeNode` is `null`, if it does not refer to a symbol with a value
* declaration, or if it is not possible to statically understand.
*/
export function typeToValue(
typeNode: ts.TypeNode | null, checker: ts.TypeChecker): TypeValueReference|null {
// It's not possible to get a value expression if the parameter doesn't even have a type.
if (typeNode === null || !ts.isTypeReferenceNode(typeNode)) {
return null;
}
const symbols = resolveTypeSymbols(typeNode, checker);
if (symbols === null) {
return null;
}
const {local, decl} = symbols;
// It's only valid to convert a type reference to a value reference if the type actually
// has a value declaration associated with it.
if (decl.valueDeclaration === undefined) {
return null;
}
// The type points to a valid value declaration. Rewrite the TypeReference into an
// Expression which references the value pointed to by the TypeReference, if possible.
// Look at the local `ts.Symbol`'s declarations and see if it comes from an import
// statement. If so, extract the module specifier and the name of the imported type.
const firstDecl = local.declarations && local.declarations[0];
if (firstDecl && ts.isImportClause(firstDecl) && firstDecl.name !== undefined) {
// This is a default import.
return {
local: true,
// Copying the name here ensures the generated references will be correctly transformed along
// with the import.
expression: ts.updateIdentifier(firstDecl.name),
defaultImportStatement: firstDecl.parent,
};
} else if (firstDecl && isImportSource(firstDecl)) {
const origin = extractModuleAndNameFromImport(firstDecl, symbols.importName);
return {local: false, valueDeclaration: decl.valueDeclaration, ...origin};
} else {
const expression = typeNodeToValueExpr(typeNode);
if (expression !== null) {
return {
local: true,
expression,
defaultImportStatement: null,
};
} else {
return null;
}
}
}
/**
* Attempt to extract a `ts.Expression` that's equivalent to a `ts.TypeNode`, as the two have
* different AST shapes but can reference the same symbols.
*
* This will return `null` if an equivalent expression cannot be constructed.
*/
export function typeNodeToValueExpr(node: ts.TypeNode): ts.Expression|null {
if (ts.isTypeReferenceNode(node)) {
return entityNameToValue(node.typeName);
} else {
return null;
}
}
/**
* Resolve a `TypeReference` node to the `ts.Symbol`s for both its declaration and its local source.
*
* In the event that the `TypeReference` refers to a locally declared symbol, these will be the
* same. If the `TypeReference` refers to an imported symbol, then `decl` will be the fully resolved
* `ts.Symbol` of the referenced symbol. `local` will be the `ts.Symbol` of the `ts.Identifer` which
* points to the import statement by which the symbol was imported.
*
* In the event `typeRef` refers to a default import, an `importName` will also be returned to
* give the identifier name within the current file by which the import is known.
*/
function resolveTypeSymbols(typeRef: ts.TypeReferenceNode, checker: ts.TypeChecker):
{local: ts.Symbol, decl: ts.Symbol, importName: string | null}|null {
const typeName = typeRef.typeName;
// typeRefSymbol is the ts.Symbol of the entire type reference.
const typeRefSymbol: ts.Symbol|undefined = checker.getSymbolAtLocation(typeName);
if (typeRefSymbol === undefined) {
return null;
}
// local is the ts.Symbol for the local ts.Identifier for the type.
// If the type is actually locally declared or is imported by name, for example:
// import {Foo} from './foo';
// then it'll be the same as top. If the type is imported via a namespace import, for example:
// import * as foo from './foo';
// and then referenced as:
// constructor(f: foo.Foo)
// then local will be the ts.Symbol of `foo`, whereas top will be the ts.Symbol of `foo.Foo`.
// This allows tracking of the import behind whatever type reference exists.
let local = typeRefSymbol;
let importName: string|null = null;
// TODO(alxhub): this is technically not correct. The user could have any import type with any
// amount of qualification following the imported type:
//
// import * as foo from 'foo'
// constructor(inject: foo.X.Y.Z)
//
// What we really want is the ability to express the arbitrary operation of `.X.Y.Z` on top of
// whatever import we generate for 'foo'. This logic is sufficient for now, though.
if (ts.isQualifiedName(typeName) && ts.isIdentifier(typeName.left) &&
ts.isIdentifier(typeName.right)) {
const localTmp = checker.getSymbolAtLocation(typeName.left);
if (localTmp !== undefined) {
local = localTmp;
importName = typeName.right.text;
}
}
// De-alias the top-level type reference symbol to get the symbol of the actual declaration.
let decl = typeRefSymbol;
if (typeRefSymbol.flags & ts.SymbolFlags.Alias) {
decl = checker.getAliasedSymbol(typeRefSymbol);
}
return {local, decl, importName};
}
function entityNameToValue(node: ts.EntityName): ts.Expression|null {
if (ts.isQualifiedName(node)) {
const left = entityNameToValue(node.left);
return left !== null ? ts.createPropertyAccess(left, node.right) : null;
} else if (ts.isIdentifier(node)) {
return ts.getMutableClone(node);
} else {
return null;
}
}
function isImportSource(node: ts.Declaration): node is(ts.ImportSpecifier | ts.NamespaceImport) {
return ts.isImportSpecifier(node) || ts.isNamespaceImport(node);
}
function extractModuleAndNameFromImport(
node: ts.ImportSpecifier | ts.NamespaceImport | ts.ImportClause,
localName: string | null): {name: string, moduleName: string} {
let name: string;
let moduleSpecifier: ts.Expression;
switch (node.kind) {
case ts.SyntaxKind.ImportSpecifier:
// The symbol was imported by name, in a ts.ImportSpecifier.
name = (node.propertyName || node.name).text;
moduleSpecifier = node.parent.parent.parent.moduleSpecifier;
break; | case ts.SyntaxKind.NamespaceImport:
// The symbol was imported via a namespace import. In this case, the name to use when
// importing it was extracted by resolveTypeSymbols.
if (localName === null) {
// resolveTypeSymbols() should have extracted the correct local name for the import.
throw new Error(`Debug failure: no local name provided for NamespaceImport`);
}
name = localName;
moduleSpecifier = node.parent.parent.moduleSpecifier;
break;
default:
throw new Error(`Unreachable: ${ts.SyntaxKind[(node as ts.Node).kind]}`);
}
if (!ts.isStringLiteral(moduleSpecifier)) {
throw new Error('not a module specifier');
}
const moduleName = moduleSpecifier.text;
return {moduleName, name};
} | random_line_split |
|
type_to_value.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {TypeValueReference} from './host';
/**
* Potentially convert a `ts.TypeNode` to a `TypeValueReference`, which indicates how to use the
* type given in the `ts.TypeNode` in a value position.
*
* This can return `null` if the `typeNode` is `null`, if it does not refer to a symbol with a value
* declaration, or if it is not possible to statically understand.
*/
export function typeToValue(
typeNode: ts.TypeNode | null, checker: ts.TypeChecker): TypeValueReference|null {
// It's not possible to get a value expression if the parameter doesn't even have a type.
if (typeNode === null || !ts.isTypeReferenceNode(typeNode)) {
return null;
}
const symbols = resolveTypeSymbols(typeNode, checker);
if (symbols === null) {
return null;
}
const {local, decl} = symbols;
// It's only valid to convert a type reference to a value reference if the type actually
// has a value declaration associated with it.
if (decl.valueDeclaration === undefined) {
return null;
}
// The type points to a valid value declaration. Rewrite the TypeReference into an
// Expression which references the value pointed to by the TypeReference, if possible.
// Look at the local `ts.Symbol`'s declarations and see if it comes from an import
// statement. If so, extract the module specifier and the name of the imported type.
const firstDecl = local.declarations && local.declarations[0];
if (firstDecl && ts.isImportClause(firstDecl) && firstDecl.name !== undefined) {
// This is a default import.
return {
local: true,
// Copying the name here ensures the generated references will be correctly transformed along
// with the import.
expression: ts.updateIdentifier(firstDecl.name),
defaultImportStatement: firstDecl.parent,
};
} else if (firstDecl && isImportSource(firstDecl)) {
const origin = extractModuleAndNameFromImport(firstDecl, symbols.importName);
return {local: false, valueDeclaration: decl.valueDeclaration, ...origin};
} else {
const expression = typeNodeToValueExpr(typeNode);
if (expression !== null) {
return {
local: true,
expression,
defaultImportStatement: null,
};
} else {
return null;
}
}
}
/**
* Attempt to extract a `ts.Expression` that's equivalent to a `ts.TypeNode`, as the two have
* different AST shapes but can reference the same symbols.
*
* This will return `null` if an equivalent expression cannot be constructed.
*/
export function typeNodeToValueExpr(node: ts.TypeNode): ts.Expression|null {
if (ts.isTypeReferenceNode(node)) {
return entityNameToValue(node.typeName);
} else {
return null;
}
}
/**
* Resolve a `TypeReference` node to the `ts.Symbol`s for both its declaration and its local source.
*
* In the event that the `TypeReference` refers to a locally declared symbol, these will be the
* same. If the `TypeReference` refers to an imported symbol, then `decl` will be the fully resolved
* `ts.Symbol` of the referenced symbol. `local` will be the `ts.Symbol` of the `ts.Identifer` which
* points to the import statement by which the symbol was imported.
*
* In the event `typeRef` refers to a default import, an `importName` will also be returned to
* give the identifier name within the current file by which the import is known.
*/
function resolveTypeSymbols(typeRef: ts.TypeReferenceNode, checker: ts.TypeChecker):
{local: ts.Symbol, decl: ts.Symbol, importName: string | null}|null {
const typeName = typeRef.typeName;
// typeRefSymbol is the ts.Symbol of the entire type reference.
const typeRefSymbol: ts.Symbol|undefined = checker.getSymbolAtLocation(typeName);
if (typeRefSymbol === undefined) {
return null;
}
// local is the ts.Symbol for the local ts.Identifier for the type.
// If the type is actually locally declared or is imported by name, for example:
// import {Foo} from './foo';
// then it'll be the same as top. If the type is imported via a namespace import, for example:
// import * as foo from './foo';
// and then referenced as:
// constructor(f: foo.Foo)
// then local will be the ts.Symbol of `foo`, whereas top will be the ts.Symbol of `foo.Foo`.
// This allows tracking of the import behind whatever type reference exists.
let local = typeRefSymbol;
let importName: string|null = null;
// TODO(alxhub): this is technically not correct. The user could have any import type with any
// amount of qualification following the imported type:
//
// import * as foo from 'foo'
// constructor(inject: foo.X.Y.Z)
//
// What we really want is the ability to express the arbitrary operation of `.X.Y.Z` on top of
// whatever import we generate for 'foo'. This logic is sufficient for now, though.
if (ts.isQualifiedName(typeName) && ts.isIdentifier(typeName.left) &&
ts.isIdentifier(typeName.right)) {
const localTmp = checker.getSymbolAtLocation(typeName.left);
if (localTmp !== undefined) {
local = localTmp;
importName = typeName.right.text;
}
}
// De-alias the top-level type reference symbol to get the symbol of the actual declaration.
let decl = typeRefSymbol;
if (typeRefSymbol.flags & ts.SymbolFlags.Alias) {
decl = checker.getAliasedSymbol(typeRefSymbol);
}
return {local, decl, importName};
}
function entityNameToValue(node: ts.EntityName): ts.Expression|null |
function isImportSource(node: ts.Declaration): node is(ts.ImportSpecifier | ts.NamespaceImport) {
return ts.isImportSpecifier(node) || ts.isNamespaceImport(node);
}
function extractModuleAndNameFromImport(
node: ts.ImportSpecifier | ts.NamespaceImport | ts.ImportClause,
localName: string | null): {name: string, moduleName: string} {
let name: string;
let moduleSpecifier: ts.Expression;
switch (node.kind) {
case ts.SyntaxKind.ImportSpecifier:
// The symbol was imported by name, in a ts.ImportSpecifier.
name = (node.propertyName || node.name).text;
moduleSpecifier = node.parent.parent.parent.moduleSpecifier;
break;
case ts.SyntaxKind.NamespaceImport:
// The symbol was imported via a namespace import. In this case, the name to use when
// importing it was extracted by resolveTypeSymbols.
if (localName === null) {
// resolveTypeSymbols() should have extracted the correct local name for the import.
throw new Error(`Debug failure: no local name provided for NamespaceImport`);
}
name = localName;
moduleSpecifier = node.parent.parent.moduleSpecifier;
break;
default:
throw new Error(`Unreachable: ${ts.SyntaxKind[(node as ts.Node).kind]}`);
}
if (!ts.isStringLiteral(moduleSpecifier)) {
throw new Error('not a module specifier');
}
const moduleName = moduleSpecifier.text;
return {moduleName, name};
}
| {
if (ts.isQualifiedName(node)) {
const left = entityNameToValue(node.left);
return left !== null ? ts.createPropertyAccess(left, node.right) : null;
} else if (ts.isIdentifier(node)) {
return ts.getMutableClone(node);
} else {
return null;
}
} | identifier_body |
type_to_value.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {TypeValueReference} from './host';
/**
* Potentially convert a `ts.TypeNode` to a `TypeValueReference`, which indicates how to use the
* type given in the `ts.TypeNode` in a value position.
*
* This can return `null` if the `typeNode` is `null`, if it does not refer to a symbol with a value
* declaration, or if it is not possible to statically understand.
*/
export function typeToValue(
typeNode: ts.TypeNode | null, checker: ts.TypeChecker): TypeValueReference|null {
// It's not possible to get a value expression if the parameter doesn't even have a type.
if (typeNode === null || !ts.isTypeReferenceNode(typeNode)) {
return null;
}
const symbols = resolveTypeSymbols(typeNode, checker);
if (symbols === null) {
return null;
}
const {local, decl} = symbols;
// It's only valid to convert a type reference to a value reference if the type actually
// has a value declaration associated with it.
if (decl.valueDeclaration === undefined) {
return null;
}
// The type points to a valid value declaration. Rewrite the TypeReference into an
// Expression which references the value pointed to by the TypeReference, if possible.
// Look at the local `ts.Symbol`'s declarations and see if it comes from an import
// statement. If so, extract the module specifier and the name of the imported type.
const firstDecl = local.declarations && local.declarations[0];
if (firstDecl && ts.isImportClause(firstDecl) && firstDecl.name !== undefined) {
// This is a default import.
return {
local: true,
// Copying the name here ensures the generated references will be correctly transformed along
// with the import.
expression: ts.updateIdentifier(firstDecl.name),
defaultImportStatement: firstDecl.parent,
};
} else if (firstDecl && isImportSource(firstDecl)) {
const origin = extractModuleAndNameFromImport(firstDecl, symbols.importName);
return {local: false, valueDeclaration: decl.valueDeclaration, ...origin};
} else {
const expression = typeNodeToValueExpr(typeNode);
if (expression !== null) {
return {
local: true,
expression,
defaultImportStatement: null,
};
} else {
return null;
}
}
}
/**
* Attempt to extract a `ts.Expression` that's equivalent to a `ts.TypeNode`, as the two have
* different AST shapes but can reference the same symbols.
*
* This will return `null` if an equivalent expression cannot be constructed.
*/
export function typeNodeToValueExpr(node: ts.TypeNode): ts.Expression|null {
if (ts.isTypeReferenceNode(node)) {
return entityNameToValue(node.typeName);
} else {
return null;
}
}
/**
* Resolve a `TypeReference` node to the `ts.Symbol`s for both its declaration and its local source.
*
* In the event that the `TypeReference` refers to a locally declared symbol, these will be the
* same. If the `TypeReference` refers to an imported symbol, then `decl` will be the fully resolved
* `ts.Symbol` of the referenced symbol. `local` will be the `ts.Symbol` of the `ts.Identifer` which
* points to the import statement by which the symbol was imported.
*
* In the event `typeRef` refers to a default import, an `importName` will also be returned to
* give the identifier name within the current file by which the import is known.
*/
function resolveTypeSymbols(typeRef: ts.TypeReferenceNode, checker: ts.TypeChecker):
{local: ts.Symbol, decl: ts.Symbol, importName: string | null}|null {
const typeName = typeRef.typeName;
// typeRefSymbol is the ts.Symbol of the entire type reference.
const typeRefSymbol: ts.Symbol|undefined = checker.getSymbolAtLocation(typeName);
if (typeRefSymbol === undefined) {
return null;
}
// local is the ts.Symbol for the local ts.Identifier for the type.
// If the type is actually locally declared or is imported by name, for example:
// import {Foo} from './foo';
// then it'll be the same as top. If the type is imported via a namespace import, for example:
// import * as foo from './foo';
// and then referenced as:
// constructor(f: foo.Foo)
// then local will be the ts.Symbol of `foo`, whereas top will be the ts.Symbol of `foo.Foo`.
// This allows tracking of the import behind whatever type reference exists.
let local = typeRefSymbol;
let importName: string|null = null;
// TODO(alxhub): this is technically not correct. The user could have any import type with any
// amount of qualification following the imported type:
//
// import * as foo from 'foo'
// constructor(inject: foo.X.Y.Z)
//
// What we really want is the ability to express the arbitrary operation of `.X.Y.Z` on top of
// whatever import we generate for 'foo'. This logic is sufficient for now, though.
if (ts.isQualifiedName(typeName) && ts.isIdentifier(typeName.left) &&
ts.isIdentifier(typeName.right)) {
const localTmp = checker.getSymbolAtLocation(typeName.left);
if (localTmp !== undefined) {
local = localTmp;
importName = typeName.right.text;
}
}
// De-alias the top-level type reference symbol to get the symbol of the actual declaration.
let decl = typeRefSymbol;
if (typeRefSymbol.flags & ts.SymbolFlags.Alias) {
decl = checker.getAliasedSymbol(typeRefSymbol);
}
return {local, decl, importName};
}
function entityNameToValue(node: ts.EntityName): ts.Expression|null {
if (ts.isQualifiedName(node)) {
const left = entityNameToValue(node.left);
return left !== null ? ts.createPropertyAccess(left, node.right) : null;
} else if (ts.isIdentifier(node)) {
return ts.getMutableClone(node);
} else {
return null;
}
}
function | (node: ts.Declaration): node is(ts.ImportSpecifier | ts.NamespaceImport) {
return ts.isImportSpecifier(node) || ts.isNamespaceImport(node);
}
function extractModuleAndNameFromImport(
node: ts.ImportSpecifier | ts.NamespaceImport | ts.ImportClause,
localName: string | null): {name: string, moduleName: string} {
let name: string;
let moduleSpecifier: ts.Expression;
switch (node.kind) {
case ts.SyntaxKind.ImportSpecifier:
// The symbol was imported by name, in a ts.ImportSpecifier.
name = (node.propertyName || node.name).text;
moduleSpecifier = node.parent.parent.parent.moduleSpecifier;
break;
case ts.SyntaxKind.NamespaceImport:
// The symbol was imported via a namespace import. In this case, the name to use when
// importing it was extracted by resolveTypeSymbols.
if (localName === null) {
// resolveTypeSymbols() should have extracted the correct local name for the import.
throw new Error(`Debug failure: no local name provided for NamespaceImport`);
}
name = localName;
moduleSpecifier = node.parent.parent.moduleSpecifier;
break;
default:
throw new Error(`Unreachable: ${ts.SyntaxKind[(node as ts.Node).kind]}`);
}
if (!ts.isStringLiteral(moduleSpecifier)) {
throw new Error('not a module specifier');
}
const moduleName = moduleSpecifier.text;
return {moduleName, name};
}
| isImportSource | identifier_name |
accept_language.rs | use header::{Language, QualityItem};
header! {
#[doc="`Accept-Language` header, defined in"]
#[doc="[RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.5)"]
#[doc=""]
#[doc="The `Accept-Language` header field can be used by user agents to"]
#[doc="indicate the set of natural languages that are preferred in the"]
#[doc="response."]
#[doc=""]
#[doc="# ABNF"]
#[doc="```plain"]
#[doc="Accept-Language = 1#( language-range [ weight ] )"] | #[doc="* `da, en-gb;q=0.8, en;q=0.7`"]
#[doc="* `en-us;q=1.0, en;q=0.5, fr`"]
(AcceptLanguage, "Accept-Language") => (QualityItem<Language>)+
test_accept_language {
// From the RFC
test_header!(test1, vec![b"da, en-gb;q=0.8, en;q=0.7"]);
// Own test
test_header!(
test2, vec![b"en-us, en; q=0.5, fr"],
Some(AcceptLanguage(vec![
qitem(Language {primary: "en".to_string(), sub: Some("us".to_string())}),
QualityItem::new(Language{primary: "en".to_string(), sub: None}, Quality(500)),
qitem(Language {primary: "fr".to_string(), sub: None}),
])));
}
}
bench_header!(bench, AcceptLanguage,
{ vec![b"en-us;q=1.0, en;q=0.5, fr".to_vec()] }); | #[doc="language-range = <language-range, see [RFC4647], Section 2.1>"]
#[doc="```"]
#[doc=""]
#[doc="# Example values"] | random_line_split |
manticore_protocol_cerberus_GetCert__req_to_wire.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
// !! DO NOT EDIT !!
// To regenerate this file, run `fuzz/generate_proto_tests.py`.
#![no_main]
#![allow(non_snake_case)]
use libfuzzer_sys::fuzz_target;
use manticore::protocol::Command;
use manticore::protocol::wire::ToWire;
use manticore::protocol::borrowed::AsStatic;
use manticore::protocol::borrowed::Borrowed;
use manticore::protocol::cerberus::GetCert as C;
type Req<'a> = <C as Command<'a>>::Req;
fuzz_target!(|data: AsStatic<'static, Req<'static>>| {
let mut out = [0u8; 1024]; | let _ = Req::borrow(&data).to_wire(&mut &mut out[..]);
}); | random_line_split |
|
boxed.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A pointer type for heap allocation.
//!
//! `Box<T>`, casually referred to as a 'box', provides the simplest form of
//! heap allocation in Rust. Boxes provide ownership for this allocation, and
//! drop their contents when they go out of scope.
//!
//! # Examples
//!
//! Creating a box:
//!
//! ```
//! let x = Box::new(5);
//! ```
//!
//! Creating a recursive data structure:
//!
//! ```
//! #[derive(Debug)]
//! enum List<T> {
//! Cons(T, Box<List<T>>),
//! Nil,
//! }
//!
//! fn main() {
//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//! println!("{:?}", list);
//! }
//! ```
//!
//! This will print `Cons(1, Cons(2, Nil))`.
//!
//! Recursive structures must be boxed, because if the definition of `Cons`
//! looked like this:
//!
//! ```rust,ignore
//! Cons(T, List<T>),
//! ```
//!
//! It wouldn't work. This is because the size of a `List` depends on how many
//! elements are in the list, and so we don't know how much memory to allocate
//! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
//! big `Cons` needs to be.
#![stable(feature = "rust1", since = "1.0.0")]
use core::prelude::*;
use core::any::Any;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{self, Hash};
use core::marker::Unsize;
use core::mem;
use core::ops::{CoerceUnsized, Deref, DerefMut};
use core::ptr::Unique;
use core::raw::{TraitObject};
/// A value that represents the heap. This is the default place that the `box`
/// keyword allocates into when no place is supplied.
///
/// The following two examples are equivalent:
///
/// ```
/// # #![feature(box_heap)]
/// #![feature(box_syntax)]
/// use std::boxed::HEAP;
///
/// fn main() {
/// let foo = box(HEAP) 5;
/// let foo = box 5;
/// }
/// ```
#[lang = "exchange_heap"]
#[unstable(feature = "box_heap",
reason = "may be renamed; uncertain about custom allocator design")]
pub const HEAP: () = ();
/// A pointer type for heap allocation.
///
/// See the [module-level documentation](../../std/boxed/index.html) for more.
#[lang = "owned_box"]
#[stable(feature = "rust1", since = "1.0.0")]
#[fundamental]
pub struct Box<T>(Unique<T>);
impl<T> Box<T> {
/// Allocates memory on the heap and then moves `x` into it.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
pub fn new(x: T) -> Box<T> {
box x
}
}
impl<T : ?Sized> Box<T> {
/// Constructs a box from the raw pointer.
///
/// After this function call, pointer is owned by resulting box.
/// In particular, it means that `Box` destructor calls destructor
/// of `T` and releases memory. Since the way `Box` allocates and
/// releases memory is unspecified, the only valid pointer to pass
/// to this function is the one taken from another `Box` with
/// `Box::into_raw` function.
///
/// Function is unsafe, because improper use of this function may
/// lead to memory problems like double-free, for example if the
/// function is called twice on the same raw pointer.
#[unstable(feature = "box_raw",
reason = "may be renamed or moved out of Box scope")]
#[inline]
// NB: may want to be called from_ptr, see comments on CStr::from_ptr
pub unsafe fn from_raw(raw: *mut T) -> Self {
mem::transmute(raw)
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// # Examples
/// ```
/// # #![feature(box_raw)]
/// let seventeen = Box::new(17u32);
/// let raw = Box::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "box_raw", reason = "may be renamed")]
#[inline]
// NB: may want to be called into_ptr, see comments on CStr::from_ptr
pub fn into_raw(b: Box<T>) -> *mut T {
unsafe { mem::transmute(b) }
}
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// # Examples
/// ```
/// # #![feature(box_raw)]
/// use std::boxed;
///
/// let seventeen = Box::new(17u32);
/// let raw = boxed::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "box_raw", reason = "may be renamed")]
#[deprecated(since = "1.2.0", reason = "renamed to Box::into_raw")]
#[inline]
pub fn into_raw<T : ?Sized>(b: Box<T>) -> *mut T {
Box::into_raw(b)
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Default> Default for Box<T> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<T> { box Default::default() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Box<[T]> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for Box<T> {
/// Returns a new box with a `clone()` of this box's contents.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let y = x.clone();
/// ```
#[inline]
fn clone(&self) -> Box<T> { box {(**self).clone()} }
/// Copies `source`'s contents into `self` without creating a new allocation.
///
/// # Examples
///
/// ```
/// # #![feature(box_raw)]
/// let x = Box::new(5);
/// let mut y = Box::new(10);
///
/// y.clone_from(&x);
///
/// assert_eq!(*y, 5);
/// ```
#[inline]
fn clone_from(&mut self, source: &Box<T>) {
(**self).clone_from(&(**source));
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
#[inline]
fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
#[inline]
fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
#[inline]
fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
#[inline]
fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
#[inline]
fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
#[inline]
fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Ord> Ord for Box<T> {
#[inline]
fn cmp(&self, other: &Box<T>) -> Ordering {
Ord::cmp(&**self, &**other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Eq> Eq for Box<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Hash> Hash for Box<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
| pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let raw = Box::into_raw(self);
let to: TraitObject =
mem::transmute::<*mut Any, TraitObject>(raw);
// Extract the data pointer
Ok(Box::from_raw(to.data as *mut T))
}
} else {
Err(self)
}
}
}
impl Box<Any + Send> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
<Box<Any>>::downcast(self).map_err(|s| unsafe {
// reapply the Send marker
mem::transmute::<Box<Any>, Box<Any + Send>>(s)
})
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Pointer for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// It's not possible to extract the inner Uniq directly from the Box,
// instead we cast it to a *const which aliases the Unique
let ptr: *const T = &**self;
fmt::Pointer::fmt(&ptr, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Deref for Box<T> {
type Target = T;
fn deref(&self) -> &T { &**self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> DerefMut for Box<T> {
fn deref_mut(&mut self) -> &mut T { &mut **self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator + ?Sized> Iterator for Box<I> {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> { (**self).next() }
fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {}
/// `FnBox` is a version of the `FnOnce` intended for use with boxed
/// closure objects. The idea is that where one would normally store a
/// `Box<FnOnce()>` in a data structure, you should use
/// `Box<FnBox()>`. The two traits behave essentially the same, except
/// that a `FnBox` closure can only be called if it is boxed. (Note
/// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
/// closures become directly usable.)
///
/// ### Example
///
/// Here is a snippet of code which creates a hashmap full of boxed
/// once closures and then removes them one by one, calling each
/// closure as it is removed. Note that the type of the closures
/// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
/// -> i32>`.
///
/// ```
/// #![feature(fnbox)]
///
/// use std::boxed::FnBox;
/// use std::collections::HashMap;
///
/// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
/// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
/// map.insert(1, Box::new(|| 22));
/// map.insert(2, Box::new(|| 44));
/// map
/// }
///
/// fn main() {
/// let mut map = make_map();
/// for i in &[1, 2] {
/// let f = map.remove(&i).unwrap();
/// assert_eq!(f(), i * 22);
/// }
/// }
/// ```
#[rustc_paren_sugar]
#[unstable(feature = "fnbox", reason = "Newly introduced")]
pub trait FnBox<A> {
type Output;
fn call_box(self: Box<Self>, args: A) -> Self::Output;
}
impl<A,F> FnBox<A> for F
where F: FnOnce<A>
{
type Output = F::Output;
fn call_box(self: Box<F>, args: A) -> F::Output {
self.call_once(args)
}
}
impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+'a> {
type Output = R;
extern "rust-call" fn call_once(self, args: A) -> R {
self.call_box(args)
}
}
impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+Send+'a> {
type Output = R;
extern "rust-call" fn call_once(self, args: A) -> R {
self.call_box(args)
}
}
impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {} | impl Box<Any> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type. | random_line_split |
boxed.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A pointer type for heap allocation.
//!
//! `Box<T>`, casually referred to as a 'box', provides the simplest form of
//! heap allocation in Rust. Boxes provide ownership for this allocation, and
//! drop their contents when they go out of scope.
//!
//! # Examples
//!
//! Creating a box:
//!
//! ```
//! let x = Box::new(5);
//! ```
//!
//! Creating a recursive data structure:
//!
//! ```
//! #[derive(Debug)]
//! enum List<T> {
//! Cons(T, Box<List<T>>),
//! Nil,
//! }
//!
//! fn main() {
//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//! println!("{:?}", list);
//! }
//! ```
//!
//! This will print `Cons(1, Cons(2, Nil))`.
//!
//! Recursive structures must be boxed, because if the definition of `Cons`
//! looked like this:
//!
//! ```rust,ignore
//! Cons(T, List<T>),
//! ```
//!
//! It wouldn't work. This is because the size of a `List` depends on how many
//! elements are in the list, and so we don't know how much memory to allocate
//! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
//! big `Cons` needs to be.
#![stable(feature = "rust1", since = "1.0.0")]
use core::prelude::*;
use core::any::Any;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{self, Hash};
use core::marker::Unsize;
use core::mem;
use core::ops::{CoerceUnsized, Deref, DerefMut};
use core::ptr::Unique;
use core::raw::{TraitObject};
/// A value that represents the heap. This is the default place that the `box`
/// keyword allocates into when no place is supplied.
///
/// The following two examples are equivalent:
///
/// ```
/// # #![feature(box_heap)]
/// #![feature(box_syntax)]
/// use std::boxed::HEAP;
///
/// fn main() {
/// let foo = box(HEAP) 5;
/// let foo = box 5;
/// }
/// ```
#[lang = "exchange_heap"]
#[unstable(feature = "box_heap",
reason = "may be renamed; uncertain about custom allocator design")]
pub const HEAP: () = ();
/// A pointer type for heap allocation.
///
/// See the [module-level documentation](../../std/boxed/index.html) for more.
#[lang = "owned_box"]
#[stable(feature = "rust1", since = "1.0.0")]
#[fundamental]
pub struct Box<T>(Unique<T>);
impl<T> Box<T> {
/// Allocates memory on the heap and then moves `x` into it.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
pub fn new(x: T) -> Box<T> {
box x
}
}
impl<T : ?Sized> Box<T> {
/// Constructs a box from the raw pointer.
///
/// After this function call, pointer is owned by resulting box.
/// In particular, it means that `Box` destructor calls destructor
/// of `T` and releases memory. Since the way `Box` allocates and
/// releases memory is unspecified, the only valid pointer to pass
/// to this function is the one taken from another `Box` with
/// `Box::into_raw` function.
///
/// Function is unsafe, because improper use of this function may
/// lead to memory problems like double-free, for example if the
/// function is called twice on the same raw pointer.
#[unstable(feature = "box_raw",
reason = "may be renamed or moved out of Box scope")]
#[inline]
// NB: may want to be called from_ptr, see comments on CStr::from_ptr
pub unsafe fn from_raw(raw: *mut T) -> Self {
mem::transmute(raw)
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// # Examples
/// ```
/// # #![feature(box_raw)]
/// let seventeen = Box::new(17u32);
/// let raw = Box::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "box_raw", reason = "may be renamed")]
#[inline]
// NB: may want to be called into_ptr, see comments on CStr::from_ptr
pub fn into_raw(b: Box<T>) -> *mut T {
unsafe { mem::transmute(b) }
}
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// # Examples
/// ```
/// # #![feature(box_raw)]
/// use std::boxed;
///
/// let seventeen = Box::new(17u32);
/// let raw = boxed::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "box_raw", reason = "may be renamed")]
#[deprecated(since = "1.2.0", reason = "renamed to Box::into_raw")]
#[inline]
pub fn into_raw<T : ?Sized>(b: Box<T>) -> *mut T {
Box::into_raw(b)
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Default> Default for Box<T> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<T> { box Default::default() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Box<[T]> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<[T]> |
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for Box<T> {
/// Returns a new box with a `clone()` of this box's contents.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let y = x.clone();
/// ```
#[inline]
fn clone(&self) -> Box<T> { box {(**self).clone()} }
/// Copies `source`'s contents into `self` without creating a new allocation.
///
/// # Examples
///
/// ```
/// # #![feature(box_raw)]
/// let x = Box::new(5);
/// let mut y = Box::new(10);
///
/// y.clone_from(&x);
///
/// assert_eq!(*y, 5);
/// ```
#[inline]
fn clone_from(&mut self, source: &Box<T>) {
(**self).clone_from(&(**source));
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
#[inline]
fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
#[inline]
fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
#[inline]
fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
#[inline]
fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
#[inline]
fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
#[inline]
fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Ord> Ord for Box<T> {
#[inline]
fn cmp(&self, other: &Box<T>) -> Ordering {
Ord::cmp(&**self, &**other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Eq> Eq for Box<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Hash> Hash for Box<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
impl Box<Any> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let raw = Box::into_raw(self);
let to: TraitObject =
mem::transmute::<*mut Any, TraitObject>(raw);
// Extract the data pointer
Ok(Box::from_raw(to.data as *mut T))
}
} else {
Err(self)
}
}
}
impl Box<Any + Send> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
<Box<Any>>::downcast(self).map_err(|s| unsafe {
// reapply the Send marker
mem::transmute::<Box<Any>, Box<Any + Send>>(s)
})
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Pointer for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// It's not possible to extract the inner Uniq directly from the Box,
// instead we cast it to a *const which aliases the Unique
let ptr: *const T = &**self;
fmt::Pointer::fmt(&ptr, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Deref for Box<T> {
type Target = T;
fn deref(&self) -> &T { &**self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> DerefMut for Box<T> {
fn deref_mut(&mut self) -> &mut T { &mut **self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator + ?Sized> Iterator for Box<I> {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> { (**self).next() }
fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {}
/// `FnBox` is a version of the `FnOnce` intended for use with boxed
/// closure objects. The idea is that where one would normally store a
/// `Box<FnOnce()>` in a data structure, you should use
/// `Box<FnBox()>`. The two traits behave essentially the same, except
/// that a `FnBox` closure can only be called if it is boxed. (Note
/// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
/// closures become directly usable.)
///
/// ### Example
///
/// Here is a snippet of code which creates a hashmap full of boxed
/// once closures and then removes them one by one, calling each
/// closure as it is removed. Note that the type of the closures
/// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
/// -> i32>`.
///
/// ```
/// #![feature(fnbox)]
///
/// use std::boxed::FnBox;
/// use std::collections::HashMap;
///
/// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
/// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
/// map.insert(1, Box::new(|| 22));
/// map.insert(2, Box::new(|| 44));
/// map
/// }
///
/// fn main() {
/// let mut map = make_map();
/// for i in &[1, 2] {
/// let f = map.remove(&i).unwrap();
/// assert_eq!(f(), i * 22);
/// }
/// }
/// ```
#[rustc_paren_sugar]
#[unstable(feature = "fnbox", reason = "Newly introduced")]
pub trait FnBox<A> {
type Output;
fn call_box(self: Box<Self>, args: A) -> Self::Output;
}
impl<A,F> FnBox<A> for F
where F: FnOnce<A>
{
type Output = F::Output;
fn call_box(self: Box<F>, args: A) -> F::Output {
self.call_once(args)
}
}
impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+'a> {
type Output = R;
extern "rust-call" fn call_once(self, args: A) -> R {
self.call_box(args)
}
}
impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+Send+'a> {
type Output = R;
extern "rust-call" fn call_once(self, args: A) -> R {
self.call_box(args)
}
}
impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
| { Box::<[T; 0]>::new([]) } | identifier_body |
boxed.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A pointer type for heap allocation.
//!
//! `Box<T>`, casually referred to as a 'box', provides the simplest form of
//! heap allocation in Rust. Boxes provide ownership for this allocation, and
//! drop their contents when they go out of scope.
//!
//! # Examples
//!
//! Creating a box:
//!
//! ```
//! let x = Box::new(5);
//! ```
//!
//! Creating a recursive data structure:
//!
//! ```
//! #[derive(Debug)]
//! enum List<T> {
//! Cons(T, Box<List<T>>),
//! Nil,
//! }
//!
//! fn main() {
//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//! println!("{:?}", list);
//! }
//! ```
//!
//! This will print `Cons(1, Cons(2, Nil))`.
//!
//! Recursive structures must be boxed, because if the definition of `Cons`
//! looked like this:
//!
//! ```rust,ignore
//! Cons(T, List<T>),
//! ```
//!
//! It wouldn't work. This is because the size of a `List` depends on how many
//! elements are in the list, and so we don't know how much memory to allocate
//! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
//! big `Cons` needs to be.
#![stable(feature = "rust1", since = "1.0.0")]
use core::prelude::*;
use core::any::Any;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{self, Hash};
use core::marker::Unsize;
use core::mem;
use core::ops::{CoerceUnsized, Deref, DerefMut};
use core::ptr::Unique;
use core::raw::{TraitObject};
/// A value that represents the heap. This is the default place that the `box`
/// keyword allocates into when no place is supplied.
///
/// The following two examples are equivalent:
///
/// ```
/// # #![feature(box_heap)]
/// #![feature(box_syntax)]
/// use std::boxed::HEAP;
///
/// fn main() {
/// let foo = box(HEAP) 5;
/// let foo = box 5;
/// }
/// ```
#[lang = "exchange_heap"]
#[unstable(feature = "box_heap",
reason = "may be renamed; uncertain about custom allocator design")]
pub const HEAP: () = ();
/// A pointer type for heap allocation.
///
/// See the [module-level documentation](../../std/boxed/index.html) for more.
#[lang = "owned_box"]
#[stable(feature = "rust1", since = "1.0.0")]
#[fundamental]
pub struct Box<T>(Unique<T>);
impl<T> Box<T> {
/// Allocates memory on the heap and then moves `x` into it.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
pub fn new(x: T) -> Box<T> {
box x
}
}
impl<T : ?Sized> Box<T> {
/// Constructs a box from the raw pointer.
///
/// After this function call, pointer is owned by resulting box.
/// In particular, it means that `Box` destructor calls destructor
/// of `T` and releases memory. Since the way `Box` allocates and
/// releases memory is unspecified, the only valid pointer to pass
/// to this function is the one taken from another `Box` with
/// `Box::into_raw` function.
///
/// Function is unsafe, because improper use of this function may
/// lead to memory problems like double-free, for example if the
/// function is called twice on the same raw pointer.
#[unstable(feature = "box_raw",
reason = "may be renamed or moved out of Box scope")]
#[inline]
// NB: may want to be called from_ptr, see comments on CStr::from_ptr
pub unsafe fn from_raw(raw: *mut T) -> Self {
mem::transmute(raw)
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// # Examples
/// ```
/// # #![feature(box_raw)]
/// let seventeen = Box::new(17u32);
/// let raw = Box::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "box_raw", reason = "may be renamed")]
#[inline]
// NB: may want to be called into_ptr, see comments on CStr::from_ptr
pub fn into_raw(b: Box<T>) -> *mut T {
unsafe { mem::transmute(b) }
}
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// # Examples
/// ```
/// # #![feature(box_raw)]
/// use std::boxed;
///
/// let seventeen = Box::new(17u32);
/// let raw = boxed::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "box_raw", reason = "may be renamed")]
#[deprecated(since = "1.2.0", reason = "renamed to Box::into_raw")]
#[inline]
pub fn into_raw<T : ?Sized>(b: Box<T>) -> *mut T {
Box::into_raw(b)
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Default> Default for Box<T> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<T> { box Default::default() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Box<[T]> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for Box<T> {
/// Returns a new box with a `clone()` of this box's contents.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let y = x.clone();
/// ```
#[inline]
fn clone(&self) -> Box<T> { box {(**self).clone()} }
/// Copies `source`'s contents into `self` without creating a new allocation.
///
/// # Examples
///
/// ```
/// # #![feature(box_raw)]
/// let x = Box::new(5);
/// let mut y = Box::new(10);
///
/// y.clone_from(&x);
///
/// assert_eq!(*y, 5);
/// ```
#[inline]
fn clone_from(&mut self, source: &Box<T>) {
(**self).clone_from(&(**source));
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
#[inline]
fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
#[inline]
fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
#[inline]
fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
#[inline]
fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
#[inline]
fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
#[inline]
fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Ord> Ord for Box<T> {
#[inline]
fn cmp(&self, other: &Box<T>) -> Ordering {
Ord::cmp(&**self, &**other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Eq> Eq for Box<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Hash> Hash for Box<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
impl Box<Any> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
if self.is::<T>() | else {
Err(self)
}
}
}
impl Box<Any + Send> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
<Box<Any>>::downcast(self).map_err(|s| unsafe {
// reapply the Send marker
mem::transmute::<Box<Any>, Box<Any + Send>>(s)
})
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Pointer for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// It's not possible to extract the inner Uniq directly from the Box,
// instead we cast it to a *const which aliases the Unique
let ptr: *const T = &**self;
fmt::Pointer::fmt(&ptr, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Deref for Box<T> {
type Target = T;
fn deref(&self) -> &T { &**self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> DerefMut for Box<T> {
fn deref_mut(&mut self) -> &mut T { &mut **self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator + ?Sized> Iterator for Box<I> {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> { (**self).next() }
fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {}
/// `FnBox` is a version of the `FnOnce` intended for use with boxed
/// closure objects. The idea is that where one would normally store a
/// `Box<FnOnce()>` in a data structure, you should use
/// `Box<FnBox()>`. The two traits behave essentially the same, except
/// that a `FnBox` closure can only be called if it is boxed. (Note
/// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
/// closures become directly usable.)
///
/// ### Example
///
/// Here is a snippet of code which creates a hashmap full of boxed
/// once closures and then removes them one by one, calling each
/// closure as it is removed. Note that the type of the closures
/// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
/// -> i32>`.
///
/// ```
/// #![feature(fnbox)]
///
/// use std::boxed::FnBox;
/// use std::collections::HashMap;
///
/// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
/// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
/// map.insert(1, Box::new(|| 22));
/// map.insert(2, Box::new(|| 44));
/// map
/// }
///
/// fn main() {
/// let mut map = make_map();
/// for i in &[1, 2] {
/// let f = map.remove(&i).unwrap();
/// assert_eq!(f(), i * 22);
/// }
/// }
/// ```
#[rustc_paren_sugar]
#[unstable(feature = "fnbox", reason = "Newly introduced")]
pub trait FnBox<A> {
type Output;
fn call_box(self: Box<Self>, args: A) -> Self::Output;
}
impl<A,F> FnBox<A> for F
where F: FnOnce<A>
{
type Output = F::Output;
fn call_box(self: Box<F>, args: A) -> F::Output {
self.call_once(args)
}
}
impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+'a> {
type Output = R;
extern "rust-call" fn call_once(self, args: A) -> R {
self.call_box(args)
}
}
impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+Send+'a> {
type Output = R;
extern "rust-call" fn call_once(self, args: A) -> R {
self.call_box(args)
}
}
impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
| {
unsafe {
// Get the raw representation of the trait object
let raw = Box::into_raw(self);
let to: TraitObject =
mem::transmute::<*mut Any, TraitObject>(raw);
// Extract the data pointer
Ok(Box::from_raw(to.data as *mut T))
}
} | conditional_block |
boxed.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A pointer type for heap allocation.
//!
//! `Box<T>`, casually referred to as a 'box', provides the simplest form of
//! heap allocation in Rust. Boxes provide ownership for this allocation, and
//! drop their contents when they go out of scope.
//!
//! # Examples
//!
//! Creating a box:
//!
//! ```
//! let x = Box::new(5);
//! ```
//!
//! Creating a recursive data structure:
//!
//! ```
//! #[derive(Debug)]
//! enum List<T> {
//! Cons(T, Box<List<T>>),
//! Nil,
//! }
//!
//! fn main() {
//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//! println!("{:?}", list);
//! }
//! ```
//!
//! This will print `Cons(1, Cons(2, Nil))`.
//!
//! Recursive structures must be boxed, because if the definition of `Cons`
//! looked like this:
//!
//! ```rust,ignore
//! Cons(T, List<T>),
//! ```
//!
//! It wouldn't work. This is because the size of a `List` depends on how many
//! elements are in the list, and so we don't know how much memory to allocate
//! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
//! big `Cons` needs to be.
#![stable(feature = "rust1", since = "1.0.0")]
use core::prelude::*;
use core::any::Any;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{self, Hash};
use core::marker::Unsize;
use core::mem;
use core::ops::{CoerceUnsized, Deref, DerefMut};
use core::ptr::Unique;
use core::raw::{TraitObject};
/// A value that represents the heap. This is the default place that the `box`
/// keyword allocates into when no place is supplied.
///
/// The following two examples are equivalent:
///
/// ```
/// # #![feature(box_heap)]
/// #![feature(box_syntax)]
/// use std::boxed::HEAP;
///
/// fn main() {
/// let foo = box(HEAP) 5;
/// let foo = box 5;
/// }
/// ```
#[lang = "exchange_heap"]
#[unstable(feature = "box_heap",
reason = "may be renamed; uncertain about custom allocator design")]
pub const HEAP: () = ();
/// A pointer type for heap allocation.
///
/// See the [module-level documentation](../../std/boxed/index.html) for more.
#[lang = "owned_box"]
#[stable(feature = "rust1", since = "1.0.0")]
#[fundamental]
pub struct Box<T>(Unique<T>);
impl<T> Box<T> {
/// Allocates memory on the heap and then moves `x` into it.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
pub fn new(x: T) -> Box<T> {
box x
}
}
impl<T : ?Sized> Box<T> {
/// Constructs a box from the raw pointer.
///
/// After this function call, pointer is owned by resulting box.
/// In particular, it means that `Box` destructor calls destructor
/// of `T` and releases memory. Since the way `Box` allocates and
/// releases memory is unspecified, the only valid pointer to pass
/// to this function is the one taken from another `Box` with
/// `Box::into_raw` function.
///
/// Function is unsafe, because improper use of this function may
/// lead to memory problems like double-free, for example if the
/// function is called twice on the same raw pointer.
#[unstable(feature = "box_raw",
reason = "may be renamed or moved out of Box scope")]
#[inline]
// NB: may want to be called from_ptr, see comments on CStr::from_ptr
pub unsafe fn from_raw(raw: *mut T) -> Self {
mem::transmute(raw)
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// # Examples
/// ```
/// # #![feature(box_raw)]
/// let seventeen = Box::new(17u32);
/// let raw = Box::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "box_raw", reason = "may be renamed")]
#[inline]
// NB: may want to be called into_ptr, see comments on CStr::from_ptr
pub fn into_raw(b: Box<T>) -> *mut T {
unsafe { mem::transmute(b) }
}
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// # Examples
/// ```
/// # #![feature(box_raw)]
/// use std::boxed;
///
/// let seventeen = Box::new(17u32);
/// let raw = boxed::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "box_raw", reason = "may be renamed")]
#[deprecated(since = "1.2.0", reason = "renamed to Box::into_raw")]
#[inline]
pub fn into_raw<T : ?Sized>(b: Box<T>) -> *mut T {
Box::into_raw(b)
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Default> Default for Box<T> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<T> { box Default::default() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Box<[T]> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for Box<T> {
/// Returns a new box with a `clone()` of this box's contents.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let y = x.clone();
/// ```
#[inline]
fn clone(&self) -> Box<T> { box {(**self).clone()} }
/// Copies `source`'s contents into `self` without creating a new allocation.
///
/// # Examples
///
/// ```
/// # #![feature(box_raw)]
/// let x = Box::new(5);
/// let mut y = Box::new(10);
///
/// y.clone_from(&x);
///
/// assert_eq!(*y, 5);
/// ```
#[inline]
fn clone_from(&mut self, source: &Box<T>) {
(**self).clone_from(&(**source));
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
#[inline]
fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
#[inline]
fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
#[inline]
fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
#[inline]
fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
#[inline]
fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
#[inline]
fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Ord> Ord for Box<T> {
#[inline]
fn cmp(&self, other: &Box<T>) -> Ordering {
Ord::cmp(&**self, &**other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Eq> Eq for Box<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Hash> Hash for Box<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
impl Box<Any> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let raw = Box::into_raw(self);
let to: TraitObject =
mem::transmute::<*mut Any, TraitObject>(raw);
// Extract the data pointer
Ok(Box::from_raw(to.data as *mut T))
}
} else {
Err(self)
}
}
}
impl Box<Any + Send> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
pub fn | <T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
<Box<Any>>::downcast(self).map_err(|s| unsafe {
// reapply the Send marker
mem::transmute::<Box<Any>, Box<Any + Send>>(s)
})
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Pointer for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// It's not possible to extract the inner Uniq directly from the Box,
// instead we cast it to a *const which aliases the Unique
let ptr: *const T = &**self;
fmt::Pointer::fmt(&ptr, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Deref for Box<T> {
type Target = T;
fn deref(&self) -> &T { &**self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> DerefMut for Box<T> {
fn deref_mut(&mut self) -> &mut T { &mut **self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator + ?Sized> Iterator for Box<I> {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> { (**self).next() }
fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {}
/// `FnBox` is a version of the `FnOnce` intended for use with boxed
/// closure objects. The idea is that where one would normally store a
/// `Box<FnOnce()>` in a data structure, you should use
/// `Box<FnBox()>`. The two traits behave essentially the same, except
/// that a `FnBox` closure can only be called if it is boxed. (Note
/// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
/// closures become directly usable.)
///
/// ### Example
///
/// Here is a snippet of code which creates a hashmap full of boxed
/// once closures and then removes them one by one, calling each
/// closure as it is removed. Note that the type of the closures
/// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
/// -> i32>`.
///
/// ```
/// #![feature(fnbox)]
///
/// use std::boxed::FnBox;
/// use std::collections::HashMap;
///
/// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
/// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
/// map.insert(1, Box::new(|| 22));
/// map.insert(2, Box::new(|| 44));
/// map
/// }
///
/// fn main() {
/// let mut map = make_map();
/// for i in &[1, 2] {
/// let f = map.remove(&i).unwrap();
/// assert_eq!(f(), i * 22);
/// }
/// }
/// ```
#[rustc_paren_sugar]
#[unstable(feature = "fnbox", reason = "Newly introduced")]
pub trait FnBox<A> {
type Output;
fn call_box(self: Box<Self>, args: A) -> Self::Output;
}
impl<A,F> FnBox<A> for F
where F: FnOnce<A>
{
type Output = F::Output;
fn call_box(self: Box<F>, args: A) -> F::Output {
self.call_once(args)
}
}
impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+'a> {
type Output = R;
extern "rust-call" fn call_once(self, args: A) -> R {
self.call_box(args)
}
}
impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+Send+'a> {
type Output = R;
extern "rust-call" fn call_once(self, args: A) -> R {
self.call_box(args)
}
}
impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
| downcast | identifier_name |
serialization_profile.py | from __future__ import print_function
import shutil
import os.path
import tempfile
import cProfile
import pstats
import nineml
from nineml.utils.comprehensive_example import (
instances_of_all_types, v1_safe_docs)
from nineml.serialization import ext_to_format, format_to_serializer
format_to_ext = dict((v, k) for k, v in ext_to_format.items()) # @UndefinedVariable @IgnorePep8
print_serialized = False
printable = ('xml', 'json', 'yaml')
_tmp_dir = tempfile.mkdtemp()
def | ():
for version in (1.0, 2.0):
if version == 1.0:
docs = v1_safe_docs
else:
docs = list(instances_of_all_types['NineML'].values())
for format in format_to_serializer: # @ReservedAssignment
try:
ext = format_to_ext[format]
except KeyError:
continue # ones that can't be written to file (e.g. dict)
for i, document in enumerate(docs):
doc = document.clone()
url = os.path.join(
_tmp_dir, 'test{}v{}{}'.format(i, version, ext))
nineml.write(url, doc, format=format, version=version,
indent=2)
if print_serialized and format in printable:
with open(url) as f:
print(f.read())
reread_doc = nineml.read(url, reload=True) # @UnusedVariable
shutil.rmtree(_tmp_dir)
out_file = os.path.join(os.getcwd(), 'serial_profile.out')
cProfile.run('function()', out_file)
p = pstats.Stats(out_file)
p.sort_stats('cumtime').print_stats()
| function | identifier_name |
serialization_profile.py | from __future__ import print_function
import shutil
import os.path
import tempfile
import cProfile
import pstats
import nineml
from nineml.utils.comprehensive_example import (
instances_of_all_types, v1_safe_docs)
from nineml.serialization import ext_to_format, format_to_serializer
format_to_ext = dict((v, k) for k, v in ext_to_format.items()) # @UndefinedVariable @IgnorePep8
print_serialized = False
printable = ('xml', 'json', 'yaml')
_tmp_dir = tempfile.mkdtemp()
def function():
for version in (1.0, 2.0):
if version == 1.0:
docs = v1_safe_docs
else:
docs = list(instances_of_all_types['NineML'].values())
for format in format_to_serializer: # @ReservedAssignment
|
shutil.rmtree(_tmp_dir)
out_file = os.path.join(os.getcwd(), 'serial_profile.out')
cProfile.run('function()', out_file)
p = pstats.Stats(out_file)
p.sort_stats('cumtime').print_stats()
| try:
ext = format_to_ext[format]
except KeyError:
continue # ones that can't be written to file (e.g. dict)
for i, document in enumerate(docs):
doc = document.clone()
url = os.path.join(
_tmp_dir, 'test{}v{}{}'.format(i, version, ext))
nineml.write(url, doc, format=format, version=version,
indent=2)
if print_serialized and format in printable:
with open(url) as f:
print(f.read())
reread_doc = nineml.read(url, reload=True) # @UnusedVariable | conditional_block |
serialization_profile.py | from __future__ import print_function
import shutil
import os.path
import tempfile
import cProfile
import pstats
import nineml
from nineml.utils.comprehensive_example import (
instances_of_all_types, v1_safe_docs)
from nineml.serialization import ext_to_format, format_to_serializer
format_to_ext = dict((v, k) for k, v in ext_to_format.items()) # @UndefinedVariable @IgnorePep8
print_serialized = False
printable = ('xml', 'json', 'yaml')
_tmp_dir = tempfile.mkdtemp()
def function():
for version in (1.0, 2.0):
if version == 1.0:
docs = v1_safe_docs
else:
docs = list(instances_of_all_types['NineML'].values())
for format in format_to_serializer: # @ReservedAssignment
try:
ext = format_to_ext[format]
except KeyError:
continue # ones that can't be written to file (e.g. dict)
for i, document in enumerate(docs):
doc = document.clone()
url = os.path.join(
_tmp_dir, 'test{}v{}{}'.format(i, version, ext))
nineml.write(url, doc, format=format, version=version,
indent=2)
if print_serialized and format in printable:
with open(url) as f:
print(f.read())
reread_doc = nineml.read(url, reload=True) # @UnusedVariable
shutil.rmtree(_tmp_dir)
out_file = os.path.join(os.getcwd(), 'serial_profile.out')
|
p = pstats.Stats(out_file)
p.sort_stats('cumtime').print_stats() | cProfile.run('function()', out_file) | random_line_split |
serialization_profile.py | from __future__ import print_function
import shutil
import os.path
import tempfile
import cProfile
import pstats
import nineml
from nineml.utils.comprehensive_example import (
instances_of_all_types, v1_safe_docs)
from nineml.serialization import ext_to_format, format_to_serializer
format_to_ext = dict((v, k) for k, v in ext_to_format.items()) # @UndefinedVariable @IgnorePep8
print_serialized = False
printable = ('xml', 'json', 'yaml')
_tmp_dir = tempfile.mkdtemp()
def function():
|
out_file = os.path.join(os.getcwd(), 'serial_profile.out')
cProfile.run('function()', out_file)
p = pstats.Stats(out_file)
p.sort_stats('cumtime').print_stats()
| for version in (1.0, 2.0):
if version == 1.0:
docs = v1_safe_docs
else:
docs = list(instances_of_all_types['NineML'].values())
for format in format_to_serializer: # @ReservedAssignment
try:
ext = format_to_ext[format]
except KeyError:
continue # ones that can't be written to file (e.g. dict)
for i, document in enumerate(docs):
doc = document.clone()
url = os.path.join(
_tmp_dir, 'test{}v{}{}'.format(i, version, ext))
nineml.write(url, doc, format=format, version=version,
indent=2)
if print_serialized and format in printable:
with open(url) as f:
print(f.read())
reread_doc = nineml.read(url, reload=True) # @UnusedVariable
shutil.rmtree(_tmp_dir) | identifier_body |
NetWkstaInfo1059.py | # encoding: utf-8
# module samba.dcerpc.wkssvc
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/wkssvc.so
# by generator 1.135
""" wkssvc DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class NetWkstaInfo1059(__talloc.Object):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
|
buf_read_only_files = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
| """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass | identifier_body |
NetWkstaInfo1059.py | # encoding: utf-8
# module samba.dcerpc.wkssvc
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/wkssvc.so
# by generator 1.135
""" wkssvc DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class NetWkstaInfo1059(__talloc.Object):
# no doc
def | (self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
buf_read_only_files = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
| __init__ | identifier_name |
NetWkstaInfo1059.py | # encoding: utf-8
# module samba.dcerpc.wkssvc | """ wkssvc DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class NetWkstaInfo1059(__talloc.Object):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
buf_read_only_files = property(lambda self: object(), lambda self, v: None, lambda self: None) # default | # from /usr/lib/python2.7/dist-packages/samba/dcerpc/wkssvc.so
# by generator 1.135 | random_line_split |
index.js | 'use strict';
(function() {
var env = '';
if (typeof module !== 'undefined' && module.exports) env = 'node';
var exports = {};
if (env === 'node') {
var layer = require('layer');
} else {
exports = this;
var layer = layer || this.layer;
}
exports.intercept = function (ctx, fn, interceptFn) {
var result = false;
var f = layer._find_context(ctx, fn, 0);
layer.set(ctx, fn, function() {
result = { called: true, args: Array.prototype.slice.call(arguments)};
if (interceptFn && typeof interceptFn === 'function') interceptFn(result);
layer.unset(f[0][f[1]]);
return new layer.Stop();
});
var resultFn = function() {
return result; |
resultFn.reset = function() {
var status = true;
try {
layer.unset(f[0][f[1]]);
} catch(e) {
status = false;
}
return status;
}
return resultFn;
}
if (env === 'node') module.exports = exports.intercept;
})(); | } | random_line_split |
gash.rs | //
// gash.rs
//
// Starting code for PS2
// Running on Rust 0.9
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu, David Evans
// Version 0.4
//
extern mod extra;
use std::{io, run, os};
use std::io::buffered::BufferedReader;
use std::io::stdin;
use extra::getopts;
use std::io::File;
use std::io::signal::{Listener, Interrupt};
use std::libc;
struct Shell {
cmd_prompt: ~str,
log: ~[~str],
}
impl Shell {
fn new(prompt_str: &str) -> Shell {
Shell {
cmd_prompt: prompt_str.to_owned(),
log: ~[],
}
}
fn run(&mut self) {
let mut stdin = BufferedReader::new(stdin());
loop {
print(self.cmd_prompt); // prints 'gash >'
io::stdio::flush();
let line = stdin.read_line().unwrap(); // reads whats on the line
let cmd_line = line.trim().to_owned(); // removes leading and trailing whitespace
let user_input: ~[&str] = cmd_line.split(' ').collect();
let mut line: ~str = ~"";
let length: uint = user_input.len();
let mut i : uint = 0;
while (i < length){
let string = user_input[i].clone();
let mut input = ~"";
match string {
"<" => {
if !(i < length-1)
{println!("invalid command");}
let file = user_input[i+1].to_owned(); // get file name
let command = line.trim().to_owned();
line = command + " " + file;
i += 1;
}
">" => {
if !(i < length-1)
{println!("invalid command");}
let file = user_input[i + 1].to_owned();
let command = line.trim().to_owned();
let message = self.find_prog(command, true).to_owned();
if message == ~"none"{
i = length;
}
write_file(file,message);
line = ~"";
i += 1;
}
"|" => {
let command = line.trim().to_owned();
let mut command2: ~str = ~"";
for k in range(i + 1,length){
match user_input[k]{
"<" => {break;}
">" =>{break;}
"|" => {break;}
_ => {command2 = command2 + " " + user_input[k];}
}
i = k;
}
command2 = command2.trim().to_owned();
let mut message = self.find_prog(command, true).to_owned();
if message == ~"none"{
i = length;
}
match File::create(&Path::new("f.md")) {
Some(mut file) => {
file.write_str(message);
}
None =>{
println("Opening file failed!");
}
}
//println(command2);
message = self.find_prog(command2 + " " + "f.md", true).to_owned();
self.find_prog("rm f.md", true);
println!("{}", message);
line = ~"";
}
_ => {
line = line + " " + string;
}
}
i += 1;
}
let result = self.find_prog(line.trim(),false);
match result {
~"return" => {unsafe{libc::exit(1 as libc::c_int)}}
//~"continue" => {continue;}
_ => {}
}
}
}
fn find_prog(&mut self, cmd_line : &str, output: bool) -> ~str{
let program = cmd_line.splitn(' ', 1).nth(0).expect("no program"); // get command
match program {
"" => { return ~"continue"; }
"exit" => { return ~"return"; }
"history" => {
self.log.push(cmd_line.to_owned());
return self.run_history(output);
}
"cd" => {
self.log.push(cmd_line.to_owned());
self.run_cd(cmd_line);
}
_ => {
self.log.push(cmd_line.to_owned());
return self.run_cmdline(cmd_line, output);
} |
fn run_cmdline(&mut self, cmd_line: &str, output: bool) -> ~str {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();
let length = argv.len()-1;
if argv[length] == ~"&" {
argv.remove(length);
let program: ~str = argv.remove(0);
let argv2 = argv.clone();
if self.cmd_exists(program){
spawn(proc() {run::process_status(program, argv2);});
}
else {
println!("{:s}: command not found", program);
}
return ~"none";
}
else{
if argv.len() > 0 {
let program: ~str = argv.remove(0);
return self.run_cmd(program, argv, output);
}
}
return ~"none";
}
fn run_cmd(&mut self, program: &str, argv: &[~str], output: bool)->~str {
if self.cmd_exists(program) {
if output == false {
run::process_status(program, argv);
return ~"none";
}
else {
let output = run::process_output(program, argv);
let output_str = output.unwrap().output;
return std::str::from_utf8(output_str).to_owned();
}
} else {
println!("{:s}: command not found", program);
}
return ~"none";
}
fn cmd_exists(&mut self, cmd_path: &str) -> bool {
let ret = run::process_output("which", [cmd_path.to_owned()]);
return ret.expect("exit code error.").status.success();
}
fn run_history(&mut self, output: bool)-> ~str{
if output == false{
for i in range(0, self.log.len()) {
println!("{}", self.log[i]);
}
return ~"none";
}
else {
let mut out: ~str = ~"";
for i in range(0, self.log.len()){
out = out + self.log[i].to_owned();
}
return out;
}
}
fn run_cd(&mut self, cmd_line: &str) {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();
if argv.len() > 0 {
if argv.len() == 1 {
self.go_to_home_dir();
return ;
}
let string: ~str = argv.remove(1);
if string == ~"$HOME" || string == ~"$home"{
self.go_to_home_dir();
return ;
}
let path = ~Path::new(string);
if (path.exists()){
let success = std::os::change_dir(path);
if !success {
println("Invalid path");
}
}
}
else {
println("Invalid input");
}
}
fn go_to_home_dir(&mut self){
match std::os::homedir() {
Some(path) => {
std::os::change_dir(&path);
}
None => {
println("$HOME is not set");
}
}
}
}
fn write_file(filename: ~str, message: ~str){
match File::create(&Path::new(filename)) {
Some(mut file) => {
file.write_str(message);
}
None =>{
println("Opening file failed!");
}
}
}
/*
fn read_file(filename: ~str) -> ~str{
let path = Path::new(filename);
match File::open(&path) {
Some(file) => {
let mut reader = BufferedReader::new(file);
let input = reader.read_to_str();
return input;
}
None =>{
println("Opening file failed");
return ~"";
}
}
}
*/
fn get_cmdline_from_args() -> Option<~str> {
/* Begin processing program arguments and initiate the parameters. */
let args = os::args();
let opts = ~[
getopts::optopt("c")
];
let matches = match getopts::getopts(args.tail(), opts) {
Ok(m) => { m }
Err(f) => { fail!(f.to_err_msg()) }
};
if matches.opt_present("c") {
let cmd_str = match matches.opt_str("c") {
Some(cmd_str) => {cmd_str.to_owned()},
None => {~""}
};
return Some(cmd_str);
} else {
return None;
}
}
fn main() {
let opt_cmd_line = get_cmdline_from_args();
spawn(proc () {
let mut listener = Listener::new();
listener.register(Interrupt);
loop{
match listener.port.recv() {
Interrupt => print!(""),
_ => (),
}
}
});
match opt_cmd_line {
Some(cmd_line) => {Shell::new("").run_cmdline(cmd_line, false);}
None => {Shell::new("gash > ").run();}
}
} | }
~"fine"
} | random_line_split |
gash.rs | //
// gash.rs
//
// Starting code for PS2
// Running on Rust 0.9
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu, David Evans
// Version 0.4
//
extern mod extra;
use std::{io, run, os};
use std::io::buffered::BufferedReader;
use std::io::stdin;
use extra::getopts;
use std::io::File;
use std::io::signal::{Listener, Interrupt};
use std::libc;
struct Shell {
cmd_prompt: ~str,
log: ~[~str],
}
impl Shell {
fn new(prompt_str: &str) -> Shell {
Shell {
cmd_prompt: prompt_str.to_owned(),
log: ~[],
}
}
fn run(&mut self) {
let mut stdin = BufferedReader::new(stdin());
loop {
print(self.cmd_prompt); // prints 'gash >'
io::stdio::flush();
let line = stdin.read_line().unwrap(); // reads whats on the line
let cmd_line = line.trim().to_owned(); // removes leading and trailing whitespace
let user_input: ~[&str] = cmd_line.split(' ').collect();
let mut line: ~str = ~"";
let length: uint = user_input.len();
let mut i : uint = 0;
while (i < length){
let string = user_input[i].clone();
let mut input = ~"";
match string {
"<" => {
if !(i < length-1)
{println!("invalid command");}
let file = user_input[i+1].to_owned(); // get file name
let command = line.trim().to_owned();
line = command + " " + file;
i += 1;
}
">" => {
if !(i < length-1)
{println!("invalid command");}
let file = user_input[i + 1].to_owned();
let command = line.trim().to_owned();
let message = self.find_prog(command, true).to_owned();
if message == ~"none"{
i = length;
}
write_file(file,message);
line = ~"";
i += 1;
}
"|" => {
let command = line.trim().to_owned();
let mut command2: ~str = ~"";
for k in range(i + 1,length){
match user_input[k]{
"<" => {break;}
">" =>{break;}
"|" => {break;}
_ => {command2 = command2 + " " + user_input[k];}
}
i = k;
}
command2 = command2.trim().to_owned();
let mut message = self.find_prog(command, true).to_owned();
if message == ~"none"{
i = length;
}
match File::create(&Path::new("f.md")) {
Some(mut file) => {
file.write_str(message);
}
None =>{
println("Opening file failed!");
}
}
//println(command2);
message = self.find_prog(command2 + " " + "f.md", true).to_owned();
self.find_prog("rm f.md", true);
println!("{}", message);
line = ~"";
}
_ => {
line = line + " " + string;
}
}
i += 1;
}
let result = self.find_prog(line.trim(),false);
match result {
~"return" => {unsafe{libc::exit(1 as libc::c_int)}}
//~"continue" => {continue;}
_ => {}
}
}
}
fn find_prog(&mut self, cmd_line : &str, output: bool) -> ~str{
let program = cmd_line.splitn(' ', 1).nth(0).expect("no program"); // get command
match program {
"" => { return ~"continue"; }
"exit" => { return ~"return"; }
"history" => {
self.log.push(cmd_line.to_owned());
return self.run_history(output);
}
"cd" => {
self.log.push(cmd_line.to_owned());
self.run_cd(cmd_line);
}
_ => {
self.log.push(cmd_line.to_owned());
return self.run_cmdline(cmd_line, output);
}
}
~"fine"
}
fn run_cmdline(&mut self, cmd_line: &str, output: bool) -> ~str {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();
let length = argv.len()-1;
if argv[length] == ~"&" {
argv.remove(length);
let program: ~str = argv.remove(0);
let argv2 = argv.clone();
if self.cmd_exists(program){
spawn(proc() {run::process_status(program, argv2);});
}
else {
println!("{:s}: command not found", program);
}
return ~"none";
}
else{
if argv.len() > 0 {
let program: ~str = argv.remove(0);
return self.run_cmd(program, argv, output);
}
}
return ~"none";
}
fn run_cmd(&mut self, program: &str, argv: &[~str], output: bool)->~str {
if self.cmd_exists(program) {
if output == false {
run::process_status(program, argv);
return ~"none";
}
else {
let output = run::process_output(program, argv);
let output_str = output.unwrap().output;
return std::str::from_utf8(output_str).to_owned();
}
} else {
println!("{:s}: command not found", program);
}
return ~"none";
}
fn cmd_exists(&mut self, cmd_path: &str) -> bool {
let ret = run::process_output("which", [cmd_path.to_owned()]);
return ret.expect("exit code error.").status.success();
}
fn run_history(&mut self, output: bool)-> ~str |
fn run_cd(&mut self, cmd_line: &str) {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();
if argv.len() > 0 {
if argv.len() == 1 {
self.go_to_home_dir();
return ;
}
let string: ~str = argv.remove(1);
if string == ~"$HOME" || string == ~"$home"{
self.go_to_home_dir();
return ;
}
let path = ~Path::new(string);
if (path.exists()){
let success = std::os::change_dir(path);
if !success {
println("Invalid path");
}
}
}
else {
println("Invalid input");
}
}
fn go_to_home_dir(&mut self){
match std::os::homedir() {
Some(path) => {
std::os::change_dir(&path);
}
None => {
println("$HOME is not set");
}
}
}
}
fn write_file(filename: ~str, message: ~str){
match File::create(&Path::new(filename)) {
Some(mut file) => {
file.write_str(message);
}
None =>{
println("Opening file failed!");
}
}
}
/*
fn read_file(filename: ~str) -> ~str{
let path = Path::new(filename);
match File::open(&path) {
Some(file) => {
let mut reader = BufferedReader::new(file);
let input = reader.read_to_str();
return input;
}
None =>{
println("Opening file failed");
return ~"";
}
}
}
*/
fn get_cmdline_from_args() -> Option<~str> {
/* Begin processing program arguments and initiate the parameters. */
let args = os::args();
let opts = ~[
getopts::optopt("c")
];
let matches = match getopts::getopts(args.tail(), opts) {
Ok(m) => { m }
Err(f) => { fail!(f.to_err_msg()) }
};
if matches.opt_present("c") {
let cmd_str = match matches.opt_str("c") {
Some(cmd_str) => {cmd_str.to_owned()},
None => {~""}
};
return Some(cmd_str);
} else {
return None;
}
}
fn main() {
let opt_cmd_line = get_cmdline_from_args();
spawn(proc () {
let mut listener = Listener::new();
listener.register(Interrupt);
loop{
match listener.port.recv() {
Interrupt => print!(""),
_ => (),
}
}
});
match opt_cmd_line {
Some(cmd_line) => {Shell::new("").run_cmdline(cmd_line, false);}
None => {Shell::new("gash > ").run();}
}
}
| {
if output == false{
for i in range(0, self.log.len()) {
println!("{}", self.log[i]);
}
return ~"none";
}
else {
let mut out: ~str = ~"";
for i in range(0, self.log.len()){
out = out + self.log[i].to_owned();
}
return out;
}
} | identifier_body |
gash.rs | //
// gash.rs
//
// Starting code for PS2
// Running on Rust 0.9
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu, David Evans
// Version 0.4
//
extern mod extra;
use std::{io, run, os};
use std::io::buffered::BufferedReader;
use std::io::stdin;
use extra::getopts;
use std::io::File;
use std::io::signal::{Listener, Interrupt};
use std::libc;
struct Shell {
cmd_prompt: ~str,
log: ~[~str],
}
impl Shell {
fn new(prompt_str: &str) -> Shell {
Shell {
cmd_prompt: prompt_str.to_owned(),
log: ~[],
}
}
fn run(&mut self) {
let mut stdin = BufferedReader::new(stdin());
loop {
print(self.cmd_prompt); // prints 'gash >'
io::stdio::flush();
let line = stdin.read_line().unwrap(); // reads whats on the line
let cmd_line = line.trim().to_owned(); // removes leading and trailing whitespace
let user_input: ~[&str] = cmd_line.split(' ').collect();
let mut line: ~str = ~"";
let length: uint = user_input.len();
let mut i : uint = 0;
while (i < length){
let string = user_input[i].clone();
let mut input = ~"";
match string {
"<" => {
if !(i < length-1)
{println!("invalid command");}
let file = user_input[i+1].to_owned(); // get file name
let command = line.trim().to_owned();
line = command + " " + file;
i += 1;
}
">" => {
if !(i < length-1)
{println!("invalid command");}
let file = user_input[i + 1].to_owned();
let command = line.trim().to_owned();
let message = self.find_prog(command, true).to_owned();
if message == ~"none"{
i = length;
}
write_file(file,message);
line = ~"";
i += 1;
}
"|" => {
let command = line.trim().to_owned();
let mut command2: ~str = ~"";
for k in range(i + 1,length){
match user_input[k]{
"<" => {break;}
">" =>{break;}
"|" => {break;}
_ => {command2 = command2 + " " + user_input[k];}
}
i = k;
}
command2 = command2.trim().to_owned();
let mut message = self.find_prog(command, true).to_owned();
if message == ~"none"{
i = length;
}
match File::create(&Path::new("f.md")) {
Some(mut file) => {
file.write_str(message);
}
None =>{
println("Opening file failed!");
}
}
//println(command2);
message = self.find_prog(command2 + " " + "f.md", true).to_owned();
self.find_prog("rm f.md", true);
println!("{}", message);
line = ~"";
}
_ => {
line = line + " " + string;
}
}
i += 1;
}
let result = self.find_prog(line.trim(),false);
match result {
~"return" => {unsafe{libc::exit(1 as libc::c_int)}}
//~"continue" => {continue;}
_ => {}
}
}
}
fn | (&mut self, cmd_line : &str, output: bool) -> ~str{
let program = cmd_line.splitn(' ', 1).nth(0).expect("no program"); // get command
match program {
"" => { return ~"continue"; }
"exit" => { return ~"return"; }
"history" => {
self.log.push(cmd_line.to_owned());
return self.run_history(output);
}
"cd" => {
self.log.push(cmd_line.to_owned());
self.run_cd(cmd_line);
}
_ => {
self.log.push(cmd_line.to_owned());
return self.run_cmdline(cmd_line, output);
}
}
~"fine"
}
fn run_cmdline(&mut self, cmd_line: &str, output: bool) -> ~str {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();
let length = argv.len()-1;
if argv[length] == ~"&" {
argv.remove(length);
let program: ~str = argv.remove(0);
let argv2 = argv.clone();
if self.cmd_exists(program){
spawn(proc() {run::process_status(program, argv2);});
}
else {
println!("{:s}: command not found", program);
}
return ~"none";
}
else{
if argv.len() > 0 {
let program: ~str = argv.remove(0);
return self.run_cmd(program, argv, output);
}
}
return ~"none";
}
fn run_cmd(&mut self, program: &str, argv: &[~str], output: bool)->~str {
if self.cmd_exists(program) {
if output == false {
run::process_status(program, argv);
return ~"none";
}
else {
let output = run::process_output(program, argv);
let output_str = output.unwrap().output;
return std::str::from_utf8(output_str).to_owned();
}
} else {
println!("{:s}: command not found", program);
}
return ~"none";
}
fn cmd_exists(&mut self, cmd_path: &str) -> bool {
let ret = run::process_output("which", [cmd_path.to_owned()]);
return ret.expect("exit code error.").status.success();
}
fn run_history(&mut self, output: bool)-> ~str{
if output == false{
for i in range(0, self.log.len()) {
println!("{}", self.log[i]);
}
return ~"none";
}
else {
let mut out: ~str = ~"";
for i in range(0, self.log.len()){
out = out + self.log[i].to_owned();
}
return out;
}
}
fn run_cd(&mut self, cmd_line: &str) {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();
if argv.len() > 0 {
if argv.len() == 1 {
self.go_to_home_dir();
return ;
}
let string: ~str = argv.remove(1);
if string == ~"$HOME" || string == ~"$home"{
self.go_to_home_dir();
return ;
}
let path = ~Path::new(string);
if (path.exists()){
let success = std::os::change_dir(path);
if !success {
println("Invalid path");
}
}
}
else {
println("Invalid input");
}
}
fn go_to_home_dir(&mut self){
match std::os::homedir() {
Some(path) => {
std::os::change_dir(&path);
}
None => {
println("$HOME is not set");
}
}
}
}
fn write_file(filename: ~str, message: ~str){
match File::create(&Path::new(filename)) {
Some(mut file) => {
file.write_str(message);
}
None =>{
println("Opening file failed!");
}
}
}
/*
fn read_file(filename: ~str) -> ~str{
let path = Path::new(filename);
match File::open(&path) {
Some(file) => {
let mut reader = BufferedReader::new(file);
let input = reader.read_to_str();
return input;
}
None =>{
println("Opening file failed");
return ~"";
}
}
}
*/
fn get_cmdline_from_args() -> Option<~str> {
/* Begin processing program arguments and initiate the parameters. */
let args = os::args();
let opts = ~[
getopts::optopt("c")
];
let matches = match getopts::getopts(args.tail(), opts) {
Ok(m) => { m }
Err(f) => { fail!(f.to_err_msg()) }
};
if matches.opt_present("c") {
let cmd_str = match matches.opt_str("c") {
Some(cmd_str) => {cmd_str.to_owned()},
None => {~""}
};
return Some(cmd_str);
} else {
return None;
}
}
fn main() {
let opt_cmd_line = get_cmdline_from_args();
spawn(proc () {
let mut listener = Listener::new();
listener.register(Interrupt);
loop{
match listener.port.recv() {
Interrupt => print!(""),
_ => (),
}
}
});
match opt_cmd_line {
Some(cmd_line) => {Shell::new("").run_cmdline(cmd_line, false);}
None => {Shell::new("gash > ").run();}
}
}
| find_prog | identifier_name |
gash.rs | //
// gash.rs
//
// Starting code for PS2
// Running on Rust 0.9
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu, David Evans
// Version 0.4
//
extern mod extra;
use std::{io, run, os};
use std::io::buffered::BufferedReader;
use std::io::stdin;
use extra::getopts;
use std::io::File;
use std::io::signal::{Listener, Interrupt};
use std::libc;
struct Shell {
cmd_prompt: ~str,
log: ~[~str],
}
impl Shell {
fn new(prompt_str: &str) -> Shell {
Shell {
cmd_prompt: prompt_str.to_owned(),
log: ~[],
}
}
fn run(&mut self) {
let mut stdin = BufferedReader::new(stdin());
loop {
print(self.cmd_prompt); // prints 'gash >'
io::stdio::flush();
let line = stdin.read_line().unwrap(); // reads whats on the line
let cmd_line = line.trim().to_owned(); // removes leading and trailing whitespace
let user_input: ~[&str] = cmd_line.split(' ').collect();
let mut line: ~str = ~"";
let length: uint = user_input.len();
let mut i : uint = 0;
while (i < length){
let string = user_input[i].clone();
let mut input = ~"";
match string {
"<" => {
if !(i < length-1)
{println!("invalid command");}
let file = user_input[i+1].to_owned(); // get file name
let command = line.trim().to_owned();
line = command + " " + file;
i += 1;
}
">" => {
if !(i < length-1)
{println!("invalid command");}
let file = user_input[i + 1].to_owned();
let command = line.trim().to_owned();
let message = self.find_prog(command, true).to_owned();
if message == ~"none"{
i = length;
}
write_file(file,message);
line = ~"";
i += 1;
}
"|" => {
let command = line.trim().to_owned();
let mut command2: ~str = ~"";
for k in range(i + 1,length){
match user_input[k]{
"<" => {break;}
">" =>{break;}
"|" => {break;}
_ => {command2 = command2 + " " + user_input[k];}
}
i = k;
}
command2 = command2.trim().to_owned();
let mut message = self.find_prog(command, true).to_owned();
if message == ~"none"{
i = length;
}
match File::create(&Path::new("f.md")) {
Some(mut file) => {
file.write_str(message);
}
None =>{
println("Opening file failed!");
}
}
//println(command2);
message = self.find_prog(command2 + " " + "f.md", true).to_owned();
self.find_prog("rm f.md", true);
println!("{}", message);
line = ~"";
}
_ => {
line = line + " " + string;
}
}
i += 1;
}
let result = self.find_prog(line.trim(),false);
match result {
~"return" => {unsafe{libc::exit(1 as libc::c_int)}}
//~"continue" => {continue;}
_ => {}
}
}
}
fn find_prog(&mut self, cmd_line : &str, output: bool) -> ~str{
let program = cmd_line.splitn(' ', 1).nth(0).expect("no program"); // get command
match program {
"" => { return ~"continue"; }
"exit" => { return ~"return"; }
"history" => {
self.log.push(cmd_line.to_owned());
return self.run_history(output);
}
"cd" => {
self.log.push(cmd_line.to_owned());
self.run_cd(cmd_line);
}
_ => {
self.log.push(cmd_line.to_owned());
return self.run_cmdline(cmd_line, output);
}
}
~"fine"
}
fn run_cmdline(&mut self, cmd_line: &str, output: bool) -> ~str {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();
let length = argv.len()-1;
if argv[length] == ~"&" {
argv.remove(length);
let program: ~str = argv.remove(0);
let argv2 = argv.clone();
if self.cmd_exists(program){
spawn(proc() {run::process_status(program, argv2);});
}
else {
println!("{:s}: command not found", program);
}
return ~"none";
}
else{
if argv.len() > 0 {
let program: ~str = argv.remove(0);
return self.run_cmd(program, argv, output);
}
}
return ~"none";
}
fn run_cmd(&mut self, program: &str, argv: &[~str], output: bool)->~str {
if self.cmd_exists(program) {
if output == false {
run::process_status(program, argv);
return ~"none";
}
else {
let output = run::process_output(program, argv);
let output_str = output.unwrap().output;
return std::str::from_utf8(output_str).to_owned();
}
} else {
println!("{:s}: command not found", program);
}
return ~"none";
}
fn cmd_exists(&mut self, cmd_path: &str) -> bool {
let ret = run::process_output("which", [cmd_path.to_owned()]);
return ret.expect("exit code error.").status.success();
}
fn run_history(&mut self, output: bool)-> ~str{
if output == false{
for i in range(0, self.log.len()) {
println!("{}", self.log[i]);
}
return ~"none";
}
else {
let mut out: ~str = ~"";
for i in range(0, self.log.len()){
out = out + self.log[i].to_owned();
}
return out;
}
}
fn run_cd(&mut self, cmd_line: &str) {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();
if argv.len() > 0 {
if argv.len() == 1 {
self.go_to_home_dir();
return ;
}
let string: ~str = argv.remove(1);
if string == ~"$HOME" || string == ~"$home"{
self.go_to_home_dir();
return ;
}
let path = ~Path::new(string);
if (path.exists()){
let success = std::os::change_dir(path);
if !success {
println("Invalid path");
}
}
}
else |
}
fn go_to_home_dir(&mut self){
match std::os::homedir() {
Some(path) => {
std::os::change_dir(&path);
}
None => {
println("$HOME is not set");
}
}
}
}
fn write_file(filename: ~str, message: ~str){
match File::create(&Path::new(filename)) {
Some(mut file) => {
file.write_str(message);
}
None =>{
println("Opening file failed!");
}
}
}
/*
fn read_file(filename: ~str) -> ~str{
let path = Path::new(filename);
match File::open(&path) {
Some(file) => {
let mut reader = BufferedReader::new(file);
let input = reader.read_to_str();
return input;
}
None =>{
println("Opening file failed");
return ~"";
}
}
}
*/
fn get_cmdline_from_args() -> Option<~str> {
/* Begin processing program arguments and initiate the parameters. */
let args = os::args();
let opts = ~[
getopts::optopt("c")
];
let matches = match getopts::getopts(args.tail(), opts) {
Ok(m) => { m }
Err(f) => { fail!(f.to_err_msg()) }
};
if matches.opt_present("c") {
let cmd_str = match matches.opt_str("c") {
Some(cmd_str) => {cmd_str.to_owned()},
None => {~""}
};
return Some(cmd_str);
} else {
return None;
}
}
fn main() {
let opt_cmd_line = get_cmdline_from_args();
spawn(proc () {
let mut listener = Listener::new();
listener.register(Interrupt);
loop{
match listener.port.recv() {
Interrupt => print!(""),
_ => (),
}
}
});
match opt_cmd_line {
Some(cmd_line) => {Shell::new("").run_cmdline(cmd_line, false);}
None => {Shell::new("gash > ").run();}
}
}
| {
println("Invalid input");
} | conditional_block |
scouter.js | // Generated by CoffeeScript 1.3.3
(function() {
describe('Scouter', function() {
it('can properly score the specificity of W3C\'s examples', function() {
var score, scouter, selector, selectors, _results;
scouter = new Scouter();
selectors = {
'*': 0,
'LI': 1,
'UL LI': 2, | '#x34y': 100,
'#s12:not(F00)': 101
};
_results = [];
for (selector in selectors) {
score = selectors[selector];
_results.push(expect(scouter.score(selector)).toBe(score));
}
return _results;
});
return it('can sort an array of selectors', function() {
var scouter, selectors, sortedSelectors;
scouter = new Scouter();
selectors = ['.header h1', 'h1', '.header', '.header h1 > em'];
sortedSelectors = ['.header h1 > em', '.header h1', '.header', 'h1'];
return expect(scouter.sort(selectors)).toEqual(sortedSelectors);
});
});
}).call(this); | 'UL OL+LI': 3,
'H1 + *[REL=up]': 11,
'UL OL LI.red': 13,
'LI.red.level': 21, | random_line_split |
properties-defined.pipe.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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/>.
*/
import {Pipe, PipeTransform} from '@angular/core';
import {CalendarStemConfig} from '../../../core/store/calendars/calendar';
@Pipe({
name: 'propertiesDefined',
})
export class PropertiesDefinedPipe implements PipeTransform {
public | (collectionConfig: CalendarStemConfig, properties: string[]): boolean {
return collectionConfig && properties.every(property => !!collectionConfig.barsProperties[property]);
}
}
| transform | identifier_name |
properties-defined.pipe.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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/>.
*/
import {Pipe, PipeTransform} from '@angular/core';
import {CalendarStemConfig} from '../../../core/store/calendars/calendar';
@Pipe({
name: 'propertiesDefined',
})
export class PropertiesDefinedPipe implements PipeTransform {
public transform(collectionConfig: CalendarStemConfig, properties: string[]): boolean {
return collectionConfig && properties.every(property => !!collectionConfig.barsProperties[property]);
}
} | * | random_line_split |
properties-defined.pipe.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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/>.
*/
import {Pipe, PipeTransform} from '@angular/core';
import {CalendarStemConfig} from '../../../core/store/calendars/calendar';
@Pipe({
name: 'propertiesDefined',
})
export class PropertiesDefinedPipe implements PipeTransform {
public transform(collectionConfig: CalendarStemConfig, properties: string[]): boolean |
}
| {
return collectionConfig && properties.every(property => !!collectionConfig.barsProperties[property]);
} | identifier_body |
issue-10806.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
| 3
}
pub fn bar() -> int {
4
}
pub mod baz {
use {foo, bar};
pub fn quux() -> int {
foo() + bar()
}
}
pub mod grault {
use {foo};
pub fn garply() -> int {
foo()
}
}
pub mod waldo {
use {};
pub fn plugh() -> int {
0
}
}
pub fn main() {
let _x = baz::quux();
let _y = grault::garply();
let _z = waldo::plugh();
} | pub fn foo() -> int { | random_line_split |
issue-10806.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub fn foo() -> int {
3
}
pub fn bar() -> int {
4
}
pub mod baz {
use {foo, bar};
pub fn | () -> int {
foo() + bar()
}
}
pub mod grault {
use {foo};
pub fn garply() -> int {
foo()
}
}
pub mod waldo {
use {};
pub fn plugh() -> int {
0
}
}
pub fn main() {
let _x = baz::quux();
let _y = grault::garply();
let _z = waldo::plugh();
}
| quux | identifier_name |
issue-10806.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub fn foo() -> int {
3
}
pub fn bar() -> int {
4
}
pub mod baz {
use {foo, bar};
pub fn quux() -> int {
foo() + bar()
}
}
pub mod grault {
use {foo};
pub fn garply() -> int |
}
pub mod waldo {
use {};
pub fn plugh() -> int {
0
}
}
pub fn main() {
let _x = baz::quux();
let _y = grault::garply();
let _z = waldo::plugh();
}
| {
foo()
} | identifier_body |
NestedListEditor.py | #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
# This file is part of the E-Cell System
#
# Copyright (C) 1996-2016 Keio University
# Copyright (C) 2008-2016 RIKEN
# Copyright (C) 2005-2009 The Molecular Sciences Institute
#
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
#
# E-Cell System is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# E-Cell System 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 E-Cell System -- see the file COPYING.
# If not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#END_HEADER
#
#'Design: Gabor Bereczki <[email protected]>',
#'Design and application Framework: Koichi Takahashi <[email protected]>',
#'Programming: Gabor Bereczki' at
# E-CELL Project, Lab. for Bioinformatics, Keio University.
#
import os
import os.path
import sys
import gtk
import gobject
from ecell.ui.model_editor.Utils import *
from ecell.ui.model_editor.Constants import *
from ecell.ui.model_editor.ModelEditor import *
from ecell.ui.model_editor.ViewComponent import *
class BadNestedList( Exception ):
def __init__( self, badString ):
self.args = "%s\n cannot be parsed as nestedlist!"%badString
class NestedListEditor(ViewComponent):
#######################
# GENERAL CASES #
#######################
def __init__( self, aParentWindow, pointOfAttach ):
self.theParentWindow = aParentWindow
# call superclass
ViewComponent.__init__( self, pointOfAttach, 'attachment_box' )
self.theNestedList = copyValue( self.theParentWindow.thePropertyValue )
self.theTextView = self['textview']
self.textBuffer = gtk.TextBuffer()
self.theTextView.set_buffer( self.textBuffer )
self.textBuffer.set_text( self.__nestedListToString( self.theNestedList,0 ) )
def getValue( self ):
aText = self.textBuffer.get_text( self.textBuffer.get_start_iter(), self.textBuffer.get_end_iter())
try:
aValue= self.__stringToNestedList( aText)
except BadNestedList:
self.theParentWindow.theModelEditor.printMessage( ''.join(sys.exc_value), ME_ERROR )
aValue = None
return aValue
def __nestedListToString( self, aNestedList, level = 1 ):
if type(aNestedList ) == type(''):
return aNestedList
stringList = []
for aSubList in aNestedList:
stringList.append( self.__nestedListToString( aSubList ) )
if level == 0:
separator = '\n,'
else:
separator = ', '
return '( ' + separator.join( stringList ) + ' ) '
def __stringToNestedList( self, aString ):
# should return a nestedlist if string format is OK
# should return None if string format is not OK, should display an error message in this case.
aString=aString.strip()
# decide whether list or string
if aString.__contains__(',') or aString.__contains__('(') or aString.__contains__(')'):
#must be list
if not (aString.startswith('(') and aString.endswith(')') ):
raise BadNestedList( aString )
stringList = self.__split(aString[1:len(aString)-1].strip())
parsedList = map( self.__stringToNestedList, stringList )
if len(parsedList) == 1 and type( parsedList[0]) != type(parsedList ):
return stringList[0]
return parsedList
else:
return aString
def __split( self, aString ):
openPara = 0
returnList = []
actualWord = ''
for aChar in aString:
if aChar == ',' and openPara == 0:
|
elif aChar == '(':
openPara +=1
actualWord += aChar
elif aChar == ')':
openPara -=1
actualWord += aChar
else:
actualWord += aChar
if openPara!=0:
raise BadNestedList( aString )
returnList.append( actualWord )
return returnList
| returnList.append( actualWord )
actualWord = '' | conditional_block |
NestedListEditor.py | #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
# This file is part of the E-Cell System
#
# Copyright (C) 1996-2016 Keio University
# Copyright (C) 2008-2016 RIKEN
# Copyright (C) 2005-2009 The Molecular Sciences Institute
#
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
#
# E-Cell System is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# E-Cell System 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 E-Cell System -- see the file COPYING.
# If not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#END_HEADER
#
#'Design: Gabor Bereczki <[email protected]>',
#'Design and application Framework: Koichi Takahashi <[email protected]>',
#'Programming: Gabor Bereczki' at
# E-CELL Project, Lab. for Bioinformatics, Keio University.
#
import os
import os.path
import sys
import gtk
import gobject
from ecell.ui.model_editor.Utils import *
from ecell.ui.model_editor.Constants import *
from ecell.ui.model_editor.ModelEditor import *
from ecell.ui.model_editor.ViewComponent import *
class BadNestedList( Exception ):
def __init__( self, badString ):
self.args = "%s\n cannot be parsed as nestedlist!"%badString
class NestedListEditor(ViewComponent):
#######################
# GENERAL CASES #
#######################
def __init__( self, aParentWindow, pointOfAttach ):
self.theParentWindow = aParentWindow
# call superclass
ViewComponent.__init__( self, pointOfAttach, 'attachment_box' )
self.theNestedList = copyValue( self.theParentWindow.thePropertyValue )
self.theTextView = self['textview']
self.textBuffer = gtk.TextBuffer()
self.theTextView.set_buffer( self.textBuffer )
self.textBuffer.set_text( self.__nestedListToString( self.theNestedList,0 ) )
def getValue( self ):
aText = self.textBuffer.get_text( self.textBuffer.get_start_iter(), self.textBuffer.get_end_iter())
try:
aValue= self.__stringToNestedList( aText)
except BadNestedList:
self.theParentWindow.theModelEditor.printMessage( ''.join(sys.exc_value), ME_ERROR )
aValue = None
return aValue
def __nestedListToString( self, aNestedList, level = 1 ):
if type(aNestedList ) == type(''):
return aNestedList
stringList = []
for aSubList in aNestedList:
stringList.append( self.__nestedListToString( aSubList ) )
if level == 0:
separator = '\n,'
else:
separator = ', '
return '( ' + separator.join( stringList ) + ' ) '
def __stringToNestedList( self, aString ):
# should return a nestedlist if string format is OK
# should return None if string format is not OK, should display an error message in this case.
aString=aString.strip()
# decide whether list or string
if aString.__contains__(',') or aString.__contains__('(') or aString.__contains__(')'):
#must be list
if not (aString.startswith('(') and aString.endswith(')') ):
raise BadNestedList( aString )
stringList = self.__split(aString[1:len(aString)-1].strip()) | parsedList = map( self.__stringToNestedList, stringList )
if len(parsedList) == 1 and type( parsedList[0]) != type(parsedList ):
return stringList[0]
return parsedList
else:
return aString
def __split( self, aString ):
openPara = 0
returnList = []
actualWord = ''
for aChar in aString:
if aChar == ',' and openPara == 0:
returnList.append( actualWord )
actualWord = ''
elif aChar == '(':
openPara +=1
actualWord += aChar
elif aChar == ')':
openPara -=1
actualWord += aChar
else:
actualWord += aChar
if openPara!=0:
raise BadNestedList( aString )
returnList.append( actualWord )
return returnList | random_line_split |
|
NestedListEditor.py | #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
# This file is part of the E-Cell System
#
# Copyright (C) 1996-2016 Keio University
# Copyright (C) 2008-2016 RIKEN
# Copyright (C) 2005-2009 The Molecular Sciences Institute
#
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
#
# E-Cell System is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# E-Cell System 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 E-Cell System -- see the file COPYING.
# If not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#END_HEADER
#
#'Design: Gabor Bereczki <[email protected]>',
#'Design and application Framework: Koichi Takahashi <[email protected]>',
#'Programming: Gabor Bereczki' at
# E-CELL Project, Lab. for Bioinformatics, Keio University.
#
import os
import os.path
import sys
import gtk
import gobject
from ecell.ui.model_editor.Utils import *
from ecell.ui.model_editor.Constants import *
from ecell.ui.model_editor.ModelEditor import *
from ecell.ui.model_editor.ViewComponent import *
class BadNestedList( Exception ):
def __init__( self, badString ):
self.args = "%s\n cannot be parsed as nestedlist!"%badString
class NestedListEditor(ViewComponent):
#######################
# GENERAL CASES #
#######################
def __init__( self, aParentWindow, pointOfAttach ):
self.theParentWindow = aParentWindow
# call superclass
ViewComponent.__init__( self, pointOfAttach, 'attachment_box' )
self.theNestedList = copyValue( self.theParentWindow.thePropertyValue )
self.theTextView = self['textview']
self.textBuffer = gtk.TextBuffer()
self.theTextView.set_buffer( self.textBuffer )
self.textBuffer.set_text( self.__nestedListToString( self.theNestedList,0 ) )
def getValue( self ):
aText = self.textBuffer.get_text( self.textBuffer.get_start_iter(), self.textBuffer.get_end_iter())
try:
aValue= self.__stringToNestedList( aText)
except BadNestedList:
self.theParentWindow.theModelEditor.printMessage( ''.join(sys.exc_value), ME_ERROR )
aValue = None
return aValue
def __nestedListToString( self, aNestedList, level = 1 ):
|
def __stringToNestedList( self, aString ):
# should return a nestedlist if string format is OK
# should return None if string format is not OK, should display an error message in this case.
aString=aString.strip()
# decide whether list or string
if aString.__contains__(',') or aString.__contains__('(') or aString.__contains__(')'):
#must be list
if not (aString.startswith('(') and aString.endswith(')') ):
raise BadNestedList( aString )
stringList = self.__split(aString[1:len(aString)-1].strip())
parsedList = map( self.__stringToNestedList, stringList )
if len(parsedList) == 1 and type( parsedList[0]) != type(parsedList ):
return stringList[0]
return parsedList
else:
return aString
def __split( self, aString ):
openPara = 0
returnList = []
actualWord = ''
for aChar in aString:
if aChar == ',' and openPara == 0:
returnList.append( actualWord )
actualWord = ''
elif aChar == '(':
openPara +=1
actualWord += aChar
elif aChar == ')':
openPara -=1
actualWord += aChar
else:
actualWord += aChar
if openPara!=0:
raise BadNestedList( aString )
returnList.append( actualWord )
return returnList
| if type(aNestedList ) == type(''):
return aNestedList
stringList = []
for aSubList in aNestedList:
stringList.append( self.__nestedListToString( aSubList ) )
if level == 0:
separator = '\n,'
else:
separator = ', '
return '( ' + separator.join( stringList ) + ' ) ' | identifier_body |
NestedListEditor.py | #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
# This file is part of the E-Cell System
#
# Copyright (C) 1996-2016 Keio University
# Copyright (C) 2008-2016 RIKEN
# Copyright (C) 2005-2009 The Molecular Sciences Institute
#
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
#
# E-Cell System is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# E-Cell System 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 E-Cell System -- see the file COPYING.
# If not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#END_HEADER
#
#'Design: Gabor Bereczki <[email protected]>',
#'Design and application Framework: Koichi Takahashi <[email protected]>',
#'Programming: Gabor Bereczki' at
# E-CELL Project, Lab. for Bioinformatics, Keio University.
#
import os
import os.path
import sys
import gtk
import gobject
from ecell.ui.model_editor.Utils import *
from ecell.ui.model_editor.Constants import *
from ecell.ui.model_editor.ModelEditor import *
from ecell.ui.model_editor.ViewComponent import *
class BadNestedList( Exception ):
def __init__( self, badString ):
self.args = "%s\n cannot be parsed as nestedlist!"%badString
class NestedListEditor(ViewComponent):
#######################
# GENERAL CASES #
#######################
def __init__( self, aParentWindow, pointOfAttach ):
self.theParentWindow = aParentWindow
# call superclass
ViewComponent.__init__( self, pointOfAttach, 'attachment_box' )
self.theNestedList = copyValue( self.theParentWindow.thePropertyValue )
self.theTextView = self['textview']
self.textBuffer = gtk.TextBuffer()
self.theTextView.set_buffer( self.textBuffer )
self.textBuffer.set_text( self.__nestedListToString( self.theNestedList,0 ) )
def getValue( self ):
aText = self.textBuffer.get_text( self.textBuffer.get_start_iter(), self.textBuffer.get_end_iter())
try:
aValue= self.__stringToNestedList( aText)
except BadNestedList:
self.theParentWindow.theModelEditor.printMessage( ''.join(sys.exc_value), ME_ERROR )
aValue = None
return aValue
def __nestedListToString( self, aNestedList, level = 1 ):
if type(aNestedList ) == type(''):
return aNestedList
stringList = []
for aSubList in aNestedList:
stringList.append( self.__nestedListToString( aSubList ) )
if level == 0:
separator = '\n,'
else:
separator = ', '
return '( ' + separator.join( stringList ) + ' ) '
def | ( self, aString ):
# should return a nestedlist if string format is OK
# should return None if string format is not OK, should display an error message in this case.
aString=aString.strip()
# decide whether list or string
if aString.__contains__(',') or aString.__contains__('(') or aString.__contains__(')'):
#must be list
if not (aString.startswith('(') and aString.endswith(')') ):
raise BadNestedList( aString )
stringList = self.__split(aString[1:len(aString)-1].strip())
parsedList = map( self.__stringToNestedList, stringList )
if len(parsedList) == 1 and type( parsedList[0]) != type(parsedList ):
return stringList[0]
return parsedList
else:
return aString
def __split( self, aString ):
openPara = 0
returnList = []
actualWord = ''
for aChar in aString:
if aChar == ',' and openPara == 0:
returnList.append( actualWord )
actualWord = ''
elif aChar == '(':
openPara +=1
actualWord += aChar
elif aChar == ')':
openPara -=1
actualWord += aChar
else:
actualWord += aChar
if openPara!=0:
raise BadNestedList( aString )
returnList.append( actualWord )
return returnList
| __stringToNestedList | identifier_name |
talleres.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { TalleresService } from './talleres.service'
@Component({
selector: 'app-talleres',
templateUrl: './talleres.component.html',
styleUrls: ['./talleres.component.css'],
providers: [TalleresService]
})
export class TalleresComponent implements OnInit {
Talleres: string;
constructor(
private _TalleresService: TalleresService,
private router: Router
)
{ this._TalleresService.getTalleres()
.subscribe(
data => this.Talleres = data,
error => alert(error)
);
}
ngOnInit()
{ if(!localStorage.getItem('currentUser'))
{ this.router.navigate(['/login']);
}
else
{ if( (localStorage.getItem('currentNacimiento')=='00/00/0000') || (localStorage.getItem('currentSexo')==''))
{ this.router.navigate(['/editar/personales']);
} | } | }
}
| random_line_split |
talleres.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { TalleresService } from './talleres.service'
@Component({
selector: 'app-talleres',
templateUrl: './talleres.component.html',
styleUrls: ['./talleres.component.css'],
providers: [TalleresService]
})
export class TalleresComponent implements OnInit {
Talleres: string;
constructor(
private _TalleresService: TalleresService,
private router: Router
)
{ this._TalleresService.getTalleres()
.subscribe(
data => this.Talleres = data,
error => alert(error)
);
}
ngOnInit()
{ if(!localStorage.getItem('currentUser'))
|
else
{ if( (localStorage.getItem('currentNacimiento')=='00/00/0000') || (localStorage.getItem('currentSexo')==''))
{ this.router.navigate(['/editar/personales']);
}
}
}
} | { this.router.navigate(['/login']);
} | conditional_block |
talleres.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { TalleresService } from './talleres.service'
@Component({
selector: 'app-talleres',
templateUrl: './talleres.component.html',
styleUrls: ['./talleres.component.css'],
providers: [TalleresService]
})
export class | implements OnInit {
Talleres: string;
constructor(
private _TalleresService: TalleresService,
private router: Router
)
{ this._TalleresService.getTalleres()
.subscribe(
data => this.Talleres = data,
error => alert(error)
);
}
ngOnInit()
{ if(!localStorage.getItem('currentUser'))
{ this.router.navigate(['/login']);
}
else
{ if( (localStorage.getItem('currentNacimiento')=='00/00/0000') || (localStorage.getItem('currentSexo')==''))
{ this.router.navigate(['/editar/personales']);
}
}
}
} | TalleresComponent | identifier_name |
mod.rs | /*
copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation.
This file is part of Blockstack.
Blockstack is free software. You may redistribute 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.
Blockstack is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY, including without 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 Blockstack. If not, see <http://www.gnu.org/licenses/>.
*/
#[macro_use] pub mod log;
#[macro_use] pub mod macros;
#[macro_use] pub mod db;
pub mod hash;
pub mod pair;
pub mod pipe;
pub mod retry;
pub mod secp256k1;
pub mod uint;
pub mod strings;
pub mod vrf;
use std::time;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
use std::fmt;
use std::error;
pub fn get_epoch_time_secs() -> u64 {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
return since_the_epoch.as_secs();
}
pub fn get_epoch_time_ms() -> u128 {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
return since_the_epoch.as_millis();
}
pub fn sleep_ms(millis: u64) -> () {
let t = time::Duration::from_millis(millis);
thread::sleep(t);
}
/// Hex deserialization error
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum HexError {
/// Length was not 64 characters
BadLength(usize),
/// Non-hex character in string
BadCharacter(char)
}
impl fmt::Display for HexError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
HexError::BadLength(n) => write!(f, "bad length {} for sha256d hex string", n),
HexError::BadCharacter(c) => write!(f, "bad character {} in sha256d hex string", c)
}
}
}
impl error::Error for HexError {
fn cause(&self) -> Option<&dyn error::Error> |
fn description(&self) -> &str {
match *self {
HexError::BadLength(_) => "sha256d hex string non-64 length",
HexError::BadCharacter(_) => "sha256d bad hex character"
}
}
}
| { None } | identifier_body |
mod.rs | /*
copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation.
This file is part of Blockstack.
Blockstack is free software. You may redistribute 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.
Blockstack is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY, including without 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 Blockstack. If not, see <http://www.gnu.org/licenses/>.
*/
#[macro_use] pub mod log;
#[macro_use] pub mod macros;
#[macro_use] pub mod db;
pub mod hash;
pub mod pair;
pub mod pipe;
pub mod retry;
pub mod secp256k1;
pub mod uint; | pub mod strings;
pub mod vrf;
use std::time;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
use std::fmt;
use std::error;
pub fn get_epoch_time_secs() -> u64 {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
return since_the_epoch.as_secs();
}
pub fn get_epoch_time_ms() -> u128 {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
return since_the_epoch.as_millis();
}
pub fn sleep_ms(millis: u64) -> () {
let t = time::Duration::from_millis(millis);
thread::sleep(t);
}
/// Hex deserialization error
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum HexError {
/// Length was not 64 characters
BadLength(usize),
/// Non-hex character in string
BadCharacter(char)
}
impl fmt::Display for HexError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
HexError::BadLength(n) => write!(f, "bad length {} for sha256d hex string", n),
HexError::BadCharacter(c) => write!(f, "bad character {} in sha256d hex string", c)
}
}
}
impl error::Error for HexError {
fn cause(&self) -> Option<&dyn error::Error> { None }
fn description(&self) -> &str {
match *self {
HexError::BadLength(_) => "sha256d hex string non-64 length",
HexError::BadCharacter(_) => "sha256d bad hex character"
}
}
} | random_line_split |
|
mod.rs | /*
copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation.
This file is part of Blockstack.
Blockstack is free software. You may redistribute 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.
Blockstack is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY, including without 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 Blockstack. If not, see <http://www.gnu.org/licenses/>.
*/
#[macro_use] pub mod log;
#[macro_use] pub mod macros;
#[macro_use] pub mod db;
pub mod hash;
pub mod pair;
pub mod pipe;
pub mod retry;
pub mod secp256k1;
pub mod uint;
pub mod strings;
pub mod vrf;
use std::time;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
use std::fmt;
use std::error;
pub fn get_epoch_time_secs() -> u64 {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
return since_the_epoch.as_secs();
}
pub fn get_epoch_time_ms() -> u128 {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
return since_the_epoch.as_millis();
}
pub fn sleep_ms(millis: u64) -> () {
let t = time::Duration::from_millis(millis);
thread::sleep(t);
}
/// Hex deserialization error
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum HexError {
/// Length was not 64 characters
BadLength(usize),
/// Non-hex character in string
BadCharacter(char)
}
impl fmt::Display for HexError {
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
HexError::BadLength(n) => write!(f, "bad length {} for sha256d hex string", n),
HexError::BadCharacter(c) => write!(f, "bad character {} in sha256d hex string", c)
}
}
}
impl error::Error for HexError {
fn cause(&self) -> Option<&dyn error::Error> { None }
fn description(&self) -> &str {
match *self {
HexError::BadLength(_) => "sha256d hex string non-64 length",
HexError::BadCharacter(_) => "sha256d bad hex character"
}
}
}
| fmt | identifier_name |
account_chart.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
class account_chart(osv.osv_memory):
"""
For Chart of Accounts
"""
_name = "account.chart"
_description = "Account chart"
_columns = {
'fiscalyear': fields.many2one('account.fiscalyear', \
'Fiscal year', \
help='Keep empty for all open fiscal years'),
'period_from': fields.many2one('account.period', 'Start period'),
'period_to': fields.many2one('account.period', 'End period'),
'target_move': fields.selection([('posted', 'All Posted Entries'),
('all', 'All Entries'),
], 'Target Moves', required=True),
}
def | (self, cr, uid, context=None):
"""Return default Fiscalyear value"""
return self.pool.get('account.fiscalyear').find(cr, uid, context=context)
def onchange_fiscalyear(self, cr, uid, ids, fiscalyear_id=False, context=None):
res = {}
if fiscalyear_id:
start_period = end_period = False
cr.execute('''
SELECT * FROM (SELECT p.id
FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
WHERE f.id = %s
ORDER BY p.date_start ASC, p.special DESC
LIMIT 1) AS period_start
UNION ALL
SELECT * FROM (SELECT p.id
FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
WHERE f.id = %s
AND p.date_start < NOW()
ORDER BY p.date_stop DESC
LIMIT 1) AS period_stop''', (fiscalyear_id, fiscalyear_id))
periods = [i[0] for i in cr.fetchall()]
if periods:
start_period = periods[0]
if len(periods) > 1:
end_period = periods[1]
res['value'] = {'period_from': start_period, 'period_to': end_period}
else:
res['value'] = {'period_from': False, 'period_to': False}
return res
def account_chart_open_window(self, cr, uid, ids, context=None):
"""
Opens chart of Accounts
@param cr: the current row, from the database cursor,
@param uid: the current user’s ID for security checks,
@param ids: List of account chart’s IDs
@return: dictionary of Open account chart window on given fiscalyear and all Entries or posted entries
"""
mod_obj = self.pool.get('ir.model.data')
act_obj = self.pool.get('ir.actions.act_window')
period_obj = self.pool.get('account.period')
fy_obj = self.pool.get('account.fiscalyear')
if context is None:
context = {}
data = self.read(cr, uid, ids, context=context)[0]
result = mod_obj.get_object_reference(cr, uid, 'account', 'action_account_tree')
id = result and result[1] or False
result = act_obj.read(cr, uid, [id], context=context)[0]
fiscalyear_id = data.get('fiscalyear', False) and data['fiscalyear'][0] or False
result['periods'] = []
if data['period_from'] and data['period_to']:
period_from = data.get('period_from', False) and data['period_from'][0] or False
period_to = data.get('period_to', False) and data['period_to'][0] or False
result['periods'] = period_obj.build_ctx_periods(cr, uid, period_from, period_to)
result['context'] = str({'fiscalyear': fiscalyear_id, 'periods': result['periods'], \
'state': data['target_move']})
if fiscalyear_id:
result['name'] += ':' + fy_obj.read(cr, uid, [fiscalyear_id], context=context)[0]['code']
return result
_defaults = {
'target_move': 'posted',
'fiscalyear': _get_fiscalyear,
}
| _get_fiscalyear | identifier_name |
account_chart.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
class account_chart(osv.osv_memory):
"""
For Chart of Accounts
"""
_name = "account.chart"
_description = "Account chart"
_columns = {
'fiscalyear': fields.many2one('account.fiscalyear', \
'Fiscal year', \
help='Keep empty for all open fiscal years'),
'period_from': fields.many2one('account.period', 'Start period'),
'period_to': fields.many2one('account.period', 'End period'),
'target_move': fields.selection([('posted', 'All Posted Entries'),
('all', 'All Entries'),
], 'Target Moves', required=True),
}
def _get_fiscalyear(self, cr, uid, context=None):
"""Return default Fiscalyear value"""
return self.pool.get('account.fiscalyear').find(cr, uid, context=context)
def onchange_fiscalyear(self, cr, uid, ids, fiscalyear_id=False, context=None):
res = {}
if fiscalyear_id:
start_period = end_period = False
cr.execute('''
SELECT * FROM (SELECT p.id
FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
WHERE f.id = %s
ORDER BY p.date_start ASC, p.special DESC
LIMIT 1) AS period_start
UNION ALL
SELECT * FROM (SELECT p.id
FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
WHERE f.id = %s
AND p.date_start < NOW()
ORDER BY p.date_stop DESC
LIMIT 1) AS period_stop''', (fiscalyear_id, fiscalyear_id))
periods = [i[0] for i in cr.fetchall()]
if periods:
start_period = periods[0]
if len(periods) > 1:
end_period = periods[1]
res['value'] = {'period_from': start_period, 'period_to': end_period}
else:
res['value'] = {'period_from': False, 'period_to': False}
return res
def account_chart_open_window(self, cr, uid, ids, context=None):
"""
Opens chart of Accounts
@param cr: the current row, from the database cursor,
@param uid: the current user’s ID for security checks,
@param ids: List of account chart’s IDs
@return: dictionary of Open account chart window on given fiscalyear and all Entries or posted entries
"""
mod_obj = self.pool.get('ir.model.data')
act_obj = self.pool.get('ir.actions.act_window')
period_obj = self.pool.get('account.period')
fy_obj = self.pool.get('account.fiscalyear') | result = mod_obj.get_object_reference(cr, uid, 'account', 'action_account_tree')
id = result and result[1] or False
result = act_obj.read(cr, uid, [id], context=context)[0]
fiscalyear_id = data.get('fiscalyear', False) and data['fiscalyear'][0] or False
result['periods'] = []
if data['period_from'] and data['period_to']:
period_from = data.get('period_from', False) and data['period_from'][0] or False
period_to = data.get('period_to', False) and data['period_to'][0] or False
result['periods'] = period_obj.build_ctx_periods(cr, uid, period_from, period_to)
result['context'] = str({'fiscalyear': fiscalyear_id, 'periods': result['periods'], \
'state': data['target_move']})
if fiscalyear_id:
result['name'] += ':' + fy_obj.read(cr, uid, [fiscalyear_id], context=context)[0]['code']
return result
_defaults = {
'target_move': 'posted',
'fiscalyear': _get_fiscalyear,
} | if context is None:
context = {}
data = self.read(cr, uid, ids, context=context)[0] | random_line_split |
account_chart.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
class account_chart(osv.osv_memory):
"""
For Chart of Accounts
"""
_name = "account.chart"
_description = "Account chart"
_columns = {
'fiscalyear': fields.many2one('account.fiscalyear', \
'Fiscal year', \
help='Keep empty for all open fiscal years'),
'period_from': fields.many2one('account.period', 'Start period'),
'period_to': fields.many2one('account.period', 'End period'),
'target_move': fields.selection([('posted', 'All Posted Entries'),
('all', 'All Entries'),
], 'Target Moves', required=True),
}
def _get_fiscalyear(self, cr, uid, context=None):
"""Return default Fiscalyear value"""
return self.pool.get('account.fiscalyear').find(cr, uid, context=context)
def onchange_fiscalyear(self, cr, uid, ids, fiscalyear_id=False, context=None):
res = {}
if fiscalyear_id:
|
else:
res['value'] = {'period_from': False, 'period_to': False}
return res
def account_chart_open_window(self, cr, uid, ids, context=None):
"""
Opens chart of Accounts
@param cr: the current row, from the database cursor,
@param uid: the current user’s ID for security checks,
@param ids: List of account chart’s IDs
@return: dictionary of Open account chart window on given fiscalyear and all Entries or posted entries
"""
mod_obj = self.pool.get('ir.model.data')
act_obj = self.pool.get('ir.actions.act_window')
period_obj = self.pool.get('account.period')
fy_obj = self.pool.get('account.fiscalyear')
if context is None:
context = {}
data = self.read(cr, uid, ids, context=context)[0]
result = mod_obj.get_object_reference(cr, uid, 'account', 'action_account_tree')
id = result and result[1] or False
result = act_obj.read(cr, uid, [id], context=context)[0]
fiscalyear_id = data.get('fiscalyear', False) and data['fiscalyear'][0] or False
result['periods'] = []
if data['period_from'] and data['period_to']:
period_from = data.get('period_from', False) and data['period_from'][0] or False
period_to = data.get('period_to', False) and data['period_to'][0] or False
result['periods'] = period_obj.build_ctx_periods(cr, uid, period_from, period_to)
result['context'] = str({'fiscalyear': fiscalyear_id, 'periods': result['periods'], \
'state': data['target_move']})
if fiscalyear_id:
result['name'] += ':' + fy_obj.read(cr, uid, [fiscalyear_id], context=context)[0]['code']
return result
_defaults = {
'target_move': 'posted',
'fiscalyear': _get_fiscalyear,
}
| start_period = end_period = False
cr.execute('''
SELECT * FROM (SELECT p.id
FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
WHERE f.id = %s
ORDER BY p.date_start ASC, p.special DESC
LIMIT 1) AS period_start
UNION ALL
SELECT * FROM (SELECT p.id
FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
WHERE f.id = %s
AND p.date_start < NOW()
ORDER BY p.date_stop DESC
LIMIT 1) AS period_stop''', (fiscalyear_id, fiscalyear_id))
periods = [i[0] for i in cr.fetchall()]
if periods:
start_period = periods[0]
if len(periods) > 1:
end_period = periods[1]
res['value'] = {'period_from': start_period, 'period_to': end_period} | conditional_block |
account_chart.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
class account_chart(osv.osv_memory):
"""
For Chart of Accounts
"""
_name = "account.chart"
_description = "Account chart"
_columns = {
'fiscalyear': fields.many2one('account.fiscalyear', \
'Fiscal year', \
help='Keep empty for all open fiscal years'),
'period_from': fields.many2one('account.period', 'Start period'),
'period_to': fields.many2one('account.period', 'End period'),
'target_move': fields.selection([('posted', 'All Posted Entries'),
('all', 'All Entries'),
], 'Target Moves', required=True),
}
def _get_fiscalyear(self, cr, uid, context=None):
"""Return default Fiscalyear value"""
return self.pool.get('account.fiscalyear').find(cr, uid, context=context)
def onchange_fiscalyear(self, cr, uid, ids, fiscalyear_id=False, context=None):
res = {}
if fiscalyear_id:
start_period = end_period = False
cr.execute('''
SELECT * FROM (SELECT p.id
FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
WHERE f.id = %s
ORDER BY p.date_start ASC, p.special DESC
LIMIT 1) AS period_start
UNION ALL
SELECT * FROM (SELECT p.id
FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
WHERE f.id = %s
AND p.date_start < NOW()
ORDER BY p.date_stop DESC
LIMIT 1) AS period_stop''', (fiscalyear_id, fiscalyear_id))
periods = [i[0] for i in cr.fetchall()]
if periods:
start_period = periods[0]
if len(periods) > 1:
end_period = periods[1]
res['value'] = {'period_from': start_period, 'period_to': end_period}
else:
res['value'] = {'period_from': False, 'period_to': False}
return res
def account_chart_open_window(self, cr, uid, ids, context=None):
| _defaults = {
'target_move': 'posted',
'fiscalyear': _get_fiscalyear,
}
| """
Opens chart of Accounts
@param cr: the current row, from the database cursor,
@param uid: the current user’s ID for security checks,
@param ids: List of account chart’s IDs
@return: dictionary of Open account chart window on given fiscalyear and all Entries or posted entries
"""
mod_obj = self.pool.get('ir.model.data')
act_obj = self.pool.get('ir.actions.act_window')
period_obj = self.pool.get('account.period')
fy_obj = self.pool.get('account.fiscalyear')
if context is None:
context = {}
data = self.read(cr, uid, ids, context=context)[0]
result = mod_obj.get_object_reference(cr, uid, 'account', 'action_account_tree')
id = result and result[1] or False
result = act_obj.read(cr, uid, [id], context=context)[0]
fiscalyear_id = data.get('fiscalyear', False) and data['fiscalyear'][0] or False
result['periods'] = []
if data['period_from'] and data['period_to']:
period_from = data.get('period_from', False) and data['period_from'][0] or False
period_to = data.get('period_to', False) and data['period_to'][0] or False
result['periods'] = period_obj.build_ctx_periods(cr, uid, period_from, period_to)
result['context'] = str({'fiscalyear': fiscalyear_id, 'periods': result['periods'], \
'state': data['target_move']})
if fiscalyear_id:
result['name'] += ':' + fy_obj.read(cr, uid, [fiscalyear_id], context=context)[0]['code']
return result
| identifier_body |
__init__.py | import time
import datetime
from MyPy.core.exceptions import (
Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError,
IntegrityError, InternalError, ProgrammingError, NotSupportedError
)
from MyPy.constants import fieldtypes
apilevel = '2.0'
threadsafety = 1
paramstyle = 'format'
def Connect(*args, **kwargs):
from MyPy.core.connection import Connection
return Connection(*args, **kwargs)
connect = Connection = Connect
Date = datetime.date
Time = datetime.time
Timestamp = datetime.datetime
def DateFromTicks(ticks):
return Date(*time.localtime(ticks)[:3])
def TimeFromTicks(ticks):
return Time(*time.localtime(ticks)[3:6])
def TimestampFromTicks(ticks):
return Timestamp(*time.localtime(ticks)[:6])
Binary = str
class DBAPITypeObject:
def __init__(self, *values):
self.values = values
def __cmp__(self, other):
if other in self.values:
return 0
if other < self.values:
|
else:
return -1
STRING = DBAPITypeObject(fieldtypes.FIELD_TYPE_ENUM, fieldtypes.FIELD_TYPE_STRING,
fieldtypes.FIELD_TYPE_VAR_STRING)
BINARY = DBAPITypeObject(fieldtypes.FIELD_TYPE_BLOB, fieldtypes.FIELD_TYPE_LONG_BLOB,
fieldtypes.FIELD_TYPE_MEDIUM_BLOB, fieldtypes.FIELD_TYPE_TINY_BLOB)
NUMBER = DBAPITypeObject(fieldtypes.FIELD_TYPE_DECIMAL, fieldtypes.FIELD_TYPE_DOUBLE,
fieldtypes.FIELD_TYPE_FLOAT, fieldtypes.FIELD_TYPE_INT24,
fieldtypes.FIELD_TYPE_LONG, fieldtypes.FIELD_TYPE_LONGLONG,
fieldtypes.FIELD_TYPE_TINY, fieldtypes.FIELD_TYPE_YEAR)
DATETIME = DBAPITypeObject(fieldtypes.FIELD_TYPE_DATETIME, fieldtypes.FIELD_TYPE_TIMESTAMP)
ROWID = DBAPITypeObject()
__all__ = [
'Connect', 'Connection', 'connect', 'apilevel', 'threadsafety', 'paramstyle',
'Error', 'Warning', 'InterfaceError', 'DatabaseError', 'DataError',
'OperationalError', 'IntegrityError', 'InternalError', 'ProgrammingError',
'NotSupportedError', 'Date', 'Time', 'Timestamp', 'Binary', 'DateFromTicks',
'DateFromTicks', 'TimestampFromTicks', 'STRING', 'BINARY', 'NUMBER',
'DATETIME', 'ROWID',
]
| return 1 | conditional_block |
__init__.py | import time
import datetime
from MyPy.core.exceptions import (
Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError,
IntegrityError, InternalError, ProgrammingError, NotSupportedError
)
from MyPy.constants import fieldtypes
apilevel = '2.0'
threadsafety = 1
paramstyle = 'format'
def Connect(*args, **kwargs):
from MyPy.core.connection import Connection
return Connection(*args, **kwargs)
connect = Connection = Connect
Date = datetime.date
Time = datetime.time
Timestamp = datetime.datetime
def DateFromTicks(ticks):
|
def TimeFromTicks(ticks):
return Time(*time.localtime(ticks)[3:6])
def TimestampFromTicks(ticks):
return Timestamp(*time.localtime(ticks)[:6])
Binary = str
class DBAPITypeObject:
def __init__(self, *values):
self.values = values
def __cmp__(self, other):
if other in self.values:
return 0
if other < self.values:
return 1
else:
return -1
STRING = DBAPITypeObject(fieldtypes.FIELD_TYPE_ENUM, fieldtypes.FIELD_TYPE_STRING,
fieldtypes.FIELD_TYPE_VAR_STRING)
BINARY = DBAPITypeObject(fieldtypes.FIELD_TYPE_BLOB, fieldtypes.FIELD_TYPE_LONG_BLOB,
fieldtypes.FIELD_TYPE_MEDIUM_BLOB, fieldtypes.FIELD_TYPE_TINY_BLOB)
NUMBER = DBAPITypeObject(fieldtypes.FIELD_TYPE_DECIMAL, fieldtypes.FIELD_TYPE_DOUBLE,
fieldtypes.FIELD_TYPE_FLOAT, fieldtypes.FIELD_TYPE_INT24,
fieldtypes.FIELD_TYPE_LONG, fieldtypes.FIELD_TYPE_LONGLONG,
fieldtypes.FIELD_TYPE_TINY, fieldtypes.FIELD_TYPE_YEAR)
DATETIME = DBAPITypeObject(fieldtypes.FIELD_TYPE_DATETIME, fieldtypes.FIELD_TYPE_TIMESTAMP)
ROWID = DBAPITypeObject()
__all__ = [
'Connect', 'Connection', 'connect', 'apilevel', 'threadsafety', 'paramstyle',
'Error', 'Warning', 'InterfaceError', 'DatabaseError', 'DataError',
'OperationalError', 'IntegrityError', 'InternalError', 'ProgrammingError',
'NotSupportedError', 'Date', 'Time', 'Timestamp', 'Binary', 'DateFromTicks',
'DateFromTicks', 'TimestampFromTicks', 'STRING', 'BINARY', 'NUMBER',
'DATETIME', 'ROWID',
]
| return Date(*time.localtime(ticks)[:3]) | identifier_body |
__init__.py | import time
import datetime
from MyPy.core.exceptions import (
Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError,
IntegrityError, InternalError, ProgrammingError, NotSupportedError
)
from MyPy.constants import fieldtypes
apilevel = '2.0' | threadsafety = 1
paramstyle = 'format'
def Connect(*args, **kwargs):
from MyPy.core.connection import Connection
return Connection(*args, **kwargs)
connect = Connection = Connect
Date = datetime.date
Time = datetime.time
Timestamp = datetime.datetime
def DateFromTicks(ticks):
return Date(*time.localtime(ticks)[:3])
def TimeFromTicks(ticks):
return Time(*time.localtime(ticks)[3:6])
def TimestampFromTicks(ticks):
return Timestamp(*time.localtime(ticks)[:6])
Binary = str
class DBAPITypeObject:
def __init__(self, *values):
self.values = values
def __cmp__(self, other):
if other in self.values:
return 0
if other < self.values:
return 1
else:
return -1
STRING = DBAPITypeObject(fieldtypes.FIELD_TYPE_ENUM, fieldtypes.FIELD_TYPE_STRING,
fieldtypes.FIELD_TYPE_VAR_STRING)
BINARY = DBAPITypeObject(fieldtypes.FIELD_TYPE_BLOB, fieldtypes.FIELD_TYPE_LONG_BLOB,
fieldtypes.FIELD_TYPE_MEDIUM_BLOB, fieldtypes.FIELD_TYPE_TINY_BLOB)
NUMBER = DBAPITypeObject(fieldtypes.FIELD_TYPE_DECIMAL, fieldtypes.FIELD_TYPE_DOUBLE,
fieldtypes.FIELD_TYPE_FLOAT, fieldtypes.FIELD_TYPE_INT24,
fieldtypes.FIELD_TYPE_LONG, fieldtypes.FIELD_TYPE_LONGLONG,
fieldtypes.FIELD_TYPE_TINY, fieldtypes.FIELD_TYPE_YEAR)
DATETIME = DBAPITypeObject(fieldtypes.FIELD_TYPE_DATETIME, fieldtypes.FIELD_TYPE_TIMESTAMP)
ROWID = DBAPITypeObject()
__all__ = [
'Connect', 'Connection', 'connect', 'apilevel', 'threadsafety', 'paramstyle',
'Error', 'Warning', 'InterfaceError', 'DatabaseError', 'DataError',
'OperationalError', 'IntegrityError', 'InternalError', 'ProgrammingError',
'NotSupportedError', 'Date', 'Time', 'Timestamp', 'Binary', 'DateFromTicks',
'DateFromTicks', 'TimestampFromTicks', 'STRING', 'BINARY', 'NUMBER',
'DATETIME', 'ROWID',
] | random_line_split |
|
__init__.py | import time
import datetime
from MyPy.core.exceptions import (
Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError,
IntegrityError, InternalError, ProgrammingError, NotSupportedError
)
from MyPy.constants import fieldtypes
apilevel = '2.0'
threadsafety = 1
paramstyle = 'format'
def Connect(*args, **kwargs):
from MyPy.core.connection import Connection
return Connection(*args, **kwargs)
connect = Connection = Connect
Date = datetime.date
Time = datetime.time
Timestamp = datetime.datetime
def DateFromTicks(ticks):
return Date(*time.localtime(ticks)[:3])
def TimeFromTicks(ticks):
return Time(*time.localtime(ticks)[3:6])
def TimestampFromTicks(ticks):
return Timestamp(*time.localtime(ticks)[:6])
Binary = str
class | :
def __init__(self, *values):
self.values = values
def __cmp__(self, other):
if other in self.values:
return 0
if other < self.values:
return 1
else:
return -1
STRING = DBAPITypeObject(fieldtypes.FIELD_TYPE_ENUM, fieldtypes.FIELD_TYPE_STRING,
fieldtypes.FIELD_TYPE_VAR_STRING)
BINARY = DBAPITypeObject(fieldtypes.FIELD_TYPE_BLOB, fieldtypes.FIELD_TYPE_LONG_BLOB,
fieldtypes.FIELD_TYPE_MEDIUM_BLOB, fieldtypes.FIELD_TYPE_TINY_BLOB)
NUMBER = DBAPITypeObject(fieldtypes.FIELD_TYPE_DECIMAL, fieldtypes.FIELD_TYPE_DOUBLE,
fieldtypes.FIELD_TYPE_FLOAT, fieldtypes.FIELD_TYPE_INT24,
fieldtypes.FIELD_TYPE_LONG, fieldtypes.FIELD_TYPE_LONGLONG,
fieldtypes.FIELD_TYPE_TINY, fieldtypes.FIELD_TYPE_YEAR)
DATETIME = DBAPITypeObject(fieldtypes.FIELD_TYPE_DATETIME, fieldtypes.FIELD_TYPE_TIMESTAMP)
ROWID = DBAPITypeObject()
__all__ = [
'Connect', 'Connection', 'connect', 'apilevel', 'threadsafety', 'paramstyle',
'Error', 'Warning', 'InterfaceError', 'DatabaseError', 'DataError',
'OperationalError', 'IntegrityError', 'InternalError', 'ProgrammingError',
'NotSupportedError', 'Date', 'Time', 'Timestamp', 'Binary', 'DateFromTicks',
'DateFromTicks', 'TimestampFromTicks', 'STRING', 'BINARY', 'NUMBER',
'DATETIME', 'ROWID',
]
| DBAPITypeObject | identifier_name |
main.ts | import {Aurelia} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import {UnhandledExceptionProvider} from './utils/module';
import {UnhandledExceptionHandler} from './utils/module';
import 'fetch';
import 'toastr';
import 'bootstrap';
import "velocity/velocity.ui";
export function configure(aurelia: Aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging()
.plugin('aurelia-animator-velocity', instance => {
instance.options.duration = 300;
instance.options.easing = "linear";
instance.enterAnimation = { properties: "fadeIn", options: { easing: "easeIn", duration: 400 } };
instance.leaveAnimation = { properties: "fadeOut", options: { easing: "easeIn", duration: 400 } };
});
aurelia.start().then(() => {
//Register the unhandled exception classes so that the specified dependencies can be injected
aurelia.container.registerSingleton(UnhandledExceptionProvider, UnhandledExceptionProvider);
aurelia.container.registerSingleton(UnhandledExceptionHandler, UnhandledExceptionHandler);
//Create the exception provider and handler so that they can register for uncaught errors
aurelia.container.get(UnhandledExceptionProvider);
aurelia.container.get(UnhandledExceptionHandler);
aurelia.container.registerSingleton(HttpClient, HttpClient);
configureHttpClient(aurelia.container.get(HttpClient));
aurelia.setRoot('app/layout/shell')
});
toastr.options.timeOut = 4000;
toastr.options.positionClass = 'toast-bottom-right';
}
function configureHttpClient(httpClient) {
httpClient.configure(config => {
config
.withBaseUrl('http://localhost:8080/')
.withDefaults({
headers: {
'Accept': 'application/json',
'X-Requested-With': 'Fetch'
}
})
.withInterceptor({
request(request) | ,
response(response) {
console.log(`Received ${response.status} ${response.url}`);
return response; // you can return a modified Response
}
});
});
} | {
console.log(`Requesting ${request.method} ${request.url}`);
return request; // you can return a modified Request, or you can short-circuit the request by returning a Response
} | identifier_body |
main.ts | import {Aurelia} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import {UnhandledExceptionProvider} from './utils/module';
import {UnhandledExceptionHandler} from './utils/module';
import 'fetch';
import 'toastr';
import 'bootstrap';
import "velocity/velocity.ui";
export function configure(aurelia: Aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging()
.plugin('aurelia-animator-velocity', instance => {
instance.options.duration = 300;
instance.options.easing = "linear";
instance.enterAnimation = { properties: "fadeIn", options: { easing: "easeIn", duration: 400 } };
instance.leaveAnimation = { properties: "fadeOut", options: { easing: "easeIn", duration: 400 } };
});
aurelia.start().then(() => {
//Register the unhandled exception classes so that the specified dependencies can be injected
aurelia.container.registerSingleton(UnhandledExceptionProvider, UnhandledExceptionProvider);
aurelia.container.registerSingleton(UnhandledExceptionHandler, UnhandledExceptionHandler);
//Create the exception provider and handler so that they can register for uncaught errors
aurelia.container.get(UnhandledExceptionProvider);
aurelia.container.get(UnhandledExceptionHandler);
aurelia.container.registerSingleton(HttpClient, HttpClient);
configureHttpClient(aurelia.container.get(HttpClient));
aurelia.setRoot('app/layout/shell')
});
toastr.options.timeOut = 4000;
toastr.options.positionClass = 'toast-bottom-right';
}
function | (httpClient) {
httpClient.configure(config => {
config
.withBaseUrl('http://localhost:8080/')
.withDefaults({
headers: {
'Accept': 'application/json',
'X-Requested-With': 'Fetch'
}
})
.withInterceptor({
request(request) {
console.log(`Requesting ${request.method} ${request.url}`);
return request; // you can return a modified Request, or you can short-circuit the request by returning a Response
},
response(response) {
console.log(`Received ${response.status} ${response.url}`);
return response; // you can return a modified Response
}
});
});
} | configureHttpClient | identifier_name |
main.ts | import {Aurelia} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import {UnhandledExceptionProvider} from './utils/module';
import {UnhandledExceptionHandler} from './utils/module'; | export function configure(aurelia: Aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging()
.plugin('aurelia-animator-velocity', instance => {
instance.options.duration = 300;
instance.options.easing = "linear";
instance.enterAnimation = { properties: "fadeIn", options: { easing: "easeIn", duration: 400 } };
instance.leaveAnimation = { properties: "fadeOut", options: { easing: "easeIn", duration: 400 } };
});
aurelia.start().then(() => {
//Register the unhandled exception classes so that the specified dependencies can be injected
aurelia.container.registerSingleton(UnhandledExceptionProvider, UnhandledExceptionProvider);
aurelia.container.registerSingleton(UnhandledExceptionHandler, UnhandledExceptionHandler);
//Create the exception provider and handler so that they can register for uncaught errors
aurelia.container.get(UnhandledExceptionProvider);
aurelia.container.get(UnhandledExceptionHandler);
aurelia.container.registerSingleton(HttpClient, HttpClient);
configureHttpClient(aurelia.container.get(HttpClient));
aurelia.setRoot('app/layout/shell')
});
toastr.options.timeOut = 4000;
toastr.options.positionClass = 'toast-bottom-right';
}
function configureHttpClient(httpClient) {
httpClient.configure(config => {
config
.withBaseUrl('http://localhost:8080/')
.withDefaults({
headers: {
'Accept': 'application/json',
'X-Requested-With': 'Fetch'
}
})
.withInterceptor({
request(request) {
console.log(`Requesting ${request.method} ${request.url}`);
return request; // you can return a modified Request, or you can short-circuit the request by returning a Response
},
response(response) {
console.log(`Received ${response.status} ${response.url}`);
return response; // you can return a modified Response
}
});
});
} | import 'fetch';
import 'toastr';
import 'bootstrap';
import "velocity/velocity.ui";
| random_line_split |
kendo.culture.en-NZ.js | /**
* Copyright 2014 Telerik AD
*
* 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(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["en-NZ"] = {
name: "en-NZ",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["-$n","$n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "$"
}
},
calendars: {
standard: {
days: {
names: ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
namesAbbr: ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],
namesShort: ["Su","Mo","Tu","We","Th","Fr","Sa"] | namesAbbr: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""]
},
AM: ["a.m.","a.m.","A.M."],
PM: ["p.m.","p.m.","P.M."],
patterns: {
d: "d/MM/yyyy",
D: "dddd, d MMMM yyyy",
F: "dddd, d MMMM yyyy h:mm:ss tt",
g: "d/MM/yyyy h:mm tt",
G: "d/MM/yyyy h:mm:ss tt",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "h:mm tt",
T: "h:mm:ss tt",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": "/",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); | },
months: {
names: ["January","February","March","April","May","June","July","August","September","October","November","December",""], | random_line_split |
parsing.rs | //! Utility functions for Header implementations.
use std::str;
use std::fmt::{self, Display};
/// Reads a single raw string when parsing a header
pub fn from_one_raw_str<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<T> {
if raw.len() != 1 {
return None;
}
// we JUST checked that raw.len() == 1, so raw[0] WILL exist.
if let Ok(s) = str::from_utf8(& unsafe { raw.get_unchecked(0) }[..]) {
if s != "" {
return str::FromStr::from_str(s).ok();
} | }
None
}
/// Reads a comma-delimited raw header into a Vec.
#[inline]
pub fn from_comma_delimited<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<Vec<T>> {
if raw.len() != 1 {
return None;
}
// we JUST checked that raw.len() == 1, so raw[0] WILL exist.
from_one_comma_delimited(& unsafe { raw.get_unchecked(0) }[..])
}
/// Reads a comma-delimited raw string into a Vec.
pub fn from_one_comma_delimited<T: str::FromStr>(raw: &[u8]) -> Option<Vec<T>> {
match str::from_utf8(raw) {
Ok(s) => {
Some(s
.split(',')
.filter_map(|x| match x.trim() {
"" => None,
y => Some(y)
})
.filter_map(|x| x.parse().ok())
.collect())
}
Err(_) => None
}
}
/// Format an array into a comma-delimited string.
pub fn fmt_comma_delimited<T: Display>(f: &mut fmt::Formatter, parts: &[T]) -> fmt::Result {
for (i, part) in parts.iter().enumerate() {
if i != 0 {
try!(f.write_str(", "));
}
try!(Display::fmt(part, f));
}
Ok(())
} | random_line_split |
|
parsing.rs | //! Utility functions for Header implementations.
use std::str;
use std::fmt::{self, Display};
/// Reads a single raw string when parsing a header
pub fn from_one_raw_str<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<T> {
if raw.len() != 1 {
return None;
}
// we JUST checked that raw.len() == 1, so raw[0] WILL exist.
if let Ok(s) = str::from_utf8(& unsafe { raw.get_unchecked(0) }[..]) {
if s != "" {
return str::FromStr::from_str(s).ok();
}
}
None
}
/// Reads a comma-delimited raw header into a Vec.
#[inline]
pub fn from_comma_delimited<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<Vec<T>> |
/// Reads a comma-delimited raw string into a Vec.
pub fn from_one_comma_delimited<T: str::FromStr>(raw: &[u8]) -> Option<Vec<T>> {
match str::from_utf8(raw) {
Ok(s) => {
Some(s
.split(',')
.filter_map(|x| match x.trim() {
"" => None,
y => Some(y)
})
.filter_map(|x| x.parse().ok())
.collect())
}
Err(_) => None
}
}
/// Format an array into a comma-delimited string.
pub fn fmt_comma_delimited<T: Display>(f: &mut fmt::Formatter, parts: &[T]) -> fmt::Result {
for (i, part) in parts.iter().enumerate() {
if i != 0 {
try!(f.write_str(", "));
}
try!(Display::fmt(part, f));
}
Ok(())
}
| {
if raw.len() != 1 {
return None;
}
// we JUST checked that raw.len() == 1, so raw[0] WILL exist.
from_one_comma_delimited(& unsafe { raw.get_unchecked(0) }[..])
} | identifier_body |
parsing.rs | //! Utility functions for Header implementations.
use std::str;
use std::fmt::{self, Display};
/// Reads a single raw string when parsing a header
pub fn | <T: str::FromStr>(raw: &[Vec<u8>]) -> Option<T> {
if raw.len() != 1 {
return None;
}
// we JUST checked that raw.len() == 1, so raw[0] WILL exist.
if let Ok(s) = str::from_utf8(& unsafe { raw.get_unchecked(0) }[..]) {
if s != "" {
return str::FromStr::from_str(s).ok();
}
}
None
}
/// Reads a comma-delimited raw header into a Vec.
#[inline]
pub fn from_comma_delimited<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<Vec<T>> {
if raw.len() != 1 {
return None;
}
// we JUST checked that raw.len() == 1, so raw[0] WILL exist.
from_one_comma_delimited(& unsafe { raw.get_unchecked(0) }[..])
}
/// Reads a comma-delimited raw string into a Vec.
pub fn from_one_comma_delimited<T: str::FromStr>(raw: &[u8]) -> Option<Vec<T>> {
match str::from_utf8(raw) {
Ok(s) => {
Some(s
.split(',')
.filter_map(|x| match x.trim() {
"" => None,
y => Some(y)
})
.filter_map(|x| x.parse().ok())
.collect())
}
Err(_) => None
}
}
/// Format an array into a comma-delimited string.
pub fn fmt_comma_delimited<T: Display>(f: &mut fmt::Formatter, parts: &[T]) -> fmt::Result {
for (i, part) in parts.iter().enumerate() {
if i != 0 {
try!(f.write_str(", "));
}
try!(Display::fmt(part, f));
}
Ok(())
}
| from_one_raw_str | identifier_name |
index.js | /* global appSettings */
var
$result,
$resultContainer,
$resultsButton,
$resultsPane,
$renderingLabel,
$window = $(window),
path = require('path'),
_ = require('lodash'),
isEnabled = true,
messenger = require(path.resolve(__dirname, '../messenger')),
renderer = require(path.resolve(__dirname, './asciidoc.js')).get(),
formats = require(path.resolve(__dirname, '../formats')),
source = '',
shell = require('shell'),
formatter = null,
subscriptions = [],
_fileInfo,
_buildFlags = [];
var detectRenderer = function (fileInfo) {
var rendererPath, currentFormatter;
currentFormatter = formats.getByFileExtension(fileInfo.ext);
if (formatter === null || currentFormatter.name !== formatter.name) |
};
var handlers = {
opened: function(fileInfo){
refreshSubscriptions();
$result.animate({
scrollTop: $result.offset().top
}, 10);
},
sourceChanged: function(fileInfo){
handlers.contentChanged(fileInfo);
},
contentChanged: function (fileInfo) {
if (isEnabled && $result) {
_fileInfo = fileInfo;
if (!_.isUndefined(_fileInfo)) {
if (_fileInfo.isBlank) {
$result.html('');
} else {
if(_fileInfo.contents.length > 0){
var flags = '';
detectRenderer(_fileInfo);
source = _fileInfo.contents;
_buildFlags.forEach(function (buildFlag) {
flags += ':' + buildFlag + ':\n'
});
source = flags + source;
if(!$renderingLabel.is(':visible')){
$renderingLabel.fadeIn('fast');
}
renderer(source, function (e) {
$result.html(e.html);
if($renderingLabel.is(':visible')){
$renderingLabel.fadeOut('fast');
}
});
}
}
}
}
},
clearBuildFlags: function (params) {
_buildFlags = [];
},
buildFlags: function (buildFlags) {
_buildFlags = buildFlags;
handlers.contentChanged(_fileInfo);
},
showResults: function() {
subscribe();
$resultsPane.css('visibility', 'visible');
$resultsButton
.removeClass('fa-chevron-left')
.addClass('fa-chevron-right')
.one('click', handlers.hideResults);
messenger.publish.layout('showResults');
},
hideResults: function () {
unsubscribe();
$resultsPane.css('visibility', 'hidden');
$resultsButton
.removeClass('fa-chevron-right')
.addClass('fa-chevron-left')
.one('click', handlers.showResults);
messenger.publish.layout('hideResults');
},
fileSelected: function(){
refreshSubscriptions();
_buildFlags = [];
},
allFilesClosed: function () {
$result.html('');
$renderingLabel.fadeOut('fast');
}
};
var subscribe = function () {
isEnabled = true;
subscriptions.push(messenger.subscribe.file('new', handlers.opened));
subscriptions.push(messenger.subscribe.file('opened', handlers.opened));
subscriptions.push(messenger.subscribe.file('contentChanged', handlers.contentChanged));
subscriptions.push(messenger.subscribe.file('sourceChange', handlers.sourceChanged));
subscriptions.push(messenger.subscribe.file('allFilesClosed', handlers.allFilesClosed));
subscriptions.push(messenger.subscribe.format('buildFlags', handlers.buildFlags));
subscriptions.push(messenger.subscribe.metadata('buildFlags.clear', handlers.clearBuildFlags));
};
var unsubscribe = function () {
isEnabled = false;
subscriptions.forEach(function (subscription) {
messenger.unsubscribe(subscription);
});
subscriptions = [];
};
var refreshSubscriptions = function(){
unsubscribe();
subscribe();
};
subscribe();
messenger.subscribe.file('selected', handlers.fileSelected);
messenger.subscribe.file('rerender', function (data, envelope) {
renderer(source, function (e) {
$result.html(e.html);
});
});
var openExternalLinksInBrowser = function (e) {
var href;
var element = e.target;
if (element.nodeName === 'A') {
href = element.getAttribute('href');
shell.openExternal(href);
e.preventDefault();
}
};
document.addEventListener('click', openExternalLinksInBrowser, false);
var setHeight = function (offSetValue) {
$resultsPane.css('height', $window.height() - offSetValue + 'px');
$window.on('resize', function (e) {
$resultsPane.css('height', $window.height() - offSetValue + 'px');
});
};
$(function () {
$result = $('#result');
$resultContainer = $('#result-container');
$resultsPane = $('#result-pane');
$resultsButton = $('#result-button');
$renderingLabel = $('#rendering-label');
$resultsPane
.css('left', appSettings.split())
.css('width', appSettings.resultsWidth());
$resultsButton.one('click', handlers.hideResults);
setHeight(appSettings.editingContainerOffset());
}); | {
formatter = currentFormatter;
rendererPath = path.resolve(__dirname, './' + formatter.name.toLowerCase());
renderer = require(rendererPath).get();
messenger.publish.file('formatChanged', formatter);
} | conditional_block |
index.js | /* global appSettings */
var
$result,
$resultContainer,
$resultsButton,
$resultsPane,
$renderingLabel,
$window = $(window),
path = require('path'),
_ = require('lodash'),
isEnabled = true,
messenger = require(path.resolve(__dirname, '../messenger')),
renderer = require(path.resolve(__dirname, './asciidoc.js')).get(),
formats = require(path.resolve(__dirname, '../formats')),
source = '',
shell = require('shell'),
formatter = null,
subscriptions = [],
_fileInfo,
_buildFlags = [];
var detectRenderer = function (fileInfo) {
var rendererPath, currentFormatter;
currentFormatter = formats.getByFileExtension(fileInfo.ext);
if (formatter === null || currentFormatter.name !== formatter.name) {
formatter = currentFormatter;
rendererPath = path.resolve(__dirname, './' + formatter.name.toLowerCase());
renderer = require(rendererPath).get();
messenger.publish.file('formatChanged', formatter);
}
};
var handlers = {
opened: function(fileInfo){
refreshSubscriptions();
$result.animate({
scrollTop: $result.offset().top
}, 10);
},
sourceChanged: function(fileInfo){
handlers.contentChanged(fileInfo);
},
contentChanged: function (fileInfo) {
if (isEnabled && $result) {
_fileInfo = fileInfo;
if (!_.isUndefined(_fileInfo)) {
if (_fileInfo.isBlank) {
$result.html('');
} else {
if(_fileInfo.contents.length > 0){
var flags = '';
detectRenderer(_fileInfo);
source = _fileInfo.contents;
_buildFlags.forEach(function (buildFlag) {
flags += ':' + buildFlag + ':\n'
});
source = flags + source;
if(!$renderingLabel.is(':visible')){
$renderingLabel.fadeIn('fast');
}
renderer(source, function (e) {
$result.html(e.html);
if($renderingLabel.is(':visible')){
$renderingLabel.fadeOut('fast');
}
});
}
}
}
}
},
clearBuildFlags: function (params) {
_buildFlags = [];
},
buildFlags: function (buildFlags) {
_buildFlags = buildFlags;
handlers.contentChanged(_fileInfo);
},
showResults: function() {
subscribe();
$resultsPane.css('visibility', 'visible');
$resultsButton
.removeClass('fa-chevron-left')
.addClass('fa-chevron-right')
.one('click', handlers.hideResults);
messenger.publish.layout('showResults');
},
hideResults: function () {
unsubscribe();
$resultsPane.css('visibility', 'hidden');
$resultsButton
.removeClass('fa-chevron-right')
.addClass('fa-chevron-left')
.one('click', handlers.showResults);
messenger.publish.layout('hideResults');
},
fileSelected: function(){
refreshSubscriptions();
_buildFlags = [];
},
allFilesClosed: function () {
$result.html('');
$renderingLabel.fadeOut('fast');
}
};
var subscribe = function () {
isEnabled = true;
subscriptions.push(messenger.subscribe.file('new', handlers.opened));
subscriptions.push(messenger.subscribe.file('opened', handlers.opened));
subscriptions.push(messenger.subscribe.file('contentChanged', handlers.contentChanged));
subscriptions.push(messenger.subscribe.file('sourceChange', handlers.sourceChanged));
subscriptions.push(messenger.subscribe.file('allFilesClosed', handlers.allFilesClosed));
subscriptions.push(messenger.subscribe.format('buildFlags', handlers.buildFlags));
subscriptions.push(messenger.subscribe.metadata('buildFlags.clear', handlers.clearBuildFlags));
};
var unsubscribe = function () {
isEnabled = false;
subscriptions.forEach(function (subscription) {
messenger.unsubscribe(subscription);
});
subscriptions = [];
};
var refreshSubscriptions = function(){
unsubscribe();
subscribe();
};
subscribe();
messenger.subscribe.file('selected', handlers.fileSelected);
messenger.subscribe.file('rerender', function (data, envelope) {
renderer(source, function (e) {
$result.html(e.html);
});
});
var openExternalLinksInBrowser = function (e) {
var href;
var element = e.target;
if (element.nodeName === 'A') {
href = element.getAttribute('href');
shell.openExternal(href);
e.preventDefault();
}
};
document.addEventListener('click', openExternalLinksInBrowser, false);
var setHeight = function (offSetValue) {
$resultsPane.css('height', $window.height() - offSetValue + 'px');
$window.on('resize', function (e) {
$resultsPane.css('height', $window.height() - offSetValue + 'px');
});
};
$(function () {
$result = $('#result');
$resultContainer = $('#result-container'); | $resultsButton = $('#result-button');
$renderingLabel = $('#rendering-label');
$resultsPane
.css('left', appSettings.split())
.css('width', appSettings.resultsWidth());
$resultsButton.one('click', handlers.hideResults);
setHeight(appSettings.editingContainerOffset());
}); | $resultsPane = $('#result-pane'); | random_line_split |
no_0977_squares_of_a_sorted_array.rs | struct Solution;
impl Solution {
// 官方题解中的思路
pub fn sorted_squares(a: Vec<i32>) -> Vec<i32> {
let mut ans = vec![0; a.len()];
if a.is_empty() {
return ans;
}
// 这个减少了一半的时间。
if a[0] >= 0 {
return a.into_iter().map(|v| v * v).collect();
}
let (mut l, mut r) = (0, a.len() - 1);
// 选择 l 和 r 中较大的那个,逆序放入 ans 中。
for pos in (0..a.len()).rev() {
if a[l].abs() > a[r].abs() {
ans[pos] = a[l].pow(2);
l += 1;
} else {
ans[pos] = a[r].pow(2);
if r == 0 {
break;
}
r -= 1; | pub fn sorted_squares1(a: Vec<i32>) -> Vec<i32> {
if a.is_empty() {
return Vec::new();
}
if a[0] >= 0 {
return a.into_iter().map(|v| v * v).collect();
}
let n = a.len();
// 第一个 >= 0 的索引,或者 a.len()
let r = a.iter().position(|&v| v >= 0);
let mut r = r.unwrap_or(n);
let mut l = r as isize - 1;
let mut ans = Vec::with_capacity(n);
while l >= 0 && r < a.len() {
if a[l as usize].abs() < a[r] {
ans.push(a[l as usize].pow(2));
l -= 1;
} else {
ans.push(a[r].pow(2));
r += 1;
}
}
if l >= 0 {
for i in (0..=l as usize).rev() {
ans.push(a[i].pow(2));
}
}
for i in r..n {
ans.push(a[i].pow(2));
}
ans
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sorted_squares() {
assert_eq!(
Solution::sorted_squares(vec![-4, -1, 0, 3, 10]),
vec![0, 1, 9, 16, 100]
);
assert_eq!(
Solution::sorted_squares(vec![-7, -3, 2, 3, 11]),
vec![4, 9, 9, 49, 121]
);
}
}
|
}
}
ans
}
| conditional_block |
no_0977_squares_of_a_sorted_array.rs | struct Solution;
impl Solution {
// 官方题解中的思路
pub fn sorted_squares(a | Vec<i32> {
let mut ans = vec![0; a.len()];
if a.is_empty() {
return ans;
}
// 这个减少了一半的时间。
if a[0] >= 0 {
return a.into_iter().map(|v| v * v).collect();
}
let (mut l, mut r) = (0, a.len() - 1);
// 选择 l 和 r 中较大的那个,逆序放入 ans 中。
for pos in (0..a.len()).rev() {
if a[l].abs() > a[r].abs() {
ans[pos] = a[l].pow(2);
l += 1;
} else {
ans[pos] = a[r].pow(2);
if r == 0 {
break;
}
r -= 1;
}
}
ans
}
pub fn sorted_squares1(a: Vec<i32>) -> Vec<i32> {
if a.is_empty() {
return Vec::new();
}
if a[0] >= 0 {
return a.into_iter().map(|v| v * v).collect();
}
let n = a.len();
// 第一个 >= 0 的索引,或者 a.len()
let r = a.iter().position(|&v| v >= 0);
let mut r = r.unwrap_or(n);
let mut l = r as isize - 1;
let mut ans = Vec::with_capacity(n);
while l >= 0 && r < a.len() {
if a[l as usize].abs() < a[r] {
ans.push(a[l as usize].pow(2));
l -= 1;
} else {
ans.push(a[r].pow(2));
r += 1;
}
}
if l >= 0 {
for i in (0..=l as usize).rev() {
ans.push(a[i].pow(2));
}
}
for i in r..n {
ans.push(a[i].pow(2));
}
ans
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sorted_squares() {
assert_eq!(
Solution::sorted_squares(vec![-4, -1, 0, 3, 10]),
vec![0, 1, 9, 16, 100]
);
assert_eq!(
Solution::sorted_squares(vec![-7, -3, 2, 3, 11]),
vec![4, 9, 9, 49, 121]
);
}
}
| : Vec<i32>) -> | identifier_name |
no_0977_squares_of_a_sorted_array.rs | struct Solution;
impl Solution {
// 官方题解中的思路
pub fn sorted_squares(a: Vec<i32>) -> Vec<i32> {
let mut ans = vec![0; a.len()];
if a.is_empty() {
return ans;
}
// 这个减少了一半的时间。
if a[0] >= 0 {
return a.into_iter().map(|v| v * v).collect();
}
let (mut l, mut r) = (0, a.len() - 1);
// 选择 l 和 r 中较大的那个,逆序放入 ans 中。
for pos in (0..a.len()).rev() {
if a[l].abs() > a[r].abs() {
ans[pos] = a[l].pow(2);
l += 1;
} else {
ans[pos] = a[r].pow(2);
if r == 0 {
break;
}
r -= 1;
}
}
ans
} | pub fn sorted_squares1(a: Vec<i32>) -> Vec<i32> {
if a.is_empty() {
return Vec::new();
}
if a[0] >= 0 {
return a.into_iter().map(|v| v * v).collect();
}
let n = a.len();
// 第一个 >= 0 的索引,或者 a.len()
let r = a.iter().position(|&v| v >= 0);
let mut r = r.unwrap_or(n);
let mut l = r as isize - 1;
let mut ans = Vec::with_capacity(n);
while l >= 0 && r < a.len() {
if a[l as usize].abs() < a[r] {
ans.push(a[l as usize].pow(2));
l -= 1;
} else {
ans.push(a[r].pow(2));
r += 1;
}
}
if l >= 0 {
for i in (0..=l as usize).rev() {
ans.push(a[i].pow(2));
}
}
for i in r..n {
ans.push(a[i].pow(2));
}
ans
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sorted_squares() {
assert_eq!(
Solution::sorted_squares(vec![-4, -1, 0, 3, 10]),
vec![0, 1, 9, 16, 100]
);
assert_eq!(
Solution::sorted_squares(vec![-7, -3, 2, 3, 11]),
vec![4, 9, 9, 49, 121]
);
}
} | random_line_split |
|
vote.test.js | var expect = require("chai").expect,
proxyquire = require("proxyquire"),
sinon = require("sinon");
var models = {};
var app = sinon.stub();
var auth = { authenticated: sinon.stub() };
var get = app.get = sinon.stub();
var post = app.post = sinon.stub();
var Country = models.Country = sinon.stub();
var Vote = models.Vote = sinon.stub();
var vote = proxyquire("../routes/vote", {
"../models": models,
"./auth": auth
});
describe("routes/vote", function() {
var req = {}, res = {};
var spy = res.render = sinon.spy();
var display, submit;
before(function() {
vote(app);
display = get.args[0][2];
submit = post.args[0][2];
});
beforeEach(function() {
spy.reset();
});
describe("GET voting page", function() {
var countries = [ { id: 1, name: "Narnia" },
{ id: 2, name: "Transylvania" }];
var promise = sinon.stub();
promise.then = sinon.stub();
beforeEach(function() {
Country.findAll = sinon.stub();
Country.findAll.returns(promise);
promise.then.callsArgWith(0, countries);
});
it("should render voting page", function() {
display(req, res);
expect(spy.calledOnce).to.equal(true);
expect(spy.args[0][0]).to.equal("vote");
});
it("should set page title and navbarActive properties", function() {
display(req, res);
var locals = spy.args[0][1];
expect(locals).to.have.property("title").that.equals("Vote");
expect(locals).to.have.property("navbarActive").that.equals("Vote");
});
it("should include countries in the response", function() {
display(req, res);
var locals = spy.args[0][1];
expect(locals).to.have.property("countries").that.deep.equals(countries);
});
it("should order the countries by name", function() {
display(req, res);
var call = Country.findAll.getCall(0);
expect(call.args[0]).to.have.property("order").that.equals("name ASC");
});
});
describe("POST /submit", function() {
var votes = [ { id: 1, score: 12 },
{ id: 2, score: 10 },
{ id: 3, score: 8 } ];
var req = {};
req.body = { data: JSON.stringify(votes) };
res.send = sinon.stub();
res.sendStatus = sinon.stub();
res.status = sinon.stub().returns(res);
var promise = sinon.stub();
promise.then = sinon.stub();
promise.catch = sinon.stub();
Vote.create = sinon.stub().returns(promise);
var user = req.user = {};
user.getGroup = sinon.stub().returns(promise);
var group = {id: 1};
beforeEach(function() {
Vote.create.reset();
Vote.create.returns(promise);
promise.then.reset();
promise.then.onFirstCall().yields([group]).returns(promise);
promise.then.yields();
});
it("should insert all the votes", function() {
submit(req, res);
expect(Vote.create.callCount).to.equal(votes.length);
for (var i = 0; i < Vote.create.callCount; i++) |
});
it("should respond OK if no error thrown", function() {
submit(req, res);
expect(res.sendStatus.calledWith(200)).to.equal(true);
});
it("should respond with an error message if there is an error", function() {
var err = "test error";
promise.then.onSecondCall().yields([err]);
submit(req, res);
expect(res.status.calledWith(500)).to.equal(true);
expect(res.send.calledOnce).to.equal(true);
});
});
});
| {
var call = Vote.create.getCall(i);
expect(call.calledWith(sinon.match({
CountryId: votes[i].id,
score: votes[i].score
})));
} | conditional_block |
vote.test.js | var expect = require("chai").expect,
proxyquire = require("proxyquire"),
sinon = require("sinon");
var models = {};
var app = sinon.stub();
var auth = { authenticated: sinon.stub() };
var get = app.get = sinon.stub();
var post = app.post = sinon.stub();
var Country = models.Country = sinon.stub();
var Vote = models.Vote = sinon.stub();
var vote = proxyquire("../routes/vote", {
"../models": models,
"./auth": auth
});
describe("routes/vote", function() {
var req = {}, res = {};
var spy = res.render = sinon.spy();
var display, submit;
before(function() {
vote(app);
display = get.args[0][2];
submit = post.args[0][2];
});
beforeEach(function() {
spy.reset();
});
describe("GET voting page", function() {
var countries = [ { id: 1, name: "Narnia" },
{ id: 2, name: "Transylvania" }];
var promise = sinon.stub();
promise.then = sinon.stub();
beforeEach(function() {
Country.findAll = sinon.stub();
Country.findAll.returns(promise);
promise.then.callsArgWith(0, countries);
});
it("should render voting page", function() {
display(req, res);
expect(spy.calledOnce).to.equal(true);
expect(spy.args[0][0]).to.equal("vote");
});
it("should set page title and navbarActive properties", function() {
display(req, res);
var locals = spy.args[0][1];
expect(locals).to.have.property("title").that.equals("Vote");
expect(locals).to.have.property("navbarActive").that.equals("Vote");
});
it("should include countries in the response", function() {
display(req, res);
var locals = spy.args[0][1];
expect(locals).to.have.property("countries").that.deep.equals(countries);
});
it("should order the countries by name", function() {
display(req, res);
var call = Country.findAll.getCall(0);
expect(call.args[0]).to.have.property("order").that.equals("name ASC");
});
});
describe("POST /submit", function() {
var votes = [ { id: 1, score: 12 },
{ id: 2, score: 10 },
{ id: 3, score: 8 } ];
var req = {};
req.body = { data: JSON.stringify(votes) };
res.send = sinon.stub();
res.sendStatus = sinon.stub();
res.status = sinon.stub().returns(res);
var promise = sinon.stub();
promise.then = sinon.stub();
promise.catch = sinon.stub();
Vote.create = sinon.stub().returns(promise);
var user = req.user = {};
user.getGroup = sinon.stub().returns(promise);
var group = {id: 1};
beforeEach(function() {
Vote.create.reset();
Vote.create.returns(promise);
promise.then.reset();
promise.then.onFirstCall().yields([group]).returns(promise);
promise.then.yields();
});
it("should insert all the votes", function() {
submit(req, res);
expect(Vote.create.callCount).to.equal(votes.length);
for (var i = 0; i < Vote.create.callCount; i++) {
var call = Vote.create.getCall(i);
expect(call.calledWith(sinon.match({
CountryId: votes[i].id,
score: votes[i].score
})));
}
});
it("should respond OK if no error thrown", function() {
submit(req, res);
expect(res.sendStatus.calledWith(200)).to.equal(true);
});
|
submit(req, res);
expect(res.status.calledWith(500)).to.equal(true);
expect(res.send.calledOnce).to.equal(true);
});
});
}); | it("should respond with an error message if there is an error", function() {
var err = "test error";
promise.then.onSecondCall().yields([err]); | random_line_split |
__init__.py | metadata = {
"abbreviation": "ex",
"capitol_timezone": "Etc/UTC",
"legislature_name": "Example Legislature",
"lower_chamber_name": "House of Representatives",
"lower_chamber_term": 2,
"lower_chamber_title": "Representative",
"upper_chamber_name": "Senate",
"upper_chamber_term": 6,
"upper_chamber_title": "Senator",
"name": "Example State",
"terms": [
{
"name": "T0",
"sessions": [
"S0"
],
"start_year": 2009,
"end_year": 2010
},
{
"name": "T1",
"sessions": [
"S1", "Special1" | {
"name": "T2",
"sessions": [
"S2", "Special2"
],
"start_year": 2013,
"end_year": 2014
}
],
"session_details": {
"S0": {"start_date": 1250000000.0, "type": "primary",
"display_name": "Session Zero"},
"S1": {"start_date": 1300000000.0, "type": "primary",
"display_name": "Session One"},
"Special1": {"start_date": 1330000000.0, "type": "special",
"display_name": "Special Session One"},
"S2": {"start_date": 1350000000.0, "type": "primary",
"display_name": "Session Two"},
"Special2": {"start_date": 1360000000.0, "type": "special",
"display_name": "Special Session Two"}
}
} | ],
"start_year": 2011,
"end_year": 2012
}, | random_line_split |
logger.rs | //! This module is a trimmed-down copy of rtx_core::util::logger,
//! which is still waiting to get released as a crate...
//! maybe there is a simple logger crate that achieves this exact behavior?
use ansi_term::Colour::{Green, Red, White, Yellow};
use ansi_term::Style;
use chrono::Local;
use log::max_level;
use log::{Level, LevelFilter, Metadata, Record, SetLoggerError};
struct RtxLogger;
static LOGGER: RtxLogger = RtxLogger;
/// Convenient printing to STDERR (with \n)
#[macro_export]
macro_rules! println_stderr(
($($arg:tt)*) => ({
use std::io::Write;
match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
Ok(_) => {},
Err(x) => panic!("Unable to write to stderr: {}", x),
}
})
);
/// Convenient printing to STDERR
#[macro_export]
macro_rules! print_stderr(
($($arg:tt)*) => ({
use std::io::Write;
match write!(&mut ::std::io::stderr(), $($arg)* ) {
Ok(_) => {},
Err(x) => panic!("Unable to write to stderr: {}", x),
}
})
);
impl log::Log for RtxLogger {
fn | (&self, metadata: &Metadata) -> bool {
metadata.level() <= max_level()
}
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
let record_target = record.target();
let details = record.args();
let category_object = if record_target.is_empty() {
"" // "unknown:unknown" ???
} else {
record_target
};
// Following the reporting syntax at: http://dlmf.nist.gov/LaTeXML/manual/errorcodes/
// let severity = if category_object.starts_with("Fatal:") {
// ""
// } else {
// match record.level() {
// Level::Info => "Info",
// Level::Warn => "Warn",
// Level::Error => "Error",
// Level::Debug => "Debug",
// Level::Trace => "Trace",
// }
// };
let message = format!("{}\t", category_object);
let painted_message = match record.level() {
Level::Info => Green.paint(message),
Level::Warn => Yellow.paint(message),
Level::Error => Red.paint(message),
Level::Debug => Style::default().paint(message),
_ => White.paint(message),
}
.to_string()
+ &details.to_string();
println_stderr!(
"\r[{}] {}",
Local::now().format("%Y-%m-%d %H:%M:%S"),
painted_message
);
}
}
fn flush(&self) {}
}
/// Initialize the logger with an appropriate level of verbosity
pub fn init(level: LevelFilter) -> Result<(), SetLoggerError> {
log::set_logger(&LOGGER).unwrap();
log::set_max_level(level);
Ok(())
}
| enabled | identifier_name |
logger.rs | //! This module is a trimmed-down copy of rtx_core::util::logger,
//! which is still waiting to get released as a crate...
//! maybe there is a simple logger crate that achieves this exact behavior?
use ansi_term::Colour::{Green, Red, White, Yellow};
use ansi_term::Style;
use chrono::Local;
use log::max_level;
use log::{Level, LevelFilter, Metadata, Record, SetLoggerError};
struct RtxLogger;
static LOGGER: RtxLogger = RtxLogger;
/// Convenient printing to STDERR (with \n)
#[macro_export]
macro_rules! println_stderr(
($($arg:tt)*) => ({
use std::io::Write;
match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
Ok(_) => {},
Err(x) => panic!("Unable to write to stderr: {}", x),
}
})
);
/// Convenient printing to STDERR
#[macro_export]
macro_rules! print_stderr(
($($arg:tt)*) => ({
use std::io::Write;
match write!(&mut ::std::io::stderr(), $($arg)* ) {
Ok(_) => {},
Err(x) => panic!("Unable to write to stderr: {}", x),
}
})
);
impl log::Log for RtxLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= max_level()
}
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
let record_target = record.target();
let details = record.args();
let category_object = if record_target.is_empty() {
"" // "unknown:unknown" ???
} else {
record_target
};
// Following the reporting syntax at: http://dlmf.nist.gov/LaTeXML/manual/errorcodes/
// let severity = if category_object.starts_with("Fatal:") {
// ""
// } else {
// match record.level() {
// Level::Info => "Info",
// Level::Warn => "Warn",
// Level::Error => "Error",
// Level::Debug => "Debug",
// Level::Trace => "Trace",
// }
// };
let message = format!("{}\t", category_object); |
let painted_message = match record.level() {
Level::Info => Green.paint(message),
Level::Warn => Yellow.paint(message),
Level::Error => Red.paint(message),
Level::Debug => Style::default().paint(message),
_ => White.paint(message),
}
.to_string()
+ &details.to_string();
println_stderr!(
"\r[{}] {}",
Local::now().format("%Y-%m-%d %H:%M:%S"),
painted_message
);
}
}
fn flush(&self) {}
}
/// Initialize the logger with an appropriate level of verbosity
pub fn init(level: LevelFilter) -> Result<(), SetLoggerError> {
log::set_logger(&LOGGER).unwrap();
log::set_max_level(level);
Ok(())
} | random_line_split |
|
logger.rs | //! This module is a trimmed-down copy of rtx_core::util::logger,
//! which is still waiting to get released as a crate...
//! maybe there is a simple logger crate that achieves this exact behavior?
use ansi_term::Colour::{Green, Red, White, Yellow};
use ansi_term::Style;
use chrono::Local;
use log::max_level;
use log::{Level, LevelFilter, Metadata, Record, SetLoggerError};
struct RtxLogger;
static LOGGER: RtxLogger = RtxLogger;
/// Convenient printing to STDERR (with \n)
#[macro_export]
macro_rules! println_stderr(
($($arg:tt)*) => ({
use std::io::Write;
match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
Ok(_) => {},
Err(x) => panic!("Unable to write to stderr: {}", x),
}
})
);
/// Convenient printing to STDERR
#[macro_export]
macro_rules! print_stderr(
($($arg:tt)*) => ({
use std::io::Write;
match write!(&mut ::std::io::stderr(), $($arg)* ) {
Ok(_) => {},
Err(x) => panic!("Unable to write to stderr: {}", x),
}
})
);
impl log::Log for RtxLogger {
fn enabled(&self, metadata: &Metadata) -> bool |
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
let record_target = record.target();
let details = record.args();
let category_object = if record_target.is_empty() {
"" // "unknown:unknown" ???
} else {
record_target
};
// Following the reporting syntax at: http://dlmf.nist.gov/LaTeXML/manual/errorcodes/
// let severity = if category_object.starts_with("Fatal:") {
// ""
// } else {
// match record.level() {
// Level::Info => "Info",
// Level::Warn => "Warn",
// Level::Error => "Error",
// Level::Debug => "Debug",
// Level::Trace => "Trace",
// }
// };
let message = format!("{}\t", category_object);
let painted_message = match record.level() {
Level::Info => Green.paint(message),
Level::Warn => Yellow.paint(message),
Level::Error => Red.paint(message),
Level::Debug => Style::default().paint(message),
_ => White.paint(message),
}
.to_string()
+ &details.to_string();
println_stderr!(
"\r[{}] {}",
Local::now().format("%Y-%m-%d %H:%M:%S"),
painted_message
);
}
}
fn flush(&self) {}
}
/// Initialize the logger with an appropriate level of verbosity
pub fn init(level: LevelFilter) -> Result<(), SetLoggerError> {
log::set_logger(&LOGGER).unwrap();
log::set_max_level(level);
Ok(())
}
| {
metadata.level() <= max_level()
} | identifier_body |
modesGlyphHover.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 EditorBrowser = require('vs/editor/browser/editorBrowser');
import EditorCommon = require('vs/editor/common/editorCommon');
import HoverOperation = require('./hoverOperation');
import HoverWidget = require('./hoverWidgets');
export interface IHoverMessage {
value?: string;
range?: EditorCommon.IRange;
className?: string;
}
class MarginComputer implements HoverOperation.IHoverComputer<IHoverMessage[]> {
private _editor: EditorBrowser.ICodeEditor;
private _lineNumber: number;
private _result: IHoverMessage[];
constructor(editor:EditorBrowser.ICodeEditor) {
this._editor = editor;
this._lineNumber = -1;
}
public setLineNumber(lineNumber: number): void {
this._lineNumber = lineNumber;
this._result = [];
}
public clearResult(): void {
this._result = [];
}
public computeSync(): IHoverMessage[] {
var result: IHoverMessage[] = [],
lineDecorations = this._editor.getLineDecorations(this._lineNumber),
i: number,
len: number,
d: EditorCommon.IModelDecoration;
for (i = 0, len = lineDecorations.length; i < len; i++) {
d = lineDecorations[i];
if (d.options.glyphMarginClassName && d.options.hoverMessage) {
result.push({
value: d.options.hoverMessage
});
}
}
return result;
}
public onResult(result: IHoverMessage[], isFromSynchronousComputation: boolean): void {
this._result = this._result.concat(result);
}
public getResult(): IHoverMessage[] {
return this._result;
}
public getResultWithLoadingMessage(): IHoverMessage[] {
return this.getResult();
}
}
export class ModesGlyphHoverWidget extends HoverWidget.GlyphHoverWidget {
static ID = 'editor.contrib.modesGlyphHoverWidget';
private _messages: IHoverMessage[];
private _lastLineNumber: number;
private _computer: MarginComputer;
private _hoverOperation: HoverOperation.HoverOperation<IHoverMessage[]>;
constructor(editor: EditorBrowser.ICodeEditor) {
super(ModesGlyphHoverWidget.ID, editor);
this._lastLineNumber = -1;
this._computer = new MarginComputer(this._editor);
this._hoverOperation = new HoverOperation.HoverOperation(
this._computer,
(result:IHoverMessage[]) => this._withResult(result),
null,
(result:any) => this._withResult(result)
);
}
public onModelDecorationsChanged(): void {
if (this._isVisible) {
// The decorations have changed and the hover is visible,
// we need to recompute the displayed text
this._hoverOperation.cancel();
this._computer.clearResult();
this._hoverOperation.start();
}
}
public startShowingAt(lineNumber: number): void {
if (this._lastLineNumber === lineNumber) {
// We have to show the widget at the exact same line number as before, so no work is needed
return;
}
this._hoverOperation.cancel();
this.hide();
this._lastLineNumber = lineNumber;
this._computer.setLineNumber(lineNumber);
this._hoverOperation.start();
}
public hide(): void {
this._lastLineNumber = -1;
this._hoverOperation.cancel();
super.hide();
}
public _withResult(result:IHoverMessage[]): void {
this._messages = result;
if (this._messages.length > 0) {
this._renderMessages(this._lastLineNumber, this._messages);
} else {
this.hide();
}
}
private | (lineNumber: number, messages: IHoverMessage[]): void {
var fragment = document.createDocumentFragment();
messages.forEach((msg) => {
var row:HTMLElement = document.createElement('div');
var span:HTMLElement = null;
if (msg.className) {
span = document.createElement('span');
span.textContent = msg.value;
span.className = msg.className;
row.appendChild(span);
} else {
row.textContent = msg.value;
}
fragment.appendChild(row);
});
this._domNode.textContent = '';
this._domNode.appendChild(fragment);
// show
this.showAt(lineNumber);
}
} | _renderMessages | identifier_name |
modesGlyphHover.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 EditorBrowser = require('vs/editor/browser/editorBrowser');
import EditorCommon = require('vs/editor/common/editorCommon');
import HoverOperation = require('./hoverOperation');
import HoverWidget = require('./hoverWidgets');
export interface IHoverMessage {
value?: string;
range?: EditorCommon.IRange;
className?: string;
}
class MarginComputer implements HoverOperation.IHoverComputer<IHoverMessage[]> {
private _editor: EditorBrowser.ICodeEditor;
private _lineNumber: number;
private _result: IHoverMessage[];
constructor(editor:EditorBrowser.ICodeEditor) {
this._editor = editor;
this._lineNumber = -1;
}
public setLineNumber(lineNumber: number): void {
this._lineNumber = lineNumber;
this._result = [];
}
public clearResult(): void {
this._result = [];
}
public computeSync(): IHoverMessage[] {
var result: IHoverMessage[] = [],
lineDecorations = this._editor.getLineDecorations(this._lineNumber),
i: number,
len: number,
d: EditorCommon.IModelDecoration;
for (i = 0, len = lineDecorations.length; i < len; i++) {
d = lineDecorations[i];
if (d.options.glyphMarginClassName && d.options.hoverMessage) {
result.push({
value: d.options.hoverMessage
});
}
}
return result;
}
public onResult(result: IHoverMessage[], isFromSynchronousComputation: boolean): void {
this._result = this._result.concat(result);
}
public getResult(): IHoverMessage[] {
return this._result;
}
public getResultWithLoadingMessage(): IHoverMessage[] {
return this.getResult();
}
}
export class ModesGlyphHoverWidget extends HoverWidget.GlyphHoverWidget {
static ID = 'editor.contrib.modesGlyphHoverWidget';
private _messages: IHoverMessage[];
private _lastLineNumber: number;
private _computer: MarginComputer;
private _hoverOperation: HoverOperation.HoverOperation<IHoverMessage[]>;
constructor(editor: EditorBrowser.ICodeEditor) {
super(ModesGlyphHoverWidget.ID, editor);
this._lastLineNumber = -1;
this._computer = new MarginComputer(this._editor);
this._hoverOperation = new HoverOperation.HoverOperation(
this._computer,
(result:IHoverMessage[]) => this._withResult(result),
null,
(result:any) => this._withResult(result)
);
}
public onModelDecorationsChanged(): void {
if (this._isVisible) {
// The decorations have changed and the hover is visible,
// we need to recompute the displayed text
this._hoverOperation.cancel();
this._computer.clearResult();
this._hoverOperation.start();
}
}
public startShowingAt(lineNumber: number): void {
if (this._lastLineNumber === lineNumber) {
// We have to show the widget at the exact same line number as before, so no work is needed
return;
}
this._hoverOperation.cancel();
this.hide();
this._lastLineNumber = lineNumber;
this._computer.setLineNumber(lineNumber);
this._hoverOperation.start();
}
public hide(): void {
this._lastLineNumber = -1;
this._hoverOperation.cancel();
super.hide();
}
public _withResult(result:IHoverMessage[]): void {
this._messages = result;
if (this._messages.length > 0) {
this._renderMessages(this._lastLineNumber, this._messages);
} else {
this.hide();
}
}
private _renderMessages(lineNumber: number, messages: IHoverMessage[]): void {
var fragment = document.createDocumentFragment();
messages.forEach((msg) => {
var row:HTMLElement = document.createElement('div');
var span:HTMLElement = null;
if (msg.className) {
span = document.createElement('span');
span.textContent = msg.value;
span.className = msg.className;
row.appendChild(span);
} else |
fragment.appendChild(row);
});
this._domNode.textContent = '';
this._domNode.appendChild(fragment);
// show
this.showAt(lineNumber);
}
} | {
row.textContent = msg.value;
} | conditional_block |
modesGlyphHover.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 EditorBrowser = require('vs/editor/browser/editorBrowser');
import EditorCommon = require('vs/editor/common/editorCommon');
import HoverOperation = require('./hoverOperation');
import HoverWidget = require('./hoverWidgets');
export interface IHoverMessage {
value?: string;
range?: EditorCommon.IRange;
className?: string;
}
class MarginComputer implements HoverOperation.IHoverComputer<IHoverMessage[]> {
private _editor: EditorBrowser.ICodeEditor;
private _lineNumber: number;
private _result: IHoverMessage[];
constructor(editor:EditorBrowser.ICodeEditor) {
this._editor = editor;
this._lineNumber = -1;
}
| public setLineNumber(lineNumber: number): void {
this._lineNumber = lineNumber;
this._result = [];
}
public clearResult(): void {
this._result = [];
}
public computeSync(): IHoverMessage[] {
var result: IHoverMessage[] = [],
lineDecorations = this._editor.getLineDecorations(this._lineNumber),
i: number,
len: number,
d: EditorCommon.IModelDecoration;
for (i = 0, len = lineDecorations.length; i < len; i++) {
d = lineDecorations[i];
if (d.options.glyphMarginClassName && d.options.hoverMessage) {
result.push({
value: d.options.hoverMessage
});
}
}
return result;
}
public onResult(result: IHoverMessage[], isFromSynchronousComputation: boolean): void {
this._result = this._result.concat(result);
}
public getResult(): IHoverMessage[] {
return this._result;
}
public getResultWithLoadingMessage(): IHoverMessage[] {
return this.getResult();
}
}
export class ModesGlyphHoverWidget extends HoverWidget.GlyphHoverWidget {
static ID = 'editor.contrib.modesGlyphHoverWidget';
private _messages: IHoverMessage[];
private _lastLineNumber: number;
private _computer: MarginComputer;
private _hoverOperation: HoverOperation.HoverOperation<IHoverMessage[]>;
constructor(editor: EditorBrowser.ICodeEditor) {
super(ModesGlyphHoverWidget.ID, editor);
this._lastLineNumber = -1;
this._computer = new MarginComputer(this._editor);
this._hoverOperation = new HoverOperation.HoverOperation(
this._computer,
(result:IHoverMessage[]) => this._withResult(result),
null,
(result:any) => this._withResult(result)
);
}
public onModelDecorationsChanged(): void {
if (this._isVisible) {
// The decorations have changed and the hover is visible,
// we need to recompute the displayed text
this._hoverOperation.cancel();
this._computer.clearResult();
this._hoverOperation.start();
}
}
public startShowingAt(lineNumber: number): void {
if (this._lastLineNumber === lineNumber) {
// We have to show the widget at the exact same line number as before, so no work is needed
return;
}
this._hoverOperation.cancel();
this.hide();
this._lastLineNumber = lineNumber;
this._computer.setLineNumber(lineNumber);
this._hoverOperation.start();
}
public hide(): void {
this._lastLineNumber = -1;
this._hoverOperation.cancel();
super.hide();
}
public _withResult(result:IHoverMessage[]): void {
this._messages = result;
if (this._messages.length > 0) {
this._renderMessages(this._lastLineNumber, this._messages);
} else {
this.hide();
}
}
private _renderMessages(lineNumber: number, messages: IHoverMessage[]): void {
var fragment = document.createDocumentFragment();
messages.forEach((msg) => {
var row:HTMLElement = document.createElement('div');
var span:HTMLElement = null;
if (msg.className) {
span = document.createElement('span');
span.textContent = msg.value;
span.className = msg.className;
row.appendChild(span);
} else {
row.textContent = msg.value;
}
fragment.appendChild(row);
});
this._domNode.textContent = '';
this._domNode.appendChild(fragment);
// show
this.showAt(lineNumber);
}
} | random_line_split |
|
mnist_ebgan_generate.py | import sugartensor as tf
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from model import *
__author__ = '[email protected]'
# set log level to debug
tf.sg_verbosity(10)
#
# hyper parameters
#
batch_size = 100
# random uniform seed
z = tf.random_uniform((batch_size, z_dim))
# generator
gen = generator(z)
#
# draw samples
#
with tf.Session() as sess:
tf.sg_init(sess)
# restore parameters
tf.sg_restore(sess, tf.train.latest_checkpoint('asset/train'), category='generator')
# run generator
imgs = sess.run(gen.sg_squeeze())
# plot result
_, ax = plt.subplots(10, 10, sharex=True, sharey=True)
for i in range(10): | plt.savefig('asset/train/sample.png', dpi=600)
tf.sg_info('Sample image saved to "asset/train/sample.png"')
plt.close() | for j in range(10):
ax[i][j].imshow(imgs[i * 10 + j], 'gray')
ax[i][j].set_axis_off() | random_line_split |
mnist_ebgan_generate.py | import sugartensor as tf
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from model import *
__author__ = '[email protected]'
# set log level to debug
tf.sg_verbosity(10)
#
# hyper parameters
#
batch_size = 100
# random uniform seed
z = tf.random_uniform((batch_size, z_dim))
# generator
gen = generator(z)
#
# draw samples
#
with tf.Session() as sess:
tf.sg_init(sess)
# restore parameters
tf.sg_restore(sess, tf.train.latest_checkpoint('asset/train'), category='generator')
# run generator
imgs = sess.run(gen.sg_squeeze())
# plot result
_, ax = plt.subplots(10, 10, sharex=True, sharey=True)
for i in range(10):
|
plt.savefig('asset/train/sample.png', dpi=600)
tf.sg_info('Sample image saved to "asset/train/sample.png"')
plt.close()
| for j in range(10):
ax[i][j].imshow(imgs[i * 10 + j], 'gray')
ax[i][j].set_axis_off() | conditional_block |
SPRITE_OVERLAP.py | # !/usr/bin/env python
"""Testing a sprite.
The ball should bounce off the sides of the window. You may resize the
window.
This test should just run without failing.
"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import unittest
from pyglet.gl import glClear
import pyglet.window
import pyglet.window.event
from pyglet import clock
from scene2d import Sprite, Image2d, FlatView
from scene2d.image import TintEffect
from scene2d.camera import FlatCamera
ball_png = os.path.join(os.path.dirname(__file__), 'ball.png')
class BouncySprite(Sprite):
|
class SpriteOverlapTest(unittest.TestCase):
def test_sprite(self):
w = pyglet.window.Window(width=320, height=320)
image = Image2d.load(ball_png)
ball1 = BouncySprite(0, 0, 64, 64, image, properties=dict(dx=10, dy=5))
ball2 = BouncySprite(288, 0, 64, 64, image,
properties=dict(dx=-10, dy=5))
view = FlatView(0, 0, 320, 320, sprites=[ball1, ball2])
view.fx, view.fy = 160, 160
clock.set_fps_limit(60)
e = TintEffect((.5, 1, .5, 1))
while not w.has_exit:
clock.tick()
w.dispatch_events()
ball1.update()
ball2.update()
if ball1.overlaps(ball2):
if 'overlap' not in ball2.properties:
ball2.properties['overlap'] = e
ball2.add_effect(e)
elif 'overlap' in ball2.properties:
ball2.remove_effect(e)
del ball2.properties['overlap']
view.clear()
view.draw()
w.flip()
w.close()
unittest.main()
| def update(self):
# move, check bounds
p = self.properties
self.x += p['dx']
self.y += p['dy']
if self.left < 0:
self.left = 0
p['dx'] = -p['dx']
elif self.right > 320:
self.right = 320
p['dx'] = -p['dx']
if self.bottom < 0:
self.bottom = 0
p['dy'] = -p['dy']
elif self.top > 320:
self.top = 320
p['dy'] = -p['dy'] | identifier_body |
SPRITE_OVERLAP.py | # !/usr/bin/env python
"""Testing a sprite.
The ball should bounce off the sides of the window. You may resize the
window.
This test should just run without failing.
"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import unittest
from pyglet.gl import glClear
import pyglet.window
import pyglet.window.event
from pyglet import clock
from scene2d import Sprite, Image2d, FlatView
from scene2d.image import TintEffect
from scene2d.camera import FlatCamera
ball_png = os.path.join(os.path.dirname(__file__), 'ball.png')
class BouncySprite(Sprite):
def update(self):
# move, check bounds
p = self.properties
self.x += p['dx']
self.y += p['dy']
if self.left < 0:
self.left = 0
p['dx'] = -p['dx']
elif self.right > 320:
self.right = 320
p['dx'] = -p['dx']
if self.bottom < 0:
|
elif self.top > 320:
self.top = 320
p['dy'] = -p['dy']
class SpriteOverlapTest(unittest.TestCase):
def test_sprite(self):
w = pyglet.window.Window(width=320, height=320)
image = Image2d.load(ball_png)
ball1 = BouncySprite(0, 0, 64, 64, image, properties=dict(dx=10, dy=5))
ball2 = BouncySprite(288, 0, 64, 64, image,
properties=dict(dx=-10, dy=5))
view = FlatView(0, 0, 320, 320, sprites=[ball1, ball2])
view.fx, view.fy = 160, 160
clock.set_fps_limit(60)
e = TintEffect((.5, 1, .5, 1))
while not w.has_exit:
clock.tick()
w.dispatch_events()
ball1.update()
ball2.update()
if ball1.overlaps(ball2):
if 'overlap' not in ball2.properties:
ball2.properties['overlap'] = e
ball2.add_effect(e)
elif 'overlap' in ball2.properties:
ball2.remove_effect(e)
del ball2.properties['overlap']
view.clear()
view.draw()
w.flip()
w.close()
unittest.main()
| self.bottom = 0
p['dy'] = -p['dy'] | conditional_block |
SPRITE_OVERLAP.py | # !/usr/bin/env python
"""Testing a sprite.
The ball should bounce off the sides of the window. You may resize the
window.
This test should just run without failing.
"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import unittest
from pyglet.gl import glClear
import pyglet.window
import pyglet.window.event
from pyglet import clock
from scene2d import Sprite, Image2d, FlatView
from scene2d.image import TintEffect
from scene2d.camera import FlatCamera
ball_png = os.path.join(os.path.dirname(__file__), 'ball.png')
class BouncySprite(Sprite):
def update(self):
# move, check bounds
p = self.properties
self.x += p['dx'] | if self.left < 0:
self.left = 0
p['dx'] = -p['dx']
elif self.right > 320:
self.right = 320
p['dx'] = -p['dx']
if self.bottom < 0:
self.bottom = 0
p['dy'] = -p['dy']
elif self.top > 320:
self.top = 320
p['dy'] = -p['dy']
class SpriteOverlapTest(unittest.TestCase):
def test_sprite(self):
w = pyglet.window.Window(width=320, height=320)
image = Image2d.load(ball_png)
ball1 = BouncySprite(0, 0, 64, 64, image, properties=dict(dx=10, dy=5))
ball2 = BouncySprite(288, 0, 64, 64, image,
properties=dict(dx=-10, dy=5))
view = FlatView(0, 0, 320, 320, sprites=[ball1, ball2])
view.fx, view.fy = 160, 160
clock.set_fps_limit(60)
e = TintEffect((.5, 1, .5, 1))
while not w.has_exit:
clock.tick()
w.dispatch_events()
ball1.update()
ball2.update()
if ball1.overlaps(ball2):
if 'overlap' not in ball2.properties:
ball2.properties['overlap'] = e
ball2.add_effect(e)
elif 'overlap' in ball2.properties:
ball2.remove_effect(e)
del ball2.properties['overlap']
view.clear()
view.draw()
w.flip()
w.close()
unittest.main() | self.y += p['dy'] | random_line_split |
SPRITE_OVERLAP.py | # !/usr/bin/env python
"""Testing a sprite.
The ball should bounce off the sides of the window. You may resize the
window.
This test should just run without failing.
"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import unittest
from pyglet.gl import glClear
import pyglet.window
import pyglet.window.event
from pyglet import clock
from scene2d import Sprite, Image2d, FlatView
from scene2d.image import TintEffect
from scene2d.camera import FlatCamera
ball_png = os.path.join(os.path.dirname(__file__), 'ball.png')
class | (Sprite):
def update(self):
# move, check bounds
p = self.properties
self.x += p['dx']
self.y += p['dy']
if self.left < 0:
self.left = 0
p['dx'] = -p['dx']
elif self.right > 320:
self.right = 320
p['dx'] = -p['dx']
if self.bottom < 0:
self.bottom = 0
p['dy'] = -p['dy']
elif self.top > 320:
self.top = 320
p['dy'] = -p['dy']
class SpriteOverlapTest(unittest.TestCase):
def test_sprite(self):
w = pyglet.window.Window(width=320, height=320)
image = Image2d.load(ball_png)
ball1 = BouncySprite(0, 0, 64, 64, image, properties=dict(dx=10, dy=5))
ball2 = BouncySprite(288, 0, 64, 64, image,
properties=dict(dx=-10, dy=5))
view = FlatView(0, 0, 320, 320, sprites=[ball1, ball2])
view.fx, view.fy = 160, 160
clock.set_fps_limit(60)
e = TintEffect((.5, 1, .5, 1))
while not w.has_exit:
clock.tick()
w.dispatch_events()
ball1.update()
ball2.update()
if ball1.overlaps(ball2):
if 'overlap' not in ball2.properties:
ball2.properties['overlap'] = e
ball2.add_effect(e)
elif 'overlap' in ball2.properties:
ball2.remove_effect(e)
del ball2.properties['overlap']
view.clear()
view.draw()
w.flip()
w.close()
unittest.main()
| BouncySprite | identifier_name |
equal_tests.py | from python.equal import Equal
def count_steps_test():
equal_instance = Equal()
array_a = [2, 2, 3, 7]
array_b = [53, 361, 188, 665, 786, 898, 447, 562, 272, 123, 229, 629, 670,
848, 994, 54, 822, 46, 208, 17, 449, 302, 466, 832, 931, 778,
156, 39, 31, 777, 749, 436, 138, 289, 453, 276, 539, 901, 839,
811, 24, 420, 440, 46, 269, 786, 101, 443, 832, 661, 460, 281,
964, 278, 465, 247, 408, 622, 638, 440, 751, 739, 876, 889, 380,
330, 517, 919, 583, 356, 83, 959, 129, 875, 5, 750, 662, 106,
193, 494, 120, 653, 128, 84, 283, 593, 683, 44, 567, 321, 484,
318, 412, 712, 559, 792, 394, 77, 711, 977, 785, 146, 936, 914,
22, 942, 664, 36, 400, 857]
array_c = [520, 862, 10, 956, 498, 956, 991, 542, 523, 664, 378, 194, 76,
90, 753, 868, 837, 830, 932, 814, 616, 78, 103, 882, 452, 397,
899, 488, 149, 108, 723, 22, 323, 733, 330, 821, 41, 322, 715,
917, 986, 93, 111, 63, 535, 864, 931, 372, 47, 215, 539, 15, 294,
642, 897, 98, 391, 796, 939, 540, 257, 662, 562, 580, 747, 893,
401, 789, 215, 468, 58, 553, 561, 169, 616, 448, 385, 900, 173,
432, 115, 712]
array_d = [761, 706, 697, 212, 97, 845, 151, 637, 102, 165, 200, 34, 912,
445, 435, 53, 12, 255, 111, 565, 816, 632, 534, 617, 18, 786,
790, 802, 253, 502, 602, 15, 208, 651, 227, 305, 848, 730, 294,
303, 895, 846, 337, 159, 291, 125, 565, 655, 380, 28, 221, 549,
13, 107, 166, 31, 245, 308, 185, 498, 810, 139, 865, 370, 790,
444, 27, 639, 174, 321, 294, 421, 168, 631, 933, 811, 756, 498,
467, 137, 878, 40, 686, 891, 499, 204, 274, 744, 512, 460, 242,
674, 599, 108, 396, 742, 552, 423, 733, 79, 96, 27, 852, 264, | 178, 273, 113, 612, 771, 497, 142, 133, 341, 914, 521, 488, 147,
953, 26, 284, 160, 648, 500, 463, 298, 568, 31, 958, 422, 379,
385, 264, 622, 716, 619, 800, 341, 732, 764, 464, 581, 258, 949,
922, 173, 470, 411, 672, 423, 789, 956, 583, 789, 808, 46, 439,
376, 430, 749, 151]
array_e = [134, 415, 784, 202, 34, 584, 543, 119, 701, 7, 700, 959, 956,
975, 484, 426, 738, 508, 201, 527, 816, 136, 668, 624, 535, 108,
1, 965, 857, 152, 478, 344, 567, 262, 546, 953, 199, 90, 72, 900,
449, 773, 211, 758, 100, 696, 536, 838, 204, 738, 717, 21, 874,
385, 997, 761, 845, 998, 78, 703, 502, 557, 47, 421, 819, 945,
375, 370, 35, 799, 622, 837, 924, 834, 595, 24, 882, 483, 862,
438, 221, 931, 811, 448, 317, 809, 561, 162, 159, 640, 217, 662,
197, 616, 435, 368, 562, 162, 739, 949, 962, 713, 786, 238, 899,
733, 263, 781, 217, 477, 220, 790, 409, 383, 590, 726, 192, 152,
240, 352, 792, 458, 366, 341, 74, 801, 709, 988, 964, 800, 938,
278, 514, 76, 516, 413, 810, 131, 547, 379, 609, 119, 169, 370,
502, 112, 448, 695, 264, 688, 399, 408, 498, 765, 749, 925, 918,
458, 913, 234, 611]
array_f = [512, 125, 928, 381, 890, 90, 512, 789, 469, 473, 908, 990, 195,
763, 102, 643, 458, 366, 684, 857, 126, 534, 974, 875, 459, 892,
686, 373, 127, 297, 576, 991, 774, 856, 372, 664, 946, 237, 806,
767, 62, 714, 758, 258, 477, 860, 253, 287, 579, 289, 496]
assert equal_instance.count_mim_steps(array_a) == 2
assert equal_instance.count_mim_steps(array_b) == 10605
assert equal_instance.count_mim_steps(array_c) == 8198
assert equal_instance.count_mim_steps(array_d) == 18762
assert equal_instance.count_mim_steps(array_e) == 16931
assert equal_instance.count_mim_steps(array_f) == 5104 | 658, 785, 76, 415, 635, 895, 904, 514, 935, 942, 757, 434, 498,
32, 178, 10, 844, 772, 36, 795, 880, 432, 537, 785, 855, 270,
864, 951, 649, 716, 568, 308, 854, 996, 75, 489, 891, 331, 355, | random_line_split |
equal_tests.py | from python.equal import Equal
def | ():
equal_instance = Equal()
array_a = [2, 2, 3, 7]
array_b = [53, 361, 188, 665, 786, 898, 447, 562, 272, 123, 229, 629, 670,
848, 994, 54, 822, 46, 208, 17, 449, 302, 466, 832, 931, 778,
156, 39, 31, 777, 749, 436, 138, 289, 453, 276, 539, 901, 839,
811, 24, 420, 440, 46, 269, 786, 101, 443, 832, 661, 460, 281,
964, 278, 465, 247, 408, 622, 638, 440, 751, 739, 876, 889, 380,
330, 517, 919, 583, 356, 83, 959, 129, 875, 5, 750, 662, 106,
193, 494, 120, 653, 128, 84, 283, 593, 683, 44, 567, 321, 484,
318, 412, 712, 559, 792, 394, 77, 711, 977, 785, 146, 936, 914,
22, 942, 664, 36, 400, 857]
array_c = [520, 862, 10, 956, 498, 956, 991, 542, 523, 664, 378, 194, 76,
90, 753, 868, 837, 830, 932, 814, 616, 78, 103, 882, 452, 397,
899, 488, 149, 108, 723, 22, 323, 733, 330, 821, 41, 322, 715,
917, 986, 93, 111, 63, 535, 864, 931, 372, 47, 215, 539, 15, 294,
642, 897, 98, 391, 796, 939, 540, 257, 662, 562, 580, 747, 893,
401, 789, 215, 468, 58, 553, 561, 169, 616, 448, 385, 900, 173,
432, 115, 712]
array_d = [761, 706, 697, 212, 97, 845, 151, 637, 102, 165, 200, 34, 912,
445, 435, 53, 12, 255, 111, 565, 816, 632, 534, 617, 18, 786,
790, 802, 253, 502, 602, 15, 208, 651, 227, 305, 848, 730, 294,
303, 895, 846, 337, 159, 291, 125, 565, 655, 380, 28, 221, 549,
13, 107, 166, 31, 245, 308, 185, 498, 810, 139, 865, 370, 790,
444, 27, 639, 174, 321, 294, 421, 168, 631, 933, 811, 756, 498,
467, 137, 878, 40, 686, 891, 499, 204, 274, 744, 512, 460, 242,
674, 599, 108, 396, 742, 552, 423, 733, 79, 96, 27, 852, 264,
658, 785, 76, 415, 635, 895, 904, 514, 935, 942, 757, 434, 498,
32, 178, 10, 844, 772, 36, 795, 880, 432, 537, 785, 855, 270,
864, 951, 649, 716, 568, 308, 854, 996, 75, 489, 891, 331, 355,
178, 273, 113, 612, 771, 497, 142, 133, 341, 914, 521, 488, 147,
953, 26, 284, 160, 648, 500, 463, 298, 568, 31, 958, 422, 379,
385, 264, 622, 716, 619, 800, 341, 732, 764, 464, 581, 258, 949,
922, 173, 470, 411, 672, 423, 789, 956, 583, 789, 808, 46, 439,
376, 430, 749, 151]
array_e = [134, 415, 784, 202, 34, 584, 543, 119, 701, 7, 700, 959, 956,
975, 484, 426, 738, 508, 201, 527, 816, 136, 668, 624, 535, 108,
1, 965, 857, 152, 478, 344, 567, 262, 546, 953, 199, 90, 72, 900,
449, 773, 211, 758, 100, 696, 536, 838, 204, 738, 717, 21, 874,
385, 997, 761, 845, 998, 78, 703, 502, 557, 47, 421, 819, 945,
375, 370, 35, 799, 622, 837, 924, 834, 595, 24, 882, 483, 862,
438, 221, 931, 811, 448, 317, 809, 561, 162, 159, 640, 217, 662,
197, 616, 435, 368, 562, 162, 739, 949, 962, 713, 786, 238, 899,
733, 263, 781, 217, 477, 220, 790, 409, 383, 590, 726, 192, 152,
240, 352, 792, 458, 366, 341, 74, 801, 709, 988, 964, 800, 938,
278, 514, 76, 516, 413, 810, 131, 547, 379, 609, 119, 169, 370,
502, 112, 448, 695, 264, 688, 399, 408, 498, 765, 749, 925, 918,
458, 913, 234, 611]
array_f = [512, 125, 928, 381, 890, 90, 512, 789, 469, 473, 908, 990, 195,
763, 102, 643, 458, 366, 684, 857, 126, 534, 974, 875, 459, 892,
686, 373, 127, 297, 576, 991, 774, 856, 372, 664, 946, 237, 806,
767, 62, 714, 758, 258, 477, 860, 253, 287, 579, 289, 496]
assert equal_instance.count_mim_steps(array_a) == 2
assert equal_instance.count_mim_steps(array_b) == 10605
assert equal_instance.count_mim_steps(array_c) == 8198
assert equal_instance.count_mim_steps(array_d) == 18762
assert equal_instance.count_mim_steps(array_e) == 16931
assert equal_instance.count_mim_steps(array_f) == 5104
| count_steps_test | identifier_name |
equal_tests.py | from python.equal import Equal
def count_steps_test():
| equal_instance = Equal()
array_a = [2, 2, 3, 7]
array_b = [53, 361, 188, 665, 786, 898, 447, 562, 272, 123, 229, 629, 670,
848, 994, 54, 822, 46, 208, 17, 449, 302, 466, 832, 931, 778,
156, 39, 31, 777, 749, 436, 138, 289, 453, 276, 539, 901, 839,
811, 24, 420, 440, 46, 269, 786, 101, 443, 832, 661, 460, 281,
964, 278, 465, 247, 408, 622, 638, 440, 751, 739, 876, 889, 380,
330, 517, 919, 583, 356, 83, 959, 129, 875, 5, 750, 662, 106,
193, 494, 120, 653, 128, 84, 283, 593, 683, 44, 567, 321, 484,
318, 412, 712, 559, 792, 394, 77, 711, 977, 785, 146, 936, 914,
22, 942, 664, 36, 400, 857]
array_c = [520, 862, 10, 956, 498, 956, 991, 542, 523, 664, 378, 194, 76,
90, 753, 868, 837, 830, 932, 814, 616, 78, 103, 882, 452, 397,
899, 488, 149, 108, 723, 22, 323, 733, 330, 821, 41, 322, 715,
917, 986, 93, 111, 63, 535, 864, 931, 372, 47, 215, 539, 15, 294,
642, 897, 98, 391, 796, 939, 540, 257, 662, 562, 580, 747, 893,
401, 789, 215, 468, 58, 553, 561, 169, 616, 448, 385, 900, 173,
432, 115, 712]
array_d = [761, 706, 697, 212, 97, 845, 151, 637, 102, 165, 200, 34, 912,
445, 435, 53, 12, 255, 111, 565, 816, 632, 534, 617, 18, 786,
790, 802, 253, 502, 602, 15, 208, 651, 227, 305, 848, 730, 294,
303, 895, 846, 337, 159, 291, 125, 565, 655, 380, 28, 221, 549,
13, 107, 166, 31, 245, 308, 185, 498, 810, 139, 865, 370, 790,
444, 27, 639, 174, 321, 294, 421, 168, 631, 933, 811, 756, 498,
467, 137, 878, 40, 686, 891, 499, 204, 274, 744, 512, 460, 242,
674, 599, 108, 396, 742, 552, 423, 733, 79, 96, 27, 852, 264,
658, 785, 76, 415, 635, 895, 904, 514, 935, 942, 757, 434, 498,
32, 178, 10, 844, 772, 36, 795, 880, 432, 537, 785, 855, 270,
864, 951, 649, 716, 568, 308, 854, 996, 75, 489, 891, 331, 355,
178, 273, 113, 612, 771, 497, 142, 133, 341, 914, 521, 488, 147,
953, 26, 284, 160, 648, 500, 463, 298, 568, 31, 958, 422, 379,
385, 264, 622, 716, 619, 800, 341, 732, 764, 464, 581, 258, 949,
922, 173, 470, 411, 672, 423, 789, 956, 583, 789, 808, 46, 439,
376, 430, 749, 151]
array_e = [134, 415, 784, 202, 34, 584, 543, 119, 701, 7, 700, 959, 956,
975, 484, 426, 738, 508, 201, 527, 816, 136, 668, 624, 535, 108,
1, 965, 857, 152, 478, 344, 567, 262, 546, 953, 199, 90, 72, 900,
449, 773, 211, 758, 100, 696, 536, 838, 204, 738, 717, 21, 874,
385, 997, 761, 845, 998, 78, 703, 502, 557, 47, 421, 819, 945,
375, 370, 35, 799, 622, 837, 924, 834, 595, 24, 882, 483, 862,
438, 221, 931, 811, 448, 317, 809, 561, 162, 159, 640, 217, 662,
197, 616, 435, 368, 562, 162, 739, 949, 962, 713, 786, 238, 899,
733, 263, 781, 217, 477, 220, 790, 409, 383, 590, 726, 192, 152,
240, 352, 792, 458, 366, 341, 74, 801, 709, 988, 964, 800, 938,
278, 514, 76, 516, 413, 810, 131, 547, 379, 609, 119, 169, 370,
502, 112, 448, 695, 264, 688, 399, 408, 498, 765, 749, 925, 918,
458, 913, 234, 611]
array_f = [512, 125, 928, 381, 890, 90, 512, 789, 469, 473, 908, 990, 195,
763, 102, 643, 458, 366, 684, 857, 126, 534, 974, 875, 459, 892,
686, 373, 127, 297, 576, 991, 774, 856, 372, 664, 946, 237, 806,
767, 62, 714, 758, 258, 477, 860, 253, 287, 579, 289, 496]
assert equal_instance.count_mim_steps(array_a) == 2
assert equal_instance.count_mim_steps(array_b) == 10605
assert equal_instance.count_mim_steps(array_c) == 8198
assert equal_instance.count_mim_steps(array_d) == 18762
assert equal_instance.count_mim_steps(array_e) == 16931
assert equal_instance.count_mim_steps(array_f) == 5104 | identifier_body |
|
link.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from .generic import *
from criacao.forms import *
from criacao.models import *
from gerenciamento.models import *
logger = logging.getLogger(__name__)
class LinkView(GenericView):
def criar(self, request):
if request.method == 'POST':
try:
name = request.POST['name']
url = request.POST['url']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Está faltando alguma informação, por favor, verifique os campos!',
}
}
else:
link = Link(name=name, url=url)
try:
link.save()
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-success' : 'Link criado com sucesso!',
'redirect' : '/criacao/link/listar/'
},
}
finally:
return data
else:
museu, museu_nome = UTIL_informacoes_museu()
form = LinkForm()
data = {
'template' : {
'request' : request,
'museu_nome' : museu_nome,
'form' : form,
},
}
return data
def visualizar(self, request):
try:
pk = self.kwargs['key']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Não foi possível processar essa visualização.',
}
}
else:
museu, museu_nome = UTIL_informacoes_museu()
link = Link.objects.get(pk=pk)
data = {
'template' : {
'request' : request,
'museu_nome' : museu_nome,
'link' : link,
},
}
finally:
return data
def editar(self, request):
if request.method == 'POST':
try:
| try:
pk = self.kwargs['key']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Não foi possível processar essa edição!',
}
}
else:
museu, museu_nome = UTIL_informacoes_museu()
link = Link.objects.get(pk=pk);
form = LinkForm(initial={
'name': link.name,
'url': link.url,
})
data = {
'template' : {
'request' : request,
'museu_nome' : museu_nome,
'link' : link,
'form' : form,
},
}
finally:
return data
def excluir(self, request):
try:
pk = self.kwargs['key']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Não foi possível processar essa exclusão!',
}
}
else:
Link.objects.get(pk=pk).delete()
data = {
'leftover' : {
'alert-success' : 'Link deletado com sucesso!',
},
}
finally:
return data
def listar(self, request):
museu, museu_nome = UTIL_informacoes_museu()
links = Link.objects.all()
try:
page = int(self.kwargs['key'])
except:
page = 1
finally:
links = paginate(obj=links, page=page, num_per_page=8)
data = {
'template' : {
'request' : request,
'museu' : museu,
'museu_nome' : museu_nome,
'links' : links,
},
}
return data | pk = self.kwargs['key']
name = request.POST['name']
url = request.POST['url']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Não foi possível processar esta edição!',
}
}
else:
link = Link.objects.get(pk=pk);
link.name=name
link.url=url
link.save()
data = {
'leftover' : {
'alert-success' : 'Link editada com sucesso!',
'redirect' : '/criacao/link/listar/'
},
}
finally:
return data
else:
| conditional_block |
link.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from .generic import *
from criacao.forms import *
from criacao.models import *
from gerenciamento.models import *
logger = logging.getLogger(__name__)
class LinkView(GenericView):
def criar(self, request):
if request.method == 'POST':
try:
name = request.POST['name']
url = request.POST['url']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Está faltando alguma informação, por favor, verifique os campos!',
}
}
else:
link = Link(name=name, url=url)
try:
link.save()
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-success' : 'Link criado com sucesso!',
'redirect' : '/criacao/link/listar/'
},
}
finally:
return data
else:
museu, museu_nome = UTIL_informacoes_museu()
form = LinkForm()
data = {
'template' : {
'request' : request,
'museu_nome' : museu_nome,
'form' : form,
},
}
return data
def visualizar(self, request):
try:
pk = self.kwargs['key']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Não foi possível processar essa visualização.',
}
}
else:
museu, museu_nome = UTIL_informacoes_museu()
link = Link.objects.get(pk=pk)
data = {
'template' : {
'request' : request,
'museu_nome' : museu_nome,
'link' : link,
},
}
finally:
return data
def editar(self, request):
if request.method == 'POST':
try:
pk = self.kwargs['key']
name = request.POST['name']
url = request.POST['url']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Não foi possível processar esta edição!',
}
}
else:
link = Link.objects.get(pk=pk);
link.name=name
link.url=url
link.save()
data = {
'leftover' : {
'alert-success' : 'Link editada com sucesso!',
'redirect' : '/criacao/link/listar/'
},
}
finally: | except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Não foi possível processar essa edição!',
}
}
else:
museu, museu_nome = UTIL_informacoes_museu()
link = Link.objects.get(pk=pk);
form = LinkForm(initial={
'name': link.name,
'url': link.url,
})
data = {
'template' : {
'request' : request,
'museu_nome' : museu_nome,
'link' : link,
'form' : form,
},
}
finally:
return data
def excluir(self, request):
try:
pk = self.kwargs['key']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Não foi possível processar essa exclusão!',
}
}
else:
Link.objects.get(pk=pk).delete()
data = {
'leftover' : {
'alert-success' : 'Link deletado com sucesso!',
},
}
finally:
return data
def listar(self, request):
museu, museu_nome = UTIL_informacoes_museu()
links = Link.objects.all()
try:
page = int(self.kwargs['key'])
except:
page = 1
finally:
links = paginate(obj=links, page=page, num_per_page=8)
data = {
'template' : {
'request' : request,
'museu' : museu,
'museu_nome' : museu_nome,
'links' : links,
},
}
return data | return data
else:
try:
pk = self.kwargs['key'] | random_line_split |
link.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from .generic import *
from criacao.forms import *
from criacao.models import *
from gerenciamento.models import *
logger = logging.getLogger(__name__)
class LinkView(GenericView):
def | (self, request):
if request.method == 'POST':
try:
name = request.POST['name']
url = request.POST['url']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Está faltando alguma informação, por favor, verifique os campos!',
}
}
else:
link = Link(name=name, url=url)
try:
link.save()
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-success' : 'Link criado com sucesso!',
'redirect' : '/criacao/link/listar/'
},
}
finally:
return data
else:
museu, museu_nome = UTIL_informacoes_museu()
form = LinkForm()
data = {
'template' : {
'request' : request,
'museu_nome' : museu_nome,
'form' : form,
},
}
return data
def visualizar(self, request):
try:
pk = self.kwargs['key']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Não foi possível processar essa visualização.',
}
}
else:
museu, museu_nome = UTIL_informacoes_museu()
link = Link.objects.get(pk=pk)
data = {
'template' : {
'request' : request,
'museu_nome' : museu_nome,
'link' : link,
},
}
finally:
return data
def editar(self, request):
if request.method == 'POST':
try:
pk = self.kwargs['key']
name = request.POST['name']
url = request.POST['url']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Não foi possível processar esta edição!',
}
}
else:
link = Link.objects.get(pk=pk);
link.name=name
link.url=url
link.save()
data = {
'leftover' : {
'alert-success' : 'Link editada com sucesso!',
'redirect' : '/criacao/link/listar/'
},
}
finally:
return data
else:
try:
pk = self.kwargs['key']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Não foi possível processar essa edição!',
}
}
else:
museu, museu_nome = UTIL_informacoes_museu()
link = Link.objects.get(pk=pk);
form = LinkForm(initial={
'name': link.name,
'url': link.url,
})
data = {
'template' : {
'request' : request,
'museu_nome' : museu_nome,
'link' : link,
'form' : form,
},
}
finally:
return data
def excluir(self, request):
try:
pk = self.kwargs['key']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Não foi possível processar essa exclusão!',
}
}
else:
Link.objects.get(pk=pk).delete()
data = {
'leftover' : {
'alert-success' : 'Link deletado com sucesso!',
},
}
finally:
return data
def listar(self, request):
museu, museu_nome = UTIL_informacoes_museu()
links = Link.objects.all()
try:
page = int(self.kwargs['key'])
except:
page = 1
finally:
links = paginate(obj=links, page=page, num_per_page=8)
data = {
'template' : {
'request' : request,
'museu' : museu,
'museu_nome' : museu_nome,
'links' : links,
},
}
return data | criar | identifier_name |
link.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from .generic import *
from criacao.forms import *
from criacao.models import *
from gerenciamento.models import *
logger = logging.getLogger(__name__)
class LinkView(GenericView):
def criar(self, request):
if request.method == 'POST':
try:
name = request.POST['name']
url = request.POST['url']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Está faltando alguma informação, por favor, verifique os campos!',
}
}
else:
link = Link(name=name, url=url)
try:
link.save()
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-success' : 'Link criado com sucesso!',
'redirect' : '/criacao/link/listar/'
},
}
finally:
return data
else:
museu, museu_nome = UTIL_informacoes_museu()
form = LinkForm()
data = {
'template' : {
'request' : request,
'museu_nome' : museu_nome,
'form' : form,
},
}
return data
def visualizar(self, request):
try:
pk = self.kwargs['key']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Não foi possível processar essa visualização.',
}
}
else:
museu, museu_nome = UTIL_informacoes_museu()
link = Link.objects.get(pk=pk)
data = {
'template' : {
'request' : request,
'museu_nome' : museu_nome,
'link' : link,
},
}
finally:
return data
def editar(self, request):
if requ | self, request):
try:
pk = self.kwargs['key']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Não foi possível processar essa exclusão!',
}
}
else:
Link.objects.get(pk=pk).delete()
data = {
'leftover' : {
'alert-success' : 'Link deletado com sucesso!',
},
}
finally:
return data
def listar(self, request):
museu, museu_nome = UTIL_informacoes_museu()
links = Link.objects.all()
try:
page = int(self.kwargs['key'])
except:
page = 1
finally:
links = paginate(obj=links, page=page, num_per_page=8)
data = {
'template' : {
'request' : request,
'museu' : museu,
'museu_nome' : museu_nome,
'links' : links,
},
}
return data | est.method == 'POST':
try:
pk = self.kwargs['key']
name = request.POST['name']
url = request.POST['url']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Não foi possível processar esta edição!',
}
}
else:
link = Link.objects.get(pk=pk);
link.name=name
link.url=url
link.save()
data = {
'leftover' : {
'alert-success' : 'Link editada com sucesso!',
'redirect' : '/criacao/link/listar/'
},
}
finally:
return data
else:
try:
pk = self.kwargs['key']
except Exception, e:
logger.error(str(e))
data = {
'leftover' : {
'alert-error' : 'Não foi possível processar essa edição!',
}
}
else:
museu, museu_nome = UTIL_informacoes_museu()
link = Link.objects.get(pk=pk);
form = LinkForm(initial={
'name': link.name,
'url': link.url,
})
data = {
'template' : {
'request' : request,
'museu_nome' : museu_nome,
'link' : link,
'form' : form,
},
}
finally:
return data
def excluir( | identifier_body |
server.py | import BaseHTTPServer, SimpleHTTPServer
import subprocess, shlex
import ssl
import time
import os
from optparse import OptionParser
port = 4443
execfile('./variables.py')
parser = OptionParser()
parser.add_option('-p', "--port", dest='port', help='Run HTTPS server on PORT', metavar='PORT')
(options, args) = parser.parse_args()
print('Running SelfKit v' + skp['SKVersion'] + ' (build ' + skp['SKBuild'] + ') web server on port ' + port.__str__() + '...')
if not os.path.exists("./server.pem"):
print './server.pem does not exist. Creating...'
command = 'openssl req -new -x509 -keyout ./server.pem -out ./server.pem -days 3650 -nodes -subj "/C=/ST=/L=/O=/CN=localhost"'
print (command)
args = shlex.split(command)
p = subprocess.call(args)
print ('Running web server...')
class SKWebHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
if (self.path == '/' or self.path == ''): self.path = '/index.html'
if os.path.exists('content' + self.path):
f = open('content' + self.path)
page = f.read()
page = replaceVariables(page)
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.send_header('X-SelfKit-Version', skp['SKVersion'])
self.end_headers()
self.wfile.write(page)
return
else:
self.send_response(400)
self.send_header('X-SelfKit-Version', skp['SKVersion'])
self.end_headers()
self.wfile.write('<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL ' + self.path + ' was not found on this server.</p></body></html>')
def | (self, format, *args):
return
if os.path.exists('./server.pem'):
httpd = BaseHTTPServer.HTTPServer(('localhost', port), SKWebHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile='server.pem', server_side=True)
httpd.serve_forever()
| log_message | identifier_name |
server.py | import BaseHTTPServer, SimpleHTTPServer
import subprocess, shlex
import ssl
import time
import os
from optparse import OptionParser
port = 4443
execfile('./variables.py')
parser = OptionParser()
parser.add_option('-p', "--port", dest='port', help='Run HTTPS server on PORT', metavar='PORT')
(options, args) = parser.parse_args()
print('Running SelfKit v' + skp['SKVersion'] + ' (build ' + skp['SKBuild'] + ') web server on port ' + port.__str__() + '...')
if not os.path.exists("./server.pem"):
print './server.pem does not exist. Creating...'
command = 'openssl req -new -x509 -keyout ./server.pem -out ./server.pem -days 3650 -nodes -subj "/C=/ST=/L=/O=/CN=localhost"'
print (command)
args = shlex.split(command)
p = subprocess.call(args)
print ('Running web server...')
class SKWebHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
|
if os.path.exists('./server.pem'):
httpd = BaseHTTPServer.HTTPServer(('localhost', port), SKWebHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile='server.pem', server_side=True)
httpd.serve_forever()
| def do_GET(self):
if (self.path == '/' or self.path == ''): self.path = '/index.html'
if os.path.exists('content' + self.path):
f = open('content' + self.path)
page = f.read()
page = replaceVariables(page)
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.send_header('X-SelfKit-Version', skp['SKVersion'])
self.end_headers()
self.wfile.write(page)
return
else:
self.send_response(400)
self.send_header('X-SelfKit-Version', skp['SKVersion'])
self.end_headers()
self.wfile.write('<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL ' + self.path + ' was not found on this server.</p></body></html>')
def log_message(self, format, *args):
return | identifier_body |
server.py | import BaseHTTPServer, SimpleHTTPServer
import subprocess, shlex
import ssl
import time
import os
from optparse import OptionParser
port = 4443
execfile('./variables.py')
parser = OptionParser()
parser.add_option('-p', "--port", dest='port', help='Run HTTPS server on PORT', metavar='PORT')
(options, args) = parser.parse_args()
print('Running SelfKit v' + skp['SKVersion'] + ' (build ' + skp['SKBuild'] + ') web server on port ' + port.__str__() + '...')
if not os.path.exists("./server.pem"):
print './server.pem does not exist. Creating...'
command = 'openssl req -new -x509 -keyout ./server.pem -out ./server.pem -days 3650 -nodes -subj "/C=/ST=/L=/O=/CN=localhost"'
print (command)
args = shlex.split(command)
p = subprocess.call(args)
print ('Running web server...')
class SKWebHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
if (self.path == '/' or self.path == ''): self.path = '/index.html'
if os.path.exists('content' + self.path):
|
else:
self.send_response(400)
self.send_header('X-SelfKit-Version', skp['SKVersion'])
self.end_headers()
self.wfile.write('<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL ' + self.path + ' was not found on this server.</p></body></html>')
def log_message(self, format, *args):
return
if os.path.exists('./server.pem'):
httpd = BaseHTTPServer.HTTPServer(('localhost', port), SKWebHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile='server.pem', server_side=True)
httpd.serve_forever()
| f = open('content' + self.path)
page = f.read()
page = replaceVariables(page)
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.send_header('X-SelfKit-Version', skp['SKVersion'])
self.end_headers()
self.wfile.write(page)
return | conditional_block |
server.py | import BaseHTTPServer, SimpleHTTPServer
import subprocess, shlex
import ssl
import time
import os
from optparse import OptionParser
port = 4443
execfile('./variables.py')
parser = OptionParser()
parser.add_option('-p', "--port", dest='port', help='Run HTTPS server on PORT', metavar='PORT')
(options, args) = parser.parse_args()
print('Running SelfKit v' + skp['SKVersion'] + ' (build ' + skp['SKBuild'] + ') web server on port ' + port.__str__() + '...')
if not os.path.exists("./server.pem"):
print './server.pem does not exist. Creating...'
command = 'openssl req -new -x509 -keyout ./server.pem -out ./server.pem -days 3650 -nodes -subj "/C=/ST=/L=/O=/CN=localhost"'
print (command)
args = shlex.split(command)
p = subprocess.call(args)
print ('Running web server...')
class SKWebHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
if (self.path == '/' or self.path == ''): self.path = '/index.html'
if os.path.exists('content' + self.path):
f = open('content' + self.path)
page = f.read()
page = replaceVariables(page)
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.send_header('X-SelfKit-Version', skp['SKVersion'])
self.end_headers()
self.wfile.write(page)
return
else:
self.send_response(400)
self.send_header('X-SelfKit-Version', skp['SKVersion'])
self.end_headers()
self.wfile.write('<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL ' + self.path + ' was not found on this server.</p></body></html>')
def log_message(self, format, *args):
return
if os.path.exists('./server.pem'): | httpd = BaseHTTPServer.HTTPServer(('localhost', port), SKWebHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile='server.pem', server_side=True)
httpd.serve_forever() | random_line_split |
|
buck_project.py | # Copyright 2018-present Facebook, 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.
from __future__ import print_function
import errno
import hashlib
import os
import shutil
import sys
import tempfile
import textwrap
import file_locks
from tracing import Tracing
def get_file_contents_if_exists(path, default=None):
with Tracing("BuckProject.get_file_contents_if_it_exists", args={"path": path}):
if not os.path.exists(path):
return default
with open(path) as f:
contents = f.read().strip()
return default if not contents else contents
def write_contents_to_file(path, contents):
with Tracing("BuckProject.write_contents_to_file", args={"path": path}):
with open(path, "w") as output_file:
output_file.write(str(contents))
def makedirs(path):
try:
os.makedirs(path)
except OSError as e:
# Potentially the case that multiple processes are running in parallel
# (e.g. a series of linters running buck query without buckd), so we
# should just swallow the error.
# This is mostly equivalent to os.makedirs(path, exist_ok=True) in
# Python 3.
if e.errno != errno.EEXIST and os.path.isdir(path):
raise
class | :
def __init__(self, root):
self.root = root
self._buck_out = os.path.join(root, "buck-out")
buck_out_tmp = os.path.join(self._buck_out, "tmp")
makedirs(buck_out_tmp)
self._buck_out_log = os.path.join(self._buck_out, "log")
makedirs(self._buck_out_log)
self.tmp_dir = tempfile.mkdtemp(prefix="buck_run.", dir=buck_out_tmp)
# Only created if buckd is used.
self.buckd_tmp_dir = None
self.buckd_dir = os.path.join(root, ".buckd")
self.buckd_version_file = os.path.join(self.buckd_dir, "buckd.version")
self.buckd_pid_file = os.path.join(self.buckd_dir, "pid")
self.buckd_stdout = os.path.join(self.buckd_dir, "stdout")
self.buckd_stderr = os.path.join(self.buckd_dir, "stderr")
buck_javaargs_path = os.path.join(self.root, ".buckjavaargs")
self.buck_javaargs = get_file_contents_if_exists(buck_javaargs_path)
buck_javaargs_path_local = os.path.join(self.root, ".buckjavaargs.local")
self.buck_javaargs_local = get_file_contents_if_exists(buck_javaargs_path_local)
def get_root_hash(self):
return hashlib.sha256(self.root.encode("utf-8")).hexdigest()
def get_buckd_transport_file_path(self):
if os.name == "nt":
return u"\\\\.\\pipe\\buckd_{0}".format(self.get_root_hash())
else:
return os.path.join(self.buckd_dir, "sock")
def get_buckd_transport_address(self):
if os.name == "nt":
return "local:buckd_{0}".format(self.get_root_hash())
else:
return "local:.buckd/sock"
def get_running_buckd_version(self):
return get_file_contents_if_exists(self.buckd_version_file)
def get_running_buckd_pid(self):
try:
return int(get_file_contents_if_exists(self.buckd_pid_file))
except ValueError:
return None
except TypeError:
return None
def get_buckd_stdout(self):
return self.buckd_stdout
def get_buckd_stderr(self):
return self.buckd_stderr
def get_buck_out_log_dir(self):
return self._buck_out_log
def clean_up_buckd(self):
with Tracing("BuckProject.clean_up_buckd"):
if os.path.exists(self.buckd_dir):
file_locks.rmtree_if_can_lock(self.buckd_dir)
def create_buckd_tmp_dir(self):
if self.buckd_tmp_dir is not None:
return self.buckd_tmp_dir
tmp_dir_parent = os.path.join(self.buckd_dir, "tmp")
makedirs(tmp_dir_parent)
self.buckd_tmp_dir = tempfile.mkdtemp(prefix="buck_run.", dir=tmp_dir_parent)
return self.buckd_tmp_dir
def save_buckd_version(self, version):
write_contents_to_file(self.buckd_version_file, version)
def save_buckd_pid(self, pid):
write_contents_to_file(self.buckd_pid_file, str(pid))
@staticmethod
def from_current_dir():
with Tracing("BuckProject.from_current_dir"):
current_dir = os.getcwd()
if "--version" in sys.argv or "-V" in sys.argv:
return BuckProject(current_dir)
at_root_dir = False
while not at_root_dir:
if os.path.exists(os.path.join(current_dir, ".buckconfig")):
return BuckProject(current_dir)
parent_dir = os.path.dirname(current_dir)
at_root_dir = current_dir == parent_dir
current_dir = parent_dir
raise NoBuckConfigFoundException()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
with Tracing("BuckProject.__exit__"):
if os.path.exists(self.tmp_dir):
try:
shutil.rmtree(self.tmp_dir)
except OSError as e:
if e.errno != errno.ENOENT:
raise
class NoBuckConfigFoundException(Exception):
def __init__(self):
no_buckconfig_message_path = ".no_buckconfig_message"
default_message = textwrap.dedent(
"""\
This does not appear to be the root of a Buck project. Please 'cd'
to the root of your project before running buck. If this really is
the root of your project, run
'touch .buckconfig'
and then re-run your buck command."""
)
message = get_file_contents_if_exists(
no_buckconfig_message_path, default_message
)
Exception.__init__(self, message)
| BuckProject | identifier_name |
buck_project.py | # Copyright 2018-present Facebook, 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.
from __future__ import print_function
import errno
import hashlib
import os
import shutil
import sys
import tempfile
import textwrap
import file_locks
from tracing import Tracing
def get_file_contents_if_exists(path, default=None):
with Tracing("BuckProject.get_file_contents_if_it_exists", args={"path": path}):
if not os.path.exists(path):
return default
with open(path) as f:
contents = f.read().strip()
return default if not contents else contents
def write_contents_to_file(path, contents):
with Tracing("BuckProject.write_contents_to_file", args={"path": path}):
with open(path, "w") as output_file:
output_file.write(str(contents))
def makedirs(path):
try:
os.makedirs(path)
except OSError as e:
# Potentially the case that multiple processes are running in parallel
# (e.g. a series of linters running buck query without buckd), so we
# should just swallow the error.
# This is mostly equivalent to os.makedirs(path, exist_ok=True) in
# Python 3.
if e.errno != errno.EEXIST and os.path.isdir(path):
raise
class BuckProject:
def __init__(self, root):
self.root = root
self._buck_out = os.path.join(root, "buck-out")
buck_out_tmp = os.path.join(self._buck_out, "tmp")
makedirs(buck_out_tmp)
self._buck_out_log = os.path.join(self._buck_out, "log")
makedirs(self._buck_out_log)
self.tmp_dir = tempfile.mkdtemp(prefix="buck_run.", dir=buck_out_tmp)
# Only created if buckd is used.
self.buckd_tmp_dir = None
self.buckd_dir = os.path.join(root, ".buckd")
self.buckd_version_file = os.path.join(self.buckd_dir, "buckd.version")
self.buckd_pid_file = os.path.join(self.buckd_dir, "pid")
self.buckd_stdout = os.path.join(self.buckd_dir, "stdout")
self.buckd_stderr = os.path.join(self.buckd_dir, "stderr")
buck_javaargs_path = os.path.join(self.root, ".buckjavaargs")
self.buck_javaargs = get_file_contents_if_exists(buck_javaargs_path)
buck_javaargs_path_local = os.path.join(self.root, ".buckjavaargs.local")
self.buck_javaargs_local = get_file_contents_if_exists(buck_javaargs_path_local)
def get_root_hash(self):
return hashlib.sha256(self.root.encode("utf-8")).hexdigest()
def get_buckd_transport_file_path(self):
if os.name == "nt":
return u"\\\\.\\pipe\\buckd_{0}".format(self.get_root_hash())
else:
return os.path.join(self.buckd_dir, "sock")
def get_buckd_transport_address(self):
if os.name == "nt":
return "local:buckd_{0}".format(self.get_root_hash())
else:
return "local:.buckd/sock"
def get_running_buckd_version(self):
return get_file_contents_if_exists(self.buckd_version_file)
def get_running_buckd_pid(self):
try:
return int(get_file_contents_if_exists(self.buckd_pid_file))
except ValueError:
return None
except TypeError:
return None
def get_buckd_stdout(self):
return self.buckd_stdout
def get_buckd_stderr(self):
return self.buckd_stderr
def get_buck_out_log_dir(self):
return self._buck_out_log
def clean_up_buckd(self):
with Tracing("BuckProject.clean_up_buckd"):
if os.path.exists(self.buckd_dir):
file_locks.rmtree_if_can_lock(self.buckd_dir)
def create_buckd_tmp_dir(self):
if self.buckd_tmp_dir is not None:
return self.buckd_tmp_dir
tmp_dir_parent = os.path.join(self.buckd_dir, "tmp")
makedirs(tmp_dir_parent)
self.buckd_tmp_dir = tempfile.mkdtemp(prefix="buck_run.", dir=tmp_dir_parent)
return self.buckd_tmp_dir
def save_buckd_version(self, version):
write_contents_to_file(self.buckd_version_file, version)
def save_buckd_pid(self, pid):
write_contents_to_file(self.buckd_pid_file, str(pid))
@staticmethod
def from_current_dir():
with Tracing("BuckProject.from_current_dir"):
current_dir = os.getcwd()
if "--version" in sys.argv or "-V" in sys.argv:
return BuckProject(current_dir)
at_root_dir = False
while not at_root_dir:
if os.path.exists(os.path.join(current_dir, ".buckconfig")):
return BuckProject(current_dir)
parent_dir = os.path.dirname(current_dir)
at_root_dir = current_dir == parent_dir
current_dir = parent_dir
raise NoBuckConfigFoundException()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
with Tracing("BuckProject.__exit__"):
if os.path.exists(self.tmp_dir):
|
class NoBuckConfigFoundException(Exception):
def __init__(self):
no_buckconfig_message_path = ".no_buckconfig_message"
default_message = textwrap.dedent(
"""\
This does not appear to be the root of a Buck project. Please 'cd'
to the root of your project before running buck. If this really is
the root of your project, run
'touch .buckconfig'
and then re-run your buck command."""
)
message = get_file_contents_if_exists(
no_buckconfig_message_path, default_message
)
Exception.__init__(self, message)
| try:
shutil.rmtree(self.tmp_dir)
except OSError as e:
if e.errno != errno.ENOENT:
raise | conditional_block |
buck_project.py | # Copyright 2018-present Facebook, 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.
from __future__ import print_function
import errno
import hashlib
import os
import shutil
import sys
import tempfile
import textwrap
import file_locks
from tracing import Tracing
def get_file_contents_if_exists(path, default=None):
with Tracing("BuckProject.get_file_contents_if_it_exists", args={"path": path}):
if not os.path.exists(path):
return default
with open(path) as f:
contents = f.read().strip()
return default if not contents else contents
def write_contents_to_file(path, contents):
with Tracing("BuckProject.write_contents_to_file", args={"path": path}):
with open(path, "w") as output_file:
output_file.write(str(contents))
def makedirs(path):
try:
os.makedirs(path)
except OSError as e:
# Potentially the case that multiple processes are running in parallel
# (e.g. a series of linters running buck query without buckd), so we
# should just swallow the error.
# This is mostly equivalent to os.makedirs(path, exist_ok=True) in
# Python 3.
if e.errno != errno.EEXIST and os.path.isdir(path):
raise
class BuckProject:
def __init__(self, root):
self.root = root
self._buck_out = os.path.join(root, "buck-out")
buck_out_tmp = os.path.join(self._buck_out, "tmp")
makedirs(buck_out_tmp)
self._buck_out_log = os.path.join(self._buck_out, "log")
makedirs(self._buck_out_log)
self.tmp_dir = tempfile.mkdtemp(prefix="buck_run.", dir=buck_out_tmp)
# Only created if buckd is used.
self.buckd_tmp_dir = None
self.buckd_dir = os.path.join(root, ".buckd")
self.buckd_version_file = os.path.join(self.buckd_dir, "buckd.version")
self.buckd_pid_file = os.path.join(self.buckd_dir, "pid")
self.buckd_stdout = os.path.join(self.buckd_dir, "stdout")
self.buckd_stderr = os.path.join(self.buckd_dir, "stderr")
buck_javaargs_path = os.path.join(self.root, ".buckjavaargs")
self.buck_javaargs = get_file_contents_if_exists(buck_javaargs_path)
buck_javaargs_path_local = os.path.join(self.root, ".buckjavaargs.local")
self.buck_javaargs_local = get_file_contents_if_exists(buck_javaargs_path_local)
def get_root_hash(self):
return hashlib.sha256(self.root.encode("utf-8")).hexdigest()
def get_buckd_transport_file_path(self):
if os.name == "nt":
return u"\\\\.\\pipe\\buckd_{0}".format(self.get_root_hash())
else:
return os.path.join(self.buckd_dir, "sock")
def get_buckd_transport_address(self):
if os.name == "nt":
return "local:buckd_{0}".format(self.get_root_hash())
else:
return "local:.buckd/sock"
def get_running_buckd_version(self):
return get_file_contents_if_exists(self.buckd_version_file)
def get_running_buckd_pid(self):
try:
return int(get_file_contents_if_exists(self.buckd_pid_file))
except ValueError:
return None
except TypeError:
return None
def get_buckd_stdout(self):
return self.buckd_stdout
def get_buckd_stderr(self):
return self.buckd_stderr
def get_buck_out_log_dir(self):
return self._buck_out_log
def clean_up_buckd(self):
with Tracing("BuckProject.clean_up_buckd"):
if os.path.exists(self.buckd_dir):
file_locks.rmtree_if_can_lock(self.buckd_dir)
def create_buckd_tmp_dir(self):
if self.buckd_tmp_dir is not None:
return self.buckd_tmp_dir
tmp_dir_parent = os.path.join(self.buckd_dir, "tmp")
makedirs(tmp_dir_parent)
self.buckd_tmp_dir = tempfile.mkdtemp(prefix="buck_run.", dir=tmp_dir_parent)
return self.buckd_tmp_dir
def save_buckd_version(self, version):
write_contents_to_file(self.buckd_version_file, version)
def save_buckd_pid(self, pid):
write_contents_to_file(self.buckd_pid_file, str(pid))
@staticmethod
def from_current_dir():
with Tracing("BuckProject.from_current_dir"):
current_dir = os.getcwd()
if "--version" in sys.argv or "-V" in sys.argv:
return BuckProject(current_dir)
at_root_dir = False
while not at_root_dir:
if os.path.exists(os.path.join(current_dir, ".buckconfig")):
return BuckProject(current_dir)
parent_dir = os.path.dirname(current_dir)
at_root_dir = current_dir == parent_dir
current_dir = parent_dir
raise NoBuckConfigFoundException()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
with Tracing("BuckProject.__exit__"):
if os.path.exists(self.tmp_dir):
try:
shutil.rmtree(self.tmp_dir)
except OSError as e:
if e.errno != errno.ENOENT:
raise
class NoBuckConfigFoundException(Exception):
def __init__(self):
| no_buckconfig_message_path = ".no_buckconfig_message"
default_message = textwrap.dedent(
"""\
This does not appear to be the root of a Buck project. Please 'cd'
to the root of your project before running buck. If this really is
the root of your project, run
'touch .buckconfig'
and then re-run your buck command."""
)
message = get_file_contents_if_exists(
no_buckconfig_message_path, default_message
)
Exception.__init__(self, message) | identifier_body |
|
buck_project.py | # Copyright 2018-present Facebook, 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.
from __future__ import print_function
import errno
import hashlib
import os
import shutil
import sys
import tempfile
import textwrap
import file_locks
from tracing import Tracing
def get_file_contents_if_exists(path, default=None):
with Tracing("BuckProject.get_file_contents_if_it_exists", args={"path": path}):
if not os.path.exists(path):
return default
with open(path) as f:
contents = f.read().strip()
return default if not contents else contents
def write_contents_to_file(path, contents):
with Tracing("BuckProject.write_contents_to_file", args={"path": path}):
with open(path, "w") as output_file:
output_file.write(str(contents))
def makedirs(path):
try:
os.makedirs(path)
except OSError as e:
# Potentially the case that multiple processes are running in parallel
# (e.g. a series of linters running buck query without buckd), so we |
class BuckProject:
def __init__(self, root):
self.root = root
self._buck_out = os.path.join(root, "buck-out")
buck_out_tmp = os.path.join(self._buck_out, "tmp")
makedirs(buck_out_tmp)
self._buck_out_log = os.path.join(self._buck_out, "log")
makedirs(self._buck_out_log)
self.tmp_dir = tempfile.mkdtemp(prefix="buck_run.", dir=buck_out_tmp)
# Only created if buckd is used.
self.buckd_tmp_dir = None
self.buckd_dir = os.path.join(root, ".buckd")
self.buckd_version_file = os.path.join(self.buckd_dir, "buckd.version")
self.buckd_pid_file = os.path.join(self.buckd_dir, "pid")
self.buckd_stdout = os.path.join(self.buckd_dir, "stdout")
self.buckd_stderr = os.path.join(self.buckd_dir, "stderr")
buck_javaargs_path = os.path.join(self.root, ".buckjavaargs")
self.buck_javaargs = get_file_contents_if_exists(buck_javaargs_path)
buck_javaargs_path_local = os.path.join(self.root, ".buckjavaargs.local")
self.buck_javaargs_local = get_file_contents_if_exists(buck_javaargs_path_local)
def get_root_hash(self):
return hashlib.sha256(self.root.encode("utf-8")).hexdigest()
def get_buckd_transport_file_path(self):
if os.name == "nt":
return u"\\\\.\\pipe\\buckd_{0}".format(self.get_root_hash())
else:
return os.path.join(self.buckd_dir, "sock")
def get_buckd_transport_address(self):
if os.name == "nt":
return "local:buckd_{0}".format(self.get_root_hash())
else:
return "local:.buckd/sock"
def get_running_buckd_version(self):
return get_file_contents_if_exists(self.buckd_version_file)
def get_running_buckd_pid(self):
try:
return int(get_file_contents_if_exists(self.buckd_pid_file))
except ValueError:
return None
except TypeError:
return None
def get_buckd_stdout(self):
return self.buckd_stdout
def get_buckd_stderr(self):
return self.buckd_stderr
def get_buck_out_log_dir(self):
return self._buck_out_log
def clean_up_buckd(self):
with Tracing("BuckProject.clean_up_buckd"):
if os.path.exists(self.buckd_dir):
file_locks.rmtree_if_can_lock(self.buckd_dir)
def create_buckd_tmp_dir(self):
if self.buckd_tmp_dir is not None:
return self.buckd_tmp_dir
tmp_dir_parent = os.path.join(self.buckd_dir, "tmp")
makedirs(tmp_dir_parent)
self.buckd_tmp_dir = tempfile.mkdtemp(prefix="buck_run.", dir=tmp_dir_parent)
return self.buckd_tmp_dir
def save_buckd_version(self, version):
write_contents_to_file(self.buckd_version_file, version)
def save_buckd_pid(self, pid):
write_contents_to_file(self.buckd_pid_file, str(pid))
@staticmethod
def from_current_dir():
with Tracing("BuckProject.from_current_dir"):
current_dir = os.getcwd()
if "--version" in sys.argv or "-V" in sys.argv:
return BuckProject(current_dir)
at_root_dir = False
while not at_root_dir:
if os.path.exists(os.path.join(current_dir, ".buckconfig")):
return BuckProject(current_dir)
parent_dir = os.path.dirname(current_dir)
at_root_dir = current_dir == parent_dir
current_dir = parent_dir
raise NoBuckConfigFoundException()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
with Tracing("BuckProject.__exit__"):
if os.path.exists(self.tmp_dir):
try:
shutil.rmtree(self.tmp_dir)
except OSError as e:
if e.errno != errno.ENOENT:
raise
class NoBuckConfigFoundException(Exception):
def __init__(self):
no_buckconfig_message_path = ".no_buckconfig_message"
default_message = textwrap.dedent(
"""\
This does not appear to be the root of a Buck project. Please 'cd'
to the root of your project before running buck. If this really is
the root of your project, run
'touch .buckconfig'
and then re-run your buck command."""
)
message = get_file_contents_if_exists(
no_buckconfig_message_path, default_message
)
Exception.__init__(self, message) | # should just swallow the error.
# This is mostly equivalent to os.makedirs(path, exist_ok=True) in
# Python 3.
if e.errno != errno.EEXIST and os.path.isdir(path):
raise | random_line_split |
main.rs | //! See <https://github.com/matklad/cargo-xtask/>.
//!
//! This binary is integrated into the `cargo` command line by using an alias in
//! `.cargo/config`. Run commands as `cargo xtask [command]`.
#![allow(clippy::exhaustive_structs)]
use std::path::PathBuf; | mod cargo;
mod ci;
mod flags;
#[cfg(feature = "default")]
mod release;
#[cfg(feature = "default")]
mod util;
use ci::CiTask;
#[cfg(feature = "default")]
use release::ReleaseTask;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn main() {
if let Err(e) = try_main() {
eprintln!("{}", e);
std::process::exit(-1);
}
}
fn try_main() -> Result<()> {
let flags = flags::Xtask::from_env()?;
match flags.subcommand {
flags::XtaskCmd::Help(_) => {
println!("{}", flags::Xtask::HELP);
Ok(())
}
flags::XtaskCmd::Ci(ci) => {
let task = CiTask::new(ci.version)?;
task.run()
}
#[cfg(feature = "default")]
flags::XtaskCmd::Release(cmd) => {
let mut task = ReleaseTask::new(cmd.name, cmd.version)?;
task.run()
}
#[cfg(feature = "default")]
flags::XtaskCmd::Publish(cmd) => {
let mut task = ReleaseTask::new(cmd.name, cmd.version)?;
task.run()
}
#[cfg(not(feature = "default"))]
_ => {
Err("This command is only available when xtask is built with default features.".into())
}
}
}
/// The metadata of a cargo workspace.
#[derive(Clone, Debug, Deserialize)]
struct Metadata {
pub workspace_root: PathBuf,
#[cfg(feature = "default")]
pub packages: Vec<cargo::Package>,
}
impl Metadata {
/// Load a new `Metadata` from the command line.
pub fn load() -> Result<Metadata> {
let metadata_json = cmd!("cargo metadata --no-deps --format-version 1").read()?;
Ok(from_json_str(&metadata_json)?)
}
}
#[cfg(feature = "default")]
#[derive(Debug, Deserialize)]
struct Config {
/// Credentials to authenticate to GitHub.
github: GithubConfig,
}
#[cfg(feature = "default")]
impl Config {
/// Load a new `Config` from `config.toml`.
fn load() -> Result<Self> {
use std::{env, path::Path};
let path = Path::new(&env!("CARGO_MANIFEST_DIR")).join("config.toml");
let config = xshell::read_file(path)?;
Ok(toml::from_str(&config)?)
}
}
#[cfg(feature = "default")]
#[derive(Debug, Deserialize)]
struct GithubConfig {
/// The username to use for authentication.
user: String,
/// The personal access token to use for authentication.
token: String,
}
#[macro_export]
macro_rules! cmd {
($cmd:tt) => {
xshell::cmd!($cmd).echo_cmd(false)
};
} |
use serde::Deserialize;
use serde_json::from_str as from_json_str;
#[cfg(feature = "default")] | random_line_split |
main.rs | //! See <https://github.com/matklad/cargo-xtask/>.
//!
//! This binary is integrated into the `cargo` command line by using an alias in
//! `.cargo/config`. Run commands as `cargo xtask [command]`.
#![allow(clippy::exhaustive_structs)]
use std::path::PathBuf;
use serde::Deserialize;
use serde_json::from_str as from_json_str;
#[cfg(feature = "default")]
mod cargo;
mod ci;
mod flags;
#[cfg(feature = "default")]
mod release;
#[cfg(feature = "default")]
mod util;
use ci::CiTask;
#[cfg(feature = "default")]
use release::ReleaseTask;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn main() {
if let Err(e) = try_main() {
eprintln!("{}", e);
std::process::exit(-1);
}
}
fn try_main() -> Result<()> {
let flags = flags::Xtask::from_env()?;
match flags.subcommand {
flags::XtaskCmd::Help(_) => {
println!("{}", flags::Xtask::HELP);
Ok(())
}
flags::XtaskCmd::Ci(ci) => {
let task = CiTask::new(ci.version)?;
task.run()
}
#[cfg(feature = "default")]
flags::XtaskCmd::Release(cmd) => {
let mut task = ReleaseTask::new(cmd.name, cmd.version)?;
task.run()
}
#[cfg(feature = "default")]
flags::XtaskCmd::Publish(cmd) => {
let mut task = ReleaseTask::new(cmd.name, cmd.version)?;
task.run()
}
#[cfg(not(feature = "default"))]
_ => {
Err("This command is only available when xtask is built with default features.".into())
}
}
}
/// The metadata of a cargo workspace.
#[derive(Clone, Debug, Deserialize)]
struct Metadata {
pub workspace_root: PathBuf,
#[cfg(feature = "default")]
pub packages: Vec<cargo::Package>,
}
impl Metadata {
/// Load a new `Metadata` from the command line.
pub fn load() -> Result<Metadata> {
let metadata_json = cmd!("cargo metadata --no-deps --format-version 1").read()?;
Ok(from_json_str(&metadata_json)?)
}
}
#[cfg(feature = "default")]
#[derive(Debug, Deserialize)]
struct Config {
/// Credentials to authenticate to GitHub.
github: GithubConfig,
}
#[cfg(feature = "default")]
impl Config {
/// Load a new `Config` from `config.toml`.
fn | () -> Result<Self> {
use std::{env, path::Path};
let path = Path::new(&env!("CARGO_MANIFEST_DIR")).join("config.toml");
let config = xshell::read_file(path)?;
Ok(toml::from_str(&config)?)
}
}
#[cfg(feature = "default")]
#[derive(Debug, Deserialize)]
struct GithubConfig {
/// The username to use for authentication.
user: String,
/// The personal access token to use for authentication.
token: String,
}
#[macro_export]
macro_rules! cmd {
($cmd:tt) => {
xshell::cmd!($cmd).echo_cmd(false)
};
}
| load | identifier_name |
main.rs | //! See <https://github.com/matklad/cargo-xtask/>.
//!
//! This binary is integrated into the `cargo` command line by using an alias in
//! `.cargo/config`. Run commands as `cargo xtask [command]`.
#![allow(clippy::exhaustive_structs)]
use std::path::PathBuf;
use serde::Deserialize;
use serde_json::from_str as from_json_str;
#[cfg(feature = "default")]
mod cargo;
mod ci;
mod flags;
#[cfg(feature = "default")]
mod release;
#[cfg(feature = "default")]
mod util;
use ci::CiTask;
#[cfg(feature = "default")]
use release::ReleaseTask;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn main() {
if let Err(e) = try_main() |
}
fn try_main() -> Result<()> {
let flags = flags::Xtask::from_env()?;
match flags.subcommand {
flags::XtaskCmd::Help(_) => {
println!("{}", flags::Xtask::HELP);
Ok(())
}
flags::XtaskCmd::Ci(ci) => {
let task = CiTask::new(ci.version)?;
task.run()
}
#[cfg(feature = "default")]
flags::XtaskCmd::Release(cmd) => {
let mut task = ReleaseTask::new(cmd.name, cmd.version)?;
task.run()
}
#[cfg(feature = "default")]
flags::XtaskCmd::Publish(cmd) => {
let mut task = ReleaseTask::new(cmd.name, cmd.version)?;
task.run()
}
#[cfg(not(feature = "default"))]
_ => {
Err("This command is only available when xtask is built with default features.".into())
}
}
}
/// The metadata of a cargo workspace.
#[derive(Clone, Debug, Deserialize)]
struct Metadata {
pub workspace_root: PathBuf,
#[cfg(feature = "default")]
pub packages: Vec<cargo::Package>,
}
impl Metadata {
/// Load a new `Metadata` from the command line.
pub fn load() -> Result<Metadata> {
let metadata_json = cmd!("cargo metadata --no-deps --format-version 1").read()?;
Ok(from_json_str(&metadata_json)?)
}
}
#[cfg(feature = "default")]
#[derive(Debug, Deserialize)]
struct Config {
/// Credentials to authenticate to GitHub.
github: GithubConfig,
}
#[cfg(feature = "default")]
impl Config {
/// Load a new `Config` from `config.toml`.
fn load() -> Result<Self> {
use std::{env, path::Path};
let path = Path::new(&env!("CARGO_MANIFEST_DIR")).join("config.toml");
let config = xshell::read_file(path)?;
Ok(toml::from_str(&config)?)
}
}
#[cfg(feature = "default")]
#[derive(Debug, Deserialize)]
struct GithubConfig {
/// The username to use for authentication.
user: String,
/// The personal access token to use for authentication.
token: String,
}
#[macro_export]
macro_rules! cmd {
($cmd:tt) => {
xshell::cmd!($cmd).echo_cmd(false)
};
}
| {
eprintln!("{}", e);
std::process::exit(-1);
} | conditional_block |
runtests.py | #!/usr/bin/env python
"""
Custom test runner
If args or options, we run the testsuite as quickly as possible.
If args but no options, we default to using the spec plugin and aborting on
first error/failure.
If options, we ignore defaults and pass options onto Nose.
Examples:
Run all tests (as fast as possible)
$ ./runtests.py
Run all unit tests (using spec output)
$ ./runtests.py tests/unit
Run all checkout unit tests (using spec output)
$ ./runtests.py tests/unit/checkout
Run all tests relating to shipping
$ ./runtests.py --attr=shipping
Re-run failing tests (needs to be run twice to first build the index)
$ ./runtests.py ... --failed
Drop into pdb when a test fails
$ ./runtests.py ... --pdb-failures
"""
import sys
import logging
import warnings
from tests.config import configure
from django.utils.six.moves import map
# No logging
logging.disable(logging.CRITICAL)
def | (verbosity, *test_args):
from django_nose import NoseTestSuiteRunner
test_runner = NoseTestSuiteRunner(verbosity=verbosity)
if not test_args:
test_args = ['tests']
num_failures = test_runner.run_tests(test_args)
if num_failures:
sys.exit(num_failures)
if __name__ == '__main__':
args = sys.argv[1:]
verbosity = 1
if not args:
# If run with no args, try and run the testsuite as fast as possible.
# That means across all cores and with no high-falutin' plugins.
import multiprocessing
try:
num_cores = multiprocessing.cpu_count()
except NotImplementedError:
num_cores = 4 # Guess
args = ['--nocapture', '--stop', '--processes=%s' % num_cores]
else:
# Some args/options specified. Check to see if any nose options have
# been specified. If they have, then don't set any
has_options = any(map(lambda x: x.startswith('--'), args))
if not has_options:
# Default options:
# --stop Abort on first error/failure
# --nocapture Don't capture STDOUT
args.extend(['--nocapture', '--stop'])
else:
# Remove options as nose will pick these up from sys.argv
for arg in args:
if arg.startswith('--verbosity'):
verbosity = int(arg[-1])
args = [arg for arg in args if not arg.startswith('-')]
configure()
with warnings.catch_warnings():
# The warnings module in default configuration will never cause tests
# to fail, as it never raises an exception. We alter that behaviour by
# turning DeprecationWarnings into exceptions, but exclude warnings
# triggered by third-party libs. Note: The context manager is not thread
# safe. Behaviour with multiple threads is undefined.
warnings.filterwarnings('error', category=DeprecationWarning)
warnings.filterwarnings('error', category=RuntimeWarning)
libs = r'(sorl\.thumbnail.*|bs4.*|webtest.*)'
warnings.filterwarnings(
'ignore', r'.*', DeprecationWarning, libs)
run_tests(verbosity, *args)
| run_tests | identifier_name |
runtests.py | #!/usr/bin/env python
"""
Custom test runner
If args or options, we run the testsuite as quickly as possible.
If args but no options, we default to using the spec plugin and aborting on
first error/failure.
If options, we ignore defaults and pass options onto Nose.
Examples:
Run all tests (as fast as possible)
$ ./runtests.py
Run all unit tests (using spec output)
$ ./runtests.py tests/unit
Run all checkout unit tests (using spec output)
$ ./runtests.py tests/unit/checkout
Run all tests relating to shipping
$ ./runtests.py --attr=shipping
Re-run failing tests (needs to be run twice to first build the index)
$ ./runtests.py ... --failed
Drop into pdb when a test fails
$ ./runtests.py ... --pdb-failures
"""
import sys
import logging
import warnings
from tests.config import configure
from django.utils.six.moves import map
# No logging
logging.disable(logging.CRITICAL)
def run_tests(verbosity, *test_args):
from django_nose import NoseTestSuiteRunner
test_runner = NoseTestSuiteRunner(verbosity=verbosity)
if not test_args:
test_args = ['tests']
num_failures = test_runner.run_tests(test_args)
if num_failures:
sys.exit(num_failures)
if __name__ == '__main__':
args = sys.argv[1:]
verbosity = 1
if not args:
# If run with no args, try and run the testsuite as fast as possible.
# That means across all cores and with no high-falutin' plugins.
import multiprocessing
try:
num_cores = multiprocessing.cpu_count()
except NotImplementedError:
num_cores = 4 # Guess
args = ['--nocapture', '--stop', '--processes=%s' % num_cores]
else:
# Some args/options specified. Check to see if any nose options have
# been specified. If they have, then don't set any
has_options = any(map(lambda x: x.startswith('--'), args))
if not has_options:
# Default options:
# --stop Abort on first error/failure
# --nocapture Don't capture STDOUT
|
else:
# Remove options as nose will pick these up from sys.argv
for arg in args:
if arg.startswith('--verbosity'):
verbosity = int(arg[-1])
args = [arg for arg in args if not arg.startswith('-')]
configure()
with warnings.catch_warnings():
# The warnings module in default configuration will never cause tests
# to fail, as it never raises an exception. We alter that behaviour by
# turning DeprecationWarnings into exceptions, but exclude warnings
# triggered by third-party libs. Note: The context manager is not thread
# safe. Behaviour with multiple threads is undefined.
warnings.filterwarnings('error', category=DeprecationWarning)
warnings.filterwarnings('error', category=RuntimeWarning)
libs = r'(sorl\.thumbnail.*|bs4.*|webtest.*)'
warnings.filterwarnings(
'ignore', r'.*', DeprecationWarning, libs)
run_tests(verbosity, *args)
| args.extend(['--nocapture', '--stop']) | conditional_block |
runtests.py | #!/usr/bin/env python
"""
Custom test runner
If args or options, we run the testsuite as quickly as possible.
If args but no options, we default to using the spec plugin and aborting on
first error/failure.
If options, we ignore defaults and pass options onto Nose.
Examples:
Run all tests (as fast as possible)
$ ./runtests.py
Run all unit tests (using spec output)
$ ./runtests.py tests/unit
Run all checkout unit tests (using spec output)
$ ./runtests.py tests/unit/checkout
Run all tests relating to shipping
$ ./runtests.py --attr=shipping
Re-run failing tests (needs to be run twice to first build the index)
$ ./runtests.py ... --failed
| Drop into pdb when a test fails
$ ./runtests.py ... --pdb-failures
"""
import sys
import logging
import warnings
from tests.config import configure
from django.utils.six.moves import map
# No logging
logging.disable(logging.CRITICAL)
def run_tests(verbosity, *test_args):
from django_nose import NoseTestSuiteRunner
test_runner = NoseTestSuiteRunner(verbosity=verbosity)
if not test_args:
test_args = ['tests']
num_failures = test_runner.run_tests(test_args)
if num_failures:
sys.exit(num_failures)
if __name__ == '__main__':
args = sys.argv[1:]
verbosity = 1
if not args:
# If run with no args, try and run the testsuite as fast as possible.
# That means across all cores and with no high-falutin' plugins.
import multiprocessing
try:
num_cores = multiprocessing.cpu_count()
except NotImplementedError:
num_cores = 4 # Guess
args = ['--nocapture', '--stop', '--processes=%s' % num_cores]
else:
# Some args/options specified. Check to see if any nose options have
# been specified. If they have, then don't set any
has_options = any(map(lambda x: x.startswith('--'), args))
if not has_options:
# Default options:
# --stop Abort on first error/failure
# --nocapture Don't capture STDOUT
args.extend(['--nocapture', '--stop'])
else:
# Remove options as nose will pick these up from sys.argv
for arg in args:
if arg.startswith('--verbosity'):
verbosity = int(arg[-1])
args = [arg for arg in args if not arg.startswith('-')]
configure()
with warnings.catch_warnings():
# The warnings module in default configuration will never cause tests
# to fail, as it never raises an exception. We alter that behaviour by
# turning DeprecationWarnings into exceptions, but exclude warnings
# triggered by third-party libs. Note: The context manager is not thread
# safe. Behaviour with multiple threads is undefined.
warnings.filterwarnings('error', category=DeprecationWarning)
warnings.filterwarnings('error', category=RuntimeWarning)
libs = r'(sorl\.thumbnail.*|bs4.*|webtest.*)'
warnings.filterwarnings(
'ignore', r'.*', DeprecationWarning, libs)
run_tests(verbosity, *args) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.